{
  "meta": {
    "title": "LS:MP SDK",
    "subtitle": "Gamescripting reference",
    "brandHtml": "<span class=\"lsmp-wordmark\">LS:<span class=\"lsmp-wordmark-accent\">MP</span></span> <span>SDK</span>"
  },
  "sections": [
    {
      "id": "start",
      "title": "Get started",
      "icon": "✦",
      "pages": [
        {
          "id": "overview",
          "title": "LS:MP scripting",
          "eyebrow": "Get started",
          "lead": "Everything your server does beyond the base game is a resource: a folder of Lua or JavaScript scripts, web pages and assets. This SDK is the `lsmp` API those scripts use.",
          "blocks": [
            {
              "type": "text",
              "md": "A **resource** is a folder in your server's `resources/`. Its **server scripts** run on your server; its **client scripts** are sent to every player and run in their game; its **web pages** draw interfaces in game. Each side can be written in **Lua or JavaScript**, with the same functions in both languages."
            },
            {
              "type": "table",
              "headers": [
                "You want to…",
                "Use"
              ],
              "rows": [
                [
                  "React to players joining, spawning, dying, leaving",
                  "[Engine events](#engine-events) with `lsmp.on`"
                ],
                [
                  "Send data between server and clients",
                  "[Events](#events) (`lsmp.emitServer` / `lsmp.emitClient`, `lsmp.onServer` / `lsmp.onClient`) and [calls](#rpc) (`lsmp.call` / `lsmp.callServer` / `lsmp.callClient`, `lsmp.onCall`)"
                ],
                [
                  "Spawn vehicles, peds and objects that everyone sees",
                  "[Entities](#server-entities), with [ownership](#server-ownership) and [dimensions](#dimensions)"
                ],
                [
                  "Store data",
                  "[Meta](#meta) for live replicated values, [storage](#server-storage), [MySQL](#server-mysql) and [files](#server-files) to keep them"
                ],
                [
                  "Show an interface",
                  "[Web pages](#web-ui) in 2D or on a surface of the world ([browsers](#browsers))"
                ],
                [
                  "Talk to players by voice",
                  "[Voice channels](#voice) driven by your scripts"
                ],
                [
                  "Call web services",
                  "The [HTTP client](#http), and [HTTP routes](#server-http-serve) on the server"
                ],
                [
                  "Drive the game itself",
                  "About 6,700 [game natives](#natives), as global functions in client scripts"
                ],
                [
                  "Ship models, maps and vehicles",
                  "[Assets and streaming](#streaming)"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Start here",
              "level": 2,
              "id": "start"
            },
            {
              "type": "cards",
              "items": [
                {
                  "icon": "🗄",
                  "title": "Run a server",
                  "href": "#install",
                  "desc": "From the download to a server you can join."
                },
                {
                  "icon": "⚡",
                  "title": "Your first resource",
                  "href": "#quick-start",
                  "desc": "A server script and a client script talking to each other, in five minutes."
                },
                {
                  "icon": "🧭",
                  "title": "Core concepts",
                  "href": "#concepts",
                  "desc": "Resources, sides, identifiers, events, ownership, dimensions: the ideas behind every page."
                },
                {
                  "icon": "🖥",
                  "title": "Build an interface",
                  "href": "#tutorial-ui",
                  "desc": "A web page in game, with messages in both directions."
                },
                {
                  "icon": "🚀",
                  "title": "Publish a mod",
                  "href": "#publish-mod",
                  "desc": "Share your resource with every LS:MP server on lsmp.gg."
                },
                {
                  "icon": "📖",
                  "title": "Reference",
                  "href": "#conventions",
                  "desc": "Types, errors, units and the rules every function follows."
                }
              ]
            },
            {
              "type": "heading",
              "text": "Coming from FiveM",
              "level": 2,
              "id": "fivem"
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "What maps to what",
              "md": "Most ideas carry over; the names change.\n\n- `fxmanifest.lua` → `manifest.json`, with `client_scripts`, `server_scripts` and `shared_scripts`. The resource's name is its folder name; no `ensure` line is needed.\n- `TriggerServerEvent` → `lsmp.emitServer`, received with `lsmp.onClient`; `TriggerClientEvent` → `lsmp.emitClient` (target first), `lsmp.emitAllClients` or `lsmp.emitDimensionClients`, received with `lsmp.onServer`. On the server, the sending player is the first argument of the handler, not a `source` global.\n- `AddEventHandler` / `TriggerEvent` → `lsmp.on` / `lsmp.emit`. Server callbacks → `lsmp.onCall` + `lsmp.callServer` / `lsmp.callClient`, built in. Exports → `lsmp.onCall` + `lsmp.call` (any resource, Lua or JavaScript). `GetHashKey` → `lsmp.hash`.\n- `Citizen.Wait` / `Citizen.CreateThread` → `lsmp.wait` / `lsmp.createThread` in Lua, `await` in JavaScript.\n- Routing buckets → [dimensions](#dimensions). State bags → [meta](#meta). `SetResourceKvp` → [`lsmp.storage`](#server-storage).\n- NUI → [browsers](#browsers): `browser.emit` / `browser.on` in the script, `lsmp.emit` / `lsmp.on` in the page.\n- Natives are camelCase globals and out-params come back as results: see [Game natives](#natives/natives-fivem)."
            }
          ]
        },
        {
          "id": "quick-start",
          "title": "Quick start: your first resource",
          "eyebrow": "Get started",
          "lead": "From an empty folder to a server script and a client script talking to each other in game, in five minutes.",
          "blocks": [
            {
              "type": "text",
              "md": "You need a [running server](#install) on your machine and the LS:MP client. We build a resource named `hello`: the client greets the server, the server answers that player, and the client asks the server how many players are online."
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Create the folder",
                  "md": "In your server's folder, create `resources/hello/`. The folder name **is** the resource's name: 1 to 64 characters, lowercase letters, digits, `_` and `-`, starting with a letter or a digit. `Hello` or `my mod` would be refused, with a suggested name in the console. Names starting with `lsmp` are reserved.",
                  "blocks": [
                    {
                      "type": "tree",
                      "tree": "resources/\n└─ hello/\n   ├─ manifest.json\n   ├─ server/\n   │  └─ main.lua      # runs on the server only\n   └─ client/\n      └─ main.lua      # sent to every player, runs in their game",
                      "only": "lua"
                    },
                    {
                      "type": "tree",
                      "tree": "resources/\n└─ hello/\n   ├─ manifest.json\n   ├─ server/\n   │  └─ main.js       # runs on the server only\n   └─ client/\n      └─ main.js       # sent to every player, runs in their game",
                      "only": "js"
                    }
                  ]
                },
                {
                  "title": "Write the manifest",
                  "md": "`manifest.json` lists which files run where. Each list takes a string or an array, and accepts patterns such as `\"client/*.lua\"`. A side can mix `.lua` and `.js` files. Every key is described in [Resource layout](#resource-layout).",
                  "blocks": [
                    {
                      "type": "code",
                      "lang": "json",
                      "title": "manifest.json",
                      "code": "{\n  \"title\": \"Hello\",\n  \"server_scripts\": [\"server/main.lua\"],\n  \"client_scripts\": [\"client/main.lua\"]\n}",
                      "only": "lua"
                    },
                    {
                      "type": "code",
                      "lang": "json",
                      "title": "manifest.json",
                      "code": "{\n  \"title\": \"Hello\",\n  \"server_scripts\": [\"server/main.js\"],\n  \"client_scripts\": [\"client/main.js\"]\n}",
                      "only": "js"
                    }
                  ]
                },
                {
                  "title": "Write the scripts",
                  "md": "The server listens for the client's `hello:ping` event and answers with `hello:pong` to that player only. It also handles the remote call `hello:playerCount`, whose return value travels back to the caller. Prefix your event names with the resource name: event names are shared by every resource.",
                  "blocks": [
                    {
                      "type": "codetabs",
                      "tabs": [
                        {
                          "label": "server/main.lua",
                          "lang": "lua",
                          "code": "-- server/main.lua\nlsmp.on(\"playerJoin\", function(playerId, name)\n  lsmp.log(name .. \" joined (#\" .. playerId .. \")\")\nend)\n\n-- A client says hello: answer that player only.\n-- 'source' is the sender's playerId, set by the server: it cannot be forged.\nlsmp.onClient(\"hello:ping\", function(source, text)\n  lsmp.log(\"ping from #\" .. source .. \": \" .. text)\n  lsmp.emitClient(source, \"hello:pong\", \"hello, \" .. lsmp.getPlayerName(source))\nend)\n\n-- A remote call: the client waits for this return value.\nlsmp.onCall(\"hello:playerCount\", function(source)\n  return #lsmp.getPlayers()\nend)"
                        },
                        {
                          "label": "client/main.lua",
                          "lang": "lua",
                          "code": "-- client/main.lua\nlsmp.onServer(\"hello:pong\", function(text)\n  lsmp.log(\"server says: \" .. text)\nend)\n\nlsmp.emitServer(\"hello:ping\", \"hi from the client\")\n\n-- The file body may wait: lsmp.callServer suspends it until the answer comes.\nlocal count, err = lsmp.callServer(\"hello:playerCount\")\nif count then\n  lsmp.log(count .. \" player(s) online\")\nelse\n  lsmp.warn(\"call failed: \" .. err)\nend"
                        },
                        {
                          "label": "server/main.js",
                          "lang": "js",
                          "code": "// server/main.js\nlsmp.on('playerJoin', (playerId, name) => {\n  lsmp.log(`${name} joined (#${playerId})`);\n});\n\n// A client says hello: answer that player only.\n// 'source' is the sender's playerId, set by the server: it cannot be forged.\nlsmp.onClient('hello:ping', (source, text) => {\n  lsmp.log(`ping from #${source}: ${text}`);\n  lsmp.emitClient(source, 'hello:pong', `hello, ${lsmp.getPlayerName(source)}`);\n});\n\n// A remote call: the client waits for this return value.\nlsmp.onCall('hello:playerCount', (source) => lsmp.getPlayers().length);"
                        },
                        {
                          "label": "client/main.js",
                          "lang": "js",
                          "code": "// client/main.js\nlsmp.onServer('hello:pong', (text) => {\n  lsmp.log(`server says: ${text}`);\n});\n\nlsmp.emitServer('hello:ping', 'hi from the client');\n\nlsmp.callServer('hello:playerCount')\n  .then((count) => lsmp.log(`${count} player(s) online`))\n  .catch((err) => lsmp.warn(`call failed: ${err.code}`));"
                        }
                      ]
                    }
                  ]
                },
                {
                  "title": "Start the resource",
                  "md": "The server loads its resources when it starts: restart it so it loads `hello` (type `quit` in the server console, the terminal or the **Console** tab of the admin panel, then start the server again). After each change to the files, restart the server again."
                },
                {
                  "title": "Join and look",
                  "md": "Join your server with LS:MP. The server console shows `[hello] … joined (#…)` and the ping. In the game, open the client console with **F8**: it shows `[hello] server says: hello, …` and the player count. Every line of a resource starts with its name."
                },
                {
                  "title": "Go further",
                  "md": "You have the whole loop: files in a folder, a manifest, both sides, events and a remote call."
                }
              ]
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "[Core concepts](#concepts): the ideas behind every page, in a few minutes.",
                "[Events and RPC](#events-guide): events, remote calls, and when to use which.",
                "[Your first web UI](#tutorial-ui): a page in game that talks to your scripts.",
                "[Storing data](#data-guide): meta, storage, MySQL and files.",
                "[A /car command](#tutorial-car): a small complete feature, with a permission and an entity.",
                "[Debugging](#debugging): logs, DevTools and common errors."
              ]
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "When something goes wrong",
              "md": "A resource that fails to start says why in the server console, in red, with the file and the line: an invalid `manifest.json`, a script that raises at load, a missing dependency. `resources` in the console lists every resource with its state."
            }
          ]
        },
        {
          "id": "concepts",
          "title": "Core concepts",
          "eyebrow": "Get started",
          "lead": "The handful of ideas every page of this SDK relies on. A few lines each, with a link to the full story.",
          "blocks": [
            {
              "type": "heading",
              "text": "Resources",
              "level": 2,
              "id": "resources"
            },
            {
              "type": "text",
              "md": "A **resource** is a folder in `resources/` with a `manifest.json`. Its **name is the folder name**, and that name is its identity everywhere: logs (`[bank] …`), the console (`resources`), dependencies, web addresses (`rsc://bank/`), and the storage that belongs to it. A resource starts, runs and stops as one unit (on a server: from the server start to its shutdown); when it stops, what it created goes with it: handlers, timers, entities, settings. See [Resource layout](#resource-layout) and [Lifecycle](#server-lifecycle)."
            },
            {
              "type": "heading",
              "text": "Server, client and page",
              "level": 2,
              "id": "sides"
            },
            {
              "type": "table",
              "headers": [
                "Side",
                "Where it runs",
                "Typical job"
              ],
              "rows": [
                [
                  "**Server**",
                  "On your server, once.",
                  "The authority: rules, money, permissions, persistent data, entities everyone shares."
                ],
                [
                  "**Client**",
                  "In each player's game, sent with the resource.",
                  "What one player sees and does: natives, HUD, input, camera, local effects."
                ],
                [
                  "**Page**",
                  "In a web page the client script opens in game.",
                  "Interfaces in HTML, CSS and JavaScript, with their own small `lsmp` object ([Page API](#page-api))."
                ]
              ]
            },
            {
              "type": "text",
              "md": "Never trust the client: anything a client sends can be forged by a modified game. Check it on the server."
            },
            {
              "type": "heading",
              "text": "Lua and JavaScript",
              "level": 2,
              "id": "languages"
            },
            {
              "type": "text",
              "md": "Every side can be written in **Lua** or **JavaScript**: the server runs Lua and Node.js, the client runs Lua and V8. The `lsmp` API has the same functions, arguments and results in both. The few differences of style (`obj:m()` against `obj.m()`, `nil` against `null`, coroutines against Promises) are listed in [Conventions](#conventions). A resource can mix both languages on one side: they talk through [events](#events)."
            },
            {
              "type": "heading",
              "text": "Identifiers",
              "level": 2,
              "id": "identifiers"
            },
            {
              "type": "table",
              "headers": [
                "Name",
                "What it identifies",
                "Valid"
              ],
              "rows": [
                [
                  "`playerId`",
                  "A connected player, for this session. Given by the server, the same on every side.",
                  "until the player leaves"
                ],
                [
                  "`lsmpId`",
                  "A player's LS:MP account. `nil` / `null` for a guest.",
                  "forever"
                ],
                [
                  "`netId`",
                  "A networked entity (vehicle, ped, object), the same on the server and on every client.",
                  "while the entity exists"
                ],
                [
                  "handle",
                  "An entity **in one player's game**: what the natives take. Get it from a `netId` with [`lsmp.getEntityFromNetId`](#client-entities).",
                  "on that client, while the entity is streamed in"
                ],
                [
                  "`dimension`",
                  "A separate world on the same server, `0` by default.",
                  "`0` to `65535`"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Engine events and script events",
              "level": 2,
              "id": "events"
            },
            {
              "type": "text",
              "md": "**Engine events** are sent by LS:MP itself: `playerJoin`, `playerSpawn`, `playerDeath`, `resourceStart`… You listen to them with `lsmp.on`; their names are reserved, so no script can fake one. The full list is in [Engine events](#engine-events).\n\n**Script events** are yours. `lsmp.emit` reaches the handlers of the **same side**, in every resource and both languages; network events carry their direction in their name: `lsmp.emitServer` (client → server, received with `onClient`) and `lsmp.emitClient` / `emitAllClients` / `emitDimensionClients` (server → players, received with `onServer`). A **call** asks a question and waits for the answer: `lsmp.call` to another resource of the same side, `lsmp.callServer` from a client, `lsmp.callClient` from the server, all answered by `lsmp.onCall`. See [Events](#events), [Remote calls](#rpc) and the [Events and RPC guide](#events-guide)."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "lsmp.on(\"playerDeath\", function(playerId, killerId)\n  lsmp.log(lsmp.getPlayerName(playerId) .. \" died\")\nend)\n\nlsmp.onClient(\"shop:buy\", function(source, item)\n  -- source: the playerId that sent the event\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "lsmp.on('playerDeath', (playerId, killerId) => {\n  lsmp.log(`${lsmp.getPlayerName(playerId)} died`);\n});\n\nlsmp.onClient('shop:buy', (source, item) => {\n  // source: the playerId that sent the event\n});"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Entities and ownership",
              "level": 2,
              "id": "ownership"
            },
            {
              "type": "text",
              "md": "A networked entity exists once for the whole server, with one `netId`. Its physics and AI are **simulated by one player's game at a time**, its **owner**, usually a player close to it; the others receive its state. When the owner leaves or moves away, another player takes over. The server decides who may own an entity and when it is deleted (`ownerPolicy`, `lifePolicy`), and can keep an entity alive after the resource that created it stops. See [Entities](#server-entities) and [Ownership](#server-ownership)."
            },
            {
              "type": "heading",
              "text": "Dimensions",
              "level": 2,
              "id": "dimensions"
            },
            {
              "type": "text",
              "md": "A **dimension** is a separate copy of the world on the same server. Players and entities only see, hear and meet what shares their dimension. Use one for an interior, a race, a private lobby. Everyone starts in dimension `0`. See [Dimensions](#dimensions)."
            },
            {
              "type": "heading",
              "text": "Meta and storage",
              "level": 2,
              "id": "data"
            },
            {
              "type": "table",
              "headers": [
                "",
                "Meta",
                "Storage"
              ],
              "rows": [
                [
                  "What",
                  "Live values attached to the server (global), a player or an entity.",
                  "Your resource's persistent key/value store."
                ],
                [
                  "Where",
                  "Replicated: every client reads them, and gets notified when they change.",
                  "On the server only."
                ],
                [
                  "How long",
                  "Until the player leaves, the entity goes, or the server stops.",
                  "Kept across restarts."
                ],
                [
                  "For",
                  "A player's job title on their nametag, a door state, a vehicle's fuel.",
                  "Balances, unlocks, settings."
                ]
              ]
            },
            {
              "type": "text",
              "md": "See [Meta](#meta), [storage](#server-storage) and the [Storing data guide](#data-guide)."
            },
            {
              "type": "heading",
              "text": "Asynchronous calls",
              "level": 2,
              "id": "async"
            },
            {
              "type": "text",
              "md": "Anything that waits for the network, the disk or the game (remote calls, HTTP, captures, resource jobs) is **asynchronous**, and never completes during the call itself. In JavaScript it returns a Promise: `await` it. In Lua the file body, every handler and `lsmp.createThread` run in a coroutine, so `local value, err = lsmp.call(…)` simply waits; a callback as last argument works too. See [Conventions](#conventions)."
            },
            {
              "type": "heading",
              "text": "Sandbox and capabilities",
              "level": 2,
              "id": "sandbox"
            },
            {
              "type": "text",
              "md": "Server resources run **sandboxed** by default: no access to the machine beyond their own data folder, and sensitive functions refused. The server operator decides, per resource, what is lifted (in `resources.json` and the admin panel), and grants **capabilities** such as changing the weather or deleting other resources' entities. A function refused for lack of a capability returns the `permission` code instead of raising. See [Operator settings](#operator-settings) and [Capabilities](#capabilities)."
            }
          ]
        }
      ]
    },
    {
      "id": "server-setup",
      "title": "Run a server",
      "icon": "🗄",
      "pages": [
        {
          "id": "install",
          "title": "Install and first start",
          "eyebrow": "Run a server",
          "lead": "From an empty folder to a server that players can join, on Windows or Linux: download, first start, setup page, and the folders the server creates.",
          "blocks": [
            {
              "type": "text",
              "md": "An LS:MP server is one program. It reads `server.cfg`, packs the resources it finds in `resources/`, starts them, and waits for players. You need a machine that stays on, an [LS:MP account](https://lsmp.gg) to link the server to, and two open ports."
            },
            {
              "type": "table",
              "headers": [
                "",
                "Windows",
                "Linux"
              ],
              "rows": [
                [
                  "System",
                  "Windows x64",
                  "x64 with glibc 2.34 or newer: Debian 12, Ubuntu 22.04, RHEL / Rocky / Alma / Oracle Linux 9, Fedora 35, or newer. Packages: libcurl, brotli, libstdc++, ca-certificates."
                ],
                [
                  "Program",
                  "`lsmp-server.exe`",
                  "`./lsmp-server`"
                ],
                [
                  "Ports",
                  "`2086` TCP (`HttpPort`), `9530` TCP **and** UDP (`GamePort`)",
                  "the same"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Install",
              "level": 2,
              "id": "install-steps"
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Download",
                  "md": "Get the server package for your system on the [download page](https://lsmp.gg/download), and unpack it in a folder of its own. Keep everything together: the program, its libraries and the `uiadmin/` folder (the admin panel's interface). On Linux, make the program executable, and do not run it as root.",
                  "code": {
                    "lang": "bash",
                    "title": "Linux",
                    "code": "cd /home/lsmp/server\nchmod +x lsmp-server"
                  }
                },
                {
                  "title": "Start it once",
                  "md": "Run the program **from its folder**: the server looks for every file in its working folder. On Windows, open a terminal in the folder and run `lsmp-server.exe`, so that you can read the console. At this first start the server writes a commented `server.cfg` with every default, packs the resources, opens its ports and prints a framed **SETUP REQUIRED** message with a one-time code. Leave it running.",
                  "code": {
                    "lang": "text",
                    "title": "server console",
                    "code": "SETUP REQUIRED\n\nOpen the admin panel of this gameserver:\n    http://203.0.113.10:2086/lsadmin\nand enter this one-time setup code:\n    XXXX-XXXX-XXXX"
                  }
                },
                {
                  "title": "Open the ports",
                  "md": "Open `HttpPort` (2086) in **TCP**, and `GamePort` (9530) in **TCP and UDP**. Behind a home router, also forward them to this machine. The commands for each system are in [Go public](#go-public)."
                },
                {
                  "title": "Run the setup page",
                  "md": "Open `http://<server-ip>:2086/lsadmin` in a web browser and enter the code. A new code is printed at each start until the setup is finished. The setup has five steps, and you can go back to any of them:",
                  "blocks": [
                    {
                      "type": "list",
                      "ordered": true,
                      "items": [
                        "**Terms**: read the LS:MP EULA to the end and accept it. It is the text of `eula.txt`, next to `server.cfg`.",
                        "**LS:MP account**: press **Continue with LS:MP**, approve on lsmp.gg, and check that the pairing code matches. LS:MP sends the server its network `Token` by itself. You can skip this step and link the server later.",
                        "**Server**: name, description, maximum players and map. A linked server can turn on the public listing here.",
                        "**Access**: how administrators sign in. **LS:MP sign-in only** is recommended; a local account needs a password of 8 characters or more.",
                        "**Finish**: review, press **Finish setup**, then **Restart now**. Everything is written to `server.cfg` and applies at this restart."
                      ]
                    }
                  ]
                },
                {
                  "title": "Join it",
                  "md": "Start LS:MP and join by address: `ip:2086`, the **HTTP** port, never the game port. Your server does nothing visible without resources: players need at least a resource that spawns them. Start from the resources that ship with the server, or [write your first one](#quick-start)."
                }
              ]
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "Setting up by hand",
              "md": "Read `eula.txt`, set `Eula=true` (and your `Token`, if you have one) in `server.cfg`, and restart. The panel then opens normally, at `/lsadmin`."
            },
            {
              "type": "heading",
              "text": "The server folder",
              "level": 2,
              "id": "install-folder"
            },
            {
              "type": "text",
              "md": "After the first start, the folder looks like this. You edit the files marked *yours*; the others are written by the server."
            },
            {
              "type": "tree",
              "tree": "server/\n├─ lsmp-server           # the program (lsmp-server.exe on Windows)\n├─ uiadmin/              # the admin panel's interface: keep it next to the program\n├─ server.cfg            # yours: ports, name, limits, token (see server.cfg reference)\n├─ resources.json        # yours: per-resource settings (enabled, sandbox, client mount)\n├─ eula.txt              # the licence you accepted\n├─ admin-users.json      # local accounts of the admin panel\n├─ blacklist.json        # bans and whitelist\n├─ perms.json            # permissions and resource capabilities\n├─ resources/            # yours: one folder per resource\n│  └─ hello/\n│     └─ manifest.json\n├─ manifest.json         # generated: what players download first\n├─ packages/             # generated: each resource packed for clients and for the server\n├─ data/                 # generated: private data folders of your resources\n├─ storage/              # generated: the persistent storage of your resources\n├─ logs/                 # generated: one log file per session\n└─ stats/                # generated: metrics history for the admin panel"
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "manifest.json at the root is not yours",
              "md": "The `manifest.json` next to the program is regenerated at every start from your resources. Edit the `manifest.json` **inside** each resource folder, and per-resource settings in [`resources.json`](#operator-settings)."
            },
            {
              "type": "heading",
              "text": "What happens at startup",
              "level": 2,
              "id": "install-startup"
            },
            {
              "type": "list",
              "ordered": true,
              "items": [
                "The server reads `server.cfg`. An unknown key, an invalid value or an old key name is reported with its line, and the default is used: see [server.cfg reference](#server-cfg).",
                "It reads `resources.json`, then scans `resources/`. Every valid folder becomes a resource named after the folder; a folder with an invalid name is refused, with the name to use instead.",
                "It packs each resource: a client package for the players and a server package for itself. A package that did not change is not rebuilt.",
                "It starts every enabled resource, dependencies first, then delivers `serverStart`.",
                "It opens the game port (`GamePort`, TCP and UDP) and serves HTTP on `HttpPort`: the manifest, the downloads, the admin panel at `/lsadmin`, and the [HTTP routes](#server-http-serve) of your resources."
              ]
            },
            {
              "type": "text",
              "md": "A player gives out the **HTTP** address (`ip:2086`). Their client downloads the manifest there, learns the game port from it, downloads the packages it is missing, then opens the game session on `GamePort`."
            },
            {
              "type": "heading",
              "text": "Add or change a resource",
              "level": 2,
              "id": "install-resources"
            },
            {
              "type": "text",
              "md": "Copy the folder into `resources/`, then restart the server: resources are read once, when the server starts, and every enabled resource starts on its own. The same goes after editing a resource."
            },
            {
              "type": "heading",
              "text": "Stop it cleanly",
              "level": 2,
              "id": "install-stop"
            },
            {
              "type": "text",
              "md": "Type `quit` in the console, press **Ctrl+C**, stop the service, or use **Shutdown** in the admin panel. The server then refuses new players, says goodbye to the connected ones (`playerLeave` with the reason `\"shutdown\"`), gives your resources `ShutdownGraceMs` (5 s) to finish their `serverStop` handlers, stops them, and writes their key/value stores. A crash or a killed process skips all of this."
            },
            {
              "type": "heading",
              "text": "Keep it running on Linux",
              "level": 2,
              "id": "install-systemd"
            },
            {
              "type": "text",
              "md": "A systemd service starts the server with the machine and restarts it after a crash. A service has no terminal: set `ConsoleStdin=false` in `server.cfg`, and use the **Console** tab of the admin panel. Read the output with `journalctl -u lsmp -e`."
            },
            {
              "type": "code",
              "lang": "ini",
              "title": "/etc/systemd/system/lsmp.service",
              "code": "[Unit]\nDescription=LS:MP gameserver\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nUser=lsmp\nWorkingDirectory=/home/lsmp/server\nExecStart=/home/lsmp/server/lsmp-server\nRestart=always\nKillSignal=SIGINT\nTimeoutStopSec=30\n\n[Install]\nWantedBy=multi-user.target"
            },
            {
              "type": "code",
              "lang": "bash",
              "code": "sudo systemctl daemon-reload\nsudo systemctl enable --now lsmp"
            },
            {
              "type": "heading",
              "text": "Troubleshooting",
              "level": 2,
              "id": "install-troubleshooting"
            },
            {
              "type": "table",
              "headers": [
                "Symptom",
                "Cause and fix"
              ],
              "rows": [
                [
                  "The Linux program does not start, with a `GLIBC` or library error",
                  "The system is too old, or libcurl or brotli is missing: see the table at the top of this page."
                ],
                [
                  "`/` answers `404` on the HTTP port",
                  "Normal: the panel is at `/lsadmin`."
                ],
                [
                  "The panel page is blank or broken",
                  "The `uiadmin/` folder is not next to the program, or the server was not started from its folder."
                ],
                [
                  "The setup code is lost",
                  "A new one is printed at each start. On a service, read `journalctl -u lsmp -e`."
                ],
                [
                  "`HttpPort (line …) and GamePort (line …) are both …` and the server exits",
                  "The two ports must differ: fix `server.cfg`."
                ],
                [
                  "`MaxPlayers` is lower than what you set",
                  "It is capped by the plan of the server's owner, with a line in the log."
                ],
                [
                  "Players connect, then nothing moves",
                  "`GamePort` is open in TCP but not in UDP."
                ],
                [
                  "Players cannot reach the server at all",
                  "Check `HttpPort` from outside your network, and that players use `ip:HttpPort`. See [Go public](#go-public)."
                ],
                [
                  "A resource does not start",
                  "The console says why, in red: invalid `manifest.json` (with line and column), a script that raises at load, a missing dependency. `resources` lists every resource with its state. See [Debugging](#debugging)."
                ],
                [
                  "`resource folder 'MyMod' is not a valid name …: use 'mymod'`",
                  "Rename the folder: names are lowercase, see [Resource layout](#resource-layout/layout-name)."
                ],
                [
                  "Ports stay in use after a crash, or at a second start",
                  "Another instance is running. To run two servers, give each one its own folder, `HttpPort` **and** `GamePort`."
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "Next",
              "md": "Tune [`server.cfg`](#server-cfg), learn the [console and admin panel](#console), [go public](#go-public), and [write a resource](#quick-start)."
            }
          ]
        },
        {
          "id": "server-cfg",
          "title": "server.cfg reference",
          "eyebrow": "Run a server",
          "lead": "Every key of the server's configuration file: type, unit, default and range, how the file is read, and what happens to a file that still uses old key names.",
          "blocks": [
            {
              "type": "text",
              "md": "`server.cfg` sits next to the server program. The server writes it, commented, at its first start, and reads it at every start. The **Settings** tab of the admin panel edits the same file, with a form and a raw view. Per-resource settings (enabled, sandbox, client mount) are not here: they live in [`resources.json`](#operator-settings)."
            },
            {
              "type": "code",
              "lang": "ini",
              "title": "server.cfg (excerpt)",
              "code": "# Game TCP/UDP port. Open both protocols on this port. Must differ from HttpPort.\n# Range: 1..65535 port. Default: 9530\nGamePort=9530\n\nHttpPort=2086\nName=My LS:MP server\nMaxPlayers=64\nPublicList=false\nToken="
            },
            {
              "type": "heading",
              "text": "How the file is read",
              "level": 2,
              "id": "cfg-rules"
            },
            {
              "type": "list",
              "items": [
                "One `Key=Value` per line. Spaces around the key and the value are ignored. A line starting with `#` or `;` is a comment.",
                "Key names are case-sensitive: `GamePort`, not `gameport`. When a key appears twice, the **last** line wins.",
                "**Booleans**: `true`/`false`, `yes`/`no`, `on`/`off` or `1`/`0`, in any case.",
                "**Lists**: comma-separated values; an empty value means an empty list.",
                "**Text** (`Name`, `Description`, Discord texts): `\\n`, `\\r`, `\\t` and `\\\\` are escapes, so a multi-line description stays on one line.",
                "The file is at most 4 MiB, 64 KiB per line. A UTF-8 BOM is accepted.",
                "Every change applies at the **next start**, except where a key says otherwise."
              ]
            },
            {
              "type": "heading",
              "text": "Mistakes and warnings",
              "level": 3,
              "id": "cfg-warnings"
            },
            {
              "type": "text",
              "md": "The server never stops on a bad line, with one exception (equal ports). Each problem is logged with its line number, and the server carries on with the default:"
            },
            {
              "type": "table",
              "headers": [
                "Problem",
                "What the log says",
                "What the server does"
              ],
              "rows": [
                [
                  "Invalid value (type, range, malformed list)",
                  "`[server.cfg] line 12: 'MaxPlayers' = 'lots' is invalid (expected …), using default 64`",
                  "Uses the default. The value of `Token` is never printed."
                ],
                [
                  "Unknown key",
                  "`[server.cfg] line 4: 'Gameport' is not a key, did you mean 'GamePort'?`",
                  "Ignores the line."
                ],
                [
                  "Old key name (see [below](#server-cfg/cfg-migration))",
                  "`[server.cfg] line 7: obsolete key 'PlayPort': use 'GamePort'`",
                  "Ignores the line; one warning per key."
                ],
                [
                  "`GamePort` equal to `HttpPort`",
                  "`HttpPort (line 3) and GamePort (line 2) are both 9530: they must differ. The server does not start.`",
                  "**Exits.** Fix the file and start again."
                ],
                [
                  "Line without `=`",
                  "`[server.cfg] line 9: expected a nonempty key=value`",
                  "Ignores the line."
                ],
                [
                  "Missing file",
                  "`server.cfg created with default settings`",
                  "Writes a commented file with every default."
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "An invalid SandboxNetConnect allows nothing",
              "md": "Every invalid value falls back to its default, except `SandboxNetConnect`: an invalid list becomes an **empty** list, which forbids every outgoing connection of sandboxed resources. Check the log after editing it."
            },
            {
              "type": "heading",
              "text": "General",
              "level": 2,
              "id": "cfg-general"
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Type",
                "Default",
                "Range / values",
                "Description"
              ],
              "rows": [
                [
                  "`Eula`",
                  "bool",
                  "`false`",
                  "",
                  "`true` accepts the LS:MP gameserver EULA (`eula.txt`). The setup page writes it for you."
                ],
                [
                  "`Name`",
                  "text",
                  "`LS:MP Server`",
                  "up to 256 UTF-8 bytes",
                  "Display name in the server browser."
                ],
                [
                  "`Description`",
                  "text",
                  "empty",
                  "up to 16384 UTF-8 bytes",
                  "Shown under the name. Use `\\n` for a new line."
                ],
                [
                  "`MaxPlayers`",
                  "int",
                  "`64`",
                  "`1`..`4096` players",
                  "Maximum connected players. Capped at startup by the plan of the server's owner, with a line in the log."
                ],
                [
                  "`Map`",
                  "enum",
                  "`mp`",
                  "`mp` \\| `sp`",
                  "The world players load: `mp` is the multiplayer map, with every multiplayer location; `sp` is the story-mode map."
                ],
                [
                  "`Token`",
                  "text",
                  "empty",
                  "printable ASCII",
                  "Your private LS:MP network token, from [My Servers](https://lsmp.gg/account#servers). Never share it. See [Go public](#go-public)."
                ],
                [
                  "`PublicList`",
                  "bool",
                  "`false`",
                  "",
                  "Advertise the server in the public server browser. Needs a valid `Token`. Switched from the admin panel on a linked server, it applies at once."
                ],
                [
                  "`LsmpNetwork`",
                  "bool",
                  "`true`",
                  "",
                  "Link with the LS:MP network. `false` cuts every link: the server is not registered or listed, players are not verified (an LS:MP ID is whatever the client claims), plan features and [benefits](#benefits) are off, no new marketplace mod is downloaded, and the server no longer learns its public address (set `PublicAddress`). Not recommended. File only: the panel has no switch for it."
                ],
                [
                  "`AutoUpdate`",
                  "bool",
                  "`true`",
                  "",
                  "Install new server versions by itself once no player has been connected for 5 minutes. Applies at once from the admin panel. See [Updates](#updates)."
                ],
                [
                  "`UpdateChannel`",
                  "text",
                  "`stable`",
                  "`a-z`, `0-9` and `-`",
                  "Release channel of the self-updater. Change it only if LS:MP asks you to."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Network and ports",
              "level": 2,
              "id": "cfg-network"
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Type",
                "Default",
                "Range / values",
                "Description"
              ],
              "rows": [
                [
                  "`GamePort`",
                  "port",
                  "`9530`",
                  "`1`..`65535`",
                  "Game port, **TCP and UDP**. Must differ from `HttpPort`."
                ],
                [
                  "`HttpPort`",
                  "port",
                  "`2086`",
                  "`1`..`65535`",
                  "HTTP port, **TCP**: the address players join, the downloads, the admin panel (`/lsadmin`) and the [HTTP routes](#server-http-serve) of your resources."
                ],
                [
                  "`PublicAddress`",
                  "text",
                  "empty",
                  "`IP:port` or `[IPv6]:port`",
                  "Address announced for joins, with the **HTTP** port: an IP address, not a domain name. Empty uses the address the server is reached at. Set it behind NAT or a proxy."
                ],
                [
                  "`ClientIdleTimeoutSec`",
                  "uint",
                  "`15`",
                  "`0`..`86400` s",
                  "Seconds without traffic before a player is disconnected. `0` turns the check off."
                ],
                [
                  "`MaxTcpConnectionsPerIp`",
                  "uint",
                  "`16`",
                  "`0`..`4294967295`",
                  "Simultaneous game TCP connections per source IP. `0` = no limit."
                ],
                [
                  "`MaxPkgStreamsPerIp`",
                  "uint",
                  "`4`",
                  "`0`..`4294967295`",
                  "Simultaneous package downloads per source IP. `0` = no limit."
                ],
                [
                  "`MaxPkgStreams`",
                  "uint",
                  "`0`",
                  "`0`..`4294967295`",
                  "Simultaneous package downloads in total. `0` = `max(64, 2 × MaxPlayers)`."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Players and protection",
              "level": 2,
              "id": "cfg-protection"
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Type",
                "Default",
                "Range / values",
                "Description"
              ],
              "rows": [
                [
                  "`RequireAdmission`",
                  "bool",
                  "`true`",
                  "",
                  "Players need a valid admission from LS:MP to join. Turn it off only for development or a LAN."
                ],
                [
                  "`AllowGuests`",
                  "bool",
                  "`true`",
                  "",
                  "Let guest players (no LS:MP account) join. `false` refuses them before they download anything. Reliable with `VerifyLsmpIntegrity`, which proves the account. Applies at once from the admin panel."
                ],
                [
                  "`VerifyLsmpIntegrity`",
                  "bool",
                  "`false`",
                  "",
                  "Have LS:MP verify every joining player. Needs a `Token` and the matching subscription."
                ],
                [
                  "`PermsTrustDeclaredIds`",
                  "bool",
                  "`false`",
                  "",
                  "Let LS:MP IDs that are **not** verified count for [permissions](#permissions). Unsafe: a modified client can claim someone else's ID. Applies at once from the admin panel."
                ],
                [
                  "`MaxClientPayloadBytes`",
                  "uint",
                  "`4194304`",
                  "`65536`..`268435456` bytes",
                  "Largest single request from an authenticated client."
                ],
                [
                  "`MaxPreAuthPayloadBytes`",
                  "uint",
                  "`1024`",
                  "`0`, or `512`..`MaxClientPayloadBytes` bytes",
                  "Largest request before authentication. `0` = same as `MaxClientPayloadBytes`."
                ],
                [
                  "`MaxClientSendQueueBytes`",
                  "uint",
                  "`67108864`",
                  "`0`..`4294967295` bytes",
                  "Outgoing bytes queued per player. `0` = no limit."
                ],
                [
                  "`ScriptEventBytesPerSec`",
                  "uint",
                  "`1048576`",
                  "`0`..`4294967295` bytes/s",
                  "Budget of script events and remote calls sent by **each** player to the server, with a 4-second burst. Events over budget are dropped. `0` = no limit."
                ],
                [
                  "`MetaMaxKeys`",
                  "uint",
                  "`256`",
                  "`0`..`65535`",
                  "[Meta](#meta) keys a client may write per player or entity. `0` = no limit."
                ],
                [
                  "`MetaMaxBlobBytes`",
                  "uint",
                  "`65536`",
                  "`0`..`4294967295` bytes",
                  "Meta bytes a client may write per player or entity. `0` = no limit."
                ],
                [
                  "`MetaMaxEntriesPerWrite`",
                  "uint",
                  "`256`",
                  "`0`..`65535`",
                  "Meta entries in one client write. `0` = no limit."
                ],
                [
                  "`MetaWriteBytesPerSec`",
                  "uint",
                  "`65536`",
                  "`0`..`4294967295` bytes/s",
                  "Meta written by each client, with a 4-second burst. `0` = no limit."
                ],
                [
                  "`MaxCreatedEntitiesPerPlayer`",
                  "uint",
                  "`2048`",
                  "`0`..`65535`",
                  "Living entities created by one client. `0` = no limit."
                ],
                [
                  "`MaxAdoptedPerPlayer`",
                  "uint",
                  "`48`",
                  "`0`..`65535`",
                  "Ordinary entities simulated by one client. `0` = no limit."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Peer-to-peer and sync",
              "level": 2,
              "id": "cfg-p2p"
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Type",
                "Default",
                "Range / values",
                "Description"
              ],
              "rows": [
                [
                  "`P2P`",
                  "bool",
                  "`true`",
                  "",
                  "Nearby players exchange movement updates directly over UDP; the server keeps authority."
                ],
                [
                  "`P2PMaxPeers`",
                  "uint",
                  "`16`",
                  "`1`..`64` peers",
                  "Direct peers per player (the closest ones). More peers mean more upload for each player."
                ],
                [
                  "`P2PRangeMeters`",
                  "uint",
                  "`250`",
                  "`50`..`1000` m",
                  "Two players link up when they are closer than this."
                ],
                [
                  "`MaxSyncRateHz`",
                  "uint",
                  "`60`",
                  "`15`..`120` Hz",
                  "Highest rate at which a player may send each entity's state. Clients normally send at 40 Hz."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "World",
              "level": 2,
              "id": "cfg-world"
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Type",
                "Default",
                "Range / values",
                "Description"
              ],
              "rows": [
                [
                  "`DefaultDimension`",
                  "uint",
                  "`0`",
                  "`0`..`65535`",
                  "[Dimension](#dimensions) every new player lands in. `0` is the shared world."
                ],
                [
                  "`DefaultDimensionPopulation`",
                  "bool",
                  "`true`",
                  "",
                  "Ambient population is allowed in dimensions unless a script says otherwise."
                ],
                [
                  "`DefaultDimensionClientEntities`",
                  "bool",
                  "`true`",
                  "",
                  "Whether players' games may create their own networked entities (ambient and scripted), in every dimension by default. `false`: only server scripts create entities. Per dimension: [`lsmp.setDimensionClientEntities`](#dimensions/fn-set-dimension-client-entities)."
                ],
                [
                  "`PickupSync`",
                  "bool",
                  "`true`",
                  "",
                  "Dropped weapons, cash and other pickups are shared by every player, and the server decides who collects them."
                ],
                [
                  "`PickupLifetimeSec`",
                  "uint",
                  "`180`",
                  "`0`..`86400` s",
                  "Time before a dropped pickup disappears. `180` matches the game; `0` keeps it forever."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Ambient population",
              "level": 2,
              "id": "cfg-population"
            },
            {
              "type": "text",
              "md": "Traffic, parked cars and pedestrians generated around each player and shared with the others. Off by default."
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Type",
                "Default",
                "Range / values",
                "Description"
              ],
              "rows": [
                [
                  "`Population`",
                  "bool",
                  "`false`",
                  "",
                  "Turns synchronized ambient population on. The dimension policy also applies."
                ],
                [
                  "`PopulationVehicles`",
                  "bool",
                  "`true`",
                  "",
                  "Moving traffic."
                ],
                [
                  "`PopulationParked`",
                  "bool",
                  "`true`",
                  "",
                  "Parked vehicles."
                ],
                [
                  "`PopulationPeds`",
                  "bool",
                  "`true`",
                  "",
                  "Walking pedestrians and animals."
                ],
                [
                  "`PopulationScenario`",
                  "bool",
                  "`true`",
                  "",
                  "Scenario pedestrians (sitting, working…)."
                ],
                [
                  "`PopulationVehicleDensity`",
                  "float",
                  "`1`",
                  "`0`..`1`",
                  "Requested moving-vehicle density. Clients lower it to fit their budgets."
                ],
                [
                  "`PopulationParkedDensity`",
                  "float",
                  "`1`",
                  "`0`..`1`",
                  "Requested parked-vehicle density."
                ],
                [
                  "`PopulationPedDensity`",
                  "float",
                  "`1`",
                  "`0`..`1`",
                  "Requested pedestrian density."
                ],
                [
                  "`PopulationScenarioDensity`",
                  "float",
                  "`1`",
                  "`0`..`1`",
                  "Requested scenario density."
                ],
                [
                  "`PopulationBudgetPeds`",
                  "uint",
                  "`140`",
                  "`0`..`1000`",
                  "Pedestrians a client keeps in total: players, scripts and population."
                ],
                [
                  "`PopulationBudgetVehicles`",
                  "uint",
                  "`120`",
                  "`0`..`1000`",
                  "Vehicles a client keeps in total: scripts and population."
                ],
                [
                  "`PopulationBudgetObjects`",
                  "uint",
                  "`2500`",
                  "`0`..`60000`",
                  "Object count at which population thins out. `0` ignores objects."
                ],
                [
                  "`PopulationMaxOwned`",
                  "uint",
                  "`96`",
                  "`0`..`1000`",
                  "Population entities simulated by one client. `0` = no limit."
                ],
                [
                  "`PopulationReserveIds`",
                  "uint",
                  "`64`",
                  "`16`..`255`",
                  "IDs reserved per client to create population without waiting for the server."
                ],
                [
                  "`PopulationRangeMeters`",
                  "float",
                  "`400`",
                  "`250`..`800` m",
                  "Distance at which players receive population generated by other players."
                ],
                [
                  "`PopulationAreaVehicles`",
                  "uint",
                  "`120`",
                  "`0`..`1000`",
                  "Population vehicles within 160 m. Keep it at least at the client vehicle budget. `0` = no cap."
                ],
                [
                  "`PopulationAreaPeds`",
                  "uint",
                  "`160`",
                  "`0`..`1000`",
                  "Population pedestrians within 160 m. Keep it at least at the client pedestrian budget. `0` = no cap."
                ],
                [
                  "`PopulationCreateRatePerSec`",
                  "uint",
                  "`60`",
                  "`1`..`1000` /s",
                  "Population creations per second per player."
                ],
                [
                  "`PopulationCrowdStart`",
                  "uint",
                  "`8`",
                  "`0`..`4095` players",
                  "Nearby players at which population starts thinning out."
                ],
                [
                  "`PopulationCrowdEnd`",
                  "uint",
                  "`32`",
                  "`0`..`4096` players",
                  "Nearby players at which population reaches zero. Must be above `PopulationCrowdStart` (both defaults are used otherwise); `0` turns thinning off."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Discord",
              "level": 2,
              "id": "cfg-discord"
            },
            {
              "type": "text",
              "md": "What players' Discord profiles show while they play on your server. Players can always turn it off. Scripts can change it with the [Discord API](#discord)."
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Type",
                "Default",
                "Range / values",
                "Description"
              ],
              "rows": [
                [
                  "`DiscordPresence`",
                  "bool",
                  "`true`",
                  "",
                  "Show this server in the player's Discord profile."
                ],
                [
                  "`DiscordJoinable`",
                  "bool",
                  "`true`",
                  "",
                  "Offer a **Join** button. Players must also allow sharing the server address."
                ],
                [
                  "`DiscordAppId`",
                  "text",
                  "empty",
                  "decimal ID",
                  "Your own Discord application, for your own branding. Needs the matching subscription."
                ],
                [
                  "`DiscordLargeImage`",
                  "text",
                  "empty",
                  "asset key (32 bytes) or `https://` URL",
                  "Large image."
                ],
                [
                  "`DiscordLargeText`",
                  "text",
                  "empty",
                  "up to 128 UTF-8 bytes",
                  "Tooltip of the large image."
                ],
                [
                  "`DiscordSmallImage`",
                  "text",
                  "empty",
                  "asset key (32 bytes) or `https://` URL",
                  "Small image."
                ],
                [
                  "`DiscordSmallText`",
                  "text",
                  "empty",
                  "up to 128 UTF-8 bytes",
                  "Tooltip of the small image."
                ],
                [
                  "`DiscordButtonLabel`",
                  "text",
                  "empty",
                  "up to 32 UTF-8 bytes",
                  "Label of a link button, shown when there is no Join button."
                ],
                [
                  "`DiscordButtonUrl`",
                  "text",
                  "empty",
                  "`https://` URL, up to 512 bytes",
                  "Target of that button."
                ],
                [
                  "`DiscordLinkHosts`",
                  "list",
                  "empty",
                  "8 domains at most",
                  "Domains (subdomains included) your scripts may use for Discord buttons and images, such as `discord.gg`."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Scripts and sandbox",
              "level": 2,
              "id": "cfg-scripts"
            },
            {
              "type": "text",
              "md": "Server resources run in a **sandbox** by default: they reach their own data folder and what you allow here, nothing else. A single resource is trusted with `\"sandbox\": false` in [`resources.json`](#operator-settings). Details in [Capabilities and sandbox](#capabilities)."
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Type",
                "Default",
                "Range / values",
                "Description"
              ],
              "rows": [
                [
                  "`LuaMemoryLimitMiB`",
                  "uint",
                  "`256`",
                  "`0`..`1048576` MiB",
                  "Memory quota of **each** Lua resource. `0` = no quota. Applies when a resource starts."
                ],
                [
                  "`JsHeapLimitMiB`",
                  "uint",
                  "`0`",
                  "`0`..`1048576` MiB",
                  "JavaScript heap shared by **all** server JS resources. `0` = sized from the machine's memory."
                ],
                [
                  "`Sandbox`",
                  "bool",
                  "`true`",
                  "",
                  "Sandbox for server resources, Lua and JavaScript. `false` trusts **every** resource with full machine access."
                ],
                [
                  "`SandboxAudit`",
                  "bool",
                  "`false`",
                  "",
                  "Log restricted operations instead of refusing them. For diagnosis only."
                ],
                [
                  "`SandboxWatchdogSec`",
                  "uint",
                  "`10`",
                  "`0`..`3600` s",
                  "Seconds a Lua or JavaScript script may run without suspending before it is interrupted. `0` turns the watchdog off. Trusted (unsandboxed) resources only get a warning."
                ],
                [
                  "`SandboxFsRead`",
                  "list",
                  "empty",
                  "folders",
                  "Extra folders sandboxed resources may read, absolute or relative to the server. Write paths as they are, without escaping backslashes."
                ],
                [
                  "`SandboxFsWrite`",
                  "list",
                  "empty",
                  "folders",
                  "Extra folders they may read and write. Their own data folder is always allowed."
                ],
                [
                  "`SandboxNetConnect`",
                  "list",
                  "`*`",
                  "rules",
                  "Outgoing connections they may open. `*` allows everything, an empty list nothing. An invalid list allows nothing."
                ],
                [
                  "`SandboxNetListen`",
                  "list",
                  "empty",
                  "`IP:port`, port, CIDR, `unix:/path`, `pipe:name`",
                  "Sockets they may listen on. Empty allows none."
                ],
                [
                  "`SandboxEnv`",
                  "list",
                  "`NODE_ENV, TZ, LANG, LC_ALL`",
                  "names; a trailing `*` matches a prefix",
                  "Environment variables they can see. Empty hides all."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Resource lifecycle and console",
              "level": 2,
              "id": "cfg-lifecycle"
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Type",
                "Default",
                "Range / values",
                "Description"
              ],
              "rows": [
                [
                  "`ResourceStartTimeoutMs`",
                  "uint",
                  "`30000`",
                  "`1000`..`600000` ms",
                  "Longest wait for the top-level `await`s of a starting resource. Past it, the resource is marked `failed`."
                ],
                [
                  "`ResourceStopGraceMs`",
                  "uint",
                  "`2000`",
                  "`0`..`30000` ms",
                  "Time given to the `resourceStop` handlers of a stopping resource."
                ],
                [
                  "`ShutdownGraceMs`",
                  "uint",
                  "`5000`",
                  "`0`..`60000` ms",
                  "Time given to resources at shutdown (`serverStop` handlers, pending MySQL queries) before they are stopped anyway."
                ],
                [
                  "`PreConnectionTimeoutMs`",
                  "uint",
                  "`10000`",
                  "`1000`..`19000` ms",
                  "Deadline of the `playerPreConnection` verdict. A handler that answers later **refuses** the player."
                ],
                [
                  "`ConsoleStdin`",
                  "bool",
                  "`true`",
                  "",
                  "Read [console](#console) commands from the terminal. Set `false` under a service manager that closes the input."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Admin panel",
              "level": 2,
              "id": "cfg-admin"
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Type",
                "Default",
                "Range / values",
                "Description"
              ],
              "rows": [
                [
                  "`AdminLsmpIds`",
                  "list",
                  "empty",
                  "decimal LS:MP IDs",
                  "Who may sign in to `/lsadmin` with **Continue with LS:MP**, besides the server's owner. Read at each sign-in."
                ],
                [
                  "`AdminPublicUrl`",
                  "text",
                  "empty",
                  "`http(s)://` origin",
                  "Address of the panel behind a domain name or a reverse proxy (`https://admin.example.com`). Empty accepts only this server's IP, loopback and private networks."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Old key names and automatic migration",
              "level": 2,
              "id": "cfg-migration"
            },
            {
              "type": "text",
              "md": "Several keys were renamed so that every unit is in the name (`…Ms`, `…Sec`, `…MiB`, `…Meters`, `…Hz`, `…PerSec`). When the server starts with a file that still uses old names, it updates the file **by itself**:"
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "It keeps a copy",
                  "md": "The original file is saved next to it as `server.cfg.bak`."
                },
                {
                  "title": "It rewrites the file",
                  "md": "Each old key line gets its new name and keeps its value. `ClientIdleTimeoutMs` is converted to seconds (rounded up), and `RoutingBucketLockdown` becomes `off` (`0`) or `strict` (`1`, `2`). The comment the server had written above the key is replaced by the new one; your own comments, the other lines and their order stay as they are."
                },
                {
                  "title": "It says so",
                  "md": "One line in the log lists the renamed keys, never their values: `[server.cfg] migrated to the v2 key names (PlayPort -> GamePort, Port -> HttpPort); the previous file is kept as …`. If the file cannot be written, the old values still apply for this start, with an error asking you to rename the keys by hand."
                }
              ]
            },
            {
              "type": "table",
              "headers": [
                "Old key",
                "Key now"
              ],
              "rows": [
                [
                  "`PlayPort`",
                  "`GamePort`"
                ],
                [
                  "`Port`",
                  "`HttpPort`"
                ],
                [
                  "`SemiP2P`, `SemiP2PMaxPeers`, `SemiP2PRange`",
                  "`P2P`, `P2PMaxPeers`, `P2PRangeMeters`"
                ],
                [
                  "`MaxSyncRate`",
                  "`MaxSyncRateHz`"
                ],
                [
                  "`LuaMemoryLimitMb`",
                  "`LuaMemoryLimitMiB`"
                ],
                [
                  "`ScriptHeapLimitMb`",
                  "`JsHeapLimitMiB`"
                ],
                [
                  "`ClientIdleTimeout`, `ClientIdleTimeoutMs`",
                  "`ClientIdleTimeoutSec`"
                ],
                [
                  "`RoutingBucket`, `RoutingBucketPopulation`, `RoutingBucketLockdown`, `DefaultDimensionLockdown`",
                  "`DefaultDimension`, `DefaultDimensionPopulation`, `DefaultDimensionClientEntities`"
                ],
                [
                  "`PickupLifetime`",
                  "`PickupLifetimeSec`"
                ],
                [
                  "`PopulationRange`, `PopulationCreateRate`",
                  "`PopulationRangeMeters`, `PopulationCreateRatePerSec`"
                ],
                [
                  "`SandboxWatchdog`",
                  "`SandboxWatchdogSec`"
                ],
                [
                  "`UnsandboxedResources`",
                  "`\"sandbox\": false` per resource in [`resources.json`](#operator-settings), copied there when that file is first created."
                ]
              ]
            },
            {
              "type": "text",
              "md": "These keys are gone and only produce a warning: `TrustDeclaredIdentity`, `LuaBytecode`, `VoiceEnabled` and `VoiceRange` (voice is set up by scripts, see [Voice](#voice)), `RequiresDiscord`, `RequiresSteam`, `LsmpApiBase`, `LsmpLinkBase`, `LsmpLinkRealm`, `LsmpMarketBase`, `UpdateBaseUrl`."
            }
          ]
        },
        {
          "id": "console",
          "title": "Console and admin panel",
          "eyebrow": "Run a server",
          "lead": "Run the server day to day: the console commands that show and moderate it, and the admin panel that monitors, moderates and reconfigures it from a web browser.",
          "blocks": [
            {
              "type": "heading",
              "text": "The console",
              "level": 2,
              "id": "console-commands"
            },
            {
              "type": "text",
              "md": "You type commands in two places, and both behave the same way:\n\n- the **terminal** the server runs in (turn it off with `ConsoleStdin=false` under a service manager, see [server.cfg](#server-cfg/cfg-lifecycle));\n- the **Console** tab of the admin panel.\n\nA command name is not case-sensitive, and a leading `/` is accepted (`/status` works). A line is at most 512 bytes. The server first looks for a **built-in** command, then for a command registered by a resource with [`lsmp.registerCommand`](#server-commands), and otherwise answers `unknown command: … ('help' lists the commands)`."
            },
            {
              "type": "heading",
              "text": "Built-in commands",
              "level": 3,
              "id": "console-builtin"
            },
            {
              "type": "table",
              "headers": [
                "Command",
                "What it does"
              ],
              "rows": [
                [
                  "`help [command]`",
                  "Lists the built-in commands, or explains one."
                ],
                [
                  "`status`",
                  "Server version, uptime, ports, players connected / maximum, resources counted by state, and the memory of the server process (Lua and JS hosts included)."
                ],
                [
                  "`players`",
                  "Connected players: player ID, name, LS:MP ID (or `guest`), dimension, ping (`-` until measured), time connected."
                ],
                [
                  "`resources`",
                  "Every resource: name, state, origin (`local` folder or marketplace `mod`), sandboxed or not, client mount. Resources start with the server and run until it stops: to apply a change to a resource, restart the server."
                ],
                [
                  "`kick <playerId> [reason…]`",
                  "Kicks a player, with an optional reason shown to them."
                ],
                [
                  "`say <text…>`",
                  "Sends a message to every player. A client resource can handle it with the `serverMessage` event; otherwise LS:MP shows it to the player."
                ],
                [
                  "`quit [reason…]`",
                  "Shuts the server down cleanly: new connections are refused, players leave with the reason `\"shutdown\"` and are disconnected, resources get `ShutdownGraceMs` for their `serverStop` handlers, then stop, and their data is written. A second `quit` during the shutdown is ignored."
                ]
              ]
            },
            {
              "type": "code",
              "lang": "text",
              "title": "server console",
              "code": "> status\nLS:MP server 0.6.254, up 2h 14m\nports: game 9530, http 2086\nplayers: 3/64\nresources: 12 started, 1 failed\nmemory: 412 MiB (server process, Lua and JS hosts included)\n> resources\nchat                              started   local  sandboxed    client auto\nshop                              failed    local  sandboxed    client auto\n2 resource(s)"
            },
            {
              "type": "list",
              "items": [
                "There is no `start`, `stop`, `restart` or `refresh`: resources start with the server and run until it stops. Typed anyway, they print `unknown command: restart (resources start with the server and run until it stops: restart the server to apply a change)`.",
                "A resource cannot register a command with the name of a built-in command: `registerCommand` raises."
              ]
            },
            {
              "type": "heading",
              "text": "Your own commands",
              "level": 3,
              "id": "console-script-commands"
            },
            {
              "type": "text",
              "md": "A command registered by a server script runs from the terminal and the admin panel with every right, whatever permission it requires from players. Players only reach it through [`lsmp.executeCommand`](#server-commands), and only with that permission. See [Console commands](#server-commands)."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- server/main.lua: a console command that lists who is online.\nlsmp.registerCommand(\"who\", { help = \"lists who is online\" }, function(args, raw, source)\n  local names = {}\n  for _, id in ipairs(lsmp.getPlayers()) do\n    names[#names + 1] = lsmp.getPlayerName(id)\n  end\n  lsmp.log(#names .. \" online: \" .. table.concat(names, \", \"))\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// server/main.js: a console command that lists who is online.\nlsmp.registerCommand('who', { help: 'lists who is online' }, () => {\n  const names = lsmp.getPlayers().map((id) => lsmp.getPlayerName(id));\n  lsmp.log(`${names.length} online: ${names.join(', ')}`);\n});"
                }
              ]
            },
            {
              "type": "heading",
              "text": "The admin panel",
              "level": 2,
              "id": "console-panel"
            },
            {
              "type": "text",
              "md": "Every server serves a web admin panel at **`/lsadmin`** on its HTTP port: `http://<server-ip>:2086/lsadmin`. Nothing to install; keep the `uiadmin/` folder that ships with the server next to the program. The root of that port serves what players download, so `/` answers `404`."
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Sign in",
                  "md": "**Continue with LS:MP** signs in the server's owner and the LS:MP IDs listed in `AdminLsmpIds`. A local account uses a user name and a password. On a new server, the panel shows the [setup](#install/install-steps) first."
                },
                {
                  "title": "Work in the tabs",
                  "md": "Monitor, moderate and reconfigure without touching the shell: see the table below."
                },
                {
                  "title": "Restart when the panel asks",
                  "md": "Settings written by the panel apply at the next start. While the files on disk differ from what runs, a banner at the top says so and lists the differences; putting a setting back clears it."
                }
              ]
            },
            {
              "type": "table",
              "headers": [
                "Tab",
                "What it does"
              ],
              "rows": [
                [
                  "**Overview**",
                  "Live CPU, memory and network of the server. The version in the sidebar checks for [updates](#updates)."
                ],
                [
                  "**Players**",
                  "Connected players, with **kick** and **ban** (by LS:MP account, address or machine). The *Bans* list lifts bans; the *Whitelist* card turns the whitelist on and edits it. Changes apply at once."
                ],
                [
                  "**Benefits**",
                  "The [in-game benefits](#benefits) sold for this server, and their deliveries."
                ],
                [
                  "**Network**",
                  "How full the network ID space is, and a list of network entities."
                ],
                [
                  "**Statistics**",
                  "History charts, sampled every minute, from the last hour to two years."
                ],
                [
                  "**P2P Map**",
                  "With `P2P` on: which players exchange their updates directly."
                ],
                [
                  "**Resources**",
                  "Every resource with three switches: **On/Off**, **Auto-mount** (players mount it as they join, or a client script starts it) and **Sandbox**. They write [`resources.json`](#operator-settings) and apply at the next start. **Permissions** opens the [capabilities](#capabilities) of a resource, which apply at once. Also lists the marketplace mods of your account for this server."
                ],
                [
                  "**Console**",
                  "The live log, with severity filters, a *History* mode for earlier sessions, and a command box that runs the [console commands](#console/console-builtin)."
                ],
                [
                  "**Permissions**",
                  "Groups, members, online players, checks and the journal: see [Permissions](#permissions). Every change applies at once."
                ],
                [
                  "**Settings**",
                  "A form for `server.cfg`, grouped in cards, with a search box and a **Raw file** view. A field left empty shows the default. Old key names are read and saved under their new names. The *Game configuration* card uploads a custom `gameconfig.xml` (below)."
                ],
                [
                  "**Administration**",
                  "Who may sign in: `AdminLsmpIds` and the local accounts."
                ],
                [
                  "**Restart / Shutdown**",
                  "Restart the server in place, or stop it cleanly."
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "danger",
              "title": "Secure the panel first",
              "md": "The panel shares the HTTP port with what players download, so that port stays reachable, and it speaks plain HTTP. Use **LS:MP sign-in only**, or a strong password. To use the panel from outside, put it behind a reverse proxy with TLS and set `AdminPublicUrl`. Repeated failed logins lock the address out for a while, longer at each repeat."
            },
            {
              "type": "table",
              "headers": [
                "Problem",
                "Fix"
              ],
              "rows": [
                [
                  "Lost access to the panel",
                  "Stop the server and delete `admin-users.json`: the default `admin` / `admin` account comes back at the next start, and must get a new password before anything else."
                ],
                [
                  "*The server refused the connection* at sign-in",
                  "Too many failed logins from your address: wait, then try again."
                ],
                [
                  "A switch of the **Resources** tab did nothing",
                  "It applies at the next server start: restart the server."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "A custom game configuration",
              "level": 2,
              "id": "console-gameconfig"
            },
            {
              "type": "text",
              "md": "Every player runs the game with the `gameconfig.xml` that ships with LS:MP, which sizes the engine pools (peds, vehicles, objects…). A server that needs other sizes can ship its own: upload it in the *Game configuration* card of **Settings**, or drop it as `resources/gameconfig.xml`. There is one at most."
            },
            {
              "type": "list",
              "items": [
                "**At start**, the server checks the file and announces it to players. A file that fails the check is not used, the console says why, and players keep the LS:MP configuration.",
                "**When a player joins**, LS:MP asks them to restart the game with your file, then joins your server again by itself. The file stays in their cache.",
                "**When they leave**, LS:MP offers to restart with its own configuration.",
                "Replacing or removing the file applies at the next server start."
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "Test it before you ship it",
              "md": "Only the shape of the file is checked: UTF-8 XML, 2 MiB at most, a `<fwAllConfigs>` root. Its values are yours, and a pool raised beyond what the engine can hold closes the game of every player. Start from the `gameconfig.xml` of your LS:MP folder, change one value at a time, and join your own server before you open it."
            }
          ]
        },
        {
          "id": "go-public",
          "title": "Go public (ports, firewall, token)",
          "eyebrow": "Run a server",
          "lead": "Make your server reachable from the Internet and listed in the LS:MP server browser: ports, firewall, router, token and public listing.",
          "blocks": [
            {
              "type": "text",
              "md": "A server needs two ports open to the Internet. Players only ever type the **HTTP** address (`ip:2086`); their game learns the game port from it."
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Default",
                "Protocol",
                "Carries"
              ],
              "rows": [
                [
                  "`HttpPort`",
                  "`2086`",
                  "TCP",
                  "The address players join, resource downloads, the admin panel, your resources' HTTP routes."
                ],
                [
                  "`GamePort`",
                  "`9530`",
                  "**TCP and UDP**",
                  "The game session: movement, events, voice."
                ]
              ]
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Open the firewall",
                  "md": "On the machine itself. A VPS may also have a firewall in its provider's panel: open the same ports there.",
                  "blocks": [
                    {
                      "type": "code",
                      "lang": "bash",
                      "title": "Windows, in an administrator terminal",
                      "code": "netsh advfirewall firewall add rule name=\"LS:MP HTTP\" dir=in action=allow protocol=TCP localport=2086\nnetsh advfirewall firewall add rule name=\"LS:MP game TCP\" dir=in action=allow protocol=TCP localport=9530\nnetsh advfirewall firewall add rule name=\"LS:MP game UDP\" dir=in action=allow protocol=UDP localport=9530"
                    },
                    {
                      "type": "code",
                      "lang": "bash",
                      "title": "Linux, with ufw",
                      "code": "sudo ufw allow 2086/tcp\nsudo ufw allow 9530/tcp\nsudo ufw allow 9530/udp"
                    },
                    {
                      "type": "code",
                      "lang": "bash",
                      "title": "Linux, with firewalld (RHEL, Rocky, Alma, Fedora)",
                      "code": "sudo firewall-cmd --permanent --add-port=2086/tcp --add-port=9530/tcp --add-port=9530/udp\nsudo firewall-cmd --reload"
                    }
                  ]
                },
                {
                  "title": "Forward the ports (home connection)",
                  "md": "Behind a home router, forward `2086` TCP and `9530` TCP **and** UDP to this machine's local address. If the address players should use is not the one the server sees (NAT, reverse proxy), set `PublicAddress=<public-ip>:2086` in `server.cfg`."
                },
                {
                  "title": "Link the server to your LS:MP account",
                  "md": "If you skipped this step of the [setup page](#install/install-steps), add a server in [My Servers](https://lsmp.gg/account#servers) and copy its token into **Settings** of the admin panel, or as `Token=` in `server.cfg`, then restart. The token identifies your server on the LS:MP network: keep it secret, never commit it to a repository."
                },
                {
                  "title": "Turn the listing on",
                  "md": "Switch **Public listing** on in **Settings**: on a linked, running server it applies at once. Setting `PublicList=true` by hand applies at the next start. Without it, the server runs fine and players reach it by address."
                },
                {
                  "title": "Check from outside",
                  "md": "Join by address from another network (a phone's connection works), then look for your server in the browser. In [My Servers](https://lsmp.gg/account#servers), set its icon, banner and loading cover."
                }
              ]
            },
            {
              "type": "heading",
              "text": "When players cannot join",
              "level": 2,
              "id": "go-public-problems"
            },
            {
              "type": "table",
              "headers": [
                "Symptom",
                "Cause and fix"
              ],
              "rows": [
                [
                  "Nobody can reach the server",
                  "`HttpPort` is closed from outside, or players use the game port. Test `http://<public-ip>:2086/lsadmin` from another network."
                ],
                [
                  "Players connect, then nothing moves",
                  "`GamePort` is open in TCP but not in UDP."
                ],
                [
                  "Friends on the Internet are refused, players on the LAN are fine",
                  "Behind NAT the server does not know its public address: set `PublicAddress`."
                ],
                [
                  "The server is not in the browser",
                  "`PublicList=true` needs a valid `Token` the server started with. Look for `Token` or listing errors in the log."
                ],
                [
                  "`MaxPlayers` is lower than set",
                  "It is capped by the plan of the server's owner."
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Before you open the doors",
              "md": "Give yourself the admin rights ([Permissions](#permissions)), secure the [admin panel](#console/console-panel), and check [`RequireAdmission`](#server-cfg/cfg-protection) is on: it is the default."
            }
          ]
        },
        {
          "id": "updates",
          "title": "Updates",
          "eyebrow": "Run a server",
          "lead": "How the server updates itself, what it never touches, and how it comes back to the previous version when a new one does not start.",
          "blocks": [
            {
              "type": "steps",
              "items": [
                {
                  "title": "It checks",
                  "md": "The server looks for a new version about once an hour, when you open the admin panel, and when you click the version in the panel's sidebar. It follows the release channel set by `UpdateChannel` (`stable`)."
                },
                {
                  "title": "It prepares",
                  "md": "A new version is downloaded and verified in the background, then tried on this machine. A version that cannot run here is never installed, and nothing changes."
                },
                {
                  "title": "It installs",
                  "md": "With `AutoUpdate=true` (the default), the server installs the prepared version once **no player has been connected for 5 minutes**. Otherwise, click the version in the panel's sidebar. New players are refused during the swap, then the server restarts in place: on Linux it keeps its process ID, so systemd, Docker or screen keep following it."
                },
                {
                  "title": "It checks itself",
                  "md": "The new version must run for 60 seconds after opening its ports. If it crashes in that window, or fails to start three times, the previous version is put back and started, and that build is never installed automatically again."
                }
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Never touched by an update",
              "md": "`server.cfg`, `resources.json`, the panel accounts, bans, permissions, your resources, their data and key/value stores, and the logs. An update replaces only the files of the server release."
            },
            {
              "type": "heading",
              "text": "Choose when it happens",
              "level": 2,
              "id": "updates-control"
            },
            {
              "type": "table",
              "headers": [
                "You want",
                "Do this"
              ],
              "rows": [
                [
                  "Updates whenever the server is empty",
                  "Nothing: `AutoUpdate=true` is the default."
                ],
                [
                  "To pick the moment yourself",
                  "Set `AutoUpdate=false` (in **Settings** it applies at once), then click the version in the panel's sidebar when you are ready."
                ],
                [
                  "A test channel LS:MP gave you",
                  "Set `UpdateChannel` to its name, and restart."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "After an update",
              "level": 2,
              "id": "updates-after"
            },
            {
              "type": "list",
              "items": [
                "The first start of a new version may rebuild the packages of your resources: players download what changed.",
                "Players need an up-to-date LS:MP client: it updates itself when they start it.",
                "Read the log of the first start. A key of `server.cfg` that changed name is [migrated by itself](#server-cfg/cfg-migration); anything the server cannot use is reported with its line."
              ]
            }
          ]
        }
      ]
    },
    {
      "id": "resources",
      "title": "Build resources",
      "icon": "📦",
      "pages": [
        {
          "id": "resource-layout",
          "title": "Resource layout and manifest",
          "eyebrow": "Build resources",
          "lead": "What a resource folder holds, how it is named, and every key of its manifest.json: scripts, files, web pages, game data, asset sets and dependencies.",
          "blocks": [
            {
              "type": "text",
              "md": "A **resource** is a folder in the server's `resources/` with a `manifest.json` that says which file runs where. The same folder works on a server, as a [local resource](#local-resources) in Story mode, and as a [marketplace mod](#publish-mod)."
            },
            {
              "type": "heading",
              "text": "A typical resource",
              "level": 2,
              "id": "layout-tree"
            },
            {
              "type": "tree",
              "tree": "resources/\n└─ shop/                    # the folder name is the resource's name\n   ├─ manifest.json         # what runs where (below)\n   ├─ shared/\n   │  └─ config.lua         # shared_scripts: runs on both sides, first\n   ├─ server/\n   │  └─ main.lua           # server_scripts: never sent to players\n   ├─ client/\n   │  └─ main.lua           # client_scripts: sent to players, runs in their game\n   ├─ web/                  # webui: served to your pages at rsc://shop/\n   │  ├─ index.html\n   │  └─ app.js\n   ├─ data/\n   │  └─ items.json         # files: sent to players, read by scripts\n   └─ stream/               # game assets (.ydr, .ytd, .ymap…), always streamed\n      └─ shop_counter.ydr",
              "only": "lua"
            },
            {
              "type": "tree",
              "tree": "resources/\n└─ shop/                    # the folder name is the resource's name\n   ├─ manifest.json         # what runs where (below)\n   ├─ shared/\n   │  └─ config.js          # shared_scripts: runs on both sides, first\n   ├─ server/\n   │  └─ main.js            # server_scripts: never sent to players\n   ├─ client/\n   │  └─ main.js            # client_scripts: sent to players, runs in their game\n   ├─ web/                  # webui: served to your pages at rsc://shop/\n   │  ├─ index.html\n   │  └─ app.js\n   ├─ data/\n   │  └─ items.json         # files: sent to players, read by scripts\n   └─ stream/               # game assets (.ydr, .ytd, .ymap…), always streamed\n      └─ shop_counter.ydr",
              "only": "js"
            },
            {
              "type": "code",
              "lang": "json",
              "title": "manifest.json",
              "code": "{\n  \"title\": \"Shop\",\n  \"description\": \"A counter where players buy items.\",\n  \"author\": \"Jane\",\n  \"version\": \"1.2.0\",\n  \"shared_scripts\": \"shared/config.lua\",\n  \"server_scripts\": \"server/*.lua\",\n  \"client_scripts\": [\"client/main.lua\"],\n  \"files\": \"data/*.json\",\n  \"webui\": \"web\",\n  \"dependencies\": \"bank\"\n}",
              "only": "lua"
            },
            {
              "type": "code",
              "lang": "json",
              "title": "manifest.json",
              "code": "{\n  \"title\": \"Shop\",\n  \"description\": \"A counter where players buy items.\",\n  \"author\": \"Jane\",\n  \"version\": \"1.2.0\",\n  \"shared_scripts\": \"shared/config.js\",\n  \"server_scripts\": \"server/*.js\",\n  \"client_scripts\": [\"client/main.js\"],\n  \"files\": \"data/*.json\",\n  \"webui\": \"web\",\n  \"dependencies\": \"bank\"\n}",
              "only": "js"
            },
            {
              "type": "text",
              "md": "Folder names such as `server/` or `web/` are conventions: only the manifest decides. Every list accepts a single string or an array of strings."
            },
            {
              "type": "heading",
              "text": "The name of a resource",
              "level": 2,
              "id": "layout-name"
            },
            {
              "type": "text",
              "md": "The **folder name is the resource's name**, and its only identity: for `lsmp.getResourceName()`, dependencies, `rsc://shop/` pages, `/res/shop/` HTTP routes, the `[shop]` prefix of its log lines, the `resources` console command, and the storage that belongs to it ([data folder, storage](#data-guide), [capabilities](#capabilities))."
            },
            {
              "type": "list",
              "items": [
                "**1 to 64 characters**: lowercase letters `a-z`, digits, `_` and `-`, starting with a letter or a digit.",
                "`lsmp`, and names starting with `lsmp-` or `lsmp_`, are reserved.",
                "A folder with another name is **not loaded**, and the log gives the name to use: `resource folder 'MyShop' is not a valid name (…): use 'myshop'`.",
                "`title` in the manifest is only a display name (admin panel, marketplace). Renaming the folder changes the identity, and with it the storage the resource finds."
              ]
            },
            {
              "type": "heading",
              "text": "Manifest keys",
              "level": 2,
              "id": "layout-keys"
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Type",
                "Default",
                "What it does"
              ],
              "rows": [
                [
                  "`title`",
                  "string",
                  "the resource name",
                  "Display name, up to 64 characters. Never an identity."
                ],
                [
                  "`description`",
                  "string",
                  "`\"\"`",
                  "Display only, up to 1024 characters."
                ],
                [
                  "`author`",
                  "string",
                  "`\"\"`",
                  "Display only, up to 128 characters."
                ],
                [
                  "`version`",
                  "string",
                  "`\"\"`",
                  "Display only, up to 64 characters. Marketplace versions are managed by lsmp.gg."
                ],
                [
                  "`shared_scripts`",
                  "string \\| string[]",
                  "`[]`",
                  "Scripts run on **both** sides, before the side-specific ones."
                ],
                [
                  "`server_scripts`",
                  "string \\| string[]",
                  "`[]`",
                  "Scripts run on the server: `.lua`, `.js`, `.mjs`, `.cjs`. Never sent to players."
                ],
                [
                  "`client_scripts`",
                  "string \\| string[]",
                  "`[]`",
                  "Scripts run in each player's game: `.lua` or `.js`, in this order."
                ],
                [
                  "`files`",
                  "string \\| string[]",
                  "`[]`",
                  "Extra files sent to players, not run: data read with [`lsmp.readResourceFile`](#core-utils), modules loaded with `require`."
                ],
                [
                  "`webui`",
                  "string \\| string[]",
                  "`[]`",
                  "Folders served to the resource's pages at `rsc://<name>/` ([below](#resource-layout/layout-webui))."
                ],
                [
                  "`dependencies`",
                  "string \\| string[]",
                  "`[]`",
                  "Resources that must be started first, on both sides."
                ],
                [
                  "`server_dependencies`",
                  "string \\| string[]",
                  "`[]`",
                  "Same, on the server only."
                ],
                [
                  "`client_dependencies`",
                  "string \\| string[]",
                  "`[]`",
                  "Same, in the player's game only."
                ],
                [
                  "`data_files`",
                  "array",
                  "`[]`",
                  "Game data files mounted in the player's game with the resource: `\"data/vehicles.meta\"`, or `{ \"path\", \"type\", \"set\", \"language\" }` ([below](#resource-layout/layout-data-files))."
                ],
                [
                  "`stream_sets`",
                  "array",
                  "`[]`",
                  "Parts of `stream/` that scripts load and unload in game: `{ \"name\", \"folder\", \"load\" }` ([below](#resource-layout/layout-stream-sets))."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Paths and patterns",
              "level": 3,
              "id": "layout-globs"
            },
            {
              "type": "list",
              "items": [
                "Paths are relative to the resource folder, with `/`. A path that leads outside the folder (absolute, `..`) is refused, and so is a link whose target is outside it.",
                "Patterns: `*` matches within one folder level, `**` any depth, `?` one character. `\"client/*.lua\"`, `\"web/**\"`.",
                "`node_modules`, `.git`, `.svn` and `.hg` folders are never sent to players. The server keeps the `node_modules` at the root and under `server/`."
              ]
            },
            {
              "type": "heading",
              "text": "Scripts and their order",
              "level": 2,
              "id": "layout-scripts"
            },
            {
              "type": "list",
              "items": [
                "On each side, `shared_scripts` run first, then the side's own scripts, each list in manifest order.",
                "A resource starts once its [dependencies](#resource-layout/layout-dependencies) on that side are started. It is `started` when every file has run to its end, or to its first wait (`lsmp.wait`, a pending call). A file that raises makes the whole resource `failed`.",
                "On the server, a resource may mix `.lua` and `.js` files. They run in **two separate script environments** (no shared globals) of **one** resource: same name, same state, same storage. JavaScript files run before Lua files. The two halves talk with [`lsmp.emit`](#events) and [`lsmp.call`](#rpc).",
                "Client scripts can be `.lua` or `.js` too, in one resource. Choosing one language per side keeps things simple: see [Runtimes](#runtimes)."
              ]
            },
            {
              "type": "heading",
              "text": "Web pages (webui)",
              "level": 2,
              "id": "layout-webui"
            },
            {
              "type": "text",
              "md": "Each `webui` folder is served at the root of `rsc://<resource name>/`: with `\"webui\": \"web\"`, the file `web/index.html` is `rsc://shop/index.html`, and `web/js/app.js` is `rsc://shop/js/app.js`. Open the page with [`lsmp.createBrowser`](#browsers). Put the **built** output of a web project here (`dist/`), not its sources. See [Web interfaces](#web-ui)."
            },
            {
              "type": "heading",
              "text": "Game data files",
              "level": 2,
              "id": "layout-data-files"
            },
            {
              "type": "text",
              "md": "`data_files` mounts game metadata in the player's game, the way the game mounts a DLC. A bare path works for the usual file names, whose type is known: `vehicles.meta`, `handling.meta`, `carvariations.meta`, `carcols.meta`, `vehiclelayouts.meta`, `weapons.meta`, `peds.meta`, `water.xml`, `dlctext.meta` and more. Give the `type` for any other name."
            },
            {
              "type": "code",
              "lang": "json",
              "title": "manifest.json",
              "code": "{\n  \"title\": \"Sports car pack\",\n  \"data_files\": [\n    \"data/vehicles.meta\",\n    \"data/handling.meta\",\n    { \"path\": \"data/my_cars_colors.meta\", \"type\": \"CARCOLS_FILE\" },\n    { \"path\": \"lang/french.gxt2\", \"language\": \"french\" },\n    { \"path\": \"data/island_water.xml\", \"set\": \"island\" }\n  ]\n}"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Meaning"
              ],
              "rows": [
                [
                  "`path`",
                  "The file, relative to the resource. Required."
                ],
                [
                  "`type`",
                  "The game's data file type (`VEHICLE_METADATA_FILE`, `CARCOLS_FILE`…). Deduced from the file name when absent."
                ],
                [
                  "`set`",
                  "Name of a stream set: the file is mounted and unmounted with that set instead of the resource."
                ],
                [
                  "`language`",
                  "For a text file (`.gxt2`): the game language it is for (`american`, `french`…). Only the one matching the player's language is mounted."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Stream sets",
              "level": 2,
              "id": "layout-stream-sets"
            },
            {
              "type": "text",
              "md": "Everything in `stream/` is streamed while the resource is mounted. A **stream set** cuts a sub-folder of `stream/` out of that block, so that a client script loads and unloads it in game: an interior, a seasonal map. Files in no set are always streamed. How to load them: [Assets and streaming](#streaming)."
            },
            {
              "type": "code",
              "lang": "json",
              "title": "manifest.json",
              "code": "{\n  \"title\": \"My island\",\n  \"client_scripts\": \"client/main.lua\",\n  \"stream_sets\": [\n    { \"name\": \"club\", \"folder\": \"stream/night_club\", \"load\": \"manual\" },\n    { \"name\": \"winter\", \"folder\": \"stream/winter\" }\n  ]\n}"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Meaning"
              ],
              "rows": [
                [
                  "`name`",
                  "string",
                  "required",
                  "The set's name for scripts: 1 to 64 characters among `a`-`z`, `0`-`9`, `_` and `-`, unique in the resource."
                ],
                [
                  "`folder`",
                  "string",
                  "required",
                  "Folder relative to the resource root, like every path of the manifest, and **inside `stream/`**: `\"stream/night_club\"`; `\"stream\"` is the whole `stream/`."
                ],
                [
                  "`load`",
                  "string",
                  "`\"auto\"`",
                  "`\"auto\"`: loaded with the resource. `\"manual\"`: loaded only when a script asks ([`loadStreamSet`](#client-resources/fn-resources-load-stream-set))."
                ]
              ]
            },
            {
              "type": "list",
              "items": [
                "Nested sets: a file belongs to the set of its **closest** folder. Declaring `stream/map` and `stream/map/night` cuts `night` out of `map`.",
                "A resource holds at most 256 sets. A name declared twice keeps the first."
              ]
            },
            {
              "type": "heading",
              "text": "Dependencies",
              "level": 2,
              "id": "layout-dependencies"
            },
            {
              "type": "list",
              "items": [
                "By exact resource name. `dependencies` apply to both sides; `server_dependencies` and `client_dependencies` to one side only, so the player's game never waits for a server-only resource.",
                "A dependency that is **missing**, **disabled** in [`resources.json`](#operator-settings) or **failed** keeps the resource from starting: it is `failed`, with a message such as `dependency 'db' of 'bank' is missing (did you mean 'mysql-db'?)`.",
                "A **cycle** fails every resource in it, and the log prints the cycle.",
                "Stopping a resource stops the resources that depend on it first.",
                "The server's operator can add load-order constraints of their own with `after` in `resources.json`."
              ]
            },
            {
              "type": "heading",
              "text": "Mistakes and warnings",
              "level": 2,
              "id": "layout-errors"
            },
            {
              "type": "table",
              "headers": [
                "In manifest.json",
                "What happens"
              ],
              "rows": [
                [
                  "Invalid JSON",
                  "The resource does not start: `resource 'shop': manifest.json is not valid JSON (line 7, column 3), not loaded`."
                ],
                [
                  "Unknown key",
                  "Warning, key ignored: `'client_script' is not a manifest key, ignored (did you mean 'client_scripts'?)`."
                ],
                [
                  "Key of the wrong type",
                  "Warning, key ignored: `'dependencies' must be a string or an array of strings, ignored`."
                ],
                [
                  "Key that no longer exists",
                  "Warning, key ignored, with what to use (table below)."
                ],
                [
                  "No `manifest.json`",
                  "Only `stream/` is used (a pure asset resource, such as a map). A `client/`, `server/` or `shared/` folder is ignored, with a warning."
                ],
                [
                  "A file larger than 16 MiB, or nested too deeply",
                  "The resource does not start."
                ]
              ]
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Use instead"
              ],
              "rows": [
                [
                  "`name`",
                  "Nothing: the identity is the folder name. Use `title` for a display name."
                ],
                [
                  "`enabled`",
                  "`\"enabled\"` in the server's [`resources.json`](#operator-settings)."
                ],
                [
                  "`client_script`, `server_script`, `shared_script`",
                  "`client_scripts`, `server_scripts`, `shared_scripts`."
                ],
                [
                  "`dependency`",
                  "`dependencies` (a string is accepted)."
                ],
                [
                  "`scripts`",
                  "List scripts in `client_scripts`, `server_scripts` or `shared_scripts`."
                ],
                [
                  "`webui_dirs`, `webui_domain`",
                  "`webui`. Pages are always served at `rsc://<resource name>/`."
                ],
                [
                  "`files_mount`",
                  "`data_files`."
                ],
                [
                  "`stream-sets`",
                  "`stream_sets`."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "What players receive",
              "level": 2,
              "id": "layout-packages"
            },
            {
              "type": "text",
              "md": "At start, the server packs each resource twice:\n\n- the **client package**, downloaded by players: `shared_scripts`, `client_scripts`, `files`, `webui` folders, `data_files` and `stream/`, nothing else. Lua scripts are checked: one with a syntax error stops the package, with the file and the line in the log.\n- the **server package**, for the server only: the folder without `stream/`, the `webui` folders and the client-only data.\n\n`server_scripts` are never sent to players. Anything a player must not read (keys, passwords) belongs on the server side ([Storing data](#data-guide)), never in `files`, `webui` or client scripts."
            }
          ]
        },
        {
          "id": "operator-settings",
          "title": "Operator settings (`resources.json`)",
          "eyebrow": "Build resources",
          "lead": "One file, next to server.cfg, for everything the server's operator decides about each resource: whether it runs, whether it is sandboxed, how players mount it, and extra load order.",
          "blocks": [
            {
              "type": "text",
              "md": "A resource's `manifest.json` belongs to its **author**. What the **operator** of a server decides lives in `resources.json`, at the root of the server folder, never inside a resource folder: updating a resource never overwrites your choices. The **Resources** tab of the admin panel writes this file; you can also edit it by hand."
            },
            {
              "type": "code",
              "lang": "json",
              "title": "resources.json",
              "code": "{\n  \"resources\": {\n    \"bank\": { \"enabled\": true, \"sandbox\": false, \"clientMount\": \"auto\" },\n    \"admin-tools\": { \"clientMount\": \"manual\" },\n    \"old-hud\": { \"enabled\": false },\n    \"shop\": { \"after\": [\"bank\"] },\n    \"mod.las-venturas\": { \"enabled\": true }\n  }\n}"
            },
            {
              "type": "list",
              "items": [
                "Each entry is keyed by the resource name. A **marketplace mod** is keyed `mod.<name>`, so that a mod and a local folder of the same name never share settings.",
                "A resource that is not in the file uses every default. Write only what you change.",
                "The file is created at the first start, with the resources whose settings differ from the defaults."
              ]
            },
            {
              "type": "heading",
              "text": "Fields",
              "level": 2,
              "id": "operator-fields"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Meaning"
              ],
              "rows": [
                [
                  "`enabled`",
                  "boolean",
                  "`true`",
                  "`false`: the resource is not packed, not started, and not sent to players."
                ],
                [
                  "`sandbox`",
                  "boolean",
                  "`true`",
                  "`false` trusts the resource: its server scripts get full machine access and [`lsmp.mysql`](#server-mysql). Only for code you trust. See [Capabilities and sandbox](#capabilities)."
                ],
                [
                  "`clientMount`",
                  "string",
                  "`\"auto\"`",
                  "`\"auto\"`: players mount it as they join. `\"manual\"`: players download it, and a client script mounts it with [`lsmp.mountResource`](#client-resources/fn-mount-resource). `\"never\"`: it is not sent to players at all (its server part still runs)."
                ],
                [
                  "`after`",
                  "string[]",
                  "`[]`",
                  "Resources to start before this one, on top of its own dependencies. A soft rule: a name that does not exist only gives a warning."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "When changes apply",
              "level": 2,
              "id": "operator-apply"
            },
            {
              "type": "table",
              "headers": [
                "You change",
                "It applies"
              ],
              "rows": [
                [
                  "Any field, from the admin panel",
                  "At the next server start. The panel shows a banner until then."
                ],
                [
                  "The file, by hand",
                  "At the next server start: resources and their settings are read once, when the server starts."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Mistakes",
              "level": 2,
              "id": "operator-errors"
            },
            {
              "type": "table",
              "headers": [
                "Problem",
                "What happens"
              ],
              "rows": [
                [
                  "Unknown field",
                  "`resources.json: 'shop': unknown setting \"autoMount\", ignored`."
                ],
                [
                  "Wrong type",
                  "`resources.json: 'shop': \"enabled\" must be true or false, default kept`."
                ],
                [
                  "Invalid `clientMount`",
                  "`… \"clientMount\" must be \"auto\", \"manual\" or \"never\", default kept`."
                ],
                [
                  "The file is not valid JSON",
                  "Every resource uses the defaults, and the file is left as it is so that you can fix it."
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "What is not here",
              "md": "Server-wide settings live in [`server.cfg`](#server-cfg). What each resource may do (capabilities) is granted in the **Permissions** of its row in the admin panel: see [Capabilities and sandbox](#capabilities)."
            }
          ]
        },
        {
          "id": "runtimes",
          "title": "Lua and JavaScript runtimes (timers, threads, modules, npm, sandbox)",
          "eyebrow": "Build resources",
          "lead": "What the Lua and JavaScript engines provide on the server and on the client: isolation, threads, timers, modules and npm, budgets.",
          "blocks": [
            {
              "type": "text",
              "md": "A resource is written in Lua, in JavaScript, or in both. Both languages see the same `lsmp` API with the same names, arguments and results; the few deliberate differences are listed in [Conventions](#conventions/lua-js)."
            },
            {
              "type": "table",
              "headers": [
                "",
                "Lua",
                "JavaScript"
              ],
              "rows": [
                [
                  "Server",
                  "Lua 5.5",
                  "Node.js 24: CommonJS and ES modules, Node core modules, npm packages"
                ],
                [
                  "Client",
                  "Lua 5.5",
                  "V8, without Node: plain scripts, no Node modules"
                ],
                [
                  "Isolation",
                  "one Lua state per resource",
                  "one context per resource"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "One resource, its own world",
              "level": 2,
              "id": "isolation"
            },
            {
              "type": "list",
              "items": [
                "Each resource has its own globals: a resource that overwrites a global, or even `lsmp.emit`, only breaks itself.",
                "Resources talk through [events](#events), [remote calls](#rpc) and [meta](#meta). Values are copied between resources, never shared.",
                "Everything a resource registered (handlers, timers, commands, threads, browsers, pools...) is cleaned up when it stops. See [Isolation and restore](#conventions/isolation).",
                "Errors are contained: an error in a handler, a timer or a thread is logged with the resource name and file position, and the rest of the resource keeps running."
              ]
            },
            {
              "type": "heading",
              "text": "Mixed Lua and JavaScript resources",
              "level": 2,
              "id": "mixed"
            },
            {
              "type": "text",
              "md": "A server resource may list both `.lua` and `.js` scripts in its [manifest](#resource-layout). They form **one** resource (same name, same state, same storage, same data folder) running in **two** engines with separate globals. The JavaScript scripts start first. The two halves talk with `lsmp.emit` (delivered to the other engine a moment later) and `lsmp.call` (a local call)."
            },
            {
              "type": "heading",
              "text": "Lua",
              "level": 2,
              "id": "lua"
            },
            {
              "type": "list",
              "items": [
                "Lua 5.5, with 64-bit integers: `math.type(x)` tells `\"integer\"` from `\"float\"`, and the API keeps them apart (`3` and `3.0` are different values). Use `//` for integer division.",
                "`Vector3` is a built-in value type of the engine, with fields `.x`, `.y` and `.z` (32-bit floats). Functions accept a plain `{x, y, z}` table as well.",
                "`print` is `lsmp.log`.",
                "The standard library functions that reach outside the resource (`io`, `os.execute`, `load`, `debug`...) raise an error that names the `lsmp` alternative (`lsmp.fs`, `lsmp.readResourceFile`). `debug.traceback` works."
              ]
            },
            {
              "type": "heading",
              "text": "Threads and waiting",
              "level": 3,
              "id": "lua-threads"
            },
            {
              "type": "text",
              "md": "Lua code waits with coroutines. The host runs the body of each script file, every event and RPC handler, and every [`lsmp.createThread`](#core-utils/fn-create-thread) function in a **host coroutine**: inside, [`lsmp.wait`](#core-utils/fn-wait) and asynchronous functions without a callback suspend only that coroutine. A coroutine you create yourself with `coroutine.create` is not a host coroutine."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "lsmp.createThread(function()\n  while true do\n    local count = #lsmp.getPlayers()\n    lsmp.setGlobalMeta(\"online\", count)\n    lsmp.wait(5000)\n  end\nend)"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Modules",
              "level": 3,
              "id": "lua-modules"
            },
            {
              "type": "text",
              "md": "On the server, `require(name)` loads another Lua file of the same resource, from its package: `require(\"lib.util\")` loads `lib/util.lua`, or `lib/util/init.lua`. Like standard Lua, a module runs once per resource and its return value is cached (`true` when it returns nothing). Names use letters, digits, `_`, `-` and `.`; there are no native (C) modules."
            },
            {
              "type": "code",
              "lang": "lua",
              "code": "local M = {}\nfunction M.format(n) return (\"$%d\"):format(n) end\nreturn M",
              "title": "lib/money.lua"
            },
            {
              "type": "code",
              "lang": "lua",
              "code": "local money = require(\"lib.money\")\nlsmp.log(money.format(1500))",
              "title": "server/main.lua"
            },
            {
              "type": "heading",
              "text": "JavaScript",
              "level": 2,
              "id": "js"
            },
            {
              "type": "list",
              "items": [
                "`console.log`, `info`, `warn`, `error` and `debug` go to the resource's log (see [Logging](#core-utils/logging)).",
                "Asynchronous `lsmp` functions return Promises: use `async`/`await`. An `async` function is the JavaScript equivalent of a Lua thread.",
                "Timers are the standard `setTimeout`/`setInterval`/`clearTimeout`/`clearInterval`. On the server they are Node timers (`Timeout` objects); on the client their ids are integers.",
                "An uncaught exception or an unhandled Promise rejection is logged; it never stops the resource or the server.",
                "Integers beyond 2^53 travel as `BigInt`."
              ]
            },
            {
              "type": "heading",
              "text": "Server: Node.js modules and npm",
              "level": 3,
              "id": "js-node"
            },
            {
              "type": "list",
              "items": [
                "Each resource has its own module system, rooted in its package. CommonJS (`require`) and ES modules (`import`, `.mjs`, or `\"type\": \"module\"` in a `package.json`) both work, with Node's rules.",
                "`require` and `import` look in the resource first, including a `node_modules` folder shipped inside the resource; then in Node's core modules and in npm packages installed next to the server.",
                "`__filename` and `__dirname` are paths inside the resource (`/<resource>/server/main.js`), not disk paths: read your own files with `lsmp.readResourceFile`, and write files in [`lsmp.getDataPath()`](#server-files/fn-get-data-path).",
                "The process belongs to the server: `process.exit()` and `process.abort()` raise. In the [sandbox](#capabilities/sandbox), child processes, native addons and internal bindings are refused, and `os.tmpdir()` is inside the resource's data folder.",
                "An ES module may use top-level `await`: the resource reaches `\"started\"` when it settles (at most `ResourceStartTimeoutMs`)."
              ]
            },
            {
              "type": "code",
              "lang": "js",
              "code": "// server/main.mjs\nimport { createHash } from \"node:crypto\";\n\nconst digest = createHash(\"sha256\").update(\"hello\").digest(\"hex\");\nlsmp.log(digest);\n\nconst config = JSON.parse(lsmp.readResourceFile(\"config.json\"));\nlsmp.log(`loaded ${Object.keys(config).length} settings`);"
            },
            {
              "type": "heading",
              "text": "Client",
              "level": 3,
              "id": "js-client"
            },
            {
              "type": "text",
              "md": "Client JavaScript runs on V8 without Node: there is no Node core module and no npm. `require` loads the files of the same resource as CommonJS modules: `./` is relative to the calling file, a bare name starts at the resource root, `.js`, `.json` and `folder/index.js` are tried, and each module runs once (cached; cycles work). A required file must reach the client: list it in the manifest's `client_scripts`, `shared_scripts` or `files`. ES modules (`import`) are server only. Each client resource has a memory budget of 256 MiB. Use the `lsmp` API and the [game natives](#natives)."
            },
            {
              "type": "heading",
              "text": "Budgets",
              "level": 2,
              "id": "budgets"
            },
            {
              "type": "list",
              "items": [
                "**Time**: a script must not block. On the server, Lua or JavaScript that runs longer than `SandboxWatchdogSec` (default 10 s) without suspending is interrupted in the sandbox (`script interrupted: time budget exceeded`); outside the sandbox it is only logged. On the client, one run is interrupted after 250 ms, and each resource gets 100 ms of script time per frame in total: a resource that keeps going over is stopped (see [Limits](#limits/time-memory)). Split long work with `lsmp.wait`/`await lsmp.wait(0)`.",
                "**Memory**: each server Lua resource has a quota (`LuaMemoryLimitMiB`, default 256 MiB); server JavaScript resources share the heap set by `JsHeapLimitMiB`.",
                "Budgets are counted per resource: a resource is never cut for the time or memory another resource used. See [Limits and quotas](#limits/time-memory)."
              ]
            }
          ]
        },
        {
          "id": "events-guide",
          "title": "Events and RPC (guide)",
          "eyebrow": "Build resources",
          "lead": "Patterns for talking between the server, the clients and your resources, and the mistakes to avoid.",
          "blocks": [
            {
              "type": "text",
              "md": "This guide shows how the server, the clients and your resources talk to each other. The reference pages are [Events](#events), [Remote calls](#rpc) and [Engine events](#engine-events)."
            },
            {
              "type": "heading",
              "text": "Choosing a tool",
              "level": 2,
              "id": "choosing"
            },
            {
              "type": "table",
              "headers": [
                "Need",
                "Tool",
                "Why"
              ],
              "rows": [
                [
                  "React to the game or the server",
                  "`lsmp.on(\"playerJoin\", ...)`",
                  "Engine events, same names on both sides."
                ],
                [
                  "Fire and forget, one side",
                  "`lsmp.emit` / `lsmp.on`",
                  "Synchronous for handlers in the same language, cheap."
                ],
                [
                  "Fire and forget, across the network",
                  "`lsmp.emitServer` → `lsmp.onClient`, `lsmp.emitClient` → `lsmp.onServer`",
                  "Ordered, no answer."
                ],
                [
                  "Ask and wait for an answer",
                  "`lsmp.callServer`, `lsmp.callClient`, `lsmp.call` → `lsmp.onCall`",
                  "One result or one error code, with a deadline."
                ],
                [
                  "Share a state everyone reads",
                  "[Meta](#meta)",
                  "Replicated, late joiners see it, `metaChange` notifies."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "A request from a client",
              "level": 2,
              "id": "client-request"
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "The client sends",
                  "md": "The client sends what the player asked for, nothing more. It never decides prices, damage or rights.",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "-- client\nlsmp.emitServer(\"shop:buy\", \"pistol\")"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "// client\nlsmp.emitServer(\"shop:buy\", \"pistol\");"
                    }
                  ]
                },
                {
                  "title": "The server checks everything",
                  "md": "On the server, the first argument of an `onClient` handler is the sending player: it cannot be forged. Every other argument comes from the client and must be checked.",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "-- server\nlocal PRICES = { pistol = 500, smg = 2500 }\n\nlsmp.onClient(\"shop:buy\", function(source, item)\n  local price = type(item) == \"string\" and PRICES[item]\n  if not price then return end\n  local money = lsmp.getPlayerMeta(source, \"money\") or 0\n  if money < price then\n    return lsmp.emitClient(source, \"shop:result\", false, \"not enough money\")\n  end\n  lsmp.setPlayerMeta(source, \"money\", money - price)\n  lsmp.emitClient(source, \"shop:result\", true, item)\nend)"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "// server\nconst PRICES = { pistol: 500, smg: 2500 };\n\nlsmp.onClient(\"shop:buy\", (source, item) => {\n  const price = typeof item === \"string\" ? PRICES[item] : undefined;\n  if (price === undefined) return;\n  const money = lsmp.getPlayerMeta(source, \"money\") ?? 0;\n  if (money < price) return lsmp.emitClient(source, \"shop:result\", false, \"not enough money\");\n  lsmp.setPlayerMeta(source, \"money\", money - price);\n  lsmp.emitClient(source, \"shop:result\", true, item);\n});"
                    }
                  ]
                },
                {
                  "title": "Or use a remote call",
                  "md": "When the client needs the answer, a remote call is simpler than two events: the result comes back to the caller, with a deadline and an error code when something goes wrong.",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "-- server\nlsmp.onCall(\"shop:buy\", function(source, item)\n  local price = type(item) == \"string\" and PRICES[item]\n  if not price then return { ok = false, reason = \"unknown item\" } end\n  -- ... same checks as above ...\n  return { ok = true }\nend)\n\n-- client, in an event handler or a thread\nlocal res, err = lsmp.callServer(\"shop:buy\", \"pistol\")\nif not res then lsmp.warn(\"shop unavailable: \" .. err) end"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "// server\nlsmp.onCall(\"shop:buy\", (source, item) => {\n  const price = typeof item === \"string\" ? PRICES[item] : undefined;\n  if (price === undefined) return { ok: false, reason: \"unknown item\" };\n  // ... same checks as above ...\n  return { ok: true };\n});\n\n// client\nasync function buy(item) {\n  try {\n    return await lsmp.callServer(\"shop:buy\", item);\n  } catch (e) {\n    lsmp.warn(`shop unavailable: ${e.code}`);\n    return null;\n  }\n}"
                    }
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "An API for other resources",
              "level": 2,
              "id": "resource-api"
            },
            {
              "type": "text",
              "md": "A resource offers functions to other resources with `lsmp.onCall` on its side; others call them with `lsmp.call`, in Lua or JavaScript, without depending on its code. On the server, such local calls receive `source = nil`/`null`, which tells them apart from player calls."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- resource \"bank\" (server)\nlsmp.onCall(\"bank:getBalance\", function(source, account)\n  if source ~= nil then return nil end -- server resources only\n  return lsmp.storage.get(\"balance:\" .. account) or 0\nend)\n\n-- another resource (server), in a host coroutine\nlocal balance, err = lsmp.call(\"bank:getBalance\", 4211)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// resource \"bank\" (server)\nlsmp.onCall(\"bank:getBalance\", (source, account) => {\n  if (source !== null) return null; // server resources only\n  return lsmp.storage.get(`balance:${account}`) ?? 0;\n});\n\n// another resource (server)\nasync function show(account) {\n  const balance = await lsmp.call(\"bank:getBalance\", account);\n  lsmp.log(`balance: ${balance}`);\n}"
                }
              ]
            },
            {
              "type": "callout",
              "variant": "tip",
              "md": "Prefix your names with the resource or feature (`bank:getBalance`, `race:start`): names are global to the side, and only one resource can handle a callable name.",
              "title": "Naming"
            },
            {
              "type": "heading",
              "text": "Broadcasting state",
              "level": 2,
              "id": "broadcast"
            },
            {
              "type": "text",
              "md": "For a value that every client needs, including players who join later, prefer [meta](#meta) to a broadcast event: a late joiner receives the current meta values, but never past events."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- server\nlsmp.setGlobalMeta(\"race:state\", { phase = \"countdown\", startsAtMs = lsmp.nowMs() + 5000 })\n\n-- client\nlsmp.on(\"metaChange\", function(scope, target, key, value)\n  if value then showRaceState(value) end\nend, { scope = \"global\", key = \"race:state\" })"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// server\nlsmp.setGlobalMeta(\"race:state\", { phase: \"countdown\", startsAtMs: lsmp.nowMs() + 5000 });\n\n// client\nlsmp.on(\"metaChange\", (scope, target, key, value) => {\n  if (value) showRaceState(value);\n}, { scope: \"global\", key: \"race:state\" });"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Common mistakes",
              "level": 2,
              "id": "mistakes"
            },
            {
              "type": "list",
              "items": [
                "**Trusting the client.** Anything after `source` in a server `onClient` or `onCall` handler can be anything. Check types and ranges, and decide prices and rights on the server.",
                "**Emitting an engine event.** `lsmp.emit(\"playerJoin\", ...)` raises: engine event names are reserved. Use your own name.",
                "**Expecting a reply from `emitServer`.** Network events have no answer. Use `lsmp.callServer`.",
                "**Sending before the other side listens.** A network event that arrives before its handler is registered is lost. Clients should ask for the state when their resource starts (a `lsmp.callServer`), rather than wait for an event they may have missed.",
                "**Waiting in the wrong place (Lua).** `lsmp.wait` and asynchronous calls without callback need a host coroutine (event handler, RPC handler, file body, `lsmp.createThread`).",
                "**Huge payloads.** A client can send at most 4 MiB − 1 KiB per event, and the server limits each player's traffic per second. Send what changed, not the whole state. See [Limits](#limits/events).",
                "**Expecting identity across resources.** Values are copied between resources: a table you emit is not the table another resource receives."
              ]
            }
          ]
        },
        {
          "id": "data-guide",
          "title": "Storing data (meta, storage, MySQL, files)",
          "eyebrow": "Build resources",
          "lead": "Where to keep data, and complete patterns to load and save player data.",
          "blocks": [
            {
              "type": "text",
              "md": "Resources keep data in five places. Pick by **who reads it** and **how long it must live**."
            },
            {
              "type": "table",
              "headers": [
                "Storage",
                "Lives",
                "Who reads it",
                "Good for",
                "Reference"
              ],
              "rows": [
                [
                  "Meta",
                  "until the player leaves, the entity is deleted or the server stops",
                  "every script, server and clients",
                  "state players see: job, team, fuel, a door lock",
                  "[Meta](#meta)"
                ],
                [
                  "Storage",
                  "on disk, forever",
                  "the resource itself, on the server",
                  "settings, counters, small records per account",
                  "[storage](#server-storage)"
                ],
                [
                  "MySQL",
                  "in your database",
                  "anything that connects to it (website, other servers)",
                  "large or relational data, data shared with a website",
                  "[MySQL](#server-mysql)"
                ],
                [
                  "Files",
                  "on disk",
                  "the resource (data folder), the operator",
                  "logs, exports, generated files",
                  "[Files](#server-files)"
                ],
                [
                  "Resource files",
                  "shipped with the resource, read-only",
                  "the resource",
                  "configuration, translations, templates",
                  "[`lsmp.readResourceFile`](#core-utils/fn-read-resource-file)"
                ]
              ]
            },
            {
              "type": "list",
              "items": [
                "Meta are **not saved**: they disappear with the player or the server. Combine them with storage or MySQL: load into meta when a player joins, save from meta when they leave.",
                "Key saved player data on the **account**, [`lsmp.getPlayerLsmpId`](#players/fn-get-player-lsmp-id), never on the playerId (reused) or the name (chosen by the player). Guests have no account: decide what they may keep.",
                "Storage, MySQL and files exist only on the server. A client gets data through [events and calls](#events-guide) or meta.",
                "MySQL needs an unsandboxed resource (see [Sandbox](#capabilities/sandbox)); storage and the data folder work everywhere."
              ]
            },
            {
              "type": "heading",
              "text": "Saving player data with storage",
              "level": 2,
              "id": "storage-player"
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Load on join",
                  "md": "Read the account's record and expose what clients need as meta.",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "lsmp.on(\"playerJoin\", function(playerId, name)\n  local account = lsmp.getPlayerLsmpId(playerId)\n  if not account then return end -- guest: nothing saved\n  local data = lsmp.storage.get(\"player:\" .. account) or { money = 1000, level = 1 }\n  lsmp.setPlayerMeta(playerId, \"money\", data.money)\n  lsmp.setPlayerMeta(playerId, \"level\", data.level)\nend)"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "lsmp.on(\"playerJoin\", (playerId, name) => {\n  const account = lsmp.getPlayerLsmpId(playerId);\n  if (account === null) return; // guest: nothing saved\n  const data = lsmp.storage.get(`player:${account}`) ?? { money: 1000, level: 1 };\n  lsmp.setPlayerMeta(playerId, \"money\", data.money);\n  lsmp.setPlayerMeta(playerId, \"level\", data.level);\n});"
                    }
                  ]
                },
                {
                  "title": "Save on leave",
                  "md": "In `playerLeave`, the leaving player's account and meta are still readable.",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "lsmp.on(\"playerLeave\", function(playerId)\n  local account = lsmp.getPlayerLsmpId(playerId)\n  if not account then return end\n  lsmp.storage.set(\"player:\" .. account, {\n    money = lsmp.getPlayerMeta(playerId, \"money\") or 0,\n    level = lsmp.getPlayerMeta(playerId, \"level\") or 1,\n  })\nend)"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "lsmp.on(\"playerLeave\", (playerId) => {\n  const account = lsmp.getPlayerLsmpId(playerId);\n  if (account === null) return;\n  lsmp.storage.set(`player:${account}`, {\n    money: lsmp.getPlayerMeta(playerId, \"money\") ?? 0,\n    level: lsmp.getPlayerMeta(playerId, \"level\") ?? 1,\n  });\n});"
                    }
                  ]
                },
                {
                  "title": "Flush when stopping",
                  "md": "Storage writes reach the disk within about 750 ms, and the server flushes on a clean shutdown. To be sure before the server stops, flush in `resourceStop`.",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "lsmp.on(\"resourceStop\", function(name)\n  if name == lsmp.getResourceName() then lsmp.storage.flush() end\nend)"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "lsmp.on(\"resourceStop\", async (name) => {\n  if (name === lsmp.getResourceName()) await lsmp.storage.flush();\n});"
                    }
                  ]
                }
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "md": "Nothing runs when the server crashes: `playerLeave` and `serverStop` are not fired. For valuable data (money from a purchase), save at the moment it changes, not only when the player leaves.",
              "title": "Crashes"
            },
            {
              "type": "heading",
              "text": "The same with MySQL",
              "level": 2,
              "id": "mysql-player"
            },
            {
              "type": "text",
              "md": "With a database, load asynchronously when the player joins. The handler can wait for the query: other players and events are not blocked."
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Create the pool once",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "local db = lsmp.mysql.createPool({ user = \"game\", password = \"secret\", database = \"lsmp\" })"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "const db = lsmp.mysql.createPool({ user: \"game\", password: \"secret\", database: \"lsmp\" });"
                    }
                  ]
                },
                {
                  "title": "Load and save",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "lsmp.on(\"playerJoin\", function(playerId)\n  local account = lsmp.getPlayerLsmpId(playerId)\n  if not account then return end\n  local rows, err = db:query(\"SELECT money FROM players WHERE account = ?\", { account })\n  if not rows then return lsmp.error(\"load failed: \" .. err) end\n  lsmp.setPlayerMeta(playerId, \"money\", rows[1] and rows[1].money or 1000)\nend)\n\nlsmp.on(\"playerLeave\", function(playerId)\n  local account = lsmp.getPlayerLsmpId(playerId)\n  if not account then return end\n  db:query(\"INSERT INTO players (account, money) VALUES (?, ?) ON DUPLICATE KEY UPDATE money = VALUES(money)\",\n    { account, lsmp.getPlayerMeta(playerId, \"money\") or 0 })\nend)"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "lsmp.on(\"playerJoin\", async (playerId) => {\n  const account = lsmp.getPlayerLsmpId(playerId);\n  if (account === null) return;\n  const rows = await db.query(\"SELECT money FROM players WHERE account = ?\", [account]);\n  lsmp.setPlayerMeta(playerId, \"money\", rows[0]?.money ?? 1000);\n});\n\nlsmp.on(\"playerLeave\", async (playerId) => {\n  const account = lsmp.getPlayerLsmpId(playerId);\n  if (account === null) return;\n  await db.query(\n    \"INSERT INTO players (account, money) VALUES (?, ?) ON DUPLICATE KEY UPDATE money = VALUES(money)\",\n    [account, lsmp.getPlayerMeta(playerId, \"money\") ?? 0],\n  );\n});"
                    }
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "Common mistakes",
              "level": 2,
              "id": "mistakes"
            },
            {
              "type": "list",
              "items": [
                "**Storing in meta and expecting it after a restart.** Meta live in memory only.",
                "**Keying on playerId or name.** Use the account (`lsmpId`).",
                "**Building SQL with string concatenation.** Always use `?` parameters.",
                "**Writing files next to the resource.** A resource has no folder of its own on disk at run time: write in `lsmp.getDataPath()`.",
                "**Huge stored values.** One value is at most 64 KiB and a store 16 MiB: move large data to MySQL or files."
              ]
            }
          ]
        },
        {
          "id": "web-ui",
          "title": "Web interfaces (guide)",
          "eyebrow": "Build resources",
          "lead": "Build in-game interfaces with HTML, CSS and JavaScript: where the files go, how the page and your script talk, focus, frameworks, and the mistakes everyone makes once.",
          "blocks": [
            {
              "type": "text",
              "md": "An interface is three pieces: **files** in a `webui` folder of your resource, a **client script** that opens them with `lsmp.createBrowser`, and the **page**, which talks to that script through its `lsmp` object. The full reference is in [Browsers](#browsers) and [The lsmp object in a page](#page-api); a step-by-step build is in the [UI tutorial](#tutorial-ui)."
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Put the page in a webui folder",
                  "md": "Declare the folder in the manifest. Its content is served at `rsc://<resource name>/`: here `web/index.html` is `rsc://hud/index.html`.",
                  "blocks": [
                    {
                      "type": "tree",
                      "tree": "resources/\n└─ hud/\n   ├─ manifest.json\n   ├─ client/\n   │  └─ main.lua\n   └─ web/\n      ├─ index.html\n      ├─ style.css\n      └─ app.js",
                      "only": "lua"
                    },
                    {
                      "type": "tree",
                      "tree": "resources/\n└─ hud/\n   ├─ manifest.json\n   ├─ client/\n   │  └─ main.js\n   └─ web/\n      ├─ index.html\n      ├─ style.css\n      └─ app.js",
                      "only": "js"
                    },
                    {
                      "type": "code",
                      "lang": "json",
                      "title": "manifest.json",
                      "code": "{\n  \"title\": \"HUD\",\n  \"client_scripts\": \"client/main.lua\",\n  \"webui\": \"web\"\n}",
                      "only": "lua"
                    },
                    {
                      "type": "code",
                      "lang": "json",
                      "title": "manifest.json",
                      "code": "{\n  \"title\": \"HUD\",\n  \"client_scripts\": \"client/main.js\",\n  \"webui\": \"web\"\n}",
                      "only": "js"
                    }
                  ]
                },
                {
                  "title": "Open it from a client script",
                  "md": "Without `bounds`, a page covers the whole screen; everything you do not paint stays transparent, so a full-screen page with a small panel in a corner is fine. Send the first data once the page is loaded.",
                  "codetabs": [
                    {
                      "label": "client/main.lua",
                      "lang": "lua",
                      "code": "local hud = lsmp.createBrowser(\"rsc://hud/index.html\")\n\nhud:on(\"load\", function()\n  hud:emit(\"money\", 1500)\nend)"
                    },
                    {
                      "label": "client/main.js",
                      "lang": "js",
                      "code": "const hud = lsmp.createBrowser('rsc://hud/index.html');\n\nhud.on('load', () => {\n  hud.emit('money', 1500);\n});"
                    }
                  ]
                },
                {
                  "title": "Listen in the page",
                  "md": "`lsmp` is there before your first script runs. Keep the page background transparent.",
                  "codetabs": [
                    {
                      "label": "web/index.html",
                      "lang": "html",
                      "web": true,
                      "code": "<!doctype html>\n<html>\n<head>\n  <link rel=\"stylesheet\" href=\"style.css\">\n</head>\n<body>\n  <div id=\"money\" class=\"panel\">$0</div>\n  <script src=\"app.js\"></script>\n</body>\n</html>"
                    },
                    {
                      "label": "web/style.css",
                      "lang": "css",
                      "web": true,
                      "code": "html, body { margin: 0; background: transparent; overflow: hidden; }\n.panel {\n  position: absolute; top: 2vh; right: 2vw;\n  padding: .6em 1em; border-radius: 8px;\n  background: rgba(0, 0, 0, .6); color: #7CFC9A;\n  font: 600 2.2vh system-ui, sans-serif;\n}"
                    },
                    {
                      "label": "web/app.js",
                      "lang": "js",
                      "web": true,
                      "code": "lsmp.on('money', (amount) => {\n  document.getElementById('money').textContent = `$${amount.toLocaleString()}`;\n});"
                    }
                  ]
                },
                {
                  "title": "Start it and look",
                  "md": "Restart the server so it loads `hud`, then join. Open the client console with **F8** to read errors, and [DevTools](#debugging/debugging-devtools) to inspect the page."
                }
              ]
            },
            {
              "type": "heading",
              "text": "Choosing the direction",
              "level": 2,
              "id": "web-ui-directions"
            },
            {
              "type": "table",
              "headers": [
                "You want",
                "Script side",
                "Page side"
              ],
              "rows": [
                [
                  "Push data to the page",
                  "`browser:emit(\"money\", 1500)`",
                  "`lsmp.on('money', fn)`"
                ],
                [
                  "Tell the script something happened",
                  "`browser:on(\"close\", fn)`",
                  "`lsmp.emit('close')`"
                ],
                [
                  "Ask the script, wait for the answer",
                  "`browser:on(\"buy\", fn)` returns the answer",
                  "`await lsmp.call('buy', id)`"
                ],
                [
                  "Ask the page, wait for the answer",
                  "`browser:call(\"getForm\")`",
                  "`lsmp.on('getForm', fn)` returns the answer"
                ],
                [
                  "Reach the server",
                  "The client script calls the server ([`lsmp.callServer`](#rpc/fn-call-server), [`lsmp.emitServer`](#events/fn-emit-server)) and forwards the result",
                  "Never directly"
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "The page is the player's",
              "md": "Pages run on the player's machine, like client scripts: a player can change what they send. Check every value in the client script, and decide everything that matters (money, items, permissions) on the **server**."
            },
            {
              "type": "heading",
              "text": "Menus: focus and cursor",
              "level": 2,
              "id": "web-ui-focus"
            },
            {
              "type": "text",
              "md": "A page without the focus is click-through: perfect for a HUD. A menu needs the mouse and keyboard: give it the focus while it is open, and take it back when it closes. The cursor shows only while a page holds the mouse. A text field that needs no mouse, like a chat, takes the keyboard alone with `setFocus(true, { cursor = false })` (`{ cursor: false }` in JS): no cursor appears while the player types. A panel that must stay usable while the player keeps playing takes the mouse alone with `{ keepInput = true }` (`{ keepInput: true }` in JS). The player can always escape with **Ctrl+Alt+Backspace**; your script then gets `focusLost`, so close the menu there too."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "client/main.lua",
                  "lang": "lua",
                  "code": "local menu = lsmp.createBrowser(\"rsc://hud/menu.html\", { visible = false })\n\nlocal function setOpen(open)\n  menu:setVisible(open)\n  menu:setFocus(open)\nend\n\nlsmp.registerCommand(\"menu\", function() setOpen(true) end)\nmenu:on(\"close\", function() setOpen(false) end)      -- the page's close button\nmenu:on(\"focusLost\", function() setOpen(false) end)  -- Ctrl+Alt+Backspace"
                },
                {
                  "label": "client/main.js",
                  "lang": "js",
                  "code": "const menu = lsmp.createBrowser('rsc://hud/menu.html', { visible: false });\n\nfunction setOpen(open) {\n  menu.setVisible(open);\n  menu.setFocus(open);\n}\n\nlsmp.registerCommand('menu', () => setOpen(true));\nmenu.on('close', () => setOpen(false));      // the page's close button\nmenu.on('focusLost', () => setOpen(false));  // Ctrl+Alt+Backspace"
                },
                {
                  "label": "web/menu.js",
                  "lang": "js",
                  "web": true,
                  "code": "document.querySelector('#close').addEventListener('click', () => lsmp.emit('close'));\ndocument.addEventListener('keydown', (e) => {\n  if (e.key === 'Escape') lsmp.emit('close');\n});"
                }
              ]
            },
            {
              "type": "list",
              "items": [
                "Hide rather than destroy a menu you reopen often: a hidden page keeps its state and opens instantly.",
                "Several pages: `zIndex` orders them. Only focused, visible pages take the mouse."
              ]
            },
            {
              "type": "heading",
              "text": "Frameworks and build tools",
              "level": 2,
              "id": "web-ui-frameworks"
            },
            {
              "type": "text",
              "md": "React, Vue, Svelte and plain modules all work. Point `webui` at the **built** output, not at the sources: `node_modules` is never sent to players anyway."
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Build into the resource",
                  "md": "Each resource has its own host (`rsc://hud/`), so absolute paths (`/assets/app.js`) and relative ones both resolve inside it.",
                  "code": {
                    "lang": "json",
                    "title": "manifest.json",
                    "code": "{\n  \"title\": \"HUD\",\n  \"client_scripts\": \"client/main.js\",\n  \"webui\": \"ui/dist\"\n}"
                  }
                },
                {
                  "title": "Develop with hot reload",
                  "md": "Outside a server session, a 2D browser may open `http://localhost`: run your dev server and point the browser at it from a [local resource](#local-resources) in Story mode. Switch back to `rsc://` before you ship: on a server, `http://` is refused.",
                  "codetabs": [
                    {
                      "label": "client/main.lua",
                      "lang": "lua",
                      "code": "local DEV = lsmp.gameType() == \"SP\"\nlocal url = DEV and \"http://localhost:5173/\" or \"rsc://hud/index.html\"\nlocal hud = lsmp.createBrowser(url)"
                    },
                    {
                      "label": "client/main.js",
                      "lang": "js",
                      "code": "const DEV = lsmp.gameType() === 'SP';\nconst url = DEV ? 'http://localhost:5173/' : 'rsc://hud/index.html';\nconst hud = lsmp.createBrowser(url);"
                    }
                  ]
                },
                {
                  "title": "Design in a normal browser",
                  "md": "Outside the game there is no `lsmp`: load the small [stand-in](#page-api/page-api-outside) first."
                }
              ]
            },
            {
              "type": "heading",
              "text": "A page in the world (3D)",
              "level": 2,
              "id": "web-ui-3d"
            },
            {
              "type": "text",
              "md": "A cinema screen, a billboard, a laptop: [`lsmp.createBrowser3D`](#browsers/fn-create-browser3d) renders a page into a texture, and [`lsmp.replaceTexture`](#textures/fn-replace-texture) puts it in place of a game texture. 3D pages have no mouse or keyboard; drive them with `emit` and `call`. Keep their size and `fps` as low as the content allows: each one costs rendering time on the player's machine."
            },
            {
              "type": "heading",
              "text": "Common mistakes",
              "level": 2,
              "id": "web-ui-mistakes"
            },
            {
              "type": "table",
              "headers": [
                "Symptom",
                "Cause and fix"
              ],
              "rows": [
                [
                  "`createBrowser` raises `URL refused`",
                  "`http://` on a server, or a typo in the scheme. Use `rsc://<resource>/…` or `https://`."
                ],
                [
                  "`loadError` with `http-404`",
                  "The file is not in a `webui` folder, or the path includes the folder name: with `\"webui\": \"web\"`, it is `rsc://hud/index.html`, not `rsc://hud/web/index.html`."
                ],
                [
                  "The page shows but receives nothing",
                  "You emitted to another handle, or the page registers its `lsmp.on` handlers too late (inside a callback). Register them at the top of the page's script."
                ],
                [
                  "`lsmp.call` rejects with `no-handler`",
                  "The script has no `browser:on` handler for that name on **this** browser."
                ],
                [
                  "The game no longer reacts to the keyboard",
                  "A page kept the focus. Call `setFocus(false)` when your menu closes; players can always press Ctrl+Alt+Backspace."
                ],
                [
                  "Clicks go through the page",
                  "It has no focus, or took the keyboard only (`cursor` set to `false`): `setFocus(true)`."
                ],
                [
                  "`alert` does nothing, stored data is missing",
                  "2D pages have no dialogs: draw your own. Storage is per server, and a 2D page and a 3D page do not share it. See [Storage, microphone, camera and limits](#browsers/browsers-sandbox)."
                ],
                [
                  "A black or white rectangle over the game",
                  "The page paints a background: set `background: transparent` on `html` and `body`."
                ]
              ]
            }
          ]
        },
        {
          "id": "streaming",
          "title": "Assets and streaming",
          "eyebrow": "Guide · client",
          "lead": "Ship models, textures, maps and vehicles with a resource, load parts of them only when they are needed, and take parts of the base game out of the world.",
          "blocks": [
            {
              "type": "text",
              "md": "A resource carries **streamed assets**: the game files (`.ydr`, `.ytd`, `.yft`, `.ymap`, `.ybn`…) that players download with it and that the game streams in as it needs them. This guide shows how to lay them out, how they combine with the game and with other resources, and how client scripts change them while the game runs. The functions are documented in [Hot resources, stream sets and archives](#client-resources)."
            },
            {
              "type": "heading",
              "text": "Where streamed files go",
              "level": 2,
              "id": "streaming-layout"
            },
            {
              "type": "text",
              "md": "Files in the `stream/` folder of a resource are streamed as soon as the resource is mounted on the client. Sub-folders are only for your own order. To load some files **later**, put them in a sub-folder of `stream/` and declare it as a **stream set** in the manifest."
            },
            {
              "type": "tree",
              "tree": "my_island/\n├─ manifest.json\n├─ client/\n│  └─ main.lua\n└─ stream/                 # streamed while the resource is mounted\n   ├─ island_terrain.ybn\n   ├─ island_terrain.ymap\n   ├─ island_props.ytyp\n   ├─ night_club/          # stream set \"club\": loaded by a script\n   │  ├─ club_interior.ymap\n   │  └─ club_props.ydr\n   └─ winter/              # stream set \"winter\": loaded with the resource\n      └─ island_snow.ytd"
            },
            {
              "type": "code",
              "lang": "json",
              "title": "manifest.json",
              "code": "{\n  \"title\": \"My island\",\n  \"client_scripts\": [\"client/main.lua\"],\n  \"stream_sets\": [\n    { \"name\": \"club\", \"folder\": \"stream/night_club\", \"load\": \"manual\" },\n    { \"name\": \"winter\", \"folder\": \"stream/winter\", \"load\": \"auto\" }\n  ]\n}"
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Meaning"
              ],
              "rows": [
                [
                  "`stream_sets[].name`",
                  "The set's name for scripts: `[a-z0-9_-]`, 1 to 64 characters."
                ],
                [
                  "`stream_sets[].folder`",
                  "Folder of the set, relative to the resource root like every path of the manifest, and inside `stream/`: `\"stream/night_club\"`. A file belongs to the set of its closest folder."
                ],
                [
                  "`stream_sets[].load`",
                  "`\"auto\"` (default): loaded with the resource. `\"manual\"`: loaded only by [`lsmp.resources.loadStreamSet`](#client-resources/fn-resources-load-stream-set)."
                ],
                [
                  "`data_files`",
                  "Game data files (metadata, text, water…) mounted with the resource, or with one of its sets. See [Resource layout](#resource-layout)."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Who wins when two files share a name",
              "level": 2,
              "id": "streaming-layers"
            },
            {
              "type": "text",
              "md": "Every mounted resource is a **layer** over the game's own files. When two layers provide the same file name, the one mounted **last** wins. Inside a resource, a loaded set wins over the rest of the resource, and a set loaded later wins over one loaded before.\n\nTaking a layer away (stopping a resource, unloading a set) lets the next one show through: another resource, the game's file, or nothing if only that layer had the name."
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "In-use assets are never pulled away",
              "md": "A model or a texture that something still draws, or that a script requested, keeps its file until it is released. Unloading a set or unregistering it does not fail because of that: the asset follows once it is free. Release what you request (`setModelAsNoLongerNeeded`, `setStreamedTextureDictAsNoLongerNeeded`) before you swap content."
            },
            {
              "type": "heading",
              "text": "Load content on demand",
              "level": 2,
              "id": "streaming-on-demand"
            },
            {
              "type": "text",
              "md": "A set declared `\"manual\"` costs nothing until a script loads it. A typical use is an interior that only matters when a player goes there."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- client/main.lua: load the club when the player comes near, unload it when they leave.\nlocal CLUB = { x = -1569.0, y = -3017.0, z = -74.0 }\nlocal loaded = false\n\nlsmp.createThread(function()\n  while true do\n    local p = getEntityCoords(playerPedId(), false)\n    local near = getDistanceBetweenCoords(p.x, p.y, p.z, CLUB.x, CLUB.y, CLUB.z, true) < 150.0\n    if near ~= loaded then\n      loaded = near\n      local ok, err\n      if near then\n        ok, err = lsmp.resources.loadStreamSet(\"my_island\", \"club\")\n      else\n        ok, err = lsmp.resources.unloadStreamSet(\"my_island\", \"club\")\n      end\n      if not ok then lsmp.warn(\"club set: \" .. err) end\n    end\n    lsmp.wait(1000)\n  end\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// client/main.js: load the club when the player comes near, unload it when they leave.\nconst CLUB = { x: -1569.0, y: -3017.0, z: -74.0 };\nlet loaded = false;\n\nsetInterval(async () => {\n  const p = getEntityCoords(playerPedId(), false);\n  const near = getDistanceBetweenCoords(p, CLUB, true) < 150.0;\n  if (near === loaded) return;\n  loaded = near;\n  try {\n    if (near) await lsmp.resources.loadStreamSet('my_island', 'club');\n    else await lsmp.resources.unloadStreamSet('my_island', 'club');\n  } catch (err) {\n    lsmp.warn(`club set: ${err.code}`);\n  }\n}, 1000);"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Replace part of the base map",
              "level": 2,
              "id": "streaming-replace"
            },
            {
              "type": "text",
              "md": "To put your own map where the game has one, take the game's pieces out first. Two tools work together:"
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "[`invalidateArchives`](#client-resources/fn-resources-invalidate-archives) switches whole archives of the game off: their maps and collisions disappear, the way a map DLC removes what it replaces.",
                "[`unregisterAssets`](#client-resources/fn-resources-unregister-assets) takes named assets out, and frees their place in the game's asset stores: that is what makes room for many new models and textures."
              ]
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Hide the transition",
                  "md": "Show a loading screen, or keep the player somewhere that stays: maps and collisions leave on the spot, and a player standing on them falls."
                },
                {
                  "title": "Switch the game's pieces off",
                  "md": "Call `invalidateArchives` with every archive of the area in **one** list, then `unregisterAssets` for the models and textures you need room for. Ship the lists as JSON files of the resource (`files` in the manifest) and read them with `lsmp.readResourceFile`."
                },
                {
                  "title": "Bring yours in",
                  "md": "Start the resource that carries the new map, or load its set. Jobs run in order: there is no need to wait for the previous step before asking."
                },
                {
                  "title": "Undo",
                  "md": "Stopping the resource that made the changes restores the archives it switched off. Leaving the server restores everything."
                }
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- Downtown replaced by our own map, in one go.\nlocal archives = lsmp.json.decode(lsmp.readResourceFile(\"data/downtown_archives.json\"))\nlocal assets = lsmp.json.decode(lsmp.readResourceFile(\"data/downtown_assets.json\"))\n\nlsmp.resources.invalidateArchives(archives, function(res, err)\n  if not res then lsmp.warn(\"archives: \" .. err) end\nend)\nlsmp.resources.unregisterAssets(assets, function(res, err)\n  if res and res.failed > 0 then lsmp.log(res.failed .. \" assets still in use\") end\nend)\nlsmp.resources.loadStreamSet(\"my_downtown\", \"city\", function(ok, err)\n  if not ok then lsmp.warn(\"city set: \" .. err) end\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// Downtown replaced by our own map, in one go.\nconst archives = JSON.parse(lsmp.readResourceFile('data/downtown_archives.json'));\nconst assets = JSON.parse(lsmp.readResourceFile('data/downtown_assets.json'));\n\nasync function replaceDowntown() {\n  // Requested together: the jobs run in this order.\n  const steps = [\n    lsmp.resources.invalidateArchives(archives),\n    lsmp.resources.unregisterAssets(assets),\n    lsmp.resources.loadStreamSet('my_downtown', 'city'),\n  ];\n  const [, res] = await Promise.all(steps);\n  if (res.failed > 0) lsmp.log(`${res.failed} assets still in use`);\n}\n\nreplaceDowntown().catch((err) => lsmp.warn(`downtown: ${err.code}`));"
                }
              ]
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "Order inside a list",
              "md": "The engine retries refused names as long as a pass makes progress, so order is not required. Listing maps (`.ymap`) first, then collisions, types (`.ytyp`), models, and textures last, simply makes it one pass."
            },
            {
              "type": "heading",
              "text": "Quiet the story scripts",
              "level": 2,
              "id": "streaming-story"
            },
            {
              "type": "text",
              "md": "The game's story scripts still run in a session. Some load extra buildings and interiors, others start activities. [`suspendScriptIpls`](#client-resources/fn-resources-suspend-script-ipls) removes the map pieces they add, and [`suspendStoryScript`](#client-resources/fn-resources-suspend-story-script) stops one script by name. Both are restored when the resource that asked stops."
            },
            {
              "type": "heading",
              "text": "Common problems",
              "level": 2,
              "id": "streaming-problems"
            },
            {
              "type": "table",
              "headers": [
                "Symptom",
                "Cause"
              ],
              "rows": [
                [
                  "A replaced model still shows the old one",
                  "The old model is still in use: an entity draws it, or a script requested it. It switches once released."
                ],
                [
                  "`unregisterAssets` reports `failed > 0`",
                  "Those names are in use, or no asset has that name. Check the names with [`getAssetState`](#client-resources/fn-resources-get-asset-state)."
                ],
                [
                  "`loadStreamSet` rejects with `not-found`",
                  "The resource is not mounted (and no `mountResource` for it is queued), or the set name differs: names are case-sensitive."
                ],
                [
                  "The player falls through the ground",
                  "A collision (`.ybn`) or a map was removed under them. Do the swap behind a loading screen."
                ],
                [
                  "An archive counts in `failed`",
                  "It is a data archive, not a streaming one, or its name is not the one the game registered."
                ]
              ]
            }
          ]
        },
        {
          "id": "local-resources",
          "title": "Local resources",
          "eyebrow": "Build resources",
          "lead": "Run a resource straight from its working folder in Story mode: no server, no packaging, reload in seconds. The same folder then goes, unchanged, to a server or to the marketplace.",
          "blocks": [
            {
              "type": "text",
              "md": "Every sub-folder of the `resources` folder of your LS:MP installation is a **local resource**: `%LocalAppData%\\LSMP\\resources` by default. It has exactly the layout a server keeps under `resources/` ([Resource layout](#resource-layout)), and it loads in **Story mode**. Use it to build a map, a vehicle pack, a client script or an interface before putting it on a server or [publishing it](#publish-mod)."
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Drop your folder",
                  "md": "Create `resources` next to the LS:MP client if it does not exist, and put your resource folder in it. The folder name is the resource name: lowercase letters, digits, `_` and `-`.",
                  "blocks": [
                    {
                      "type": "tree",
                      "tree": "%LocalAppData%\\LSMP\\\n└─ resources/\n   ├─ my-map/\n   │  ├─ manifest.json\n   │  └─ stream/\n   └─ hud/\n      ├─ manifest.json\n      ├─ client/\n      └─ web/"
                    }
                  ]
                },
                {
                  "title": "Switch it on",
                  "md": "In the LS:MP menu, **My mods** lists it with a **Local** badge and its own switch. It is **off** by default: dropping a folder is not asking for it to load. A folder with an invalid name is listed, switched off, with the name to rename it to."
                },
                {
                  "title": "Enter Story mode",
                  "md": "The resource is mounted as the world loads. Its client scripts run, and [`lsmp.gameType()`](#core-utils) answers `\"SP\"`. Open the client console with **F8** to read its log."
                }
              ]
            },
            {
              "type": "heading",
              "text": "It behaves like its future package",
              "level": 2,
              "id": "local-package"
            },
            {
              "type": "text",
              "md": "The folder is mounted through the same rules a server applies when it packs a resource for players. That is what makes the test honest:"
            },
            {
              "type": "list",
              "items": [
                "Only what the [client package](#resource-layout/layout-packages) would hold is visible: shared and client scripts, `files`, `webui`, `data_files`, `stream/`. No server script runs: there is no server in Story mode.",
                "Patterns of the manifest are resolved the way the packager resolves them.",
                "An invalid `manifest.json` keeps the resource from mounting, and **My mods** says why, with the line and column."
              ]
            },
            {
              "type": "table",
              "headers": [
                "",
                "On a server",
                "Local folder"
              ],
              "rows": [
                [
                  "Content",
                  "Frozen when the server packs it",
                  "Read from the disk each time the resource is mounted"
                ],
                [
                  "On or off",
                  "`enabled` in the server's [`resources.json`](#operator-settings)",
                  "The switch in **My mods**"
                ],
                [
                  "Server scripts",
                  "Run",
                  "Ignored"
                ],
                [
                  "Page addresses",
                  "`rsc://` and `https://`",
                  "Also `http://localhost`, for a dev server with hot reload"
                ],
                [
                  "DevTools",
                  "For developers the server allows",
                  "Always, with **Ctrl+Shift+I**"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Reload while you work",
              "level": 2,
              "id": "local-reload"
            },
            {
              "type": "text",
              "md": "Unmounting a local resource then mounting it again reads the whole folder again, manifest included, without leaving Story mode. A small helper resource makes it one command: `reload hud` in the F8 console."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "dev-tools/client/main.lua",
                  "lang": "lua",
                  "code": "lsmp.registerCommand(\"reload\", { help = \"reload a local resource\" }, function(args)\n  local name = args[1]\n  if not name then\n    lsmp.warn(\"usage: reload <resource>\")\n    return\n  end\n  lsmp.unmountResource(name, function()\n    lsmp.mountResource(name, function(ok, err)\n      if ok then lsmp.log(name .. \" reloaded\") else lsmp.warn(name .. \" failed: \" .. err) end\n    end)\n  end)\nend)"
                },
                {
                  "label": "dev-tools/client/main.js",
                  "lang": "js",
                  "code": "lsmp.registerCommand('reload', { help: 'reload a local resource' }, async (args) => {\n  const name = args[0];\n  if (!name) return lsmp.warn('usage: reload <resource>');\n  try {\n    await lsmp.unmountResource(name);\n    await lsmp.mountResource(name);\n    lsmp.log(`${name} reloaded`);\n  } catch (err) {\n    lsmp.warn(`${name} failed: ${err.code}`);\n  }\n});"
                }
              ]
            },
            {
              "type": "list",
              "items": [
                "Scripts, JSON files and web pages can be edited at any time.",
                "**Streamed assets are locked while mounted**: a `.ydr`, `.ytd` or `.ymap` of a mounted resource cannot be overwritten, and your export tool reports the file as in use. Unmount the resource, write the asset, mount it again.",
                "See [Hot resources](#client-resources) for `mountResource` and `unmountResource`, and [Debugging](#debugging) for DevTools."
              ]
            },
            {
              "type": "heading",
              "text": "No manifest yet?",
              "level": 2,
              "id": "local-generated-manifest"
            },
            {
              "type": "text",
              "md": "A folder dropped without a `manifest.json` is not an error: it is someone starting. LS:MP reads the folder and **writes** the manifest it can deduce, once. From then on the file is yours: it is never regenerated or replaced. To get a fresh one after reorganising the folder, delete it."
            },
            {
              "type": "table",
              "headers": [
                "Key",
                "Deduced from"
              ],
              "rows": [
                [
                  "`title`",
                  "The folder name."
                ],
                [
                  "`shared_scripts`, `client_scripts`, `server_scripts`",
                  "The usual folders (`shared/`, `client/`, `server/`) as patterns; elsewhere, a script filed by its folder (`src/client/x.js`) or its name (`cl_*`, `sv_*`, `sh_*`)."
                ],
                [
                  "`files`",
                  "What `client/` and `shared/` hold besides code."
                ],
                [
                  "`data_files`",
                  "Game metadata recognised by its name (`vehicles.meta`, `handling.meta`…), and the data file lines of a FiveM `fxmanifest.lua`."
                ],
                [
                  "`webui`",
                  "The built output of a web project (`dist/` or `build/` next to a `package.json`), otherwise a folder holding an `index.html`."
                ]
              ]
            },
            {
              "type": "list",
              "items": [
                "**Nothing is guessed.** A script whose side nothing tells (`main.lua` at the root) is not declared, and a `config.json` at the root is not added to `files`.",
                "FiveM scripts are not declared: they use another API and have to be ported. Their assets and data files are taken as they are: a FiveM vehicle pack loads without writing anything.",
                "Game assets outside `stream/` are never streamed: move them into `stream/`.",
                "Everything left out is listed in a `\"_review\"` key of the generated manifest, with what to write to include it. The key is ignored by LS:MP; delete it when you are done."
              ]
            },
            {
              "type": "heading",
              "text": "Good to know",
              "level": 2,
              "id": "local-good-to-know"
            },
            {
              "type": "list",
              "items": [
                "Hidden folders (`.git`, `.vscode`) are skipped.",
                "**The folder wins over the published mod.** If you enable both a mod you published and the folder where you rework it, the folder runs, and its assets take precedence.",
                "Local resources only exist in Story mode. On a server, players get that server's resources and nothing else."
              ]
            }
          ]
        },
        {
          "id": "debugging",
          "title": "Debugging (logs, DevTools, common errors)",
          "eyebrow": "Build resources",
          "lead": "Find out why a resource does not start or does not behave: where every message goes, how to inspect your web pages with Chrome DevTools, and the errors you will meet first.",
          "blocks": [
            {
              "type": "heading",
              "text": "Where messages go",
              "level": 2,
              "id": "debugging-logs"
            },
            {
              "type": "table",
              "headers": [
                "From",
                "Read it in"
              ],
              "rows": [
                [
                  "Server scripts, server packaging, `server.cfg`",
                  "The server's terminal, the **Console** tab of the admin panel, and `logs/` in the server folder (one file per session; the panel's *History* mode browses them)."
                ],
                [
                  "Client scripts",
                  "The client console: **F8** in game."
                ],
                [
                  "Web pages",
                  "The page's own console, in [DevTools](#debugging/debugging-devtools)."
                ]
              ]
            },
            {
              "type": "list",
              "items": [
                "Every line written by a resource starts with its name: `[shop] …`. Use [`lsmp.log`, `lsmp.warn`, `lsmp.error` and `lsmp.debug`](#core-utils); `lsmp.setLogLevel` hides the debug lines when you are done.",
                "A handler that raises is isolated: the error is logged in red with the resource, the file and the line, and the other handlers still run.",
                "A call that returns `nil`/`false` on a run-time failure leaves its code in [`lsmp.getLastError()`](#core-utils). Codes are listed in [Error codes](#error-codes).",
                "`resources` in the server console lists every resource with its state: `started`, `failed`, `stopped`…"
              ]
            },
            {
              "type": "heading",
              "text": "A fast loop",
              "level": 2,
              "id": "debugging-loop"
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Run a local server",
                  "md": "On your own machine, with `RequireAdmission=false` and `PublicList=false`, so you can join it at `127.0.0.1:2086`."
                },
                {
                  "title": "Edit, then restart the server",
                  "md": "The server reads its resources once, when it starts: after a change, restart it (`quit` in its console, then start it again) and join again. For client scripts and pages, [local resources](#local-resources) reload in seconds in Story mode."
                },
                {
                  "title": "Read both consoles",
                  "md": "The server console for the server half, F8 for the client half, DevTools for pages."
                },
                {
                  "title": "For client-only work, skip the server",
                  "md": "Maps, vehicles, interfaces and client scripts run as [local resources](#local-resources) in Story mode, with DevTools always open to you."
                }
              ]
            },
            {
              "type": "heading",
              "text": "Common errors",
              "level": 2,
              "id": "debugging-errors"
            },
            {
              "type": "table",
              "headers": [
                "Message",
                "Cause and fix"
              ],
              "rows": [
                [
                  "`resource folder 'MyShop' is not a valid name (…): use 'myshop', not loaded`",
                  "Rename the folder: [names](#resource-layout/layout-name) are lowercase."
                ],
                [
                  "`resource 'shop': manifest.json is not valid JSON (line 7, column 3), not loaded`",
                  "A missing comma or quote at that place. JSON allows no comments and no trailing comma."
                ],
                [
                  "`manifest.json: 'client_script' is not a manifest key, ignored (did you mean 'client_scripts'?)`",
                  "A typo or an old key: the key is ignored, so its scripts do not run. See [Manifest keys](#resource-layout/layout-keys)."
                ],
                [
                  "`no manifest.json, its client/ folder is ignored`",
                  "Scripts run only when a manifest lists them."
                ],
                [
                  "`dependency 'db' of 'bank' is missing (did you mean 'mysql-db'?)`",
                  "Install the dependency, fix its name, or enable it in [`resources.json`](#operator-settings)."
                ],
                [
                  "A resource is `failed` with an error in one of its files",
                  "A script raised while loading. Everything the resource had registered is removed; fix the file and restart the server."
                ],
                [
                  "A resource is `failed` after 30 seconds",
                  "A top-level `await` never finished: `ResourceStartTimeoutMs` ([server.cfg](#server-cfg/cfg-lifecycle))."
                ],
                [
                  "`resource 'x' is disabled in resources.json`",
                  "Set `\"enabled\": true` in [`resources.json`](#operator-settings), then restart the server."
                ],
                [
                  "A server script is refused a file, a connection or a module",
                  "The [sandbox](#capabilities) blocked it; the log line names the operation. Allow it in `server.cfg`, grant a capability, or trust the resource."
                ],
                [
                  "A script is interrupted after 10 seconds",
                  "It blocked the server: the watchdog (`SandboxWatchdogSec`) stopped it. Never wait in a loop; use timers or `lsmp.wait`."
                ],
                [
                  "Players are refused with *server check timed out*",
                  "A `playerPreConnection` handler did not answer within `PreConnectionTimeoutMs`. The warning names the resource."
                ],
                [
                  "Events from a client stop arriving under heavy use",
                  "That player went over `ScriptEventBytesPerSec`: excess events are dropped. Send less, or less often."
                ],
                [
                  "A call (`call`, `callServer`, `callClient`) fails with `no-handler`",
                  "No resource registered that name with `lsmp.onCall` on the other side, or it is not started yet."
                ],
                [
                  "A browser gets `loadError` with `refused-url` or `http-404`",
                  "See [Web interfaces](#web-ui/web-ui-mistakes)."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "DevTools for your pages",
              "level": 2,
              "id": "debugging-devtools"
            },
            {
              "type": "text",
              "md": "Your [browser](#browsers) pages are ordinary web pages: inspect them with the DevTools of **Chrome** or **Edge** on the same machine (Elements, Console, Sources and the debugger, Network, Performance, Memory, Application). Only the server's pages are offered; LS:MP's own interface is never listed."
            },
            {
              "type": "table",
              "headers": [
                "Where the player is",
                "DevTools"
              ],
              "rows": [
                [
                  "Story mode, [local resources](#local-resources)",
                  "Always allowed."
                ],
                [
                  "On a server",
                  "Only for a player the server marks as developer with [`lsmp.setPlayerDev`](#server-moderation/fn-set-player-dev), or who has the [permission](#permissions) `lsmp.devtools` (members of the default `admin` group have it). Losing both, or leaving the server, closes every DevTools window."
                ]
              ]
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "On a server, allow yourself",
                  "md": "Put yourself in a group with `lsmp.devtools` in the **Permissions** tab of the admin panel, or mark your developers from a server script:",
                  "codetabs": [
                    {
                      "label": "server/main.lua",
                      "lang": "lua",
                      "code": "local DEVELOPERS = { [1234567] = true }   -- LS:MP IDs\n\nlsmp.on(\"playerJoin\", function(playerId)\n  if DEVELOPERS[lsmp.getPlayerLsmpId(playerId)] then\n    lsmp.setPlayerDev(playerId, true)\n  end\nend)"
                    },
                    {
                      "label": "server/main.js",
                      "lang": "js",
                      "code": "const DEVELOPERS = new Set([1234567]);   // LS:MP IDs\n\nlsmp.on('playerJoin', (playerId) => {\n  if (DEVELOPERS.has(lsmp.getPlayerLsmpId(playerId))) {\n    lsmp.setPlayerDev(playerId, true);\n  }\n});"
                    }
                  ]
                },
                {
                  "title": "Press Ctrl+Shift+I in game",
                  "md": "Or type `devtools` in the F8 console. Your web browser opens a local page, `http://127.0.0.1:9222/`, that lists the pages you can inspect. If you are not allowed, the console says why."
                },
                {
                  "title": "Open a page in Chrome or Edge",
                  "md": "Each page has a **Copy link** button: paste the link in the address bar of Chrome or Edge. Or open `chrome://inspect` (`edge://inspect`): the pages appear under *Remote Target*, each with an **inspect** link."
                }
              ]
            },
            {
              "type": "table",
              "headers": [
                "Listed as",
                "What it is"
              ],
              "rows": [
                [
                  "**Gameserver UI (2D browsers)**",
                  "The surface that holds every 2D page of the server, each in its own frame. In the *Console*, pick the frame with the context selector (`top ▾`)."
                ],
                [
                  "**3D browser #id**",
                  "One entry per 3D browser."
                ]
              ]
            },
            {
              "type": "table",
              "headers": [
                "Console command (F8)",
                "What it does"
              ],
              "rows": [
                [
                  "`devtools`",
                  "Opens the access and the page that lists your pages. Same as Ctrl+Shift+I."
                ],
                [
                  "`devtools <port>`",
                  "The same on another port (`1024`–`65535`). The default is `9222`, or one of the nine after it when it is taken."
                ],
                [
                  "`devtools status`",
                  "Whether you are allowed, whether the access is open and where, and how many pages are listed."
                ],
                [
                  "`devtools close`",
                  "Closes the access and every DevTools window."
                ]
              ]
            },
            {
              "type": "list",
              "items": [
                "**Local only**: the access listens on `127.0.0.1`, and only once you ask for it.",
                "One DevTools window per page at a time.",
                "**A paused debugger freezes the page**; on the 2D surface, it freezes every 2D page of the server until you resume.",
                "*Ctrl+R* reloads a 3D page. On the 2D surface it is refused (it would reload every page): reload one page from its script with `browser:setUrl`.",
                "Popups opened by your pages are not listed."
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "A convenience, not a protection",
              "md": "The developer status and the `lsmp.devtools` permission keep DevTools away from ordinary players; they do not stop a modified client. Pages and client scripts run on the player's machine either way: never put a secret in them, and decide what matters on the server."
            }
          ]
        }
      ]
    },
    {
      "id": "publish",
      "title": "Publish",
      "icon": "🚀",
      "pages": [
        {
          "id": "publish-mod",
          "title": "Publish a mod on lsmp.gg",
          "eyebrow": "Publish",
          "lead": "Put a resource online for every LS:MP player: prepare the folder, upload it, and ship new versions. LS:MP checks it, packs it and serves it; you never build an archive yourself.",
          "blocks": [
            {
              "type": "text",
              "md": "A mod is a [resource folder](#resource-layout): the same folder that runs on your server or as a [local resource](#local-resources). Players get it with one click, in game and on the site; servers can run it too."
            },
            {
              "type": "table",
              "headers": [
                "",
                "Free mod",
                "Paid mod or subscription"
              ],
              "rows": [
                [
                  "Where",
                  "lsmp.gg → your profile → **My creations** → **Publish mod**",
                  "On Summum, the LS:MP store: create the product there. Your Summum mods are also listed in **My creations**, with a link to manage them."
                ],
                [
                  "Upload",
                  "The same uploader, the same checks",
                  "The same uploader, the same checks"
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Before you start",
              "md": "Your LS:MP account needs a **verified email address**: publishing stays closed until you open the activation link. Uploads are limited per 24 hours; **My creations** shows what is left."
            },
            {
              "type": "heading",
              "text": "Prepare the folder",
              "level": 2,
              "id": "publish-prepare"
            },
            {
              "type": "list",
              "items": [
                "**Test it first**, as a [local resource](#local-resources) in Story mode and, if it has a server part, on your own server.",
                "**One folder, with `manifest.json` at its top.** Select that folder itself, not the one above it.",
                "**Without a manifest**, only `stream/` is sent: right for a pure asset mod (a map, vehicles), whose `.ydr`, `.ytd`, `.ymap`… are streamed from there. Data files (`.meta`, `.gxt2`) and scripts need a manifest.",
                "Game assets are only ever streamed from `stream/`.",
                "Leave out what players must not get: `node_modules`, `.git` and similar folders are dropped anyway, but secrets in client files are not. Server-side keys belong to the server owner's configuration, not to your mod."
              ]
            },
            {
              "type": "tree",
              "tree": "my-mod/                 ← select this folder\n├─ manifest.json\n├─ client/\n├─ server/\n├─ web/\n└─ stream/"
            },
            {
              "type": "heading",
              "text": "Publish a free mod",
              "level": 2,
              "id": "publish-steps"
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Details",
                  "md": "Title, **address** (`lsmp.gg/mods/<address>`: 3 to 40 lowercase letters, digits and single hyphens), target (**LS:MP servers**, **Singleplayer**, or both), category and sub-categories, description, and the other free mods of yours it depends on, if any. The address is final once the mod is published."
                },
                {
                  "title": "Media",
                  "md": "Images and videos for the mod's page; the first one is the cover. Optional: you can add them later from **My creations**."
                },
                {
                  "title": "Folder",
                  "md": "Drop the folder, or browse to it. The upload is encrypted."
                },
                {
                  "title": "Review",
                  "md": "LS:MP checks the folder in your browser before anything is sent: what it delivers (client scripts, server scripts, assets) and what would make it fail. **Errors** block the upload: fix them in your folder, then select it again with **Change**. **Warnings** and notes do not block. Choose what to protect: **3D models**, **textures**, **resources**."
                },
                {
                  "title": "Progress",
                  "md": "Three phases: **Upload**, **Packaging** (LS:MP builds the client package and, if needed, the server package), **Publishing**. You may have to wait for a packager when many uploads run at once."
                },
                {
                  "title": "Finish",
                  "md": "*Your mod is live*: players can get it now. Copy the link of its page to share it."
                }
              ]
            },
            {
              "type": "heading",
              "text": "What the checks look at",
              "level": 2,
              "id": "publish-checks"
            },
            {
              "type": "text",
              "md": "The same rules as a server's packaging, so a mod that loads on your server publishes cleanly:"
            },
            {
              "type": "list",
              "items": [
                "`manifest.json` must be valid JSON; unknown or old keys are reported ([Manifest keys](#resource-layout/layout-keys)).",
                "Every script and file the manifest names must exist inside the folder; paths cannot lead outside it.",
                "Size limits per file, in total, in number of files and in folder depth, set by the service and shown when you drop the folder.",
                "Two files cannot share the same path.",
                "An upload whose content already exists is refused as *already published*."
              ]
            },
            {
              "type": "heading",
              "text": "New versions",
              "level": 2,
              "id": "publish-versions"
            },
            {
              "type": "text",
              "md": "In **My creations**, open the mod and press **Add version**: give it a version number, then drop the folder again. The same checks run, and the new version goes live at the end. Players see *Update available* in their library; **Version history** lists every release."
            },
            {
              "type": "heading",
              "text": "Mods on servers",
              "level": 2,
              "id": "publish-servers"
            },
            {
              "type": "list",
              "items": [
                "A mod for **LS:MP servers** runs like any resource. Server owners get it for their server on lsmp.gg; the server downloads it at start, and it shows in the `resources` console list as a `mod`. Its resource name, the one scripts see (`lsmp.getResourceName()`, `rsc://`, dependencies, logs), is its slug followed by its mod id: `las-venturas-41` for the mod `las-venturas` with id 41.",
                "Its settings in the server's [`resources.json`](#operator-settings) and its data (data folder, storage, capabilities) are keyed `mod.<name>` (`mod.las-venturas-41`), so they never mix with a local folder of the same name.",
                "If a server has a local resource folder with the same name as a mod, the mod is not loaded, and the log names both.",
                "Your server scripts run in the server's sandbox by default: ask only for what you need, and document it for server owners ([Capabilities](#capabilities))."
              ]
            },
            {
              "type": "heading",
              "text": "Remove a mod",
              "level": 2,
              "id": "publish-remove"
            },
            {
              "type": "text",
              "md": "**Delete this mod** in **My creations** withdraws every version. Players who have it keep it for 72 hours, then its files are purged. Its address stays reserved."
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "Let players try it",
              "md": "A marketplace product with a client part gets a **Try in game** button. Give your mod a short `TRY` branch that takes the player straight to what you made: see [Marketplace trials](#marketplace-trials)."
            }
          ]
        },
        {
          "id": "marketplace-trials",
          "title": "Marketplace trials",
          "eyebrow": "Publish",
          "lead": "Players can try a marketplace mod in game before they buy it. What that trial world is, and the few lines that make your mod shine in it.",
          "blocks": [
            {
              "type": "text",
              "md": "Every marketplace product with a **client part** (assets in `stream/`, or client scripts) gets a **Try in game** button. It starts a world built for that one mod: LS:MP loads the mod's client part and **nothing else**, and your client scripts know where they are: [`lsmp.gameType()`](#core-utils) returns `\"TRY\"`. Their job is to take the player straight to what you sell: an interior, a map, a vehicle, an interface."
            },
            {
              "type": "heading",
              "text": "The trial world",
              "level": 2,
              "id": "trial-world"
            },
            {
              "type": "list",
              "items": [
                "**A fresh session, without a save**: no missions, no progress, no character of the player's. The map is the one your mod targets: the multiplayer map for a server mod, the story-mode map for a single-player mod.",
                "**Only LS:MP scripts run**: your mod's Lua and JavaScript. No game mission script runs, including one your mod would try to start.",
                "**Your mod, alone**: no other mod, none of the player's single-player mods, no `.asi` plugin.",
                "**No server**: the server part of your mod is never downloaded. `emitServer`, server calls, network [meta](#meta) and [voice](#voice) have no effect, exactly as in Story mode.",
                "**No pause menu, no replay recording.** **F1** (or the key the player chose for the LS:MP menu) opens the LS:MP menu: *Resume*, *Get it*, *End trial*. A banner says so all along.",
                "**Discord** shows the player as trying your mod, by its name."
              ]
            },
            {
              "type": "heading",
              "text": "Where the player arrives",
              "level": 2,
              "id": "trial-arrival"
            },
            {
              "type": "text",
              "md": "LS:MP sets the scene **once**, when the player arrives. Everything can be changed with [natives](#natives): they all work normally in a trial."
            },
            {
              "type": "table",
              "headers": [
                "",
                "Default",
                "To change it"
              ],
              "rows": [
                [
                  "Position",
                  "Legion Square: `195.0, -933.7, 30.7`, heading `145`",
                  "`setEntityCoordsNoOffset`, `setEntityHeading`: [below](#marketplace-trials/trial-teleport)"
                ],
                [
                  "Health",
                  "Invincible",
                  "`setPlayerInvincible(playerId(), false)`"
                ],
                [
                  "Wanted level",
                  "Capped at 0",
                  "`setMaxWantedLevel`"
                ],
                [
                  "Clock",
                  "13:00, paused",
                  "`setClockTime`, `pauseClock(false)`"
                ],
                [
                  "Weather",
                  "`EXTRASUNNY`, persistent",
                  "`setWeatherTypeNowPersist`, `clearWeatherTypePersist`"
                ],
                [
                  "Death, arrest",
                  "If your script removed invincibility, LS:MP stands the player up again at the arrival point a few seconds after a death",
                  ""
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Take the player to your content",
              "level": 2,
              "id": "trial-teleport"
            },
            {
              "type": "text",
              "md": "While the player is placed, the LS:MP loading screen stays up: at least 1.2 seconds once your scripts have started, then until the player stands still, 6 seconds at most. If your script moved the player more than 20 m, LS:MP then loads the area around them (up to 20 seconds) before the screen fades in.\n\nSo **teleport at the top level of your client script**, or within its first frames: the player never sees Legion Square. The player is frozen during that window: you can teleport them, not walk them."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "client/main.lua",
                  "lang": "lua",
                  "code": "if lsmp.gameType() == \"TRY\" then\n  -- Marketplace trial: bring the player straight to the interior.\n  local ped = playerPedId()\n  setEntityCoordsNoOffset(ped, -1520.4, 110.1, 50.9, false, false, false)\n  setEntityHeading(ped, 90.0)\nend"
                },
                {
                  "label": "client/main.js",
                  "lang": "js",
                  "code": "if (lsmp.gameType() === 'TRY') {\n  // Marketplace trial: bring the player straight to the interior.\n  const ped = playerPedId();\n  setEntityCoordsNoOffset(ped, -1520.4, 110.1, 50.9, false, false, false);\n  setEntityHeading(ped, 90.0);\n}"
                }
              ]
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "There is nothing to spawn",
              "md": "A trial has no arrival to script: LS:MP places the player and closes the loading screen itself. The spawn and loading-screen functions of a [server arrival](#local-player) do nothing here."
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "Give your mod a TRY branch",
              "md": "Without one, the player lands on Legion Square and sees nothing of what you sell: your assets are streamed, but nobody is there to look at them."
            },
            {
              "type": "heading",
              "text": "Trials, from the player's side",
              "level": 2,
              "id": "trial-player"
            },
            {
              "type": "list",
              "items": [
                "Trials belong to an LS:MP account: guests cannot try mods.",
                "Free trials are limited per account each **week**; past the quota, the menu says so.",
                "A player who already owns the mod simply gets it, without using a trial.",
                "A trial always runs the **latest published version** with a client part. A server-only mod has nothing to show, and gets no button.",
                "Your protected assets stay protected during a trial, and your server code is never sent."
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Single-player mods run in Story mode too",
              "md": "The client scripts of single-player mods also run in Story mode, once the world is visible. There, `lsmp.gameType()` returns `\"SP\"`: check it before relying on anything a server provides."
            }
          ]
        },
        {
          "id": "benefits",
          "title": "In-game benefits",
          "eyebrow": "Server & client · Lua & JS",
          "lead": "Sell ranks, currency or kits for your server on Summum, on the store or without leaving the game, and deliver them from a server script without ever losing a purchase.",
          "blocks": [
            {
              "type": "text",
              "md": "An **in-game benefit** is something a player buys for **your** server: a VIP rank, a stack of in-game money, a vehicle. It is a product of your Summum store: the player buys it **on Summum**, on its product page or in game, and Summum takes the payment. LS:MP then carries the purchase to your server, where a server script **applies** it and **confirms** it. LS:MP keeps track of every purchase until a script confirms it, so a crash, a restart or a disconnection only delays a delivery, never loses it."
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Create the benefit",
                  "md": "In your Summum store, create a product with the LS:MP integration, choose **In-game benefit**, attach it to your server and give it a **benefit server key**: the name your scripts use, such as `vip-month` or `cash-100k` (lowercase letters, digits and hyphens between words). Restart the server once after its first benefit: selling is switched on at start."
                },
                {
                  "title": "Sell it",
                  "md": "Players buy it on its Summum page. To sell it **in game** as well, a client script puts its key in a cart and opens it: see [Selling in game](#benefits/benefits-in-game)."
                },
                {
                  "title": "Apply it",
                  "md": "When the buyer is connected, the [`benefitGrant`](#engine-events/ev-benefit-grant) event gives your server script the purchase, wherever it was bought. Apply it in your own data (a rank, a balance...)."
                },
                {
                  "title": "Confirm it",
                  "md": "Call [`lsmp.benefits.consume`](#benefits/fn-benefits-consume) with the purchase id once your change is saved. Until then, the purchase is presented again at each of the player's sessions."
                }
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "What the server needs",
              "md": "The server must be connected to the LS:MP network with its token ([server.cfg](#server-cfg)). A server that sells benefits always verifies its players: a paid benefit is never delivered to an account a client only claims. The resource needs the `benefits.read` [capability](#capabilities) for the events and `fetch`, and `benefits.consume` to confirm. Marketplace mods do not get `benefits.read` unless the server owner grants it."
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "A complete resource",
              "md": "The `in-game-benefit` resource of the server download does all of this: `/shop` sells VIP and cash in game, the server applies each purchase exactly once, and takes back what is refunded. See [Example resources](#examples)."
            },
            {
              "type": "heading",
              "text": "The life of a purchase",
              "level": 2,
              "id": "benefits-lifecycle"
            },
            {
              "type": "table",
              "headers": [
                "Status",
                "Meaning",
                "Your script"
              ],
              "rows": [
                [
                  "`pending`",
                  "Paid, not yet received by this server.",
                  "Apply it, then `consume`."
                ],
                [
                  "`delivered`",
                  "Received by this server.",
                  "Apply it, then `consume`."
                ],
                [
                  "`consumed`",
                  "Applied and confirmed.",
                  "Nothing."
                ],
                [
                  "`revoked`",
                  "Refunded before it was confirmed.",
                  "Nothing to take back."
                ],
                [
                  "`revoking`",
                  "Refunded after it was confirmed.",
                  "Take it back, then `consumeRevocation`."
                ],
                [
                  "`reversed`",
                  "Taken back and confirmed.",
                  "Nothing."
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "At least once",
              "md": "A purchase is presented once per session until it is confirmed. A script that applies a benefit and stops before confirming will see it again at the player's next session. Make applying **idempotent**: store the purchase `id` together with the change, in the same transaction, and skip an id you already applied."
            },
            {
              "type": "heading",
              "text": "Delivering on the server",
              "level": 2,
              "id": "benefits-events"
            },
            {
              "type": "text",
              "md": "[`benefitGrant`](#engine-events/ev-benefit-grant) `(lsmpId, benefit)` presents a purchase to apply, [`benefitRevoke`](#engine-events/ev-benefit-revoke) `(lsmpId, benefit)` one to take back. They fire for a **connected** player: for what is outstanding when they join, and live when they buy while playing, on the product page or in game. `benefit` is a [`Benefit`](#benefits/benefit). Only resources holding `benefits.read` receive them, and each of them receives every purchase of the server: handle the keys of your resource only, and never confirm the others."
            },
            {
              "type": "function",
              "name": "lsmp.benefits.fetch",
              "id": "fn-benefits-fetch",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.benefits.fetch(lsmpId [, opts] [, cb]) --> {Benefit}, err",
                "js": "lsmp.benefits.fetch(lsmpId: number|string, opts?: BenefitFetchOptions): Promise<Benefit[]>"
              },
              "summary": "Read the outstanding purchases of an account on this server.",
              "md": "Outstanding means `pending`, `delivered` or `revoking`: what a script still has to do. Oldest first. The answer may be a page: read again with `after` set to the last `id` you received, until an empty list. Useful to reconcile at a time of your choosing; the events already present everything to connected players. A guest account has nothing.\n\nNeeds the `benefits.read` [capability](#capabilities).",
              "params": [
                {
                  "name": "lsmpId",
                  "type": "lsmpId",
                  "desc": "The account: the number from [`getPlayerLsmpId`](#players/fn-get-player-lsmp-id), or its string form."
                },
                {
                  "name": "opts",
                  "type": "BenefitFetchOptions",
                  "desc": "See [`BenefitFetchOptions`](#benefits/benefit-fetch-options).",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "{Benefit}, err",
                  "desc": "A list of [`Benefit`](#benefits/benefit), or `nil` and a failure code.",
                  "only": "lua"
                },
                {
                  "type": "Promise<Benefit[]>",
                  "desc": "Resolves with a list of [`Benefit`](#benefits/benefit); rejects with a failure code.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`unavailable`",
                      "This server sells no benefits, or the LS:MP network cannot be reached."
                    ],
                    [
                      "`limit`",
                      "Too many requests in a short time."
                    ],
                    [
                      "`timeout`",
                      "No answer in time."
                    ],
                    [
                      "`invalid`",
                      "The account or the cursor is not valid."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `benefits.read`."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- Every purchase an account still has to receive or give back, page by page.\n-- Call it from an event or command handler: fetch waits for LS:MP there.\nlocal function outstanding(lsmpId)\n  local all, after = {}, 0\n  while true do\n    local page, err = lsmp.benefits.fetch(lsmpId, { after = after })\n    if not page then return nil, err end\n    if #page == 0 then return all end\n    for _, b in ipairs(page) do all[#all + 1] = b end\n    after = page[#page].id\n  end\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// Every purchase an account still has to receive or give back, page by page.\nasync function outstanding(lsmpId) {\n  const all = [];\n  for (let after = 0; ;) {\n    const page = await lsmp.benefits.fetch(lsmpId, { after });\n    if (page.length === 0) return all;\n    all.push(...page);\n    after = page[page.length - 1].id;\n  }\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.benefits.consume",
              "id": "fn-benefits-consume",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.benefits.consume(id [, lsmpId] [, cb]) --> BenefitConsumeResult, err",
                "js": "lsmp.benefits.consume(id: number, lsmpId?: number|string): Promise<BenefitConsumeResult>"
              },
              "summary": "Confirm that a purchase was applied.",
              "md": "Call it **after** your change is saved. The confirmation is written to disk before it is sent: if the network cannot be reached it is kept and sent later (`queued: true`), and the purchase is not presented again in the meantime. Give the `lsmpId` you applied it to: the network then refuses a purchase that belongs to someone else.\n\nIf the purchase was refunded in the meantime, the result has `status: \"revoking\"`: take the benefit back and confirm with [`consumeRevocation`](#benefits/fn-benefits-consume-revocation).\n\nNeeds the `benefits.consume` [capability](#capabilities).",
              "params": [
                {
                  "name": "id",
                  "type": "int",
                  "desc": "The purchase `id`."
                },
                {
                  "name": "lsmpId",
                  "type": "lsmpId",
                  "desc": "The account it was applied to.",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "BenefitConsumeResult, err",
                  "desc": "A [`BenefitConsumeResult`](#benefits/benefit-consume-result), or `nil` and a failure code.",
                  "only": "lua"
                },
                {
                  "type": "Promise<BenefitConsumeResult>",
                  "desc": "Resolves with a [`BenefitConsumeResult`](#benefits/benefit-consume-result); rejects with a failure code.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "Not a purchase of this server."
                    ],
                    [
                      "`invalid`",
                      "Not this account's purchase, or the id is not valid."
                    ],
                    [
                      "`unavailable`",
                      "This server sells no benefits."
                    ],
                    [
                      "`io`",
                      "The confirmation could not be written to the server's disk: keep your own record and try again."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `benefits.consume`."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.on(\"benefitGrant\", function(lsmpId, benefit)\n  if benefit.key ~= \"cash-100k\" then return end   -- another resource's benefit: leave it\n  -- applyOnce saves the change with the purchase id, and skips an id it already applied.\n  if not Wallet.applyOnce(benefit.id, lsmpId, 100000 * benefit.quantity) then return end\n  local res, err = lsmp.benefits.consume(benefit.id, lsmpId)\n  if not res then\n    lsmp.warn(\"purchase \" .. benefit.id .. \" applied, not confirmed yet: \" .. err)\n  elseif res.status == \"revoking\" then\n    -- Refunded in the meantime: take it back at once.\n    Wallet.revertOnce(benefit.id, lsmpId)\n    lsmp.benefits.consumeRevocation(benefit.id, lsmpId)\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.on('benefitGrant', async (lsmpId, benefit) => {\n  if (benefit.key !== 'cash-100k') return;   // another resource's benefit: leave it\n  // applyOnce saves the change with the purchase id, and skips an id it already applied.\n  if (!(await Wallet.applyOnce(benefit.id, lsmpId, 100000 * benefit.quantity))) return;\n  try {\n    const res = await lsmp.benefits.consume(benefit.id, lsmpId);\n    if (res.status === 'revoking') {\n      // Refunded in the meantime: take it back at once.\n      await Wallet.revertOnce(benefit.id, lsmpId);\n      await lsmp.benefits.consumeRevocation(benefit.id, lsmpId);\n    }\n  } catch (err) {\n    lsmp.warn(`purchase ${benefit.id} applied, not confirmed yet: ${err.code}`);\n  }\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.benefits.consumeRevocation",
              "id": "fn-benefits-consume-revocation",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.benefits.consumeRevocation(id [, lsmpId] [, cb]) --> BenefitConsumeResult, err",
                "js": "lsmp.benefits.consumeRevocation(id: number, lsmpId?: number|string): Promise<BenefitConsumeResult>"
              },
              "summary": "Confirm that a refunded purchase was taken back.",
              "md": "For a purchase in the `revoking` status, after your reversal is saved. Same guarantees as [`consume`](#benefits/fn-benefits-consume).\n\nNeeds the `benefits.consume` [capability](#capabilities).",
              "params": [
                {
                  "name": "id",
                  "type": "int",
                  "desc": "The purchase `id`."
                },
                {
                  "name": "lsmpId",
                  "type": "lsmpId",
                  "desc": "The account it was taken back from.",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "BenefitConsumeResult, err",
                  "desc": "A [`BenefitConsumeResult`](#benefits/benefit-consume-result), or `nil` and a failure code.",
                  "only": "lua"
                },
                {
                  "type": "Promise<BenefitConsumeResult>",
                  "desc": "Resolves with a [`BenefitConsumeResult`](#benefits/benefit-consume-result); rejects with a failure code.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "Not a purchase of this server."
                    ],
                    [
                      "`invalid`",
                      "The purchase is not refunded, or not this account's."
                    ],
                    [
                      "`unavailable`",
                      "This server sells no benefits."
                    ],
                    [
                      "`io`",
                      "The confirmation could not be written to the server's disk."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `benefits.consume`."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.on(\"benefitRevoke\", function(lsmpId, benefit)\n  if benefit.key ~= \"cash-100k\" then return end\n  Wallet.revertOnce(benefit.id, lsmpId)\n  lsmp.benefits.consumeRevocation(benefit.id, lsmpId)\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.on('benefitRevoke', async (lsmpId, benefit) => {\n  if (benefit.key !== 'cash-100k') return;\n  await Wallet.revertOnce(benefit.id, lsmpId);\n  await lsmp.benefits.consumeRevocation(benefit.id, lsmpId);\n});"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Selling in game",
              "level": 2,
              "id": "benefits-in-game"
            },
            {
              "type": "text",
              "md": "A client script can sell your benefits without the player leaving the game. It fills a **cart** with benefit keys and opens it: LS:MP prepares a Summum order for the player's LS:MP account and shows Summum's checkout in the LS:MP **secure payment window**. Sign-in, payment and bank checks all happen in that window, and your script sees none of it. A completed payment reaches your server through `benefitGrant`, like a purchase made on the product page.\n\nA cart names each benefit by its **key**, the same `key` that `benefitGrant` reports. LS:MP finds the product among the benefits on sale for **the server the player is connected to**: your scripts never handle store product ids, and can only sell their own server's benefits."
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "The client never learns whether the player paid",
              "md": "A cart only tells you that its window was shown, then closed, and who closed it. A closed window says nothing about the payment: the player may have paid, given up, or still be waiting for their bank. Never grant anything from the client: deliver on the server, where the same code also delivers what the player bought on the product page."
            },
            {
              "type": "heading",
              "text": "Building a cart",
              "level": 3,
              "id": "benefits-cart"
            },
            {
              "type": "function",
              "name": "lsmp.createCart",
              "id": "fn-create-cart",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.createCart() --> Cart",
                "js": "lsmp.createCart(): Cart"
              },
              "summary": "Create an empty cart owned by this resource.",
              "md": "Nothing is sent or checked until the cart is opened. A resource can keep several carts, but the client has only one payment window at a time.",
              "returns": {
                "type": "Cart",
                "desc": "A new, empty cart, in the `\"idle\"` state."
              }
            },
            {
              "type": "function",
              "name": "cart.add",
              "id": "fn-cart-add",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "cart:add(key [, quantity]) --> Cart",
                "js": "cart.add(key: string, quantity: number = 1): Cart"
              },
              "summary": "Add a benefit, or more of one already in the cart.",
              "md": "A cart holds at most **50** different benefits, and at most **99** of each. Going over raises a `RangeError`. A key that is not well formed raises an error at once; a well-formed key that this server does not sell is refused when the cart opens (`invalid`).",
              "params": [
                {
                  "name": "key",
                  "type": "string",
                  "desc": "The benefit server key, exactly as set in the product editor (for example `\"vip-month\"`): 1 to 63 letters, digits, `_` or `-`. Case matters."
                },
                {
                  "name": "quantity",
                  "type": "int",
                  "desc": "How many to add, `1` to `99`.",
                  "optional": true,
                  "default": "1"
                }
              ],
              "returns": {
                "type": "Cart",
                "desc": "The cart itself, so that calls can be chained."
              }
            },
            {
              "type": "function",
              "name": "cart.remove",
              "id": "fn-cart-remove",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "cart:remove(key) --> boolean",
                "js": "cart.remove(key: string): boolean"
              },
              "summary": "Remove a benefit line.",
              "params": [
                {
                  "name": "key",
                  "type": "string",
                  "desc": "The key of the benefit to remove."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the benefit was in the cart."
              }
            },
            {
              "type": "function",
              "name": "cart.clear",
              "id": "fn-cart-clear",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "cart:clear() --> Cart",
                "js": "cart.clear(): Cart"
              },
              "summary": "Remove every benefit.",
              "returns": {
                "type": "Cart",
                "desc": "The cart itself, so that calls can be chained."
              }
            },
            {
              "type": "function",
              "name": "cart.getItems",
              "id": "fn-cart-get-items",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "cart:getItems() --> {CartItem}",
                "js": "cart.getItems(): CartItem[]"
              },
              "summary": "The lines of the cart, in the order they were added.",
              "returns": {
                "type": "CartItem[]",
                "desc": "A list of [`CartItem`](#benefits/cart-item), new on each call: changing it does not change the cart."
              }
            },
            {
              "type": "function",
              "name": "cart.getState",
              "id": "fn-cart-get-state",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "cart:getState() --> string",
                "js": "cart.getState(): string"
              },
              "summary": "Where the cart stands.",
              "returns": {
                "type": "string",
                "desc": "`\"idle\"` (never opened), `\"opening\"` (the order is being prepared), `\"open\"` (the payment window is shown) or `\"closed\"` (its last opening is over; it can be opened again)."
              }
            },
            {
              "type": "heading",
              "text": "Opening the payment window",
              "level": 3,
              "id": "benefits-open"
            },
            {
              "type": "function",
              "name": "cart.open",
              "id": "fn-cart-open",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "cart:open([cb]) --> string, err",
                "js": "cart.open(): Promise<string>"
              },
              "summary": "Show the cart in the LS:MP secure payment window, and wait until it closes.",
              "md": "Each opening sends the items the cart holds at that moment. LS:MP checks them with Summum first: the window appears a moment later, or the opening is refused. Asynchronous: see [Conventions](#conventions).\n\nThe result is how a window **that was shown** closed: `\"player\"` (the player closed it), `\"script\"` (`cart.close`) or `\"error\"` (the window was lost). It never says whether the player paid. A refusal before the window appears rejects with one of these codes, the error message giving the precise reason:",
              "returns": [
                {
                  "type": "string, err",
                  "desc": "`\"player\"`, `\"script\"` or `\"error\"`; `nil` and a code when the window could not be shown.",
                  "only": "lua"
                },
                {
                  "type": "Promise<string>",
                  "desc": "Resolves with `\"player\"`, `\"script\"` or `\"error\"`; rejects with a code when the window could not be shown.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Code",
                    "Meaning"
                  ],
                  "rows": [
                    [
                      "`invalid`",
                      "The cart is empty, or a key is not a benefit on sale on this server."
                    ],
                    [
                      "`limit`",
                      "This cart, or another one, already has a window open or being prepared; or too many openings or purchases in a short time."
                    ],
                    [
                      "`denied`",
                      "The player is a guest or not signed in to LS:MP, or the opening was cancelled by `cart.close`."
                    ],
                    [
                      "`unavailable`",
                      "The player is not on a server that sells benefits, or this server has not verified the player yet; payments are unavailable right now; or the game has plugins loaded that rule payments out."
                    ],
                    [
                      "`error`",
                      "Anything else that kept the window from appearing."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- /cash [packs]: up to 10 packs of the benefit \"cash-100k\" in one cart.\nlocal REFUSED = {\n  denied = \"Sign in to LS:MP to buy: guests cannot pay.\",\n  limit = \"A payment window is already open, or one just closed.\",\n  unavailable = \"Payments are not available right now.\",\n}\n\nlsmp.registerCommand(\"cash\", { help = \"Buy in-game cash\" }, function(args)\n  local packs = math.min(math.max(math.floor(tonumber(args[1]) or 1), 1), 10)\n  local closedBy, err = lsmp.createCart():add(\"cash-100k\", packs):open()\n  if not closedBy then\n    lsmp.warn(REFUSED[err] or (\"the payment window did not open: \" .. err))\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// /cash [packs]: up to 10 packs of the benefit \"cash-100k\" in one cart.\nconst REFUSED = {\n  denied: 'Sign in to LS:MP to buy: guests cannot pay.',\n  limit: 'A payment window is already open, or one just closed.',\n  unavailable: 'Payments are not available right now.',\n};\n\nlsmp.registerCommand('cash', { help: 'Buy in-game cash' }, async (args) => {\n  const packs = Math.min(Math.max(parseInt(args[0], 10) || 1, 1), 10);\n  try {\n    await lsmp.createCart().add('cash-100k', packs).open();\n  } catch (err) {\n    lsmp.warn(REFUSED[err.code] ?? `the payment window did not open: ${err.code}`);\n  }\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "cart.close",
              "id": "fn-cart-close",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "cart:close() --> boolean",
                "js": "cart.close(): boolean"
              },
              "summary": "Close this cart's window, or cancel its opening.",
              "md": "A window that is shown closes and `open` resolves with `\"script\"`. A cart still being prepared is cancelled: `open` rejects with `denied`.",
              "returns": {
                "type": "boolean",
                "desc": "`true` if there was a window to close or an opening to cancel."
              }
            },
            {
              "type": "heading",
              "text": "Rules and limits",
              "level": 3,
              "id": "benefits-rules"
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "**One window at a time** on the client, whichever resource opened it.",
                "**Keys, not products.** A key sells the benefit on sale under it on this server, whatever its store product: re-publishing or replacing a product changes nothing in your scripts. Should two products of the server grant the same key, the most recently published one on sale is sold.",
                "**Exclusive input.** While the window is open, the game, your scripts and your pages receive no input. No script can draw over the window, read it or type into it.",
                "**Pop-ups stay in the window.** A link of the payment page that opens a new window (the terms of sale, some payment methods) opens inside the payment window, under the same bar, one at a time. Closing it brings the payment back.",
                "**Cooldown.** After a window closes, scripts wait a few seconds before they can open a new one, and the number of openings per minute is limited. Open a cart when the player asks for it, with a command or a click in your interface, never on a timer.",
                "**When the resource stops**, a cart still being prepared is cancelled. A window already shown stays until the player closes it."
              ]
            },
            {
              "type": "heading",
              "text": "Complete example",
              "level": 2,
              "id": "benefits-example"
            },
            {
              "type": "text",
              "md": "VIP by the month, sold in game with `/vip` and delivered on the server exactly once: the purchase id is saved with the change, so a purchase presented again after a crash is only confirmed. A refunded purchase comes back through `benefitRevoke` (see [`consumeRevocation`](#benefits/fn-benefits-consume-revocation)); the `in-game-benefit` resource handles that too."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "server/main.lua",
                  "lang": "lua",
                  "code": "-- VIP by the month: the benefit whose server key is \"vip-month\".\nlocal DAY_MS = 24 * 60 * 60 * 1000\n\nlsmp.on(\"benefitGrant\", function(lsmpId, benefit)\n  if benefit.key ~= \"vip-month\" then return end   -- another resource's benefit: leave it\n\n  local key = \"vip:\" .. lsmpId\n  local vip = lsmp.storage.get(key) or { untilMs = 0, applied = {} }\n  local id = tostring(benefit.id)\n  if not vip.applied[id] then\n    -- Counted from the payment: a player who paid while away loses no day.\n    vip.untilMs = math.max(vip.untilMs, benefit.purchasedAtMs) + 30 * DAY_MS * benefit.quantity\n    vip.applied[id] = true   -- the id is saved in the same write as the change\n    if not lsmp.storage.set(key, vip) or not lsmp.storage.flush() then\n      return   -- not on disk: the purchase comes back at the next session\n    end\n  end\n\n  -- Applied now or at an earlier session: confirm it.\n  local res, err = lsmp.benefits.consume(benefit.id, lsmpId)\n  if not res then\n    lsmp.warn((\"purchase %d applied, not confirmed yet: %s\"):format(benefit.id, err))\n  end\nend)"
                },
                {
                  "label": "client/main.lua",
                  "lang": "lua",
                  "code": "-- /vip: sells the benefit \"vip-month\" without leaving the game.\nlsmp.registerCommand(\"vip\", { help = \"Buy 30 days of VIP\" }, function()\n  local closedBy, err = lsmp.createCart():add(\"vip-month\"):open()\n  if closedBy == \"player\" then\n    -- Not a proof of payment: the server applies the VIP when benefitGrant brings it.\n    lsmp.log(\"If you paid, your VIP arrives in a moment.\")\n  elseif not closedBy then\n    lsmp.warn(\"the payment window did not open: \" .. err)\n  end\nend)"
                },
                {
                  "label": "server/main.js",
                  "lang": "js",
                  "code": "// VIP by the month: the benefit whose server key is \"vip-month\".\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\nlsmp.on('benefitGrant', async (lsmpId, benefit) => {\n  if (benefit.key !== 'vip-month') return;   // another resource's benefit: leave it\n\n  const key = `vip:${lsmpId}`;\n  const vip = lsmp.storage.get(key) ?? { untilMs: 0, applied: {} };\n  if (!vip.applied[benefit.id]) {\n    // Counted from the payment: a player who paid while away loses no day.\n    vip.untilMs = Math.max(vip.untilMs, benefit.purchasedAtMs) + 30 * DAY_MS * benefit.quantity;\n    vip.applied[benefit.id] = true;   // the id is saved in the same write as the change\n    if (!lsmp.storage.set(key, vip)) return;   // not saved: it comes back at the next session\n    try {\n      await lsmp.storage.flush();\n    } catch {\n      return;\n    }\n  }\n\n  // Applied now or at an earlier session: confirm it.\n  try {\n    await lsmp.benefits.consume(benefit.id, lsmpId);\n  } catch (err) {\n    lsmp.warn(`purchase ${benefit.id} applied, not confirmed yet: ${err.code}`);\n  }\n});"
                },
                {
                  "label": "client/main.js",
                  "lang": "js",
                  "code": "// /vip: sells the benefit \"vip-month\" without leaving the game.\nlsmp.registerCommand('vip', { help: 'Buy 30 days of VIP' }, async () => {\n  try {\n    const closedBy = await lsmp.createCart().add('vip-month').open();\n    // Not a proof of payment: the server applies the VIP when benefitGrant brings it.\n    if (closedBy === 'player') lsmp.log('If you paid, your VIP arrives in a moment.');\n  } catch (err) {\n    lsmp.warn(`the payment window did not open: ${err.code}`);\n  }\n});"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Shapes",
              "level": 2,
              "id": "benefits-shapes"
            },
            {
              "type": "heading",
              "text": "Benefit",
              "level": 3,
              "id": "benefit"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`id`",
                  "int",
                  "—",
                  "The purchase id: unique across LS:MP, increasing. Use it to apply each purchase once."
                ],
                [
                  "`key`",
                  "string",
                  "—",
                  "The key you gave the benefit on lsmp.gg. Ignore the keys your resource does not handle."
                ],
                [
                  "`quantity`",
                  "int",
                  "—",
                  "How many units were bought."
                ],
                [
                  "`purchasedAtMs`",
                  "epochMs",
                  "—",
                  "When it was paid. Compute any expiry from it."
                ],
                [
                  "`status`",
                  "string",
                  "—",
                  "See [the life of a purchase](#benefits/benefits-lifecycle)."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "BenefitFetchOptions",
              "level": 3,
              "id": "benefit-fetch-options"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`after`",
                  "int",
                  "`0`",
                  "Return only purchases with a greater `id` (the next page)."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "BenefitConsumeResult",
              "level": 3,
              "id": "benefit-consume-result"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`id`",
                  "int",
                  "—",
                  "The purchase id."
                ],
                [
                  "`status`",
                  "string",
                  "—",
                  "The status after the call, or `\"queued\"` when the confirmation waits for the network."
                ],
                [
                  "`applied`",
                  "boolean",
                  "—",
                  "`false` when the purchase was already in that state (a repeated call)."
                ],
                [
                  "`queued`",
                  "boolean",
                  "—",
                  "`true` when the confirmation is kept and will be sent later."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "CartItem",
              "level": 3,
              "id": "cart-item"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`key`",
                  "string",
                  "—",
                  "The benefit server key."
                ],
                [
                  "`quantity`",
                  "int",
                  "—",
                  "How many, `1` to `99`."
                ]
              ]
            }
          ]
        }
      ]
    },
    {
      "id": "api-shared",
      "title": "Shared API",
      "icon": "🧩",
      "pages": [
        {
          "id": "events",
          "title": "Events",
          "eyebrow": "Shared · Lua & JS",
          "lead": "Local events between resources on one side, and network events between the server and clients.",
          "blocks": [
            {
              "type": "text",
              "md": "Events let resources talk without knowing each other. **Local** events (`emit`, `on`) stay on the side where they are emitted: the server, or one client, and reach both Lua and JavaScript resources there. **Network** events carry the direction in their name: a client sends to the server with `emitServer` and the server listens with `onClient`; the server sends to clients with `emitClient`, `emitAllClients` or `emitDimensionClients` and clients listen with `onServer`. To get an answer back, use [remote calls](#rpc) instead. The [Events and RPC guide](#events-guide) shows complete patterns."
            },
            {
              "type": "table",
              "headers": [
                "You want to",
                "Use"
              ],
              "rows": [
                [
                  "react to something LS:MP does (a player joins, a resource stops)",
                  "`lsmp.on` with an [engine event](#engine-events)"
                ],
                [
                  "notify other resources on the same side (Lua or JS)",
                  "`lsmp.emit` + `lsmp.on`"
                ],
                [
                  "tell the server something (client)",
                  "`lsmp.emitServer` (client) + `lsmp.onClient` (server)"
                ],
                [
                  "tell clients something (server)",
                  "`lsmp.emitClient` / `emitAllClients` / `emitDimensionClients` (server) + `lsmp.onServer` (client)"
                ],
                [
                  "ask and wait for an answer",
                  "[`lsmp.call` / `callServer` / `callClient`](#rpc)"
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "md": "An `emit` never reaches an `onServer` or `onClient` handler, and a network event never reaches an `on` handler. The same name can be used for both without conflict.",
              "title": "Local and network are separate"
            },
            {
              "type": "heading",
              "text": "Local events",
              "level": 2,
              "id": "local"
            },
            {
              "type": "function",
              "name": "lsmp.on",
              "id": "fn-on",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(name, fn [, filter]) --> function",
                "js": "lsmp.on(name: string, fn: Function, filter?: MetaFilter): () => boolean"
              },
              "summary": "Subscribes to a local event or an engine event, and returns the function that unsubscribes.",
              "md": "The handler receives the arguments given to `emit` (or the [engine event](#engine-events)'s arguments). The same `(name, fn)` pair is only registered once. A handler that raises is logged with its resource name and the other handlers still run. In Lua the handler runs in its own coroutine, so it may wait.",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name. Engine event names are allowed here."
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The handler, `fn(...args)`."
                },
                {
                  "name": "filter",
                  "type": "MetaFilter",
                  "optional": true,
                  "desc": "Only for `metaChange`: `{ scope, key, target }`. See [`metaChange`](#engine-events/ev-meta-change)."
                }
              ],
              "returns": [
                {
                  "type": "function",
                  "desc": "The unsubscribe function; it returns `true` if it removed the handler.",
                  "only": "lua"
                },
                {
                  "type": "() => boolean",
                  "desc": "The unsubscribe function; it returns `true` if it removed the handler.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.on(\"shop:purchase\", function(playerId, item, price)\n  lsmp.log((\"%d bought %s for $%d\"):format(playerId, item, price))\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.on(\"shop:purchase\", (playerId, item, price) => {\n  lsmp.log(`${playerId} bought ${item} for $${price}`);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.once",
              "id": "fn-once",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.once(name, fn [, filter]) --> function",
                "js": "lsmp.once(name: string, fn: Function, filter?: MetaFilter): () => boolean"
              },
              "summary": "Like `lsmp.on`, but the handler is removed just before its first call.",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name. Engine event names are allowed."
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The handler, called at most once."
                },
                {
                  "name": "filter",
                  "type": "MetaFilter",
                  "optional": true,
                  "desc": "Only for `metaChange`."
                }
              ],
              "returns": [
                {
                  "type": "function",
                  "desc": "The unsubscribe function.",
                  "only": "lua"
                },
                {
                  "type": "() => boolean",
                  "desc": "The unsubscribe function.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.off",
              "id": "fn-off",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.off(name, fn) --> boolean",
                "js": "lsmp.off(name: string, fn: Function): boolean"
              },
              "summary": "Removes a handler this resource registered with `lsmp.on` or `lsmp.once`.",
              "md": "Pass the same function that was registered. Calling the function returned by `lsmp.on` does the same. Removing during a dispatch takes effect at the next dispatch.",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name."
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The registered handler."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if a handler was removed."
              }
            },
            {
              "type": "function",
              "name": "lsmp.emit",
              "id": "fn-emit",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.emit(name, ...)",
                "js": "lsmp.emit(name: string, ...args: Value[]): void"
              },
              "summary": "Emits a local event on this side, to every resource and both engines.",
              "md": "Handlers in the caller's language run **immediately**, during the call, in registration order. Handlers in the other language (Lua ↔ JavaScript) on the same side run **a little later**, in the same order. The emitting resource's own handlers receive the very values passed; other resources receive copies. Engine event names cannot be emitted.",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name: 1 to 128 bytes of UTF-8, case-sensitive. See [Reserved names](#conventions/reserved-names)."
                },
                {
                  "name": "...args",
                  "type": "value",
                  "optional": true,
                  "desc": "Up to 32 [transportable values](#conventions/transportable-values)."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- resource \"shop\"\nlsmp.emit(\"shop:purchase\", playerId, \"pistol\", 500)\n\n-- resource \"stats\" (any language)\nlsmp.on(\"shop:purchase\", function(playerId, item, price)\n  lsmp.log(item .. \" sold\")\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// resource \"shop\"\nlsmp.emit(\"shop:purchase\", playerId, \"pistol\", 500);\n\n// resource \"stats\" (any language)\nlsmp.on(\"shop:purchase\", (playerId, item, price) => lsmp.log(`${item} sold`));"
                  }
                ]
              },
              "notes": [
                {
                  "type": "callout",
                  "variant": "warn",
                  "md": "- At most 32 `emit` calls can be nested (a handler that emits, whose handler emits...): beyond, the call raises.\n- Arguments are encoded once when a handler outside the emitting resource listens: a value that is not transportable raises even if your own handlers would accept it.",
                  "title": "Good to know"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Network events",
              "level": 2,
              "id": "network"
            },
            {
              "type": "text",
              "md": "Network events between a client and the server arrive **in the order** they were sent, together with remote calls and their answers. When they arrive, they are delivered to both engines (Lua and JavaScript) of the receiving side. A resource that is not started yet, or has no handler at that moment, does not get the event: nothing is queued."
            },
            {
              "type": "heading",
              "text": "From a client to the server",
              "level": 3,
              "id": "client-to-server"
            },
            {
              "type": "function",
              "engines": [
                "lua",
                "js"
              ],
              "name": "lsmp.emitServer",
              "id": "fn-emit-server",
              "side": "client",
              "signature": {
                "lua": "lsmp.emitServer(name, ...) --> boolean",
                "js": "lsmp.emitServer(name: string, ...args: Value[]): boolean"
              },
              "summary": "Sends an event to the server.",
              "md": "Nothing is queued when the client is not in a session: the call returns `false`.",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name: 1 to 128 bytes of UTF-8, case-sensitive. See [Reserved names](#conventions/reserved-names)."
                },
                {
                  "name": "...args",
                  "type": "value",
                  "optional": true,
                  "desc": "Up to 32 [transportable values](#conventions/transportable-values)."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` when not in a session."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.emitServer(\"chat:send\", \"hello\")"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.emitServer(\"chat:send\", \"hello\");"
                  }
                ]
              },
              "notes": [
                {
                  "type": "callout",
                  "variant": "info",
                  "md": "One event is at most 4 MiB − 1 KiB encoded; bigger raises. The server limits what each player may send per second (`ScriptEventBytesPerSec`): events beyond it are dropped on the server. See [Limits](#limits/events).",
                  "title": "Size and rate"
                }
              ]
            },
            {
              "type": "function",
              "engines": [
                "lua",
                "js"
              ],
              "name": "lsmp.onClient",
              "id": "fn-on-client",
              "side": "server",
              "signature": {
                "lua": "lsmp.onClient(name, fn) --> function",
                "js": "lsmp.onClient(name: string, fn: Function): () => boolean"
              },
              "summary": "Subscribes to an event sent by clients.",
              "md": "The first argument of the handler is the playerId of the sender. It comes from the connection and cannot be forged; **everything else comes from a client and must be checked** (types, ranges, permissions).",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name (engine event names are refused)."
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "`fn(source, ...args)`."
                }
              ],
              "returns": [
                {
                  "type": "function",
                  "desc": "The unsubscribe function.",
                  "only": "lua"
                },
                {
                  "type": "() => boolean",
                  "desc": "The unsubscribe function.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- server\nlsmp.onClient(\"chat:send\", function(source, text)\n  if type(text) ~= \"string\" or #text == 0 or #text > 200 then return end\n  lsmp.emitAllClients(\"chat:message\", lsmp.getPlayerName(source), text)\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// server\nlsmp.onClient(\"chat:send\", (source, text) => {\n  if (typeof text !== \"string\" || text.length === 0 || text.length > 200) return;\n  lsmp.emitAllClients(\"chat:message\", lsmp.getPlayerName(source), text);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "engines": [
                "lua",
                "js"
              ],
              "name": "lsmp.offClient",
              "id": "fn-off-client",
              "side": "server",
              "signature": {
                "lua": "lsmp.offClient(name, fn) --> boolean",
                "js": "lsmp.offClient(name: string, fn: Function): boolean"
              },
              "summary": "Removes a client-event handler of this resource.",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name."
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The registered handler."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if a handler was removed."
              }
            },
            {
              "type": "heading",
              "text": "From the server to clients",
              "level": 3,
              "id": "server-to-clients"
            },
            {
              "type": "function",
              "engines": [
                "lua",
                "js"
              ],
              "name": "lsmp.emitClient",
              "id": "fn-emit-client",
              "side": "server",
              "signature": {
                "lua": "lsmp.emitClient(target, name, ...) --> boolean",
                "js": "lsmp.emitClient(target: number | number[], name: string, ...args: Value[]): boolean"
              },
              "summary": "Sends an event to one player or to a list of players.",
              "md": "The target comes first, as in [`callClient`](#rpc/fn-call-client).",
              "params": [
                {
                  "name": "target",
                  "type": "playerId | list",
                  "desc": "One playerId, or a list of playerIds."
                },
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name: 1 to 128 bytes of UTF-8, case-sensitive. See [Reserved names](#conventions/reserved-names)."
                },
                {
                  "name": "...args",
                  "type": "value",
                  "optional": true,
                  "desc": "Up to 32 [transportable values](#conventions/transportable-values)."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if at least one target was connected."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.emitClient(playerId, \"hud:notify\", \"Welcome!\")\nlsmp.emitClient({ 1, 4, 7 }, \"race:start\", { laps = 3 })"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.emitClient(playerId, \"hud:notify\", \"Welcome!\");\nlsmp.emitClient([1, 4, 7], \"race:start\", { laps: 3 });"
                  }
                ]
              },
              "notes": [
                {
                  "type": "callout",
                  "variant": "info",
                  "md": "One event is at most 16 MiB encoded; bigger raises and nothing is sent. A client whose connection cannot keep up is disconnected. See [Limits](#limits/events).",
                  "title": "Size"
                }
              ]
            },
            {
              "type": "function",
              "engines": [
                "lua",
                "js"
              ],
              "name": "lsmp.emitAllClients",
              "id": "fn-emit-all-clients",
              "side": "server",
              "signature": {
                "lua": "lsmp.emitAllClients(name, ...) --> integer",
                "js": "lsmp.emitAllClients(name: string, ...args: Value[]): number"
              },
              "summary": "Sends an event to every connected player.",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name: 1 to 128 bytes of UTF-8, case-sensitive. See [Reserved names](#conventions/reserved-names)."
                },
                {
                  "name": "...args",
                  "type": "value",
                  "optional": true,
                  "desc": "Up to 32 [transportable values](#conventions/transportable-values)."
                }
              ],
              "returns": [
                {
                  "type": "integer",
                  "desc": "The number of players reached.",
                  "only": "lua"
                },
                {
                  "type": "number",
                  "desc": "The number of players reached.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.emitAllClients(\"weather:alert\", \"storm in 5 minutes\")"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.emitAllClients(\"weather:alert\", \"storm in 5 minutes\");"
                  }
                ]
              }
            },
            {
              "type": "function",
              "engines": [
                "lua",
                "js"
              ],
              "name": "lsmp.emitDimensionClients",
              "id": "fn-emit-dimension-clients",
              "side": "server",
              "signature": {
                "lua": "lsmp.emitDimensionClients(dimension, name, ...) --> integer",
                "js": "lsmp.emitDimensionClients(dimension: number, name: string, ...args: Value[]): number"
              },
              "summary": "Sends an event to every player currently in a dimension.",
              "params": [
                {
                  "name": "dimension",
                  "type": "dimension",
                  "desc": "The dimension, `0..65535`."
                },
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name: 1 to 128 bytes of UTF-8, case-sensitive. See [Reserved names](#conventions/reserved-names)."
                },
                {
                  "name": "...args",
                  "type": "value",
                  "optional": true,
                  "desc": "Up to 32 [transportable values](#conventions/transportable-values)."
                }
              ],
              "returns": [
                {
                  "type": "integer",
                  "desc": "The number of players reached.",
                  "only": "lua"
                },
                {
                  "type": "number",
                  "desc": "The number of players reached.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.emitDimensionClients(12, \"arena:countdown\", 3)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.emitDimensionClients(12, \"arena:countdown\", 3);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "engines": [
                "lua",
                "js"
              ],
              "name": "lsmp.onServer",
              "id": "fn-on-server",
              "side": "client",
              "signature": {
                "lua": "lsmp.onServer(name, fn) --> function",
                "js": "lsmp.onServer(name: string, fn: Function): () => boolean"
              },
              "summary": "Subscribes to an event sent by the server.",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name (engine event names are refused)."
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "`fn(...args)`."
                }
              ],
              "returns": [
                {
                  "type": "function",
                  "desc": "The unsubscribe function.",
                  "only": "lua"
                },
                {
                  "type": "() => boolean",
                  "desc": "The unsubscribe function.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.onServer(\"chat:message\", function(name, text)\n  lsmp.log(name .. \": \" .. text)\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.onServer(\"chat:message\", (name, text) => {\n  lsmp.log(`${name}: ${text}`);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "engines": [
                "lua",
                "js"
              ],
              "name": "lsmp.offServer",
              "id": "fn-off-server",
              "side": "client",
              "signature": {
                "lua": "lsmp.offServer(name, fn) --> boolean",
                "js": "lsmp.offServer(name: string, fn: Function): boolean"
              },
              "summary": "Removes a server-event handler of this resource.",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Event name."
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The registered handler."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if a handler was removed."
              }
            }
          ]
        },
        {
          "id": "rpc",
          "title": "Remote calls (RPC)",
          "eyebrow": "Shared · Lua & JS",
          "lead": "Call a function in another resource, on the server or on a player's client, and get its result back.",
          "blocks": [
            {
              "type": "text",
              "md": "A call runs a function registered with `lsmp.onCall` and gives you its result. Three functions cover every case, and the direction is in the name:"
            },
            {
              "type": "list",
              "items": [
                "`lsmp.call` calls a function of **this side**: on the server, a function of another server resource; on a client, a function of another resource of the same client. Lua and JavaScript resources call each other freely. Nothing goes over the network.",
                "`lsmp.callServer` (client) calls a function published by the **server**.",
                "`lsmp.callClient` (server) calls a function published by **one player's client**.",
                "There is no client-to-client call: go through the server."
              ]
            },
            {
              "type": "table",
              "headers": [
                "Caller",
                "Function",
                "Handler",
                "Handler receives"
              ],
              "rows": [
                [
                  "any resource, same side",
                  "`lsmp.call(name, ...)`",
                  "`onCall` of this side",
                  "server: `source = nil`/`null`, then the arguments; client: the arguments"
                ],
                [
                  "client",
                  "`lsmp.callServer(name, ...)`",
                  "server `onCall`",
                  "`source` (the calling player), then the arguments"
                ],
                [
                  "server resource",
                  "`lsmp.callClient(playerId, name, ...)`",
                  "that player's client `onCall`",
                  "the arguments"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Rules",
              "level": 2,
              "id": "rules"
            },
            {
              "type": "list",
              "items": [
                "**One handler per name and per side**, across all resources and both engines: the same handler answers `lsmp.call` from this side and calls from the other side. A second `onCall` with the same name raises `'x' is already handled by resource 'y'`.",
                "The handler **returns** the result: one [transportable value](#conventions/transportable-values). In Lua only the first returned value counts, and the handler may suspend; in JavaScript it may return a Promise.",
                "If the handler raises, rejects or returns a value that cannot be sent, the caller fails with `error`. The message stays in the log of the side that handled the call: a client never sees server error messages.",
                "The default deadline is 10 000 ms. Give `{ name = \"x\", timeoutMs = 2000 }` instead of the name to change it (1 to 300 000 ms). At the deadline the caller gets `timeout`; a late answer is dropped.",
                "A call never blocks, and is always asynchronous, even inside one resource. Answers of two calls can arrive in any order.",
                "When the called resource stops, calls it was handling fail with `error` and later calls with `no-handler`. When the calling resource stops, its pending calls end with `cancelled`."
              ]
            },
            {
              "type": "table",
              "headers": [
                "Code",
                "When"
              ],
              "rows": [
                [
                  "`timeout`",
                  "No answer before the deadline."
                ],
                [
                  "`no-handler`",
                  "Nobody handles this name on the side that was called."
                ],
                [
                  "`error`",
                  "The handler raised, rejected, or returned a value that cannot be sent."
                ],
                [
                  "`disconnected`",
                  "The client is not in a session, or the player left before answering."
                ],
                [
                  "`not-found`",
                  "`callClient` to a player who is not connected."
                ],
                [
                  "`limit`",
                  "4096 calls of the resource are already pending, or the request is too large to send."
                ],
                [
                  "`cancelled`",
                  "The calling resource stopped."
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "danger",
              "md": "A server `onCall` handler is reachable by every connected player with any arguments. Check types, ranges and the player's rights (`source`) before doing anything.",
              "title": "Never trust the client"
            },
            {
              "type": "heading",
              "text": "Functions",
              "level": 2,
              "id": "functions"
            },
            {
              "type": "function",
              "name": "lsmp.onCall",
              "id": "fn-on-call",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.onCall(name, fn) --> function",
                "js": "lsmp.onCall(name: string, fn: Function): () => boolean"
              },
              "summary": "Registers **the** handler of a callable name on this side.",
              "md": "Server handler: `fn(source, ...args)`, where `source` is the calling playerId, or `nil`/`null` for a local call (`lsmp.call`). Client handler: `fn(...args)`. The returned value is the result.",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Callable name (1 to 128 bytes; engine event names and the `lsmp:` prefix are refused)."
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The handler; its return value (or resolved Promise) is the result."
                }
              ],
              "returns": [
                {
                  "type": "function",
                  "desc": "The unregister function.",
                  "only": "lua"
                },
                {
                  "type": "() => boolean",
                  "desc": "The unregister function.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- server\nlsmp.onCall(\"bank:withdraw\", function(source, amount)\n  if math.type(amount) ~= \"integer\" or amount <= 0 then return { ok = false } end\n  local account = lsmp.getPlayerLsmpId(source)\n  if not account then return { ok = false } end\n  local balance = lsmp.storage.get(\"balance:\" .. account) or 0\n  if balance < amount then return { ok = false, balance = balance } end\n  lsmp.storage.set(\"balance:\" .. account, balance - amount)\n  return { ok = true, balance = balance - amount }\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// server\nlsmp.onCall(\"bank:withdraw\", (source, amount) => {\n  if (!Number.isInteger(amount) || amount <= 0) return { ok: false };\n  const account = lsmp.getPlayerLsmpId(source);\n  if (account === null) return { ok: false };\n  const balance = lsmp.storage.get(`balance:${account}`) ?? 0;\n  if (balance < amount) return { ok: false, balance };\n  lsmp.storage.set(`balance:${account}`, balance - amount);\n  return { ok: true, balance: balance - amount };\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.offCall",
              "id": "fn-off-call",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.offCall(name, fn) --> boolean",
                "js": "lsmp.offCall(name: string, fn: Function): boolean"
              },
              "summary": "Unregisters this resource's handler of a name.",
              "md": "Calls already received still answer; later calls get `no-handler`.",
              "params": [
                {
                  "name": "name",
                  "type": "event",
                  "desc": "Callable name."
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The registered handler."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the handler was removed."
              }
            },
            {
              "type": "function",
              "name": "lsmp.call",
              "id": "fn-call",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.call(name, ... [, cb]) --> any, err",
                "js": "lsmp.call(name: string | CallOptions, ...args: Value[]): Promise<Value>"
              },
              "summary": "Calls the handler of a name on **this side** (another resource, Lua or JavaScript) and returns its result. Asynchronous.",
              "md": "Nothing goes over the network: this is how resources share functions (\"exports\"). On the server the handler receives `source = nil`/`null`. The handler always runs later, never inside the call. In Lua, pass a callback as last argument, or call from a coroutine (see [Asynchronous functions](#conventions/async)).",
              "params": [
                {
                  "name": "name",
                  "type": "event | CallOptions",
                  "desc": "The name, or `{ name, timeoutMs }` (`timeoutMs` 1 to 300 000, default 10 000)."
                },
                {
                  "name": "...args",
                  "type": "value",
                  "optional": true,
                  "desc": "Up to 32 transportable values."
                }
              ],
              "returns": [
                {
                  "type": "any, err",
                  "desc": "The handler's result. Failure codes: see [Rules](#rpc/rules).",
                  "only": "lua"
                },
                {
                  "type": "Promise<Value>",
                  "desc": "The handler's result. Failure codes: see [Rules](#rpc/rules).",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- server, resource \"inventory\" (Lua)\nlsmp.onCall(\"inventory:count\", function(source, playerId, item)\n  return countItem(playerId, item)\nend)\n\n-- server, resource \"shop\" (Lua or JavaScript), in a host coroutine\nlocal n, err = lsmp.call(\"inventory:count\", playerId, \"pistol\")\nif not n then lsmp.warn(\"inventory unavailable: \" .. err) end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// server, resource \"inventory\" (JavaScript)\nlsmp.onCall(\"inventory:count\", (source, playerId, item) => countItem(playerId, item));\n\n// server, resource \"shop\" (Lua or JavaScript)\nasync function stock(playerId) {\n  try {\n    return await lsmp.call(\"inventory:count\", playerId, \"pistol\");\n  } catch (e) {\n    lsmp.warn(`inventory unavailable: ${e.code}`);\n    return 0;\n  }\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.callServer",
              "id": "fn-call-server",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.callServer(name, ... [, cb]) --> any, err",
                "js": "lsmp.callServer(name: string | CallOptions, ...args: Value[]): Promise<Value>"
              },
              "summary": "Calls the **server** handler of a name and returns its result. Asynchronous.",
              "md": "The handler receives the calling player as `source`. The call keeps its order with `emitServer`. Outside a session it fails with `disconnected`. In Lua, pass a callback as last argument, or call from a coroutine (see [Asynchronous functions](#conventions/async)).",
              "params": [
                {
                  "name": "name",
                  "type": "event | CallOptions",
                  "desc": "The name, or `{ name, timeoutMs }` (`timeoutMs` 1 to 300 000, default 10 000)."
                },
                {
                  "name": "...args",
                  "type": "value",
                  "optional": true,
                  "desc": "Up to 32 transportable values."
                }
              ],
              "returns": [
                {
                  "type": "any, err",
                  "desc": "The handler's result. Failure codes: see [Rules](#rpc/rules).",
                  "only": "lua"
                },
                {
                  "type": "Promise<Value>",
                  "desc": "The handler's result. Failure codes: see [Rules](#rpc/rules).",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- client, inside a host coroutine (event handler, file body, lsmp.createThread)\nlocal res, err = lsmp.callServer({ name = \"bank:withdraw\", timeoutMs = 5000 }, 200)\nif not res then\n  lsmp.warn(\"withdraw failed: \" .. err)\nelseif res.ok then\n  lsmp.log(\"new balance: \" .. res.balance)\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// client\nasync function withdraw(amount) {\n  try {\n    const res = await lsmp.callServer({ name: \"bank:withdraw\", timeoutMs: 5000 }, amount);\n    if (res.ok) lsmp.log(`new balance: ${res.balance}`);\n  } catch (e) {\n    lsmp.warn(`withdraw failed: ${e.code}`);\n  }\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.callClient",
              "id": "fn-call-client",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.callClient(playerId, name, ... [, cb]) --> any, err",
                "js": "lsmp.callClient(playerId: number, name: string | CallOptions, ...args: Value[]): Promise<Value>"
              },
              "summary": "Calls the handler of a name on one player's client and returns its result. Asynchronous.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player whose client is called."
                },
                {
                  "name": "name",
                  "type": "event | CallOptions",
                  "desc": "The name, or `{ name, timeoutMs }`."
                },
                {
                  "name": "...args",
                  "type": "value",
                  "optional": true,
                  "desc": "Up to 32 transportable values."
                }
              ],
              "returns": [
                {
                  "type": "any, err",
                  "desc": "The client handler's result.",
                  "only": "lua"
                },
                {
                  "type": "Promise<Value>",
                  "desc": "The client handler's result.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- client\nlsmp.onCall(\"ui:confirm\", function(question)\n  return showConfirmDialog(question) -- your own function, may suspend\nend)\n\n-- server, in a host coroutine\nlocal yes, err = lsmp.callClient(playerId, { name = \"ui:confirm\", timeoutMs = 30000 }, \"Sell your car?\")\nif yes then sellCar(playerId) end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// client\nlsmp.onCall(\"ui:confirm\", async (question) => showConfirmDialog(question));\n\n// server\nasync function askToSell(playerId) {\n  const yes = await lsmp.callClient(playerId, { name: \"ui:confirm\", timeoutMs: 30000 }, \"Sell your car?\");\n  if (yes) sellCar(playerId);\n}"
                  }
                ]
              },
              "notes": [
                {
                  "type": "callout",
                  "variant": "info",
                  "md": "The request can be up to 16 MiB encoded; the answer from the client up to 4 MiB − 1 KiB.",
                  "title": "Sizes"
                }
              ]
            }
          ]
        },
        {
          "id": "core-utils",
          "title": "Logging, timers, hashing, JSON, resources",
          "eyebrow": "Shared · Lua & JS",
          "lead": "Logging, timers and threads, clocks, hashing, random bytes, JSON for Lua, and information about resources.",
          "blocks": [
            {
              "type": "text",
              "md": "Small tools every resource uses: logging, timers and threads, clocks, hashing (`lsmp.hash`), random bytes, JSON (Lua) and information about resources. They exist on the server and on the client, with the same behaviour."
            },
            {
              "type": "heading",
              "text": "Logging",
              "level": 2,
              "id": "logging"
            },
            {
              "type": "text",
              "md": "Every line is written to the console of the side that logs (server console and admin panel, or the client console), prefixed with the resource name. In Lua, `print` is `lsmp.log`. In JavaScript, `console.log`/`console.info` go to `lsmp.log`, `console.warn` to `lsmp.warn`, `console.error` to `lsmp.error` and `console.debug` to `lsmp.debug`."
            },
            {
              "type": "function",
              "name": "lsmp.log",
              "id": "fn-log",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.log(...)",
                "js": "lsmp.log(...values: any[]): void"
              },
              "summary": "Writes an information line.",
              "params": [
                {
                  "name": "...values",
                  "type": "any",
                  "optional": true,
                  "desc": "Values to write, separated by a tab. Strings are written as they are."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.log(\"players online:\", #lsmp.getPlayers())"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.log(\"players online:\", lsmp.getPlayers().length);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.warn",
              "id": "fn-warn",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.warn(...)",
                "js": "lsmp.warn(...values: any[]): void"
              },
              "summary": "Writes a warning line.",
              "params": [
                {
                  "name": "...values",
                  "type": "any",
                  "optional": true,
                  "desc": "Values to write, separated by a tab. Strings are written as they are."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.error",
              "id": "fn-error",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.error(...)",
                "js": "lsmp.error(...values: any[]): void"
              },
              "summary": "Writes an error line. It does not raise.",
              "params": [
                {
                  "name": "...values",
                  "type": "any",
                  "optional": true,
                  "desc": "Values to write, separated by a tab. Strings are written as they are."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.debug",
              "id": "fn-debug",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.debug(...)",
                "js": "lsmp.debug(...values: any[]): void"
              },
              "summary": "Writes a debug line, hidden unless the resource's level is `\"debug\"`.",
              "params": [
                {
                  "name": "...values",
                  "type": "any",
                  "optional": true,
                  "desc": "Values to write, separated by a tab. Strings are written as they are."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.setLogLevel",
              "id": "fn-set-log-level",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setLogLevel(level)",
                "js": "lsmp.setLogLevel(level: string): void"
              },
              "summary": "Sets the lowest level written for **this resource** only.",
              "md": "Errors raised by the resource's handlers are always written, whatever the level.",
              "params": [
                {
                  "name": "level",
                  "type": "string",
                  "desc": "`\"debug\"`, `\"info\"` (default), `\"warn\"`, `\"error\"` or `\"off\"`."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.setLogLevel(\"debug\")"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.setLogLevel(\"debug\");"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.getLogLevel",
              "id": "fn-get-log-level",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getLogLevel() --> string",
                "js": "lsmp.getLogLevel(): string"
              },
              "summary": "The current level of this resource (`\"info\"` by default).",
              "returns": {
                "type": "string"
              }
            },
            {
              "type": "heading",
              "text": "Errors",
              "level": 2,
              "id": "errors"
            },
            {
              "type": "function",
              "name": "lsmp.getLastError",
              "id": "fn-get-last-error",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getLastError() --> string?",
                "js": "lsmp.getLastError(): string | null"
              },
              "summary": "The failure code of the last synchronous `lsmp` call of this resource that failed, or `nil`/`null` if the last such call succeeded.",
              "md": "Each call that can fail resets it. In Lua the code is also the second return value of the failing call, so this function is mostly for JavaScript, where a failed action only returns `false` or `null`. See [Error codes](#error-codes).",
              "returns": [
                {
                  "type": "string?",
                  "desc": "A code such as `\"not-found\"` or `\"permission\"`.",
                  "only": "lua"
                },
                {
                  "type": "string | null",
                  "desc": "A code such as `\"not-found\"` or `\"permission\"`.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local ok = lsmp.deleteEntity(netId)\nif not ok then lsmp.warn(lsmp.getLastError()) end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "if (!lsmp.deleteEntity(netId)) lsmp.warn(lsmp.getLastError());"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Threads and waiting",
              "level": 2,
              "id": "threads"
            },
            {
              "type": "function",
              "name": "lsmp.wait",
              "id": "fn-wait",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.wait([ms])",
                "js": "lsmp.wait(ms: number = 0): Promise<void>"
              },
              "summary": "Waits for a number of milliseconds.",
              "md": "**Lua**: suspends the current host coroutine (a file body, an event or RPC handler, a `lsmp.createThread` function); `0` waits for the next tick. Called elsewhere, it raises. **JavaScript**: returns a Promise that resolves after `ms`; use it with `await`.",
              "params": [
                {
                  "name": "ms",
                  "type": "ms",
                  "optional": true,
                  "default": "0",
                  "desc": "Milliseconds to wait."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.createThread(function()\n  while true do\n    lsmp.emitAllClients(\"clock:tick\", lsmp.nowMs())\n    lsmp.wait(60000)\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "(async () => {\n  for (;;) {\n    lsmp.emitAllClients(\"clock:tick\", lsmp.nowMs());\n    await lsmp.wait(60000);\n  }\n})();"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.createThread",
              "id": "fn-create-thread",
              "side": "shared",
              "engines": [
                "lua"
              ],
              "signature": {
                "lua": "lsmp.createThread(fn, ...)"
              },
              "summary": "Lua only: runs `fn(...)` in a new coroutine, right now, until it first waits.",
              "md": "The thread can call `lsmp.wait` and asynchronous functions without a callback. An error inside it is logged with the resource name and never reaches the caller. In JavaScript, use an `async` function.",
              "params": [
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The thread body."
                },
                {
                  "name": "...args",
                  "type": "any",
                  "optional": true,
                  "desc": "Arguments passed to `fn`."
                }
              ]
            },
            {
              "type": "heading",
              "text": "Timers",
              "level": 2,
              "id": "timers"
            },
            {
              "type": "text",
              "md": "The standard timer functions are globals in every context. A timer belongs to its resource and is cancelled when the resource stops. `clearTimeout` and `clearInterval` are the same function."
            },
            {
              "type": "function",
              "name": "setTimeout",
              "id": "fn-set-timeout",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "setTimeout(fn [, ms, ...]) --> integer",
                "js": "setTimeout(fn: Function, ms: number = 0, ...args: any[]): number"
              },
              "summary": "Calls `fn(...args)` once after `ms` milliseconds.",
              "params": [
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The callback."
                },
                {
                  "name": "ms",
                  "type": "ms",
                  "optional": true,
                  "default": "0",
                  "desc": "Delay. `0` runs it at the next turn."
                },
                {
                  "name": "...args",
                  "type": "any",
                  "optional": true,
                  "desc": "Arguments passed to `fn`."
                }
              ],
              "returns": [
                {
                  "type": "integer",
                  "desc": "The timer id (an integer above 0, unique in the resource; a Node `Timeout` object in JavaScript on the server).",
                  "only": "lua"
                },
                {
                  "type": "number",
                  "desc": "The timer id (an integer above 0, unique in the resource; a Node `Timeout` object in JavaScript on the server).",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local id = setTimeout(function(name) lsmp.log(\"hello \" .. name) end, 1000, \"world\")"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const id = setTimeout((name) => lsmp.log(`hello ${name}`), 1000, \"world\");"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "setInterval",
              "id": "fn-set-interval",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "setInterval(fn [, ms, ...]) --> integer",
                "js": "setInterval(fn: Function, ms: number = 1, ...args: any[]): number"
              },
              "summary": "Calls `fn(...args)` every `ms` milliseconds.",
              "md": "The next call is planned from the end of the previous one, so a slow server never gets a burst of late calls. The period is at least 1 ms.",
              "params": [
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The callback."
                },
                {
                  "name": "ms",
                  "type": "ms",
                  "optional": true,
                  "default": "1",
                  "desc": "Period."
                },
                {
                  "name": "...args",
                  "type": "any",
                  "optional": true,
                  "desc": "Arguments passed to `fn`."
                }
              ],
              "returns": [
                {
                  "type": "integer",
                  "desc": "The timer id.",
                  "only": "lua"
                },
                {
                  "type": "number",
                  "desc": "The timer id.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "clearTimeout",
              "id": "fn-clear-timeout",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "clearTimeout([id])",
                "js": "clearTimeout(id?: number): void"
              },
              "summary": "Cancels a timer of this resource.",
              "md": "An unknown id, or the id of another resource's timer, does nothing.",
              "params": [
                {
                  "name": "id",
                  "type": "integer",
                  "desc": "The timer id. A missing id does nothing.",
                  "optional": true
                }
              ]
            },
            {
              "type": "function",
              "name": "clearInterval",
              "id": "fn-clear-interval",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "clearInterval([id])",
                "js": "clearInterval(id?: number): void"
              },
              "summary": "Same function as `clearTimeout`.",
              "params": [
                {
                  "name": "id",
                  "type": "integer",
                  "desc": "The timer id. A missing id does nothing.",
                  "optional": true
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.onTick",
              "id": "fn-on-tick",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.onTick(fn) --> function",
                "js": "lsmp.onTick(fn: Function): () => boolean"
              },
              "summary": "Calls `fn` every game frame with the milliseconds since the previous frame.",
              "md": "For drawing and per-frame input only: keep it short. The first call receives `0`. A tick handler cannot suspend (use `lsmp.createThread` or an `async` function). It is disabled after 8 errors in a row.",
              "params": [
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "`fn(dtMs)`."
                }
              ],
              "returns": [
                {
                  "type": "function",
                  "desc": "The unsubscribe function.",
                  "only": "lua"
                },
                {
                  "type": "() => boolean",
                  "desc": "The unsubscribe function.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.onTick(function(dtMs)\n  drawText(0.5, 0.05, \"FPS: \" .. math.floor(1000 / math.max(dtMs, 1)))\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.onTick((dtMs) => {\n  drawText(0.5, 0.05, `FPS: ${Math.floor(1000 / Math.max(dtMs, 1))}`);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.offTick",
              "id": "fn-off-tick",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.offTick(fn) --> boolean",
                "js": "lsmp.offTick(fn: Function): boolean"
              },
              "summary": "Removes a tick handler of this resource.",
              "params": [
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The handler."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if it was removed."
              }
            },
            {
              "type": "heading",
              "text": "Clocks",
              "level": 2,
              "id": "clocks"
            },
            {
              "type": "function",
              "name": "lsmp.getTickCount",
              "id": "fn-get-tick-count",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getTickCount() --> integer",
                "js": "lsmp.getTickCount(): number"
              },
              "summary": "A monotonic clock in milliseconds. Only differences between two values mean something.",
              "returns": [
                {
                  "type": "integer",
                  "only": "lua"
                },
                {
                  "type": "number",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local t0 = lsmp.getTickCount()\ndoWork()\nlsmp.debug(\"took \" .. (lsmp.getTickCount() - t0) .. \" ms\")"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const t0 = lsmp.getTickCount();\ndoWork();\nlsmp.debug(`took ${lsmp.getTickCount() - t0} ms`);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.nowMs",
              "id": "fn-now-ms",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.nowMs() --> integer",
                "js": "lsmp.nowMs(): number"
              },
              "summary": "The wall-clock time in milliseconds since the Unix epoch.",
              "md": "Use it for timestamps you store or send (`untilMs`, `atMs`...).",
              "returns": [
                {
                  "type": "integer",
                  "only": "lua"
                },
                {
                  "type": "number",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Hashing and random",
              "level": 2,
              "id": "hashing"
            },
            {
              "type": "function",
              "name": "lsmp.hash",
              "id": "fn-hash",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.hash(name) --> integer",
                "js": "lsmp.hash(name: string): number"
              },
              "summary": "The game hash of a name, unsigned (`0..2^32-1`).",
              "md": "ASCII letters are lower-cased first, so `\"ADDER\"` and `\"adder\"` give the same hash. It is the value the game uses for models, weapons and most names, and the same as the native `getHashKey`. Functions that take a `hash` also accept the name directly. `lsmp.joaat` is the same function, under the name of the algorithm (Jenkins one-at-a-time) that GTA modders know.",
              "params": [
                {
                  "name": "name",
                  "type": "string",
                  "desc": "The name to hash."
                }
              ],
              "returns": [
                {
                  "type": "integer",
                  "only": "lua"
                },
                {
                  "type": "number",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "if lsmp.getEntityModel(netId) == lsmp.hash(\"adder\") then\n  lsmp.log(\"an Adder\")\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "if (lsmp.getEntityModel(netId) === lsmp.hash(\"adder\")) lsmp.log(\"an Adder\");"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.joaat",
              "id": "fn-joaat",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.joaat(name) --> integer",
                "js": "lsmp.joaat(name: string): number"
              },
              "summary": "Alias of [`lsmp.hash`](#core-utils/fn-hash): same function, same result. Prefer `lsmp.hash`."
            },
            {
              "type": "function",
              "name": "lsmp.randomBytes",
              "id": "fn-random-bytes",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.randomBytes(n) --> string",
                "js": "lsmp.randomBytes(n: number): Uint8Array"
              },
              "summary": "Cryptographically secure random bytes.",
              "md": "Use it for tokens, salts and identifiers that must not be guessed. `math.random` and `Math.random` are predictable.",
              "params": [
                {
                  "name": "n",
                  "type": "integer",
                  "desc": "Number of bytes, 1 to 65 536."
                }
              ],
              "returns": [
                {
                  "type": "string",
                  "desc": "The bytes.",
                  "only": "lua"
                },
                {
                  "type": "Uint8Array",
                  "desc": "The bytes.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local token = lsmp.randomBytes(16):gsub(\".\", function(c) return (\"%02x\"):format(c:byte()) end)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const token = Buffer.from(lsmp.randomBytes(16)).toString(\"hex\"); // server (Node)"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.bytes",
              "id": "fn-bytes",
              "side": "shared",
              "engines": [
                "lua"
              ],
              "signature": {
                "lua": "lsmp.bytes(s) --> Bytes"
              },
              "summary": "Lua only: marks a string as binary data, so it travels as bytes.",
              "md": "A JavaScript receiver then gets a `Uint8Array` instead of a string. A string that is not valid UTF-8 is always sent as bytes. See [Transportable values](#conventions/transportable-values).",
              "params": [
                {
                  "name": "s",
                  "type": "string",
                  "desc": "The data."
                }
              ],
              "returns": {
                "type": "Bytes",
                "desc": "A marked value to pass to `emit`, `emitServer`, `emitClient`, `call`, meta or storage."
              }
            },
            {
              "type": "heading",
              "text": "JSON (Lua)",
              "level": 2,
              "id": "json"
            },
            {
              "type": "text",
              "md": "JavaScript has `JSON`. Lua uses these three functions, which map JSON `null` to [`lsmp.null`](#conventions/const-null)."
            },
            {
              "type": "function",
              "name": "lsmp.json.encode",
              "id": "fn-json-encode",
              "side": "shared",
              "engines": [
                "lua"
              ],
              "signature": {
                "lua": "lsmp.json.encode(value [, opts]) --> string"
              },
              "summary": "Lua only: the JSON text of a value.",
              "md": "`lsmp.null` becomes `null`; an empty table becomes `[]` (use `lsmp.json.array` to be explicit, and a table with string keys for objects). A value that cannot be written (function, mixed keys) raises.",
              "params": [
                {
                  "name": "value",
                  "type": "any",
                  "desc": "The value."
                },
                {
                  "name": "opts",
                  "type": "JsonEncodeOptions",
                  "optional": true,
                  "desc": "`{ pretty = false }`: indented output."
                }
              ],
              "returns": {
                "type": "string"
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local text = lsmp.json.encode({ name = \"Ada\", tags = { \"admin\" } })"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.json.decode",
              "id": "fn-json-decode",
              "side": "shared",
              "engines": [
                "lua"
              ],
              "signature": {
                "lua": "lsmp.json.decode(text) --> value | nil, \"invalid\""
              },
              "summary": "Lua only: parses JSON text.",
              "md": "Inside arrays `null` becomes `lsmp.null` (the length is kept); inside objects a `null` member is simply absent. Invalid text is not an error: the call returns `nil, \"invalid\", { message }`.",
              "params": [
                {
                  "name": "text",
                  "type": "string",
                  "desc": "JSON text."
                }
              ],
              "returns": {
                "type": "value | nil, \"invalid\""
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local cfg, err, details = lsmp.json.decode(lsmp.readResourceFile(\"config.json\"))\nif not cfg then lsmp.error(\"bad config.json: \" .. details.message) end"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.json.array",
              "id": "fn-json-array",
              "side": "shared",
              "engines": [
                "lua"
              ],
              "signature": {
                "lua": "lsmp.json.array(t) --> table"
              },
              "summary": "Lua only: marks a table so `json.encode` writes it as an array, even when empty.",
              "params": [
                {
                  "name": "t",
                  "type": "table",
                  "desc": "The table."
                }
              ],
              "returns": {
                "type": "table",
                "desc": "The same table."
              }
            },
            {
              "type": "heading",
              "text": "Resources",
              "level": 2,
              "id": "resources"
            },
            {
              "type": "text",
              "md": "A resource is identified by its **name**: its folder name on the server. See [Resource layout](#resource-layout). Starting and stopping resources from a script is on the [Server and resource lifecycle](#server-lifecycle) page."
            },
            {
              "type": "function",
              "name": "lsmp.getResourceName",
              "id": "fn-get-resource-name",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getResourceName() --> string",
                "js": "lsmp.getResourceName(): string"
              },
              "summary": "The name of the calling resource.",
              "returns": {
                "type": "string"
              }
            },
            {
              "type": "function",
              "name": "lsmp.getResourceState",
              "id": "fn-get-resource-state",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getResourceState(name) --> ResourceState?",
                "js": "lsmp.getResourceState(name: string): ResourceState | null"
              },
              "summary": "The state of a resource on this side.",
              "params": [
                {
                  "name": "name",
                  "type": "name",
                  "desc": "Resource name."
                }
              ],
              "returns": [
                {
                  "type": "ResourceState?",
                  "desc": "`\"starting\"`, `\"started\"`, `\"failed\"`, `\"stopping\"` or `\"stopped\"`; `nil`/`null` if unknown.",
                  "only": "lua"
                },
                {
                  "type": "ResourceState | null",
                  "desc": "`\"starting\"`, `\"started\"`, `\"failed\"`, `\"stopping\"` or `\"stopped\"`; `nil`/`null` if unknown.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "if lsmp.getResourceState(\"mysql-accounts\") ~= \"started\" then\n  lsmp.warn(\"accounts are not available\")\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "if (lsmp.getResourceState(\"mysql-accounts\") !== \"started\") lsmp.warn(\"accounts are not available\");"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.getResources",
              "id": "fn-get-resources",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getResources() --> {ResourceInfo}",
                "js": "lsmp.getResources(): ResourceInfo[]"
              },
              "summary": "Every resource known on this side, in load order.",
              "returns": [
                {
                  "type": "{ResourceInfo}",
                  "desc": "A list of `{ name, state }`.",
                  "only": "lua"
                },
                {
                  "type": "ResourceInfo[]",
                  "desc": "A list of `{ name, state }`.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.readResourceFile",
              "id": "fn-read-resource-file",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.readResourceFile(path [, opts]) --> string|string?",
                "js": "lsmp.readResourceFile(path: string, opts?: ReadFileOptions): string | Uint8Array | null"
              },
              "summary": "Reads a file of the calling resource's own package.",
              "md": "Use it for configuration, translations and templates shipped with the resource. The path is relative to the resource folder, with `/` separators; `..` and absolute paths are refused, so a resource only reads its own files. Text (UTF-8) by default.",
              "params": [
                {
                  "name": "path",
                  "type": "string",
                  "desc": "Path inside the resource, for example `\"config/shop.json\"`."
                },
                {
                  "name": "opts",
                  "type": "ReadFileOptions",
                  "optional": true,
                  "desc": "`{ binary = true }` returns bytes (`Uint8Array` in JavaScript; Lua strings hold bytes anyway)."
                }
              ],
              "returns": [
                {
                  "type": "string?",
                  "desc": "The content, or `nil`/`null` if the file is not in the package.",
                  "only": "lua"
                },
                {
                  "type": "string | Uint8Array | null",
                  "desc": "The content, or `nil`/`null` if the file is not in the package.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local prices = lsmp.json.decode(lsmp.readResourceFile(\"config/prices.json\"))"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const prices = JSON.parse(lsmp.readResourceFile(\"config/prices.json\"));"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.resourceFileExists",
              "id": "fn-resource-file-exists",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resourceFileExists(path) --> boolean",
                "js": "lsmp.resourceFileExists(path: string): boolean"
              },
              "summary": "Whether the calling resource's package holds a file.",
              "params": [
                {
                  "name": "path",
                  "type": "string",
                  "desc": "Path inside the resource."
                }
              ],
              "returns": {
                "type": "boolean"
              }
            },
            {
              "type": "function",
              "name": "lsmp.gameType",
              "id": "fn-game-type",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.gameType() --> string",
                "js": "lsmp.gameType(): string"
              },
              "summary": "The kind of session the script runs in.",
              "md": "`\"MP\"` on a server session. A client can also run resources in single player (`\"SP\"`) or in a marketplace trial (`\"TRY\"`).",
              "returns": {
                "type": "string"
              }
            },
            {
              "type": "function",
              "name": "lsmp.getVersion",
              "id": "fn-get-version",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getVersion() --> VersionInfo",
                "js": "lsmp.getVersion(): VersionInfo"
              },
              "summary": "Version information.",
              "returns": [
                {
                  "type": "VersionInfo",
                  "desc": "`{ lsmp, game, gameBuild }`: the LS:MP version, and on a client the game version and build number (`nil`/`null` on the server).",
                  "only": "lua"
                },
                {
                  "type": "VersionInfo",
                  "desc": "`{ lsmp, game, gameBuild }`: the LS:MP version, and on a client the game version and build number (`nil`/`null` on the server).",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.ResourceState",
              "id": "const-resource-state",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.ResourceState",
                "js": "lsmp.ResourceState"
              },
              "summary": "The states a resource goes through.",
              "md": "`lsmp.ResourceState.Starting` = `\"starting\"` · `lsmp.ResourceState.Started` = `\"started\"` · `lsmp.ResourceState.Failed` = `\"failed\"` · `lsmp.ResourceState.Stopping` = `\"stopping\"` · `lsmp.ResourceState.Stopped` = `\"stopped\"`"
            }
          ]
        },
        {
          "id": "http",
          "title": "HTTP client",
          "eyebrow": "Shared · Lua & JS",
          "lead": "Call web services from a script: your own backend, a Discord webhook, a public API.",
          "blocks": [
            {
              "type": "text",
              "md": "`lsmp.http` sends one request and gives back the response. The calls are asynchronous: JS gets a `Promise`, Lua suspends the calling handler or takes a callback (see [Conventions](#conventions)).\n\nA response arrives **whatever its status**: a `404` or a `500` is a response, check `res.ok` or `res.status`. A call fails only when no response came back at all."
            },
            {
              "type": "table",
              "headers": [
                "",
                "Server",
                "Client"
              ],
              "rows": [
                [
                  "Schemes",
                  "`https://` and `http://`",
                  "`https://` only"
                ],
                [
                  "Addresses",
                  "Any, unless the operator restricts the resource (sandbox)",
                  "Public addresses only. `localhost` or a literal loopback, private or reserved IP in the URL raises `RangeError` at the call; a host name that resolves to such an address fails with `permission`."
                ],
                [
                  "Requests in flight",
                  "Sandboxed resource: 256; more fail with `limit`",
                  "8 per resource (20 per second), 32 for the whole client, 128 MiB of response bodies held at once; more fail with `limit`"
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Server resources in the sandbox",
              "md": "A sandboxed server resource reaches only the destinations the operator allows in `SandboxNetConnect` ([server.cfg](#server-cfg)). Anything else fails with `permission`. See [Resource capabilities and sandbox](#capabilities)."
            },
            {
              "type": "heading",
              "text": "Requests",
              "level": 2,
              "id": "http-requests"
            },
            {
              "type": "function",
              "name": "lsmp.http.request",
              "id": "fn-http-request",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.http.request(opts [, cb]) --> HttpResponse, err",
                "js": "lsmp.http.request(opts: HttpRequest): Promise<HttpResponse>"
              },
              "summary": "Send a request with any method.",
              "md": "Every option of [`HttpRequest`](#http/http-request) is accepted; `url` is required. A value the request cannot carry raises before anything is sent: a header or query value with a line break, a header the transport sets itself (`Content-Length`, `Transfer-Encoding`, `Host`, `Connection`), a body on `GET` or `HEAD`, an unknown method.",
              "params": [
                {
                  "name": "opts",
                  "type": "HttpRequest",
                  "desc": "The request: see [`HttpRequest`](#http/http-request)."
                }
              ],
              "returns": [
                {
                  "type": "HttpResponse, err",
                  "desc": "The response (see [`HttpResponse`](#http/http-response)); `nil` and a failure code when no response came back.",
                  "only": "lua"
                },
                {
                  "type": "Promise<HttpResponse>",
                  "desc": "Resolves with the [`HttpResponse`](#http/http-response); rejects with a failure code when no response came back.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`timeout`",
                      "No complete response within `timeoutMs`."
                    ],
                    [
                      "`io`",
                      "Name resolution, connection, TLS or protocol error."
                    ],
                    [
                      "`permission`",
                      "Destination refused: on a client, a host name that resolves to a private or reserved address; on the server, outside the sandbox rules."
                    ],
                    [
                      "`limit`",
                      "The response body is larger than `maxBytes`."
                    ],
                    [
                      "`error`",
                      "With `responseType: \"json\"`, the body is not valid JSON. The status, headers and raw body come with the error (JS: `err.status`, `err.headers`, `err.body`; Lua: third return value)."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local function uploadScore(player, score)\n  local res, err = lsmp.http.request({\n    url = \"https://api.example.com/scores\",\n    method = \"PUT\",\n    headers = { Authorization = \"Bearer \" .. TOKEN },\n    json = { player = player, score = score },\n    timeoutMs = 10000,\n  })\n  if not res then\n    lsmp.warn(\"score upload failed: \" .. err)\n  elseif not res.ok then\n    lsmp.warn(\"score upload refused: HTTP \" .. res.status)\n  end\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "async function uploadScore(player, score) {\n  try {\n    const res = await lsmp.http.request({\n      url: 'https://api.example.com/scores',\n      method: 'PUT',\n      headers: { Authorization: `Bearer ${TOKEN}` },\n      json: { player, score },\n      timeoutMs: 10000,\n    });\n    if (!res.ok) lsmp.warn(`score upload refused: HTTP ${res.status}`);\n  } catch (err) {\n    lsmp.warn(`score upload failed: ${err.code}`);\n  }\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.http.get",
              "id": "fn-http-get",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.http.get(url [, opts] [, cb]) --> HttpResponse, err",
                "js": "lsmp.http.get(url: string, opts?: HttpRequest): Promise<HttpResponse>"
              },
              "summary": "Send a `GET` request.",
              "md": "Takes the options of [`HttpRequest`](#http/http-request) except `url`, `method`, `body` and `json`: a body on a `GET` raises, it never turns the request into a `POST`. Same failure codes as [`request`](#http/fn-http-request).",
              "params": [
                {
                  "name": "url",
                  "type": "string",
                  "desc": "The address, query string included or added with the `query` option."
                },
                {
                  "name": "opts",
                  "type": "HttpRequest",
                  "desc": "Headers, query, timeout, response type...: see [`HttpRequest`](#http/http-request).",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "HttpResponse, err",
                  "desc": "The response, or `nil` and a failure code.",
                  "only": "lua"
                },
                {
                  "type": "Promise<HttpResponse>",
                  "desc": "Resolves with the response; rejects with a failure code.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.registerCommand(\"motd\", function()\n  local res, err = lsmp.http.get(\"https://api.example.com/motd\", {\n    query = { lang = \"en\" },\n    responseType = \"json\",\n  })\n  if res and res.ok then\n    lsmp.log(\"message of the day: \" .. res.body.text)\n  else\n    lsmp.warn(\"no message of the day: \" .. (err or res.status))\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.registerCommand('motd', async () => {\n  try {\n    const res = await lsmp.http.get('https://api.example.com/motd', {\n      query: { lang: 'en' },\n      responseType: 'json',\n    });\n    if (res.ok) lsmp.log(`message of the day: ${res.body.text}`);\n  } catch (err) {\n    lsmp.warn(`no message of the day: ${err.code}`);\n  }\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.http.post",
              "id": "fn-http-post",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.http.post(url [, opts] [, cb]) --> HttpResponse, err",
                "js": "lsmp.http.post(url: string, opts?: HttpRequest): Promise<HttpResponse>"
              },
              "summary": "Send a `POST` request.",
              "md": "Takes the options of [`HttpRequest`](#http/http-request) except `url` and `method`. Give the body with `body` (text or bytes) or `json` (any value, encoded for you with `Content-Type: application/json`). Same failure codes as [`request`](#http/fn-http-request).",
              "params": [
                {
                  "name": "url",
                  "type": "string",
                  "desc": "The address."
                },
                {
                  "name": "opts",
                  "type": "HttpRequest",
                  "desc": "Body, headers, timeout...: see [`HttpRequest`](#http/http-request).",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "HttpResponse, err",
                  "desc": "The response, or `nil` and a failure code.",
                  "only": "lua"
                },
                {
                  "type": "Promise<HttpResponse>",
                  "desc": "Resolves with the response; rejects with a failure code.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- A message in a Discord channel, through a webhook.\nlocal res, err = lsmp.http.post(WEBHOOK_URL, {\n  json = { content = \"Server restarting in 5 minutes\" },\n})\nif not res then lsmp.warn(\"webhook: \" .. err) end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// A message in a Discord channel, through a webhook.\nlsmp.http.post(WEBHOOK_URL, { json: { content: 'Server restarting in 5 minutes' } })\n  .catch((err) => lsmp.warn(`webhook: ${err.code}`));"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Shapes",
              "level": 2,
              "id": "http-shapes"
            },
            {
              "type": "heading",
              "text": "HttpRequest",
              "level": 3,
              "id": "http-request"
            },
            {
              "type": "text",
              "md": "An unknown option name raises, with a suggestion when it is close to a real one."
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`url`",
                  "string",
                  "—",
                  "Required for `request`. `https://...` (`http://` on the server only). No spaces or control characters."
                ],
                [
                  "`method`",
                  "string",
                  "`\"GET\"`",
                  "`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD` or `OPTIONS`. `request` only."
                ],
                [
                  "`headers`",
                  "table",
                  "—",
                  "Header names to values. A value is a string or a finite number."
                ],
                [
                  "`query`",
                  "table",
                  "—",
                  "Parameters added to the URL, encoded for you. Values: strings or finite numbers."
                ],
                [
                  "`body`",
                  "string | bytes",
                  "—",
                  "Raw request body. Not with `json`, never on `GET`/`HEAD`."
                ],
                [
                  "`json`",
                  "value",
                  "—",
                  "A value sent as JSON, with `Content-Type: application/json` unless you set one."
                ],
                [
                  "`timeoutMs`",
                  "ms",
                  "`30000`",
                  "Whole request, `1` to `300000`."
                ],
                [
                  "`responseType`",
                  "string",
                  "`\"text\"`",
                  "`\"text\"` (a string), `\"bytes\"` (JS `Uint8Array`, Lua string) or `\"json\"` (the decoded value)."
                ],
                [
                  "`followRedirects`",
                  "boolean",
                  "`true`",
                  "Follow `3xx` redirections."
                ],
                [
                  "`http3`",
                  "boolean",
                  "`false`",
                  "Try HTTP/3 first."
                ],
                [
                  "`maxBytes`",
                  "int",
                  "`67108864`",
                  "Largest response body accepted (64 MiB at most). Larger: failure `limit`."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "HttpResponse",
              "level": 3,
              "id": "http-response"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`ok`",
                  "boolean",
                  "—",
                  "`true` for a status from `200` to `299`."
                ],
                [
                  "`status`",
                  "int",
                  "—",
                  "The HTTP status."
                ],
                [
                  "`statusText`",
                  "string",
                  "—",
                  "The reason phrase sent by the server, possibly empty."
                ],
                [
                  "`headers`",
                  "table",
                  "—",
                  "Header names in lower case. A repeated header is joined with `\", \"`, except `set-cookie`, which is a list."
                ],
                [
                  "`body`",
                  "string | bytes | value",
                  "—",
                  "As asked by `responseType`."
                ],
                [
                  "`url`",
                  "string",
                  "—",
                  "The address that was requested (query included)."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Good to know",
              "level": 2,
              "id": "http-good-to-know"
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "**Secrets stay on the server.** A token written in a client script is readable by every player: call authenticated services from a server script, and let clients ask the server.",
                "**A response is not a success.** Always look at `res.ok` or `res.status` before using the body.",
                "**One request, one answer.** There is no streaming: the whole body is received, up to `maxBytes`, before the call returns.",
                "To answer HTTP requests instead of sending them, see [HTTP routes](#server-http-serve)."
              ]
            }
          ]
        },
        {
          "id": "players",
          "title": "Players",
          "eyebrow": "Shared · Lua & JS",
          "lead": "Who is connected, what they are called, which account they play with, and where their ped is.",
          "blocks": [
            {
              "type": "text",
              "md": "Every connected player has a **playerId**: a small number for the length of their session. It identifies the player in every function, event and network message. When the player leaves, the number is given to the next player who joins.\n\nTo remember a player beyond a session (money, a character, a ban), use their **account**: the `lsmpId`. Guests have no account."
            },
            {
              "type": "table",
              "headers": [
                "Identifier",
                "Lives",
                "Use it for"
              ],
              "rows": [
                [
                  "`playerId`",
                  "One session. Reused after the player leaves.",
                  "Every API call, events, network messages."
                ],
                [
                  "`lsmpId`",
                  "Forever. The same on every server.",
                  "Saved data, bans, permissions. `nil`/`null` for a guest."
                ],
                [
                  "Name",
                  "Chosen by the player, may change.",
                  "Display only. Never a key."
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "Is the account real?",
              "md": "A player's `lsmpId` is proven only when the server verifies its players (\"Verify players with LS:MP\" in the admin panel, see [server.cfg](#server-cfg)). Without verification it is what the client declares: fine for display and statistics, not for anything a cheater would want to steal. See [Admission and moderation](#server-moderation)."
            },
            {
              "type": "heading",
              "text": "Listing players",
              "level": 2,
              "id": "players-list"
            },
            {
              "type": "function",
              "name": "lsmp.getPlayers",
              "id": "fn-get-players",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getPlayers() --> {integer}",
                "js": "lsmp.getPlayers(): number[]"
              },
              "summary": "Every player, by playerId, in ascending order.",
              "md": "On the server: the connected players. On a client: the players of the session this client knows, the local player included. A new list on each call.",
              "returns": [
                {
                  "type": "{integer}",
                  "desc": "A list of playerIds, possibly empty.",
                  "only": "lua"
                },
                {
                  "type": "number[]",
                  "desc": "A list of playerIds, possibly empty.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "for _, id in ipairs(lsmp.getPlayers()) do\n  lsmp.log(id, lsmp.getPlayerName(id))\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "for (const id of lsmp.getPlayers()) {\n  lsmp.log(id, lsmp.getPlayerName(id));\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.playerExists",
              "id": "fn-player-exists",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.playerExists(playerId) --> boolean",
                "js": "lsmp.playerExists(playerId: number): boolean"
              },
              "summary": "Whether a playerId is in use.",
              "md": "On the server, `true` while the player is connected; on a client, while the player is in the session. Inside a [`playerLeave`](#engine-events) handler it is already `false` for the leaving player, even though their name and account can still be read.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player to test."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the player is there."
              }
            },
            {
              "type": "heading",
              "text": "Name and account",
              "level": 2,
              "id": "players-identity"
            },
            {
              "type": "function",
              "name": "lsmp.getPlayerName",
              "id": "fn-get-player-name",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getPlayerName(playerId) --> string?",
                "js": "lsmp.getPlayerName(playerId: number): string | null"
              },
              "summary": "The name a player connected with.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "string?",
                  "desc": "The name, or `nil`/`null` if the player is unknown.",
                  "only": "lua"
                },
                {
                  "type": "string | null",
                  "desc": "The name, or `nil`/`null` if the player is unknown.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getPlayerLsmpId",
              "id": "fn-get-player-lsmp-id",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getPlayerLsmpId(playerId) --> integer?",
                "js": "lsmp.getPlayerLsmpId(playerId: number): number | null"
              },
              "summary": "The LS:MP account of a player, as a number.",
              "md": "The same number on every server and every session: key saved data on it.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The account number, or `nil`/`null` for a guest or an unknown player.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The account number, or `nil`/`null` for a guest or an unknown player.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.on(\"playerJoin\", function(playerId, name)\n  local account = lsmp.getPlayerLsmpId(playerId)\n  if account then\n    lsmp.log(name .. \" plays with account \" .. account)\n  else\n    lsmp.log(name .. \" is a guest\")\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.on('playerJoin', (playerId, name) => {\n  const account = lsmp.getPlayerLsmpId(playerId);\n  if (account !== null) lsmp.log(`${name} plays with account ${account}`);\n  else lsmp.log(`${name} is a guest`);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.isPlayerGuest",
              "id": "fn-is-player-guest",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.isPlayerGuest(playerId) --> boolean?",
                "js": "lsmp.isPlayerGuest(playerId: number): boolean | null"
              },
              "summary": "Whether a player has no LS:MP account.",
              "md": "Compare with `false` to test for a registered player: `nil`/`null` means the player is unknown, not registered.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "boolean?",
                  "desc": "`true` for a guest, `false` for a registered player, `nil`/`null` if the player is unknown.",
                  "only": "lua"
                },
                {
                  "type": "boolean | null",
                  "desc": "`true` for a guest, `false` for a registered player, `nil`/`null` if the player is unknown.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getLsmpAvatarUrl",
              "id": "fn-get-lsmp-avatar-url",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getLsmpAvatarUrl(playerId) --> string?",
                "js": "lsmp.getLsmpAvatarUrl(playerId: number): string | null"
              },
              "summary": "The versioned profile avatar shared by a player.",
              "md": "On the server, reads the reference shared by the connected player. On the client, only the local player can be queried, and the same consent applies. Guests, missing avatars, disconnected players and players who decline sharing return `nil`/`null`. A consent change to off clears the reference for the current session. To share again, reconnect. Use a default icon when the result is absent or the image fails to load.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The current player handle. On the client, pass the result of `lsmp.getLocalPlayer()`."
                }
              ],
              "returns": [
                {
                  "type": "string?",
                  "desc": "An absolute HTTPS URL for the current avatar version, or `nil`/`null` when unavailable.",
                  "only": "lua"
                },
                {
                  "type": "string | null",
                  "desc": "An absolute HTTPS URL for the current avatar version, or `nil`/`null` when unavailable.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.isPlayerDev",
              "id": "fn-is-player-dev",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.isPlayerDev(playerId) --> boolean?",
                "js": "lsmp.isPlayerDev(playerId: number): boolean | null"
              },
              "summary": "Whether a player has developer status (DevTools allowed).",
              "md": "On a client, only the local player is known: for anybody else the answer is `nil`/`null`. Developer status is given with [`setPlayerDev`](#server-moderation/fn-set-player-dev).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "boolean?",
                  "desc": "`true` or `false`, or `nil`/`null` if the player is unknown.",
                  "only": "lua"
                },
                {
                  "type": "boolean | null",
                  "desc": "`true` or `false`, or `nil`/`null` if the player is unknown.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getPlayerDimension",
              "id": "fn-get-player-dimension",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getPlayerDimension(playerId) --> integer?",
                "js": "lsmp.getPlayerDimension(playerId: number): number | null"
              },
              "summary": "The dimension a player is in.",
              "md": "A client knows the dimension of every player of its session. Moving players between dimensions is on the [Dimensions](#dimensions) page.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The dimension, or `nil`/`null` if the player is unknown.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The dimension, or `nil`/`null` if the player is unknown.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Identifiers (server)",
              "level": 2,
              "id": "players-identifiers"
            },
            {
              "type": "text",
              "md": "Identifiers describe how a player connected. `lsmp` (the account, as a string) and `name` are always readable. `ip` (the address of the game connection) and `hwid` (a fingerprint of the machine) are private: they need the `players.identity` [capability](#capabilities)."
            },
            {
              "type": "function",
              "name": "lsmp.getPlayerIdentifier",
              "id": "fn-get-player-identifier",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getPlayerIdentifier(playerId, type) --> string?",
                "js": "lsmp.getPlayerIdentifier(playerId: number, type: string): string | null"
              },
              "summary": "One identifier of a connected player.",
              "md": "Can fail at run time: see [error codes](#error-codes).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "type",
                  "type": "string",
                  "desc": "`\"lsmp\"`, `\"name\"`, `\"ip\"` or `\"hwid\"`."
                }
              ],
              "returns": [
                {
                  "type": "string?",
                  "desc": "The identifier as a string, or `nil`/`null` if the player is unknown, has no such identifier (a guest has no `lsmp`), or the capability is missing.",
                  "only": "lua"
                },
                {
                  "type": "string | null",
                  "desc": "The identifier as a string, or `nil`/`null` if the player is unknown, has no such identifier (a guest has no `lsmp`), or the capability is missing.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "`\"ip\"` or `\"hwid\"` without the `players.identity` capability."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getPlayerIdentifiers",
              "id": "fn-get-player-identifiers",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getPlayerIdentifiers(playerId) --> table?",
                "js": "lsmp.getPlayerIdentifiers(playerId: number): table | null"
              },
              "summary": "Every identifier of a connected player, as one table.",
              "md": "`{ lsmp, name, ip, hwid }`. A type the player does not have is absent; `ip` and `hwid` are absent without the `players.identity` [capability](#capabilities).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "table?",
                  "desc": "The identifiers, or `nil`/`null` if the player is unknown.",
                  "only": "lua"
                },
                {
                  "type": "table | null",
                  "desc": "The identifiers, or `nil`/`null` if the player is unknown.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local ids = lsmp.getPlayerIdentifiers(source)\nif ids then\n  for kind, value in pairs(ids) do\n    lsmp.log(kind, value)\n  end\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const ids = lsmp.getPlayerIdentifiers(source);\nif (ids) {\n  for (const [kind, value] of Object.entries(ids)) lsmp.log(kind, value);\n}"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "The player's ped",
              "level": 2,
              "id": "players-ped"
            },
            {
              "type": "text",
              "md": "The ped is the character a player walks around with. The server and a client name it differently: the server uses its **netId**, a client its **game handle** (what natives take). See [Entities and streaming](#client-entities) for the difference."
            },
            {
              "type": "function",
              "name": "lsmp.getPlayerPed",
              "id": "fn-get-player-ped",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getPlayerPed(playerId) --> integer?",
                "js": "lsmp.getPlayerPed(playerId: number): number | null"
              },
              "summary": "The netId of a player's ped.",
              "md": "A player has no ped before their first spawn.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The netId, or `nil`/`null` if the player has no ped yet or is unknown.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The netId, or `nil`/`null` if the player has no ped yet or is unknown.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local ped = lsmp.getPlayerPed(playerId)\nlocal pos = ped and lsmp.getEntityCoords(ped)\nif pos then\n  lsmp.log((\"player %d is at %.1f, %.1f, %.1f\"):format(playerId, pos.x, pos.y, pos.z))\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const ped = lsmp.getPlayerPed(playerId);\nconst pos = ped !== null ? lsmp.getEntityCoords(ped) : null;\nif (pos) lsmp.log(`player ${playerId} is at ${pos.x.toFixed(1)}, ${pos.y.toFixed(1)}, ${pos.z.toFixed(1)}`);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.getPlayerPed",
              "id": "fn-get-player-ped-client",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getPlayerPed(playerId) --> integer?",
                "js": "lsmp.getPlayerPed(playerId: number): number | null"
              },
              "summary": "The game handle of a player's ped, while it exists on this client.",
              "md": "A player far away is not streamed on this client and has no ped here. For the local player, the native `playerPedId()` gives the same handle.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The game handle, or `nil`/`null` while the ped is not on this client.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The game handle, or `nil`/`null` while the ped is not on this client.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Events",
              "level": 2,
              "id": "players-events"
            },
            {
              "type": "text",
              "md": "[`playerJoin`](#engine-events) and [`playerLeave`](#engine-events) fire on both sides when a player arrives and leaves. On a client, `playerJoin` is not fired for the local player (use [`lsmp.getLocalPlayer()`](#local-player)), and the `detail` of `playerLeave` is always `nil`/`null`. The events are not replayed: a script that starts while players are connected reads `lsmp.getPlayers()` once, then follows the events."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "local online = {}\n\n-- Players already here when the resource starts.\nfor _, id in ipairs(lsmp.getPlayers()) do\n  online[id] = lsmp.getPlayerName(id)\nend\n\nlsmp.on(\"playerJoin\", function(playerId, name)\n  online[playerId] = name\nend)\n\nlsmp.on(\"playerLeave\", function(playerId, name, reason)\n  online[playerId] = nil\n  lsmp.log(name .. \" left (\" .. reason .. \")\")\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "const online = new Map();\n\n// Players already here when the resource starts.\nfor (const id of lsmp.getPlayers()) online.set(id, lsmp.getPlayerName(id));\n\nlsmp.on('playerJoin', (playerId, name) => {\n  online.set(playerId, name);\n});\n\nlsmp.on('playerLeave', (playerId, name, reason) => {\n  online.delete(playerId);\n  lsmp.log(`${name} left (${reason})`);\n});"
                }
              ]
            }
          ]
        },
        {
          "id": "meta",
          "title": "Meta (replicated key/values)",
          "eyebrow": "Shared · Lua & JS",
          "lead": "Small values attached to players, entities or the session, replicated to every client.",
          "blocks": [
            {
              "type": "text",
              "md": "Meta are small key/value pairs attached to a **player**, an **entity**, or the whole session (**global**). The server replicates them to every client: one write, and every script on every machine can read the value. Use them for state that clients display or react to: a job, a team, a vehicle's fuel, a door's lock."
            },
            {
              "type": "table",
              "headers": [
                "Scope",
                "Read",
                "Written by",
                "Lives until"
              ],
              "rows": [
                [
                  "player",
                  "everywhere, `getPlayerMeta`",
                  "server scripts; a client for its own player",
                  "the player leaves"
                ],
                [
                  "entity",
                  "everywhere, `getEntityMeta`",
                  "server scripts; the client that owns (simulates) the entity",
                  "the entity is deleted"
                ],
                [
                  "global",
                  "everywhere, `getGlobalMeta`",
                  "server scripts only",
                  "the server stops"
                ]
              ]
            },
            {
              "type": "list",
              "items": [
                "Values are copied: reading returns a new copy, and changing it does nothing until you write it back.",
                "Writing the same value again does nothing (no network traffic, no event).",
                "Every change fires the [`metaChange`](#engine-events/ev-meta-change) engine event on the server and on clients. Filter it by scope, key and target.",
                "Meta are **not saved**. To keep data across sessions, store it with [storage](#server-storage) or [MySQL](#server-mysql) and restore it on `playerJoin`. See [Storing data](#data-guide).",
                "Keys starting with `lsmp:` belong to LS:MP: they read as absent and writing them raises."
              ]
            },
            {
              "type": "callout",
              "variant": "danger",
              "md": "A client can write its own player's meta and the meta of entities it simulates. Never trust such values on the server for anything that matters (money, rights): keep authoritative values in server-written meta, and check the `source` of `metaChange`.",
              "title": "Client writes"
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- server: give a job\nlsmp.setPlayerMeta(playerId, \"job\", { name = \"police\", grade = 2 })\n\n-- client: react to it\nlsmp.on(\"metaChange\", function(scope, target, key, value)\n  if value then lsmp.log(\"job: \" .. value.name) end\nend, { scope = \"player\", key = \"job\" })"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// server: give a job\nlsmp.setPlayerMeta(playerId, \"job\", { name: \"police\", grade: 2 });\n\n// client: react to it\nlsmp.on(\"metaChange\", (scope, target, key, value) => {\n  if (value) lsmp.log(`job: ${value.name}`);\n}, { scope: \"player\", key: \"job\" });"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Reading",
              "level": 2,
              "id": "reading"
            },
            {
              "type": "function",
              "name": "lsmp.getPlayerMeta",
              "id": "fn-get-player-meta",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getPlayerMeta(playerId, key) --> any?",
                "js": "lsmp.getPlayerMeta(playerId: number, key: string): Value | null"
              },
              "summary": "A player's meta value.",
              "md": "Still readable inside `playerLeave` handlers for the leaving player.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "key",
                  "type": "string",
                  "desc": "Key: 1 to 128 bytes of UTF-8, not starting with `lsmp:`."
                }
              ],
              "returns": [
                {
                  "type": "any?",
                  "desc": "The value, or `nil`/`null` if absent or if the player is unknown.",
                  "only": "lua"
                },
                {
                  "type": "Value | null",
                  "desc": "The value, or `nil`/`null` if absent or if the player is unknown.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local job = lsmp.getPlayerMeta(playerId, \"job\")\nif job and job.name == \"police\" then openArmory(playerId) end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const job = lsmp.getPlayerMeta(playerId, \"job\");\nif (job?.name === \"police\") openArmory(playerId);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.getEntityMeta",
              "id": "fn-get-entity-meta",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getEntityMeta(netId, key) --> any?",
                "js": "lsmp.getEntityMeta(netId: number, key: string): Value | null"
              },
              "summary": "An entity's meta value.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                },
                {
                  "name": "key",
                  "type": "string",
                  "desc": "Key: 1 to 128 bytes of UTF-8, not starting with `lsmp:`."
                }
              ],
              "returns": [
                {
                  "type": "any?",
                  "desc": "The value, or `nil`/`null` if absent or if the entity is unknown.",
                  "only": "lua"
                },
                {
                  "type": "Value | null",
                  "desc": "The value, or `nil`/`null` if absent or if the entity is unknown.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getGlobalMeta",
              "id": "fn-get-global-meta",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getGlobalMeta(key) --> any?",
                "js": "lsmp.getGlobalMeta(key: string): Value | null"
              },
              "summary": "A global meta value.",
              "params": [
                {
                  "name": "key",
                  "type": "string",
                  "desc": "Key: 1 to 128 bytes of UTF-8, not starting with `lsmp:`."
                }
              ],
              "returns": [
                {
                  "type": "any?",
                  "desc": "The value, or `nil`/`null` if absent.",
                  "only": "lua"
                },
                {
                  "type": "Value | null",
                  "desc": "The value, or `nil`/`null` if absent.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Writing on the server",
              "level": 2,
              "id": "server"
            },
            {
              "type": "function",
              "name": "lsmp.setPlayerMeta",
              "id": "fn-set-player-meta",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setPlayerMeta(playerId, key, value) --> boolean",
                "js": "lsmp.setPlayerMeta(playerId: number, key: string, value: Value): boolean"
              },
              "summary": "Sets or deletes a player's meta value, replicated to every client.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "key",
                  "type": "string",
                  "desc": "Key: 1 to 128 bytes of UTF-8, not starting with `lsmp:`."
                },
                {
                  "name": "value",
                  "type": "value",
                  "desc": "Any [transportable value](#conventions/transportable-values) up to 8192 bytes encoded. `nil`/`null` deletes the key."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` (`not-found`) if the player is unknown."
              }
            },
            {
              "type": "function",
              "name": "lsmp.setEntityMeta",
              "id": "fn-set-entity-meta",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setEntityMeta(netId, key, value) --> boolean",
                "js": "lsmp.setEntityMeta(netId: number, key: string, value: Value): boolean"
              },
              "summary": "Sets or deletes an entity's meta value, replicated to every client.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                },
                {
                  "name": "key",
                  "type": "string",
                  "desc": "Key: 1 to 128 bytes of UTF-8, not starting with `lsmp:`."
                },
                {
                  "name": "value",
                  "type": "value",
                  "desc": "Any [transportable value](#conventions/transportable-values) up to 8192 bytes encoded. `nil`/`null` deletes the key."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` (`not-found`) if the entity is unknown."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.setEntityMeta(car, \"fuel\", 0.75)\nlsmp.setEntityMeta(car, \"locked\", true)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.setEntityMeta(car, \"fuel\", 0.75);\nlsmp.setEntityMeta(car, \"locked\", true);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.setGlobalMeta",
              "id": "fn-set-global-meta",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setGlobalMeta(key, value) --> boolean",
                "js": "lsmp.setGlobalMeta(key: string, value: Value): boolean"
              },
              "summary": "Sets or deletes a global meta value, replicated to every client.",
              "params": [
                {
                  "name": "key",
                  "type": "string",
                  "desc": "Key: 1 to 128 bytes of UTF-8, not starting with `lsmp:`."
                },
                {
                  "name": "value",
                  "type": "value",
                  "desc": "Any [transportable value](#conventions/transportable-values) up to 8192 bytes encoded. `nil`/`null` deletes the key."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` when done."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.setGlobalMeta(\"event:active\", \"carnival\")"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.setGlobalMeta(\"event:active\", \"carnival\");"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Writing on a client",
              "level": 2,
              "id": "client"
            },
            {
              "type": "text",
              "md": "A client writes only what it owns. Its writes reach the server and the other clients, and are limited by the server (`MetaMaxKeys`, `MetaMaxBlobBytes`, `MetaWriteBytesPerSec`; see [Limits](#limits/storage))."
            },
            {
              "type": "function",
              "name": "lsmp.setPlayerMeta",
              "id": "fn-set-player-meta-client",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setPlayerMeta(playerId, key, value) --> boolean",
                "js": "lsmp.setPlayerMeta(playerId: number, key: string, value: Value): boolean"
              },
              "summary": "Sets or deletes a meta value on the **local** player.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "Must be the local player."
                },
                {
                  "name": "key",
                  "type": "string",
                  "desc": "Key: 1 to 128 bytes of UTF-8, not starting with `lsmp:`."
                },
                {
                  "name": "value",
                  "type": "value",
                  "desc": "Any [transportable value](#conventions/transportable-values) up to 8192 bytes encoded. `nil`/`null` deletes the key."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `disconnected` (not in a session) or `limit` (server budget or rate)."
              }
            },
            {
              "type": "function",
              "name": "lsmp.setEntityMeta",
              "id": "fn-set-entity-meta-client",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setEntityMeta(netId, key, value) --> boolean",
                "js": "lsmp.setEntityMeta(netId: number, key: string, value: Value): boolean"
              },
              "summary": "Sets or deletes a meta value on an entity this client owns.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "An entity simulated by this client."
                },
                {
                  "name": "key",
                  "type": "string",
                  "desc": "Key: 1 to 128 bytes of UTF-8, not starting with `lsmp:`."
                },
                {
                  "name": "value",
                  "type": "value",
                  "desc": "Any [transportable value](#conventions/transportable-values) up to 8192 bytes encoded. `nil`/`null` deletes the key."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `permission` (not the owner), `not-found`, `disconnected` or `limit`."
              }
            }
          ]
        },
        {
          "id": "spatial",
          "title": "Spatial queries",
          "eyebrow": "Shared · Lua & JS",
          "lead": "Find the closest player or entity, or every entity within a radius.",
          "blocks": [
            {
              "type": "text",
              "md": "Find players and networked entities around a position. On the **server** the search covers every entity of one dimension (the default world unless you pass `dimension`). On a **client** it covers the entities this client knows, which are the ones streamed around the player; the `dimension` option does not apply there."
            },
            {
              "type": "text",
              "md": "Distances are measured in 3D, in meters, from the last synchronized positions."
            },
            {
              "type": "heading",
              "text": "Options",
              "level": 2,
              "id": "options"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`maxRadius`",
                  "meters",
                  "`0`",
                  "`getClosestPlayer`, `getClosestEntity`: ignore anything farther. `0` means no limit."
                ],
                [
                  "`types`",
                  "list of strings",
                  "all",
                  "`getClosestEntity`, `getEntitiesInRadius`: any of `\"vehicle\"`, `\"ped\"`, `\"object\"`, `\"playerPed\"`."
                ],
                [
                  "`dimension`",
                  "dimension",
                  "`0`",
                  "Server only: the dimension to search."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Functions",
              "level": 2,
              "id": "functions"
            },
            {
              "type": "function",
              "name": "lsmp.getClosestPlayer",
              "id": "fn-get-closest-player",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getClosestPlayer(position [, opts]) --> integer?",
                "js": "lsmp.getClosestPlayer(position: Vec3Like, opts?: ClosestOptions): number | null"
              },
              "summary": "The player whose ped is closest to a position.",
              "md": "On a client the local player is included: exclude it yourself if needed.",
              "params": [
                {
                  "name": "position",
                  "type": "vec3",
                  "desc": "The center of the search."
                },
                {
                  "name": "opts",
                  "type": "ClosestOptions",
                  "optional": true,
                  "desc": "`{ maxRadius, dimension }`."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "A playerId, or `nil`/`null` if none.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "A playerId, or `nil`/`null` if none.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local target = lsmp.getClosestPlayer(lsmp.getEntityCoords(lsmp.getPlayerPed(source)), { maxRadius = 3.0 })"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const target = lsmp.getClosestPlayer(lsmp.getEntityCoords(lsmp.getPlayerPed(source)), { maxRadius: 3 });"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.getClosestEntity",
              "id": "fn-get-closest-entity",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getClosestEntity(position [, opts]) --> integer?",
                "js": "lsmp.getClosestEntity(position: Vec3Like, opts?: ClosestOptions): number | null"
              },
              "summary": "The networked entity closest to a position.",
              "params": [
                {
                  "name": "position",
                  "type": "vec3",
                  "desc": "The center of the search."
                },
                {
                  "name": "opts",
                  "type": "ClosestOptions",
                  "optional": true,
                  "desc": "`{ types, maxRadius, dimension }`."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "A netId, or `nil`/`null` if none.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "A netId, or `nil`/`null` if none.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local car = lsmp.getClosestEntity(position, { types = { \"vehicle\" }, maxRadius = 10.0 })"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const car = lsmp.getClosestEntity(position, { types: [\"vehicle\"], maxRadius: 10 });"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.getEntitiesInRadius",
              "id": "fn-get-entities-in-radius",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getEntitiesInRadius(position, radius [, opts]) --> {integer}",
                "js": "lsmp.getEntitiesInRadius(position: Vec3Like, radius: number, opts?: QueryOptions): Uint32Array"
              },
              "summary": "Every networked entity within a radius.",
              "params": [
                {
                  "name": "position",
                  "type": "vec3",
                  "desc": "The center of the search."
                },
                {
                  "name": "radius",
                  "type": "meters",
                  "desc": "Search radius."
                },
                {
                  "name": "opts",
                  "type": "QueryOptions",
                  "optional": true,
                  "desc": "`{ types, dimension }`."
                }
              ],
              "returns": [
                {
                  "type": "{integer}",
                  "desc": "The netIds, in no particular order. A `Uint32Array` in JavaScript: use `for...of` or `Array.from`.",
                  "only": "lua"
                },
                {
                  "type": "Uint32Array",
                  "desc": "The netIds, in no particular order. A `Uint32Array` in JavaScript: use `for...of` or `Array.from`.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "for _, netId in ipairs(lsmp.getEntitiesInRadius(position, 25.0, { types = { \"ped\" } })) do\n  lsmp.setEntityIntent(netId, { type = \"flee\", target = \"nearestPlayer\" })\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "for (const netId of lsmp.getEntitiesInRadius(position, 25, { types: [\"ped\"] })) {\n  lsmp.setEntityIntent(netId, { type: \"flee\", target: \"nearestPlayer\" });\n}"
                  }
                ]
              }
            }
          ]
        },
        {
          "id": "weather",
          "title": "Weather and time",
          "eyebrow": "Shared · Lua & JS",
          "lead": "One sky for the whole server: a random weather cycle every player sees the same way, that scripts can override.",
          "blocks": [
            {
              "type": "text",
              "md": "The server runs a **weather cycle**: segments of a few minutes each, chosen at random from a seed, joined by smooth transitions. Every client computes the same cycle, so all players see the same sky at the same moment, without any traffic.\n\nA server script can **force** a weather for a while, then hand back to the cycle. A client script can give **its own player** a different sky, for a cutscene or an interior, without changing anybody else's.\n\nThe game clock is shared the same way: every player has the same time of day, and it runs on its own (one game day lasts 48 real minutes). Clock natives that set the time have no effect during a session."
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "One forced weather at a time",
              "md": "The forced weather belongs to the resource that set it. When that resource stops, the weather goes back to what was there before: the weather forced by another resource, or the cycle. A weather forced on the client works the same way, per resource."
            },
            {
              "type": "heading",
              "text": "Reading the weather",
              "level": 2,
              "id": "weather-read"
            },
            {
              "type": "function",
              "name": "lsmp.weather.get",
              "id": "fn-weather-get",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.weather.get() --> WeatherState?",
                "js": "lsmp.weather.get(): WeatherState | null"
              },
              "summary": "The synchronized weather at this moment.",
              "md": "See [`WeatherState`](#weather/weather-state). On a client, `nil`/`null` until the first state arrived from the server, a moment after connecting.",
              "returns": [
                {
                  "type": "WeatherState?",
                  "desc": "The current state.",
                  "only": "lua"
                },
                {
                  "type": "WeatherState | null",
                  "desc": "The current state.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local w = lsmp.weather.get()\nif w then\n  lsmp.log(\"weather: \" .. w.type .. (w.forced and \" (forced)\" or \"\"))\n  if w.next then\n    lsmp.log((\"next: %s in %d s\"):format(w.next, w.nextChangeMs // 1000))\n  end\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const w = lsmp.weather.get();\nif (w) {\n  lsmp.log(`weather: ${w.type}${w.forced ? ' (forced)' : ''}`);\n  if (w.next) lsmp.log(`next: ${w.next} in ${Math.floor(w.nextChangeMs / 1000)} s`);\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.weather.getForecast",
              "id": "fn-weather-get-forecast",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.weather.getForecast([count]) --> {WeatherForecastEntry}",
                "js": "lsmp.weather.getForecast(count: number = 6): WeatherForecastEntry[]"
              },
              "summary": "The next changes of the weather cycle.",
              "md": "Each entry is a [`WeatherForecastEntry`](#weather/weather-forecast-entry). While a weather is forced, the forecast shows the cycle that resumes after it.",
              "params": [
                {
                  "name": "count",
                  "type": "int",
                  "desc": "How many upcoming changes, `1` to `32`.",
                  "optional": true,
                  "default": "6"
                }
              ],
              "returns": [
                {
                  "type": "{WeatherForecastEntry}",
                  "desc": "The upcoming changes, soonest first.",
                  "only": "lua"
                },
                {
                  "type": "WeatherForecastEntry[]",
                  "desc": "The upcoming changes, soonest first.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.weather.getTypes",
              "id": "fn-weather-get-types",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.weather.getTypes() --> {string}",
                "js": "lsmp.weather.getTypes(): string[]"
              },
              "summary": "The weather names `set` and `setLocal` accept.",
              "md": "For example `\"EXTRASUNNY\"`, `\"RAIN\"`, `\"THUNDER\"`, `\"SNOW\"`, `\"XMAS\"`, `\"HALLOWEEN\"`. Names are upper case.",
              "returns": [
                {
                  "type": "{string}",
                  "desc": "Every weather name.",
                  "only": "lua"
                },
                {
                  "type": "string[]",
                  "desc": "Every weather name.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Forcing the weather (server)",
              "level": 2,
              "id": "weather-server"
            },
            {
              "type": "function",
              "name": "lsmp.weather.set",
              "id": "fn-weather-set",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.weather.set(type [, opts]) --> boolean",
                "js": "lsmp.weather.set(type: string, opts?: WeatherSetOptions): boolean"
              },
              "summary": "Force a weather on every player.",
              "md": "The change fades in over `transitionMs`. With a `durationMs`, the cycle resumes on its own after that time (with the same fade); without, the weather stays until a script changes it or the resource stops. Clients receive the new weather in the same second.\n\nNeeds the `world.weather` [capability](#capabilities).",
              "params": [
                {
                  "name": "type",
                  "type": "string",
                  "desc": "A name from [`getTypes`](#weather/fn-weather-get-types)."
                },
                {
                  "name": "opts",
                  "type": "WeatherSetOptions",
                  "desc": "See [`WeatherSetOptions`](#weather/weather-set-options).",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the weather was set."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The resource does not hold `world.weather`."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- /storm: one thunderstorm, fading in over 30 s, for 10 minutes.\nlsmp.registerCommand(\"storm\", { help = \"Ten minutes of thunderstorm\" }, function()\n  lsmp.weather.set(\"THUNDER\", { transitionMs = 30000, durationMs = 600000 })\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// /storm: one thunderstorm, fading in over 30 s, for 10 minutes.\nlsmp.registerCommand('storm', { help: 'Ten minutes of thunderstorm' }, () => {\n  lsmp.weather.set('THUNDER', { transitionMs: 30000, durationMs: 600000 });\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.weather.resumeCycle",
              "id": "fn-weather-resume-cycle",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.weather.resumeCycle([opts]) --> boolean",
                "js": "lsmp.weather.resumeCycle(opts?: WeatherTransitionOptions): boolean"
              },
              "summary": "Stop forcing the weather and go back to the cycle.",
              "md": "Needs the `world.weather` [capability](#capabilities).",
              "params": [
                {
                  "name": "opts",
                  "type": "WeatherTransitionOptions",
                  "desc": "`{ transitionMs }`: the fade back, `0` to `3600000` ms.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if a forced weather was lifted, `false` if the cycle was already running."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The resource does not hold `world.weather`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.weather.setSeed",
              "id": "fn-weather-set-seed",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.weather.setSeed(seed) --> boolean",
                "js": "lsmp.weather.setSeed(seed: number): boolean"
              },
              "summary": "Choose the seed of the weather cycle.",
              "md": "The same seed gives the same sequence of weathers. Changing it changes the coming segments for everybody; the current one finishes first.\n\nNeeds the `world.weather` [capability](#capabilities).",
              "params": [
                {
                  "name": "seed",
                  "type": "uint",
                  "desc": "Any integer from `0` to `4294967295`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the seed was set."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The resource does not hold `world.weather`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "A sky of your own (client)",
              "level": 2,
              "id": "weather-client"
            },
            {
              "type": "function",
              "name": "lsmp.weather.setLocal",
              "id": "fn-weather-set-local",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.weather.setLocal(type [, opts]) --> boolean",
                "js": "lsmp.weather.setLocal(type: string, opts?: WeatherTransitionOptions): boolean"
              },
              "summary": "Show this player a different weather.",
              "md": "Only the local player sees it; the shared weather goes on for everybody else, and comes back with [`clearLocal`](#weather/fn-weather-clear-local). When several resources set one, the last call wins; each is removed when its resource stops.",
              "params": [
                {
                  "name": "type",
                  "type": "string",
                  "desc": "A name from [`getTypes`](#weather/fn-weather-get-types)."
                },
                {
                  "name": "opts",
                  "type": "WeatherTransitionOptions",
                  "desc": "`{ transitionMs }`: the fade, `0` to `3600000` ms.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the weather was applied."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- Clear sky inside the arena, whatever the weather outside.\nlsmp.on(\"arena:enter\", function()\n  lsmp.weather.setLocal(\"EXTRASUNNY\", { transitionMs = 2000 })\nend)\nlsmp.on(\"arena:leave\", function()\n  lsmp.weather.clearLocal({ transitionMs = 2000 })\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// Clear sky inside the arena, whatever the weather outside.\nlsmp.on('arena:enter', () => lsmp.weather.setLocal('EXTRASUNNY', { transitionMs: 2000 }));\nlsmp.on('arena:leave', () => lsmp.weather.clearLocal({ transitionMs: 2000 }));"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.weather.clearLocal",
              "id": "fn-weather-clear-local",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.weather.clearLocal([opts]) --> boolean",
                "js": "lsmp.weather.clearLocal(opts?: WeatherTransitionOptions): boolean"
              },
              "summary": "Remove this resource's local weather.",
              "params": [
                {
                  "name": "opts",
                  "type": "WeatherTransitionOptions",
                  "desc": "`{ transitionMs }`: the fade back to the shared weather.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if this resource had a local weather."
              }
            },
            {
              "type": "function",
              "name": "lsmp.weather.getState",
              "id": "fn-weather-get-state",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.weather.getState() --> WeatherMix",
                "js": "lsmp.weather.getState(): WeatherMix"
              },
              "summary": "The weather the game is drawing at this moment.",
              "md": "During a transition the game blends two weathers: `{ type1, type2, percent }`, with the weathers as hashes and `percent` from `0` (all `type1`) to `1` (all `type2`). Useful to match an effect to what the player sees.",
              "returns": {
                "type": "WeatherMix",
                "desc": "The blend being drawn."
              }
            },
            {
              "type": "heading",
              "text": "Event",
              "level": 2,
              "id": "weather-event"
            },
            {
              "type": "text",
              "md": "[`weatherChange`](#engine-events) `(type, previous, transitionMs)` fires on both sides when a new weather starts fading in, whether the cycle moved on or a script forced it. `previous` is `nil`/`null` when unknown."
            },
            {
              "type": "heading",
              "text": "Shapes",
              "level": 2,
              "id": "weather-shapes"
            },
            {
              "type": "heading",
              "text": "WeatherState",
              "level": 3,
              "id": "weather-state"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`type`",
                  "string",
                  "—",
                  "The weather fading in, or in place."
                ],
                [
                  "`previous`",
                  "string?",
                  "—",
                  "The weather it replaces while a transition runs."
                ],
                [
                  "`transitionMs`",
                  "ms",
                  "—",
                  "Total length of the transition in progress (`0` when none)."
                ],
                [
                  "`transitionTimeMs`",
                  "ms",
                  "—",
                  "Time already elapsed in that transition."
                ],
                [
                  "`forced`",
                  "boolean",
                  "—",
                  "`true` while a script forces the weather."
                ],
                [
                  "`forcedTimeLeftMs`",
                  "ms?",
                  "—",
                  "Time before the cycle resumes; absent when forced with no duration, or not forced."
                ],
                [
                  "`next`",
                  "string?",
                  "—",
                  "The next weather of the cycle."
                ],
                [
                  "`nextChangeMs`",
                  "ms?",
                  "—",
                  "Time before that change."
                ],
                [
                  "`seed`",
                  "uint",
                  "—",
                  "The seed of the cycle."
                ],
                [
                  "`localOverride`",
                  "string?",
                  "—",
                  "Client only: the local weather set with `setLocal`, if any."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "WeatherForecastEntry",
              "level": 3,
              "id": "weather-forecast-entry"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`type`",
                  "string",
                  "—",
                  "The weather of that segment."
                ],
                [
                  "`atMs`",
                  "epochMs",
                  "—",
                  "When it starts fading in (Unix time, milliseconds)."
                ],
                [
                  "`durationMs`",
                  "ms?",
                  "—",
                  "How long the segment lasts, when known."
                ],
                [
                  "`transitionMs`",
                  "ms",
                  "—",
                  "Length of its fade-in."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "WeatherSetOptions",
              "level": 3,
              "id": "weather-set-options"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`transitionMs`",
                  "ms",
                  "`0`",
                  "Fade from the current weather, `0` to `3600000`."
                ],
                [
                  "`durationMs`",
                  "ms",
                  "`0`",
                  "How long to keep it before the cycle resumes. `0`: until changed."
                ]
              ]
            }
          ]
        },
        {
          "id": "permissions",
          "title": "Permissions",
          "eyebrow": "Shared · Lua & JS",
          "lead": "Decide who may do what: groups, rules and identities, checked on the server and mirrored to each player's client.",
          "blocks": [
            {
              "type": "text",
              "md": "A **permission** is a dotted, lower-case name such as `vehicle.spawn`. Your scripts decide which permissions exist and check them; the server owner decides who holds them, in the admin panel (Permissions tab) or in `perms.json` next to the server. Scripts can manage them too.\n\nThe **server** is the only place where a permission protects anything. Each client receives a read-only copy of its own player's permissions, resolved the same way, so that an interface can show or hide what the player may use without asking."
            },
            {
              "type": "heading",
              "text": "How a permission is decided",
              "level": 2,
              "id": "permissions-model"
            },
            {
              "type": "list",
              "ordered": true,
              "items": [
                "**Rules.** A rule allows or denies a name, and covers everything below it: a rule on `vehicle` covers `vehicle.spawn.tank`. `*` covers everything; `vehicle.*` means the same as `vehicle`.",
                "**Sources.** A player gets rules from, in this order: rules a script set for their session, rules attached to their identity, then their groups from the highest priority down. The **first source with a rule covering the permission decides**; the others are not consulted.",
                "**Within a source**, the most precise rule wins (`vehicle.tank` before `vehicle`, before `*`). A group inherits the rules of its parent; its own rule wins over the parent's at the same precision.",
                "**Ties.** Two sources of the same priority that disagree: the denial wins.",
                "**No rule at all means no.** A permission is never held by default."
              ]
            },
            {
              "type": "text",
              "md": "Every server starts with two groups: `default`, which every player is in, and `admin`, which allows `*`."
            },
            {
              "type": "heading",
              "text": "Identities",
              "level": 2,
              "id": "permissions-identities"
            },
            {
              "type": "text",
              "md": "Rules and memberships that must last are attached to an **identity**, written `type:value`: `lsmp:380201629467` (an account, the base62 form of the id is accepted too) or `ip:203.0.113.7`. An `lsmp` identity counts only when the server verifies its players, unless the owner sets `PermsTrustDeclaredIds` ([server.cfg](#server-cfg)): an account id is public, and without verification anyone could claim one.\n\nA **playerId** given as a target sets rules or groups for the **current session** only. Nothing is saved, it is gone when the player leaves, and it applies whatever the verification."
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Who may change permissions",
              "md": "Every function that writes (groups, rules, memberships) needs the `perms.manage` [capability](#capabilities). Without it, the call returns `false` and [`lsmp.getLastError()`](#core-utils) gives `permission`."
            },
            {
              "type": "heading",
              "text": "Checking a player (server)",
              "level": 2,
              "id": "permissions-check"
            },
            {
              "type": "function",
              "name": "lsmp.perms.has",
              "id": "fn-perms-has",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.has(playerId, permission) --> boolean",
                "js": "lsmp.perms.has(playerId: number, permission: string): boolean"
              },
              "summary": "Whether a player holds a permission.",
              "md": "The answer is cached and costs next to nothing: call it on every request a player makes.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "permission",
                  "type": "string",
                  "desc": "A permission name, without wildcard."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if a rule allows it; `false` otherwise, and for an unknown player."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.onClient(\"garage:spawnTank\", function(source)\n  if not lsmp.perms.has(source, \"vehicle.spawn.tank\") then\n    lsmp.emitClient(source, \"chat:message\", { name = \"\", text = \"Not allowed.\", system = true })\n    return\n  end\n  -- spawn the tank\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.onClient('garage:spawnTank', (source) => {\n  if (!lsmp.perms.has(source, 'vehicle.spawn.tank')) {\n    lsmp.emitClient(source, 'chat:message', { name: '', text: 'Not allowed.', system: true });\n    return;\n  }\n  // spawn the tank\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.perms.explain",
              "id": "fn-perms-explain",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.explain(playerId, permission) --> PermExplain?",
                "js": "lsmp.perms.explain(playerId: number, permission: string): PermExplain | null"
              },
              "summary": "Why a player holds a permission, or not.",
              "md": "See [`PermExplain`](#permissions/perm-explain). Useful in a command that answers \"why can't I...\".",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "permission",
                  "type": "string",
                  "desc": "A permission name."
                }
              ],
              "returns": [
                {
                  "type": "PermExplain?",
                  "desc": "The explanation, or `nil`/`null` for an unknown player.",
                  "only": "lua"
                },
                {
                  "type": "PermExplain | null",
                  "desc": "The explanation, or `nil`/`null` for an unknown player.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.getPlayerGroups",
              "id": "fn-perms-get-player-groups",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.getPlayerGroups(playerId [, opts]) --> {PermGroupRef}?",
                "js": "lsmp.perms.getPlayerGroups(playerId: number, opts?: InheritOptions): PermGroupRef[] | null"
              },
              "summary": "The groups of a player, from the highest priority down.",
              "md": "Each entry is a [`PermGroupRef`](#permissions/perm-group-ref). `default` is always there.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "opts",
                  "type": "InheritOptions",
                  "desc": "`{ inherited }`: include the groups held only through a parent (default `true`).",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "{PermGroupRef}?",
                  "desc": "The groups, or `nil`/`null` for an unknown player.",
                  "only": "lua"
                },
                {
                  "type": "PermGroupRef[] | null",
                  "desc": "The groups, or `nil`/`null` for an unknown player.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.inGroup",
              "id": "fn-perms-in-group",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.inGroup(playerId, group [, opts]) --> boolean?",
                "js": "lsmp.perms.inGroup(playerId: number, group: string, opts?: InheritOptions): boolean | null"
              },
              "summary": "Whether a player is in a group.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "group",
                  "type": "string",
                  "desc": "The group id."
                },
                {
                  "name": "opts",
                  "type": "InheritOptions",
                  "desc": "`{ inherited }`: count membership through a parent (default `true`).",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "boolean?",
                  "desc": "`true` or `false`, or `nil`/`null` for an unknown player.",
                  "only": "lua"
                },
                {
                  "type": "boolean | null",
                  "desc": "`true` or `false`, or `nil`/`null` for an unknown player.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.getPlayerIdentities",
              "id": "fn-perms-get-player-identities",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.getPlayerIdentities(playerId) --> {string}?",
                "js": "lsmp.perms.getPlayerIdentities(playerId: number): string[] | null"
              },
              "summary": "The identities of a connected player.",
              "md": "For example `{ \"lsmp:380201629467\", \"ip:203.0.113.7\" }`. `ip:` identities need the `players.identity` [capability](#capabilities); without it they are left out.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "{string}?",
                  "desc": "The identities, or `nil`/`null` for an unknown player.",
                  "only": "lua"
                },
                {
                  "type": "string[] | null",
                  "desc": "The identities, or `nil`/`null` for an unknown player.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.getPlayerIdentity",
              "id": "fn-perms-get-player-identity",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.getPlayerIdentity(playerId [, type]) --> string?",
                "js": "lsmp.perms.getPlayerIdentity(playerId: number, type: string = \"lsmp\"): string | null"
              },
              "summary": "One identity of a connected player, ready to use as a target.",
              "md": "Pass the result to [`addToGroup`](#permissions/fn-perms-add-to-group) or [`allow`](#permissions/fn-perms-allow) to make a change last beyond the session.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "type",
                  "type": "string",
                  "desc": "`\"lsmp\"` or `\"ip\"`.",
                  "optional": true,
                  "default": "\"lsmp\""
                }
              ],
              "returns": [
                {
                  "type": "string?",
                  "desc": "The identity, or `nil`/`null` if the player is unknown or has none of that type (a guest has no `lsmp` identity).",
                  "only": "lua"
                },
                {
                  "type": "string | null",
                  "desc": "The identity, or `nil`/`null` if the player is unknown or has none of that type (a guest has no `lsmp` identity).",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "`\"ip\"` without the `players.identity` capability."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "Reading groups and identities (server)",
              "level": 2,
              "id": "permissions-read"
            },
            {
              "type": "function",
              "name": "lsmp.perms.getGroups",
              "id": "fn-perms-get-groups",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.getGroups() --> {PermGroup}",
                "js": "lsmp.perms.getGroups(): PermGroup[]"
              },
              "summary": "Every group of the server.",
              "md": "Each entry is a [`PermGroup`](#permissions/perm-group), without its rules.",
              "returns": [
                {
                  "type": "{PermGroup}",
                  "desc": "The groups.",
                  "only": "lua"
                },
                {
                  "type": "PermGroup[]",
                  "desc": "The groups.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.getGroup",
              "id": "fn-perms-get-group",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.getGroup(id) --> PermGroup?",
                "js": "lsmp.perms.getGroup(id: string): PermGroup | null"
              },
              "summary": "One group, with its rules.",
              "md": "A [`PermGroup`](#permissions/perm-group) with `rules`: a table of permission patterns to `true` (allow) or `false` (deny).",
              "params": [
                {
                  "name": "id",
                  "type": "string",
                  "desc": "The group id."
                }
              ],
              "returns": [
                {
                  "type": "PermGroup?",
                  "desc": "The group, or `nil`/`null` if it does not exist.",
                  "only": "lua"
                },
                {
                  "type": "PermGroup | null",
                  "desc": "The group, or `nil`/`null` if it does not exist.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.getGroupMembers",
              "id": "fn-perms-get-group-members",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.getGroupMembers(id) --> {PermMember}?",
                "js": "lsmp.perms.getGroupMembers(id: string): PermMember[] | null"
              },
              "summary": "The identities that are members of a group.",
              "md": "Each entry is `{ identity, label, untilMs, note }`: `untilMs` is the end of a temporary membership (`nil`/`null` when permanent). Session memberships set with a playerId are not listed. `ip:` identities need the `players.identity` [capability](#capabilities).",
              "params": [
                {
                  "name": "id",
                  "type": "string",
                  "desc": "The group id."
                }
              ],
              "returns": [
                {
                  "type": "{PermMember}?",
                  "desc": "The members, or `nil`/`null` if the group does not exist.",
                  "only": "lua"
                },
                {
                  "type": "PermMember[] | null",
                  "desc": "The members, or `nil`/`null` if the group does not exist.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.getIdentity",
              "id": "fn-perms-get-identity",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.getIdentity(identity) --> PermIdentity?",
                "js": "lsmp.perms.getIdentity(identity: string): PermIdentity | null"
              },
              "summary": "What is attached to an identity.",
              "md": "`{ identity, label, lastSeenMs, groups, rules }`: `groups` lists `{ group, untilMs, note }`, `rules` maps patterns to `true` or `false`.",
              "params": [
                {
                  "name": "identity",
                  "type": "string",
                  "desc": "An identity such as `\"lsmp:380201629467\"`."
                }
              ],
              "returns": [
                {
                  "type": "PermIdentity?",
                  "desc": "The identity, or `nil`/`null` if nothing is attached to it.",
                  "only": "lua"
                },
                {
                  "type": "PermIdentity | null",
                  "desc": "The identity, or `nil`/`null` if nothing is attached to it.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "An `ip:` identity without the `players.identity` capability."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "Declaring permissions",
              "level": 2,
              "id": "permissions-declare"
            },
            {
              "type": "function",
              "name": "lsmp.perms.declare",
              "id": "fn-perms-declare",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.declare(permission [, description])",
                "js": "lsmp.perms.declare(permission: string, description?: string): void"
              },
              "summary": "List a permission this resource checks, with a description.",
              "md": "Optional, and only for the server owner: the admin panel suggests declared permissions while they write a rule. Declarations go away when the resource stops. Declaring changes nobody's rights.",
              "params": [
                {
                  "name": "permission",
                  "type": "string",
                  "desc": "The permission name."
                },
                {
                  "name": "description",
                  "type": "string",
                  "desc": "One sentence shown in the panel.",
                  "optional": true
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.perms.declare(\"garage.tank\", \"Spawn a tank from the garage\")"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.perms.declare('garage.tank', 'Spawn a tank from the garage');"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Changing permissions (server)",
              "level": 2,
              "id": "permissions-write"
            },
            {
              "type": "text",
              "md": "Changes are saved to `perms.json` at once (except session targets) and reach the players concerned within a moment: their checks change, their client receives a new copy, and [`playerPermsChange`](#engine-events) fires."
            },
            {
              "type": "function",
              "name": "lsmp.perms.createGroup",
              "id": "fn-perms-create-group",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.createGroup(id [, opts]) --> boolean",
                "js": "lsmp.perms.createGroup(id: string, opts?: PermGroupOptions): boolean"
              },
              "summary": "Create a group.",
              "md": "An existing group is left untouched: the call returns `false` with the code `exists`. That makes it safe at the top of a script: once the group exists, the server owner may rename it, recolor it or change its rules, and a restart does not undo that. Add rules with [`allow`](#permissions/fn-perms-allow) right after a successful creation.\n\nNeeds the `perms.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "id",
                  "type": "string",
                  "desc": "The group id: lower case, 32 characters at most."
                },
                {
                  "name": "opts",
                  "type": "PermGroupOptions",
                  "desc": "See [`PermGroupOptions`](#permissions/perm-group-options).",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the group was created."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`exists`",
                      "A group with this id exists."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `perms.manage`."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "if lsmp.perms.createGroup(\"vip\", { label = \"VIP\", color = \"#f1c40f\", priority = 20 }) then\n  lsmp.perms.allow(\"group:vip\", \"garage.tank\")\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "if (lsmp.perms.createGroup('vip', { label: 'VIP', color: '#f1c40f', priority: 20 })) {\n  lsmp.perms.allow('group:vip', 'garage.tank');\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.perms.updateGroup",
              "id": "fn-perms-update-group",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.updateGroup(id, patch) --> boolean",
                "js": "lsmp.perms.updateGroup(id: string, patch: PermGroupOptions): boolean"
              },
              "summary": "Change the label, color, priority or parent of a group.",
              "md": "Only the fields given change.\n\nNeeds the `perms.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "id",
                  "type": "string",
                  "desc": "The group id."
                },
                {
                  "name": "patch",
                  "type": "PermGroupOptions",
                  "desc": "See [`PermGroupOptions`](#permissions/perm-group-options)."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the group was changed."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "No such group."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `perms.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.renameGroup",
              "id": "fn-perms-rename-group",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.renameGroup(id, newId) --> boolean",
                "js": "lsmp.perms.renameGroup(id: string, newId: string): boolean"
              },
              "summary": "Change the id of a group.",
              "md": "Memberships, parents and rules that name the group follow the new id.\n\nNeeds the `perms.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "id",
                  "type": "string",
                  "desc": "The current id."
                },
                {
                  "name": "newId",
                  "type": "string",
                  "desc": "The new id."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the group was renamed."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "No such group."
                    ],
                    [
                      "`exists`",
                      "`newId` is taken."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `perms.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.deleteGroup",
              "id": "fn-perms-delete-group",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.deleteGroup(id) --> boolean",
                "js": "lsmp.perms.deleteGroup(id: string): boolean"
              },
              "summary": "Delete a group and its memberships.",
              "md": "The `default` group cannot be deleted.\n\nNeeds the `perms.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "id",
                  "type": "string",
                  "desc": "The group id."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the group was deleted."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "No such group."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `perms.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.allow",
              "id": "fn-perms-allow",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.allow(target, rule) --> boolean",
                "js": "lsmp.perms.allow(target: number | string, rule: string): boolean"
              },
              "summary": "Add a rule that allows a permission.",
              "md": "An existing rule on the same pattern for the same target is replaced.\n\nNeeds the `perms.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "target",
                  "type": "playerId|string",
                  "desc": "A playerId (this session only), `\"group:<id>\"`, or an identity such as `\"lsmp:380201629467\"`."
                },
                {
                  "name": "rule",
                  "type": "string",
                  "desc": "A permission name, `name.*` or `*`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the rule was written."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The resource does not hold `perms.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.deny",
              "id": "fn-perms-deny",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.deny(target, rule) --> boolean",
                "js": "lsmp.perms.deny(target: number | string, rule: string): boolean"
              },
              "summary": "Add a rule that denies a permission.",
              "md": "Useful to carve an exception: allow `vehicle` and deny `vehicle.tank`.\n\nNeeds the `perms.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "target",
                  "type": "playerId|string",
                  "desc": "A playerId (this session only), `\"group:<id>\"`, or an identity such as `\"lsmp:380201629467\"`."
                },
                {
                  "name": "rule",
                  "type": "string",
                  "desc": "A permission name, `name.*` or `*`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the rule was written."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The resource does not hold `perms.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.unset",
              "id": "fn-perms-unset",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.unset(target, rule) --> boolean",
                "js": "lsmp.perms.unset(target: number | string, rule: string): boolean"
              },
              "summary": "Remove a rule, whether it allowed or denied.",
              "md": "Needs the `perms.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "target",
                  "type": "playerId|string",
                  "desc": "A playerId (this session only), `\"group:<id>\"`, or an identity such as `\"lsmp:380201629467\"`."
                },
                {
                  "name": "rule",
                  "type": "string",
                  "desc": "The pattern of the rule."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if a rule was removed."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The resource does not hold `perms.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.addToGroup",
              "id": "fn-perms-add-to-group",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.addToGroup(target, group [, opts]) --> boolean",
                "js": "lsmp.perms.addToGroup(target: number | string, group: string, opts?: MembershipOptions): boolean"
              },
              "summary": "Put a player or an identity in a group, possibly for a limited time.",
              "md": "With a playerId the membership lasts for the session, and takes no end date. With an identity it is saved, and lasts until removed or until its end (`durationMs` or `untilMs`). Every player is already in `default`.\n\nNeeds the `perms.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "target",
                  "type": "playerId|string",
                  "desc": "A playerId (this session only) or an identity."
                },
                {
                  "name": "group",
                  "type": "string",
                  "desc": "The group id."
                },
                {
                  "name": "opts",
                  "type": "MembershipOptions",
                  "desc": "See [`MembershipOptions`](#permissions/membership-options).",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` once the target is in the group (also when it already was)."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "No such group, or the player is unknown."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `perms.manage`."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- A month of VIP for a player's account.\nlocal identity = lsmp.perms.getPlayerIdentity(playerId)\nif identity then\n  lsmp.perms.addToGroup(identity, \"vip\", { durationMs = 30 * 86400000, note = \"Event winner\" })\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// A month of VIP for a player's account.\nconst identity = lsmp.perms.getPlayerIdentity(playerId);\nif (identity) lsmp.perms.addToGroup(identity, 'vip', { durationMs: 30 * 86400000, note: 'Event winner' });"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.perms.removeFromGroup",
              "id": "fn-perms-remove-from-group",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.removeFromGroup(target, group) --> boolean",
                "js": "lsmp.perms.removeFromGroup(target: number | string, group: string): boolean"
              },
              "summary": "Take a player or an identity out of a group.",
              "md": "Needs the `perms.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "target",
                  "type": "playerId|string",
                  "desc": "A playerId (session membership) or an identity."
                },
                {
                  "name": "group",
                  "type": "string",
                  "desc": "The group id."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if a membership was removed."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The resource does not hold `perms.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.deleteIdentity",
              "id": "fn-perms-delete-identity",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.deleteIdentity(identity) --> boolean",
                "js": "lsmp.perms.deleteIdentity(identity: string): boolean"
              },
              "summary": "Forget every rule and membership of an identity.",
              "md": "Needs the `perms.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "identity",
                  "type": "string",
                  "desc": "The identity."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if something was removed."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The resource does not hold `perms.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "The resource's own capabilities",
              "level": 2,
              "id": "permissions-capabilities"
            },
            {
              "type": "text",
              "md": "Capabilities are what a **resource** may do with sensitive functions (kick, ban, change permissions...), granted by the server owner per resource. They are described on [Resource capabilities and sandbox](#capabilities)."
            },
            {
              "type": "function",
              "name": "lsmp.perms.getCapabilities",
              "id": "fn-perms-get-capabilities",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.getCapabilities() --> {string}",
                "js": "lsmp.perms.getCapabilities(): string[]"
              },
              "summary": "The capabilities this resource holds.",
              "returns": [
                {
                  "type": "{string}",
                  "desc": "Capability ids, such as `\"players.kick\"`.",
                  "only": "lua"
                },
                {
                  "type": "string[]",
                  "desc": "Capability ids, such as `\"players.kick\"`.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.hasCapability",
              "id": "fn-perms-has-capability",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.hasCapability(capability) --> boolean",
                "js": "lsmp.perms.hasCapability(capability: string): boolean"
              },
              "summary": "Whether this resource holds a capability.",
              "md": "To adapt a feature before calling a function that would fail with `permission`.",
              "params": [
                {
                  "name": "capability",
                  "type": "string",
                  "desc": "A capability id."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the resource holds it; `false` otherwise, and for an unknown id."
              }
            },
            {
              "type": "heading",
              "text": "On the client",
              "level": 2,
              "id": "permissions-client"
            },
            {
              "type": "text",
              "md": "Each client holds a copy of **its own player's** effective permissions, sent by the server when the player joins and again each time they change. The checks below read that copy; they never ask the server."
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "Display only",
              "md": "A modified client can grant itself anything in its copy. Use these functions to show or hide interface elements, and check again on the server before acting."
            },
            {
              "type": "function",
              "name": "lsmp.perms.has",
              "id": "fn-perms-has-client",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.has(permission) --> boolean",
                "js": "lsmp.perms.has(permission: string): boolean"
              },
              "summary": "Whether the local player holds a permission.",
              "params": [
                {
                  "name": "permission",
                  "type": "string",
                  "desc": "A permission name."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if allowed; `false` otherwise, and before the copy arrived."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "if lsmp.perms.has(\"garage.tank\") then\n  lsmp.log(\"tanks are available in your garage\")\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "if (lsmp.perms.has('garage.tank')) lsmp.log('tanks are available in your garage');"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.perms.explain",
              "id": "fn-perms-explain-client",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.explain(permission) --> PermExplain",
                "js": "lsmp.perms.explain(permission: string): PermExplain"
              },
              "summary": "Why the local player holds a permission, or not.",
              "md": "See [`PermExplain`](#permissions/perm-explain).",
              "params": [
                {
                  "name": "permission",
                  "type": "string",
                  "desc": "A permission name."
                }
              ],
              "returns": {
                "type": "PermExplain",
                "desc": "The explanation."
              }
            },
            {
              "type": "function",
              "name": "lsmp.perms.getGroups",
              "id": "fn-perms-get-groups-client",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.getGroups([opts]) --> {PermGroupRef}",
                "js": "lsmp.perms.getGroups(opts?: InheritOptions): PermGroupRef[]"
              },
              "summary": "The groups of the local player.",
              "params": [
                {
                  "name": "opts",
                  "type": "InheritOptions",
                  "desc": "`{ inherited }`: include the groups held through a parent (default `true`).",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "{PermGroupRef}",
                  "desc": "A list of [`PermGroupRef`](#permissions/perm-group-ref), empty before the copy arrived.",
                  "only": "lua"
                },
                {
                  "type": "PermGroupRef[]",
                  "desc": "A list of [`PermGroupRef`](#permissions/perm-group-ref), empty before the copy arrived.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.perms.inGroup",
              "id": "fn-perms-in-group-client",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.inGroup(group [, opts]) --> boolean",
                "js": "lsmp.perms.inGroup(group: string, opts?: InheritOptions): boolean"
              },
              "summary": "Whether the local player is in a group.",
              "params": [
                {
                  "name": "group",
                  "type": "string",
                  "desc": "The group id."
                },
                {
                  "name": "opts",
                  "type": "InheritOptions",
                  "desc": "`{ inherited }` (default `true`).",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` or `false`."
              }
            },
            {
              "type": "function",
              "name": "lsmp.perms.isReady",
              "id": "fn-perms-is-ready",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.isReady() --> boolean",
                "js": "lsmp.perms.isReady(): boolean"
              },
              "summary": "Whether the copy of the permissions has arrived.",
              "md": "It usually arrives before client scripts start. Until then every check answers `false`.",
              "returns": {
                "type": "boolean",
                "desc": "`true` once the copy is there."
              }
            },
            {
              "type": "function",
              "name": "lsmp.perms.isComplete",
              "id": "fn-perms-is-complete",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.perms.isComplete() --> boolean",
                "js": "lsmp.perms.isComplete(): boolean"
              },
              "summary": "Whether the copy holds everything.",
              "md": "A player with an extremely large set of rules receives an empty copy marked incomplete instead of a partial one: every check then answers `false` on the client. The server checks are not affected.",
              "returns": {
                "type": "boolean",
                "desc": "`false` when the copy was too large to send."
              }
            },
            {
              "type": "text",
              "md": "[`playerPermsChange`](#engine-events) fires on the client when a new copy arrives, and on the server when a player's effective permissions change."
            },
            {
              "type": "heading",
              "text": "Shapes",
              "level": 2,
              "id": "permissions-shapes"
            },
            {
              "type": "heading",
              "text": "PermExplain",
              "level": 3,
              "id": "perm-explain"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`allowed`",
                  "boolean",
                  "—",
                  "The answer."
                ],
                [
                  "`matched`",
                  "boolean",
                  "—",
                  "`false` when no rule covers the permission (refused by default)."
                ],
                [
                  "`source`",
                  "string",
                  "—",
                  "Where the deciding rule comes from: `\"session\"`, `\"identity\"` or `\"group\"`; `\"none\"` when no rule matched."
                ],
                [
                  "`group`",
                  "string?",
                  "—",
                  "The group of the deciding rule."
                ],
                [
                  "`rule`",
                  "string?",
                  "—",
                  "The pattern of the deciding rule."
                ],
                [
                  "`permission`",
                  "string",
                  "—",
                  "The permission asked about, normalized."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "PermGroupRef",
              "level": 3,
              "id": "perm-group-ref"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`id`",
                  "string",
                  "—",
                  "The group id."
                ],
                [
                  "`label`",
                  "string",
                  "—",
                  "Its display name."
                ],
                [
                  "`color`",
                  "string?",
                  "—",
                  "`\"#rrggbb\"`."
                ],
                [
                  "`priority`",
                  "int",
                  "—",
                  "Higher wins."
                ],
                [
                  "`direct`",
                  "boolean",
                  "—",
                  "`false` when held only through a parent."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "PermGroup",
              "level": 3,
              "id": "perm-group"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`id`",
                  "string",
                  "—",
                  "The group id."
                ],
                [
                  "`label`",
                  "string",
                  "—",
                  "Its display name."
                ],
                [
                  "`color`",
                  "string?",
                  "—",
                  "`\"#rrggbb\"`."
                ],
                [
                  "`priority`",
                  "int",
                  "—",
                  "Higher wins."
                ],
                [
                  "`parent`",
                  "string?",
                  "—",
                  "The group it inherits from."
                ],
                [
                  "`builtin`",
                  "boolean",
                  "—",
                  "`true` for `default`."
                ],
                [
                  "`members`",
                  "int",
                  "—",
                  "How many saved identities are members."
                ],
                [
                  "`rules`",
                  "table",
                  "—",
                  "`getGroup` only: patterns to `true` (allow) or `false` (deny)."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "PermGroupOptions",
              "level": 3,
              "id": "perm-group-options"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`label`",
                  "string",
                  "the id",
                  "Display name, 64 bytes at most."
                ],
                [
                  "`color`",
                  "color",
                  "—",
                  "Any [color](#conventions) form."
                ],
                [
                  "`priority`",
                  "int",
                  "`0`",
                  "Higher wins when sources disagree."
                ],
                [
                  "`parent`",
                  "string",
                  "—",
                  "A group to inherit rules from."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "MembershipOptions",
              "level": 3,
              "id": "membership-options"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`durationMs`",
                  "ms",
                  "—",
                  "Ends this long after the call."
                ],
                [
                  "`untilMs`",
                  "epochMs",
                  "—",
                  "Ends at this time. Not with `durationMs`."
                ],
                [
                  "`note`",
                  "string",
                  "—",
                  "Shown in the admin panel."
                ]
              ]
            }
          ]
        },
        {
          "id": "voice",
          "title": "Voice",
          "eyebrow": "Shared · Lua & JS",
          "lead": "Proximity chat, radios, team channels: the server decides who hears whom, each client shapes its own microphone and mix.",
          "blocks": [
            {
              "type": "text",
              "md": "LS:MP has **no voice chat by default**. Two players hear each other only when a server script has created a **channel** and put them both on it. Until then nothing is relayed, and each client keeps its microphone closed.\n\nThe server decides everything about who hears whom: channels, roles, ranges and mutes. A client cannot put itself on a channel, widen its range or notice that it is muted. The client side only shapes the local microphone and what the player hears."
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "Start from voice-mgr",
              "md": "The bundled `voice-mgr` resource is a complete setup: one 3D channel for the whole server with whisper, normal and shout ranges, and radio frequencies joined with `/radio <frequency>`. Keep it, tune its configuration, or write your own. See [Bundled example resources](#examples)."
            },
            {
              "type": "heading",
              "text": "Channels and roles",
              "level": 2,
              "id": "voice-model"
            },
            {
              "type": "table",
              "headers": [
                "Kind",
                "Option",
                "Heard"
              ],
              "rows": [
                [
                  "**Flat**",
                  "`spatial: false` (default)",
                  "At the same level everywhere: a radio, a phone call, a team channel."
                ],
                [
                  "**3D**",
                  "`spatial: true`",
                  "From the speaker's ped, up to `range` metres, fading with the distance."
                ]
              ]
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "A player **speaks** on a channel where their role is `\"talk\"` or `\"both\"`, and **hears** a channel where it is `\"listen\"` or `\"both\"`. A listen-only admin channel or a receive-only broadcast needs nothing more.",
                "On a 3D channel, the listener must be within the **speaker's** range: the range belongs to the speaker, which is what makes whisper, normal and shout one number on one channel.",
                "When several channels join the same speaker to the same listener, one is used: the highest `priority`, then 3D before flat (a radio mate standing next to you is heard where they stand), then the longest range.",
                "Voice stops at the edge of a [dimension](#dimensions): two players on the same channel in different dimensions do not hear each other.",
                "A client opens its microphone only once its player has the talk role on at least one channel."
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Channels belong to their resource",
              "md": "A channel is owned by the resource that created it and is destroyed, with its memberships, when that resource stops. Create the channels when the resource starts (see the example below)."
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Capability",
              "md": "Every function that changes voice (channels, memberships, ranges, mutes) needs the `voice.manage` [capability](#capabilities). Without it the call returns `false` and [`lsmp.getLastError()`](#core-utils) gives `permission`. Reading works without it."
            },
            {
              "type": "function",
              "name": "lsmp.VoiceRole",
              "id": "const-voice-role",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.VoiceRole",
                "js": "lsmp.VoiceRole"
              },
              "summary": "The roles a player can have on a channel.",
              "md": "`lsmp.VoiceRole.Listen` = `\"listen\"` · `lsmp.VoiceRole.Talk` = `\"talk\"` · `lsmp.VoiceRole.Both` = `\"both\"`"
            },
            {
              "type": "text",
              "md": "Every function that takes a `channel` accepts its **name** or its **hash** (see [`getChannelId`](#voice/fn-voice-get-channel-id))."
            },
            {
              "type": "heading",
              "text": "Channels (server)",
              "level": 2,
              "id": "voice-channels"
            },
            {
              "type": "function",
              "name": "lsmp.voice.createChannel",
              "id": "fn-voice-create-channel",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.createChannel(channel [, opts]) --> boolean",
                "js": "lsmp.voice.createChannel(channel: string | number, opts?: VoiceChannelOptions): boolean"
              },
              "summary": "Create a channel owned by this resource.",
              "md": "An existing channel is left as it is: the call returns `false` with the code `exists`; change it with [`setChannelOptions`](#voice/fn-voice-set-channel-options). Options not given take their default ([`VoiceChannelOptions`](#voice/voice-channel-options)).\n\nNeeds the `voice.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name (or a hash)."
                },
                {
                  "name": "opts",
                  "type": "VoiceChannelOptions",
                  "desc": "See [`VoiceChannelOptions`](#voice/voice-channel-options).",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the channel was created."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`exists`",
                      "The channel exists."
                    ],
                    [
                      "`limit`",
                      "The server holds 4096 channels."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `voice.manage`."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- One 3D channel for everybody, created when the resource starts.\nlocal PROXIMITY = \"proximity\"\nif not lsmp.voice.createChannel(PROXIMITY, { spatial = true, range = 20 }) then\n  lsmp.voice.setChannelOptions(PROXIMITY, { spatial = true, range = 20 })\nend\n\nfor _, id in ipairs(lsmp.getPlayers()) do\n  lsmp.voice.setPlayerChannel(id, PROXIMITY, lsmp.VoiceRole.Both)\nend\nlsmp.on(\"playerJoin\", function(playerId)\n  lsmp.voice.setPlayerChannel(playerId, PROXIMITY, lsmp.VoiceRole.Both)\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// One 3D channel for everybody, created when the resource starts.\nconst PROXIMITY = 'proximity';\nif (!lsmp.voice.createChannel(PROXIMITY, { spatial: true, range: 20 }))\n  lsmp.voice.setChannelOptions(PROXIMITY, { spatial: true, range: 20 });\n\nfor (const id of lsmp.getPlayers()) lsmp.voice.setPlayerChannel(id, PROXIMITY, lsmp.VoiceRole.Both);\nlsmp.on('playerJoin', (playerId) => {\n  lsmp.voice.setPlayerChannel(playerId, PROXIMITY, lsmp.VoiceRole.Both);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.voice.setChannelOptions",
              "id": "fn-voice-set-channel-options",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.setChannelOptions(channel, opts) --> boolean",
                "js": "lsmp.voice.setChannelOptions(channel: string | number, opts: VoiceChannelOptions): boolean"
              },
              "summary": "Change some options of a channel.",
              "md": "The options not given keep their value. The change applies at once to everybody on the channel.\n\nNeeds the `voice.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name or a hash."
                },
                {
                  "name": "opts",
                  "type": "VoiceChannelOptions",
                  "desc": "See [`VoiceChannelOptions`](#voice/voice-channel-options)."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the channel was changed."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "No such channel."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `voice.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.getChannelOptions",
              "id": "fn-voice-get-channel-options",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.getChannelOptions(channel) --> VoiceChannelOptions?",
                "js": "lsmp.voice.getChannelOptions(channel: string | number): VoiceChannelOptions | null"
              },
              "summary": "The options in force on a channel.",
              "md": "Every field is filled in, with the values the server applies after clamping.",
              "params": [
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name or a hash."
                }
              ],
              "returns": [
                {
                  "type": "VoiceChannelOptions?",
                  "desc": "The options, or `nil`/`null` if the channel does not exist.",
                  "only": "lua"
                },
                {
                  "type": "VoiceChannelOptions | null",
                  "desc": "The options, or `nil`/`null` if the channel does not exist.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.destroyChannel",
              "id": "fn-voice-destroy-channel",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.destroyChannel(channel) --> boolean",
                "js": "lsmp.voice.destroyChannel(channel: string | number): boolean"
              },
              "summary": "Destroy a channel and take every player off it.",
              "md": "Worth doing for channels created on demand, such as a radio frequency nobody is on any more.\n\nNeeds the `voice.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name or a hash."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the channel was destroyed."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "No such channel."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `voice.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.channelExists",
              "id": "fn-voice-channel-exists",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.channelExists(channel) --> boolean",
                "js": "lsmp.voice.channelExists(channel: string | number): boolean"
              },
              "summary": "Whether a channel exists.",
              "params": [
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name or a hash."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if it exists."
              }
            },
            {
              "type": "function",
              "name": "lsmp.voice.getChannels",
              "id": "fn-voice-get-channels",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.getChannels() --> {integer}",
                "js": "lsmp.voice.getChannels(): number[]"
              },
              "summary": "Every channel of the server, as hashes.",
              "md": "The channels of every resource. [`getChannelName`](#voice/fn-voice-get-channel-name) gives a channel's name back.",
              "returns": [
                {
                  "type": "{integer}",
                  "desc": "The channel hashes.",
                  "only": "lua"
                },
                {
                  "type": "number[]",
                  "desc": "The channel hashes.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.getChannelName",
              "id": "fn-voice-get-channel-name",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.getChannelName(channel) --> string?",
                "js": "lsmp.voice.getChannelName(channel: string | number): string | null"
              },
              "summary": "The name a channel was created with.",
              "params": [
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name or a hash."
                }
              ],
              "returns": [
                {
                  "type": "string?",
                  "desc": "The name, or `nil`/`null` if the channel does not exist or was created from a hash.",
                  "only": "lua"
                },
                {
                  "type": "string | null",
                  "desc": "The name, or `nil`/`null` if the channel does not exist or was created from a hash.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.getChannelPlayers",
              "id": "fn-voice-get-channel-players",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.getChannelPlayers(channel) --> {VoiceMember}",
                "js": "lsmp.voice.getChannelPlayers(channel: string | number): VoiceMember[]"
              },
              "summary": "The players on a channel.",
              "params": [
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name or a hash."
                }
              ],
              "returns": [
                {
                  "type": "{VoiceMember}",
                  "desc": "A list of `{ playerId, role }`, empty for a channel that does not exist.",
                  "only": "lua"
                },
                {
                  "type": "VoiceMember[]",
                  "desc": "A list of `{ playerId, role }`, empty for a channel that does not exist.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.getChannelId",
              "id": "fn-voice-get-channel-id",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.getChannelId(name) --> integer",
                "js": "lsmp.voice.getChannelId(name: string): number"
              },
              "summary": "The hash of a channel name.",
              "md": "The same on the server and on every client, so both sides agree on a channel. Every function already accepts a name: compute the hash only to store it, or in a loop that runs every frame.",
              "params": [
                {
                  "name": "name",
                  "type": "string",
                  "desc": "The channel name."
                }
              ],
              "returns": [
                {
                  "type": "integer",
                  "desc": "The hash.",
                  "only": "lua"
                },
                {
                  "type": "number",
                  "desc": "The hash.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Players on channels (server)",
              "level": 2,
              "id": "voice-players"
            },
            {
              "type": "function",
              "name": "lsmp.voice.setPlayerChannel",
              "id": "fn-voice-set-player-channel",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.setPlayerChannel(playerId, channel, role) --> boolean",
                "js": "lsmp.voice.setPlayerChannel(playerId: number, channel: string | number, role: string): boolean"
              },
              "summary": "Put a player on a channel with a role, or change their role.",
              "md": "The channel must exist: a mistyped name returns `false` instead of creating a channel nobody else is on. Changing the role keeps the player's range on that channel. A player can be on **8** channels at most.\n\nNeeds the `voice.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name or a hash."
                },
                {
                  "name": "role",
                  "type": "string",
                  "desc": "`\"listen\"`, `\"talk\"` or `\"both\"` ([`lsmp.VoiceRole`](#voice/const-voice-role))."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the membership was set."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "Unknown player or channel."
                    ],
                    [
                      "`limit`",
                      "The player is on 8 channels."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `voice.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.removePlayerChannel",
              "id": "fn-voice-remove-player-channel",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.removePlayerChannel(playerId, channel) --> boolean",
                "js": "lsmp.voice.removePlayerChannel(playerId: number, channel: string | number): boolean"
              },
              "summary": "Take a player off a channel.",
              "md": "Needs the `voice.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name or a hash."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the player was on the channel."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "The player was not on the channel."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `voice.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.getPlayerChannel",
              "id": "fn-voice-get-player-channel",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.getPlayerChannel(playerId, channel) --> string?",
                "js": "lsmp.voice.getPlayerChannel(playerId: number, channel: string | number): string | null"
              },
              "summary": "A player's role on one channel.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name or a hash."
                }
              ],
              "returns": [
                {
                  "type": "string?",
                  "desc": "`\"listen\"`, `\"talk\"` or `\"both\"`, or `nil`/`null` if the player is not on the channel.",
                  "only": "lua"
                },
                {
                  "type": "string | null",
                  "desc": "`\"listen\"`, `\"talk\"` or `\"both\"`, or `nil`/`null` if the player is not on the channel.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.getPlayerChannels",
              "id": "fn-voice-get-player-channels",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.getPlayerChannels(playerId) --> {VoiceMembership}?",
                "js": "lsmp.voice.getPlayerChannels(playerId: number): VoiceMembership[] | null"
              },
              "summary": "Every channel a player is on.",
              "md": "Each entry is `{ channel, role }`, with `channel` as a hash.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "{VoiceMembership}?",
                  "desc": "The memberships, or `nil`/`null` for an unknown player.",
                  "only": "lua"
                },
                {
                  "type": "VoiceMembership[] | null",
                  "desc": "The memberships, or `nil`/`null` for an unknown player.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.clearPlayerChannels",
              "id": "fn-voice-clear-player-channels",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.clearPlayerChannels(playerId) --> boolean",
                "js": "lsmp.voice.clearPlayerChannels(playerId: number): boolean"
              },
              "summary": "Take a player off every channel.",
              "md": "The player then hears nobody and is heard by nobody, and their microphone closes, until a script puts them back on a channel.\n\nNeeds the `voice.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the player is known."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "Unknown player."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `voice.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.setPlayerRange",
              "id": "fn-voice-set-player-range",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.setPlayerRange(playerId, channel, meters) --> boolean",
                "js": "lsmp.voice.setPlayerRange(playerId: number, channel: string | number, meters: number): boolean"
              },
              "summary": "How far a player's voice carries on a 3D channel.",
              "md": "Replaces the channel's `range` for this player's voice only; the other options of the channel still apply. No effect on a flat channel.\n\nNeeds the `voice.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The speaker."
                },
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name or a hash."
                },
                {
                  "name": "meters",
                  "type": "meters",
                  "desc": "The range, `0` or more (500 at most is used). `0` goes back to the channel's range."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the player is on the channel."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "The player is not on the channel."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `voice.manage`."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- Whisper, normal, shout: one number on the same channel.\nlocal RANGES = { whisper = 3, normal = 0, shout = 45 }\n\nlsmp.onCall(\"voice:setRange\", function(source, mode)\n  local meters = RANGES[mode]\n  if not meters then return false end\n  return lsmp.voice.setPlayerRange(source, \"proximity\", meters)\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// Whisper, normal, shout: one number on the same channel.\nconst RANGES = { whisper: 3, normal: 0, shout: 45 };\n\nlsmp.onCall('voice:setRange', (source, mode) => {\n  if (!Object.hasOwn(RANGES, mode)) return false;\n  return lsmp.voice.setPlayerRange(source, 'proximity', RANGES[mode]);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.voice.getPlayerRange",
              "id": "fn-voice-get-player-range",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.getPlayerRange(playerId, channel) --> number?",
                "js": "lsmp.voice.getPlayerRange(playerId: number, channel: string | number): number | null"
              },
              "summary": "The range a player's voice carries on a 3D channel.",
              "md": "Their own range if one was set, otherwise the channel's.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The speaker."
                },
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A name or a hash."
                }
              ],
              "returns": [
                {
                  "type": "number?",
                  "desc": "The range in metres, or `nil`/`null` if the player is not on the channel.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The range in metres, or `nil`/`null` if the player is not on the channel.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Moderation and activity (server)",
              "level": 2,
              "id": "voice-moderation"
            },
            {
              "type": "function",
              "name": "lsmp.voice.setPlayerMuted",
              "id": "fn-voice-set-player-muted",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.setPlayerMuted(playerId, muted) --> boolean",
                "js": "lsmp.voice.setPlayerMuted(playerId: number, muted: boolean): boolean"
              },
              "summary": "Silence a player on every channel, or give their voice back.",
              "md": "Nothing from a muted player is relayed. Their client is not told. To lower one speaker for one listener instead, see the client's volume settings below.\n\nNeeds the `voice.manage` [capability](#capabilities).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "muted",
                  "type": "boolean",
                  "desc": "`true` to mute, `false` to unmute."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the player is known."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "Unknown player."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `voice.manage`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.isPlayerMuted",
              "id": "fn-voice-is-player-muted",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.isPlayerMuted(playerId) --> boolean?",
                "js": "lsmp.voice.isPlayerMuted(playerId: number): boolean | null"
              },
              "summary": "Whether a player is muted by the server.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "boolean?",
                  "desc": "`true` or `false`, or `nil`/`null` for an unknown player.",
                  "only": "lua"
                },
                {
                  "type": "boolean | null",
                  "desc": "`true` or `false`, or `nil`/`null` for an unknown player.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.isPlayerTalking",
              "id": "fn-voice-is-player-talking",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.isPlayerTalking(playerId) --> boolean",
                "js": "lsmp.voice.isPlayerTalking(playerId: number): boolean"
              },
              "summary": "Whether a player is transmitting.",
              "md": "Ends at once when the player releases their key, otherwise after a short silence. A muted player, or a player with no talk role, is never talking: nobody hears them. For changes rather than polling, listen to [`voiceStart` and `voiceStop`](#engine-events).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` while the player transmits."
              }
            },
            {
              "type": "heading",
              "text": "Events",
              "level": 2,
              "id": "voice-events"
            },
            {
              "type": "text",
              "md": "[`voiceStart`](#engine-events) `(playerId)` and [`voiceStop`](#engine-events) `(playerId)` fire on both sides when a player starts and stops transmitting. A client is told about the speakers it hears."
            },
            {
              "type": "heading",
              "text": "VoiceChannelOptions",
              "level": 3,
              "id": "voice-channel-options"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`spatial`",
                  "boolean",
                  "`false`",
                  "`true` for a 3D channel. Only `volume` and `priority` apply to a flat channel."
                ],
                [
                  "`range`",
                  "meters",
                  "`20`",
                  "How far a voice carries, up to `500`."
                ],
                [
                  "`refDistance`",
                  "meters",
                  "`2`",
                  "Full volume up to this distance."
                ],
                [
                  "`rolloff`",
                  "number",
                  "`0.6`",
                  "How fast the volume falls beyond `refDistance`, `0` to `10`."
                ],
                [
                  "`distanceModel`",
                  "string",
                  "`\"inverse\"`",
                  "`\"inverse\"` (natural), `\"linear\"` (straight down to silence at the range) or `\"exponential\"`."
                ],
                [
                  "`volume`",
                  "number",
                  "`1`",
                  "Channel gain, `0` to `4`."
                ],
                [
                  "`directional`",
                  "boolean",
                  "`true`",
                  "Left/right panning from where the speaker stands."
                ],
                [
                  "`muffle`",
                  "boolean",
                  "`true`",
                  "A muffled sound from far away or from behind."
                ],
                [
                  "`priority`",
                  "int",
                  "`0`",
                  "Which channel wins when several join the same two players (highest first)."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Limits",
              "level": 2,
              "id": "voice-limits"
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "A player is on **8** channels at most; the server holds **4096**.",
                "A speaker is relayed to **64** listeners at most: the nearest ones on 3D channels, with room kept for flat-channel listeners.",
                "A client plays **24** speakers at once.",
                "A player who turned voice chat off in their settings receives nothing."
              ]
            },
            {
              "type": "heading",
              "text": "On the client",
              "level": 2,
              "id": "voice-client"
            },
            {
              "type": "text",
              "md": "The client shapes the local microphone and mix. The player's own settings in the LS:MP menu (Settings > Voice) always win: a script can restrict the microphone, never open it against the player's choice."
            },
            {
              "type": "function",
              "name": "lsmp.VoiceInputMode",
              "id": "const-voice-input-mode",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.VoiceInputMode",
                "js": "lsmp.VoiceInputMode"
              },
              "summary": "How the local microphone opens.",
              "md": "`lsmp.VoiceInputMode.Off` = `\"off\"` · `lsmp.VoiceInputMode.PushToTalk` = `\"pushToTalk\"` · `lsmp.VoiceInputMode.VoiceActivity` = `\"voiceActivity\"`"
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Owned settings",
              "md": "Every setter below changes a setting owned by the calling resource: the last writer wins, and the value comes back when that resource stops."
            },
            {
              "type": "function",
              "name": "lsmp.voice.setInputMode",
              "id": "fn-voice-set-input-mode",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.setInputMode(mode)",
                "js": "lsmp.voice.setInputMode(mode: string): void"
              },
              "summary": "Restrict how the microphone opens.",
              "md": "The mode in force is the stricter of this one and the player's own setting: a script can turn push-to-talk on, or the microphone off, but never open it against the player's choice.",
              "params": [
                {
                  "name": "mode",
                  "type": "string",
                  "desc": "`\"off\"`, `\"pushToTalk\"` or `\"voiceActivity\"` ([`lsmp.VoiceInputMode`](#voice/const-voice-input-mode))."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.getInputMode",
              "id": "fn-voice-get-input-mode",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.getInputMode() --> string",
                "js": "lsmp.voice.getInputMode(): string"
              },
              "summary": "The microphone mode in force.",
              "returns": {
                "type": "string",
                "desc": "`\"off\"`, `\"pushToTalk\"` or `\"voiceActivity\"`."
              }
            },
            {
              "type": "function",
              "name": "lsmp.voice.setTalking",
              "id": "fn-voice-set-talking",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.setTalking(talking)",
                "js": "lsmp.voice.setTalking(talking: boolean): void"
              },
              "summary": "Hold the push-to-talk open or closed.",
              "md": "For a radio key or a phone call driven by your script. It opens the microphone only for players who allowed servers to do so in their settings; the others hold their own push-to-talk key.",
              "params": [
                {
                  "name": "talking",
                  "type": "boolean",
                  "desc": "`true` to transmit, `false` to stop."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local RADIO_KEY = 171   -- Caps Lock on a default layout\nlocal held = false\n\nlsmp.onTick(function()\n  local now = isControlPressed(0, RADIO_KEY)\n  if now ~= held then\n    held = now\n    lsmp.voice.setTalking(now)\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const RADIO_KEY = 171;   // Caps Lock on a default layout\nlet held = false;\n\nlsmp.onTick(() => {\n  const now = isControlPressed(0, RADIO_KEY);\n  if (now !== held) {\n    held = now;\n    lsmp.voice.setTalking(now);\n  }\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.voice.isTransmitting",
              "id": "fn-voice-is-transmitting",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.isTransmitting() --> boolean",
                "js": "lsmp.voice.isTransmitting(): boolean"
              },
              "summary": "Whether the local microphone is sending.",
              "md": "For a microphone indicator. `false` while the player has no talk role on any channel.",
              "returns": {
                "type": "boolean",
                "desc": "`true` while sending."
              }
            },
            {
              "type": "function",
              "name": "lsmp.voice.getMicLevel",
              "id": "fn-voice-get-mic-level",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.getMicLevel() --> number",
                "js": "lsmp.voice.getMicLevel(): number"
              },
              "summary": "The loudness of the local microphone.",
              "md": "For a level meter, or to help the player pick a threshold.",
              "returns": {
                "type": "number",
                "desc": "The level, `0` to `1`."
              }
            },
            {
              "type": "function",
              "name": "lsmp.voice.setMicGain",
              "id": "fn-voice-set-mic-gain",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.setMicGain(gain)",
                "js": "lsmp.voice.setMicGain(gain: number): void"
              },
              "summary": "Amplify or soften the local microphone.",
              "params": [
                {
                  "name": "gain",
                  "type": "number",
                  "desc": "`0` to `4`; `1` leaves it unchanged."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.setThreshold",
              "id": "fn-voice-set-threshold",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.setThreshold(rms)",
                "js": "lsmp.voice.setThreshold(rms: number): void"
              },
              "summary": "How loud the player must speak to transmit in voice activity mode.",
              "params": [
                {
                  "name": "rms",
                  "type": "number",
                  "desc": "The level, `0` to `1`, compared with [`getMicLevel`](#voice/fn-voice-get-mic-level)."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.setVolume",
              "id": "fn-voice-set-volume",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.setVolume(volume)",
                "js": "lsmp.voice.setVolume(volume: number): void"
              },
              "summary": "The volume of every voice this player hears.",
              "params": [
                {
                  "name": "volume",
                  "type": "number",
                  "desc": "`0` to `4`; `1` is normal."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.setPlayerVolume",
              "id": "fn-voice-set-player-volume",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.setPlayerVolume(playerId, volume)",
                "js": "lsmp.voice.setPlayerVolume(playerId: number, volume: number): void"
              },
              "summary": "The volume of one speaker, for this player only.",
              "md": "A listener's preference: the speaker and the other players are not affected. To silence a player for everybody, the server uses [`setPlayerMuted`](#voice/fn-voice-set-player-muted).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The speaker."
                },
                {
                  "name": "volume",
                  "type": "number",
                  "desc": "`0` to `4`; `0` silences them."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.voice.setChannelVolume",
              "id": "fn-voice-set-channel-volume",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.voice.setChannelVolume(channel, volume)",
                "js": "lsmp.voice.setChannelVolume(channel: string | number, volume: number): void"
              },
              "summary": "The volume of one channel, for this player only.",
              "md": "For example, a quieter radio than the voices around.",
              "params": [
                {
                  "name": "channel",
                  "type": "string|hashOut",
                  "desc": "A channel name or hash."
                },
                {
                  "name": "volume",
                  "type": "number",
                  "desc": "`0` to `4`."
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "id": "api-server",
      "title": "Server API",
      "icon": "⚡",
      "pages": [
        {
          "id": "server-entities",
          "title": "Entities and pickups",
          "eyebrow": "Server · Lua & JS",
          "lead": "Create, read and delete networked vehicles, peds, objects and pickups from the server.",
          "blocks": [
            {
              "type": "text",
              "md": "The server creates and tracks **networked entities**: vehicles, peds and objects that every player in range sees. Each has a **netId**, the same number on the server and on every client. On a client, turn it into a game handle with `lsmp.getEntityFromNetId` and use the game natives (see [Client entities](#client-entities))."
            },
            {
              "type": "text",
              "md": "The server does not run the game simulation: a player's client **simulates** each entity (its *owner*) and sends its state. The server knows position, model, type, owner, dimension and seats; for anything else (health, damage, appearance) ask the owner's client. Who simulates what is explained in [Ownership and AI intents](#server-ownership)."
            },
            {
              "type": "list",
              "items": [
                "Entities a resource creates **belong to it**. Acting on others (deleting, changing policies, intents, pickup collectors) needs the `entities.foreign` [capability](#capabilities).",
                "When the resource stops, its entities and pickups are deleted, except those with `lifePolicy = \"keep\"`.",
                "A netId is reused after its entity is deleted: if you keep netIds for a long time, check `entityExists` and the model before acting."
              ]
            },
            {
              "type": "heading",
              "text": "Creating and deleting",
              "level": 2,
              "id": "create"
            },
            {
              "type": "function",
              "name": "lsmp.createEntity",
              "id": "fn-create-entity",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.createEntity(type, model, position [, opts]) --> integer?",
                "js": "lsmp.createEntity(type: string, model: number|string, position: Vec3Like, opts?: CreateEntityOptions): number | null"
              },
              "summary": "Creates a networked vehicle, ped or object, owned by the calling resource.",
              "md": "The entity is created with no owner unless `owner` is given; the nearest capable player adopts it (see [Ownership](#server-ownership)). Its default life policy is `\"whileRelevant\"`: it is deleted when no player is in range any more. Use `lifePolicy = \"keep\"` for entities that must stay.",
              "params": [
                {
                  "name": "type",
                  "type": "string",
                  "desc": "`\"vehicle\"`, `\"ped\"` or `\"object\"`."
                },
                {
                  "name": "model",
                  "type": "hash",
                  "desc": "Model name or hash (not 0)."
                },
                {
                  "name": "position",
                  "type": "vec3",
                  "desc": "Where to create it."
                },
                {
                  "name": "opts",
                  "type": "CreateEntityOptions",
                  "optional": true,
                  "desc": "See the table below."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The netId, or `nil`/`null` on failure: `limit` (no free netId), `permission` (client entities disabled in that dimension), `not-found` (`owner` not connected), `invalid` (`owner` in another dimension).",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The netId, or `nil`/`null` on failure: `limit` (no free netId), `permission` (client entities disabled in that dimension), `not-found` (`owner` not connected), `invalid` (`owner` in another dimension).",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local car = lsmp.createEntity(\"vehicle\", \"adder\", { x = -75.0, y = -818.0, z = 326.0 }, {\n  heading = 90.0,\n  lifePolicy = \"keep\",\n})\nif car then lsmp.setEntityMeta(car, \"owner\", \"Ada\") end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const car = lsmp.createEntity(\"vehicle\", \"adder\", { x: -75, y: -818, z: 326 }, {\n  heading: 90,\n  lifePolicy: \"keep\",\n});\nif (car !== null) lsmp.setEntityMeta(car, \"owner\", \"Ada\");"
                  }
                ]
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Option",
                    "Type",
                    "Default",
                    "Description"
                  ],
                  "rows": [
                    [
                      "`heading`",
                      "degrees",
                      "`0`",
                      "Facing (yaw). Exclusive with `rotation`."
                    ],
                    [
                      "`rotation`",
                      "rotation",
                      "—",
                      "Full rotation `{x, y, z}` in degrees (pitch, roll, yaw)."
                    ],
                    [
                      "`owner`",
                      "playerId",
                      "—",
                      "The player who simulates it first. Its dimension is used when `dimension` is not given."
                    ],
                    [
                      "`dimension`",
                      "dimension",
                      "`0`",
                      "The [dimension](#dimensions) to create it in."
                    ],
                    [
                      "`ownerPolicy`",
                      "string",
                      "`\"auto\"`",
                      "Who may simulate it: see [owner policies](#server-ownership/owner-policies)."
                    ],
                    [
                      "`lifePolicy`",
                      "string",
                      "`\"whileRelevant\"`",
                      "When it is deleted: see [life policies](#server-ownership/life-policies)."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.deleteEntity",
              "id": "fn-delete-entity",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.deleteEntity(netId) --> boolean",
                "js": "lsmp.deleteEntity(netId: number): boolean"
              },
              "summary": "Deletes an entity.",
              "md": "Entities created by another resource or by a client need the `entities.foreign` capability. A player's ped cannot be deleted.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `not-found`, `permission`, or `invalid` (a player's ped)."
              }
            },
            {
              "type": "function",
              "name": "lsmp.entityExists",
              "id": "fn-entity-exists",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.entityExists(netId) --> boolean",
                "js": "lsmp.entityExists(netId: number): boolean"
              },
              "summary": "Whether a netId designates a live entity.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": {
                "type": "boolean"
              }
            },
            {
              "type": "heading",
              "text": "Reading",
              "level": 2,
              "id": "reading"
            },
            {
              "type": "text",
              "md": "These read what the server knows: the last state sent by the owner. Positions are fresh to a few tens of milliseconds for a simulated entity. To read several fields at the same instant, prefer `getEntityState`."
            },
            {
              "type": "function",
              "name": "lsmp.getEntityCoords",
              "id": "fn-get-entity-coords",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getEntityCoords(netId) --> Vector3?",
                "js": "lsmp.getEntityCoords(netId: number): Vec3 | null"
              },
              "summary": "The last synchronized position.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": [
                {
                  "type": "Vector3?",
                  "desc": "`nil`/`null` if the entity is unknown.",
                  "only": "lua"
                },
                {
                  "type": "Vec3 | null",
                  "desc": "`nil`/`null` if the entity is unknown.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getEntityModel",
              "id": "fn-get-entity-model",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getEntityModel(netId) --> integer?",
                "js": "lsmp.getEntityModel(netId: number): number | null"
              },
              "summary": "The model hash, unsigned.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "`nil`/`null` if unknown.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "`nil`/`null` if unknown.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getEntityType",
              "id": "fn-get-entity-type",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getEntityType(netId) --> string?",
                "js": "lsmp.getEntityType(netId: number): string | null"
              },
              "summary": "The entity type.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": [
                {
                  "type": "string?",
                  "desc": "`\"vehicle\"`, `\"ped\"`, `\"object\"` or `\"playerPed\"`; `nil`/`null` if unknown.",
                  "only": "lua"
                },
                {
                  "type": "string | null",
                  "desc": "`\"vehicle\"`, `\"ped\"`, `\"object\"` or `\"playerPed\"`; `nil`/`null` if unknown.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getEntityState",
              "id": "fn-get-entity-state",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getEntityState(netId) --> EntityState?",
                "js": "lsmp.getEntityState(netId: number): EntityState | null"
              },
              "summary": "A consistent snapshot of what the server knows about an entity.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": [
                {
                  "type": "EntityState?",
                  "desc": "See the table; `nil`/`null` if unknown.",
                  "only": "lua"
                },
                {
                  "type": "EntityState | null",
                  "desc": "See the table; `nil`/`null` if unknown.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local s = lsmp.getEntityState(netId)\nif s and s.type == \"ped\" and s.vehicle then\n  lsmp.log(\"in vehicle \" .. s.vehicle .. \", seat \" .. s.seat)\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const s = lsmp.getEntityState(netId);\nif (s?.type === \"ped\" && s.vehicle !== null) lsmp.log(`in vehicle ${s.vehicle}, seat ${s.seat}`);"
                  }
                ]
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Field",
                    "Type",
                    "Description"
                  ],
                  "rows": [
                    [
                      "`coords`",
                      "Vector3",
                      "Position."
                    ],
                    [
                      "`model`",
                      "hash",
                      "Model, unsigned."
                    ],
                    [
                      "`type`",
                      "string",
                      "Entity type."
                    ],
                    [
                      "`owner`",
                      "playerId?",
                      "Player simulating it; absent when orphan."
                    ],
                    [
                      "`dimension`",
                      "dimension",
                      "Its dimension."
                    ],
                    [
                      "`lastSyncMs`",
                      "ms?",
                      "Age of the last update; absent if never synchronized."
                    ],
                    [
                      "`vehicle`",
                      "netId?",
                      "For a ped: the vehicle it is in."
                    ],
                    [
                      "`seat`",
                      "integer?",
                      "For a ped in a vehicle: its seat (`0` = driver)."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getEntities",
              "id": "fn-get-entities",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getEntities([opts]) --> {integer}",
                "js": "lsmp.getEntities(opts?: QueryOptions): Uint32Array"
              },
              "summary": "The netIds of all networked entities, optionally filtered.",
              "params": [
                {
                  "name": "opts",
                  "type": "QueryOptions",
                  "optional": true,
                  "desc": "`{ types, dimension }`: a list of entity types (default all) and one dimension (default all)."
                }
              ],
              "returns": [
                {
                  "type": "{integer}",
                  "desc": "The netIds.",
                  "only": "lua"
                },
                {
                  "type": "Uint32Array",
                  "desc": "The netIds.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local vehicles = lsmp.getEntities({ types = { \"vehicle\" }, dimension = 0 })\nlsmp.log(#vehicles .. \" vehicles in the main world\")"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const vehicles = lsmp.getEntities({ types: [\"vehicle\"], dimension: 0 });\nlsmp.log(`${vehicles.length} vehicles in the main world`);"
                  }
                ]
              }
            },
            {
              "type": "text",
              "md": "To search around a position, see [Spatial queries](#spatial)."
            },
            {
              "type": "heading",
              "text": "Vehicles and seats",
              "level": 2,
              "id": "seats"
            },
            {
              "type": "function",
              "name": "lsmp.getVehicleOccupants",
              "id": "fn-get-vehicle-occupants",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getVehicleOccupants(vehicle) --> {SeatOccupant}?",
                "js": "lsmp.getVehicleOccupants(vehicle: number): SeatOccupant[] | null"
              },
              "summary": "The occupied seats of a vehicle.",
              "params": [
                {
                  "name": "vehicle",
                  "type": "netId",
                  "desc": "The vehicle."
                }
              ],
              "returns": [
                {
                  "type": "{SeatOccupant}?",
                  "desc": "A list of `{ seat, ped }` (`seat` 0 = driver), or `nil`/`null` if it is not a known vehicle.",
                  "only": "lua"
                },
                {
                  "type": "SeatOccupant[] | null",
                  "desc": "A list of `{ seat, ped }` (`seat` 0 = driver), or `nil`/`null` if it is not a known vehicle.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "for _, o in ipairs(lsmp.getVehicleOccupants(car) or {}) do\n  lsmp.log(\"seat \" .. o.seat .. \": ped \" .. o.ped)\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "for (const { seat, ped } of lsmp.getVehicleOccupants(car) ?? []) lsmp.log(`seat ${seat}: ped ${ped}`);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.getPedInVehicleSeat",
              "id": "fn-get-ped-in-vehicle-seat",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getPedInVehicleSeat(vehicle, seat) --> integer?",
                "js": "lsmp.getPedInVehicleSeat(vehicle: number, seat: number): number | null"
              },
              "summary": "The ped in one seat of a vehicle.",
              "params": [
                {
                  "name": "vehicle",
                  "type": "netId",
                  "desc": "The vehicle."
                },
                {
                  "name": "seat",
                  "type": "integer",
                  "desc": "`0` = driver, `1` and up = passengers."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The ped's netId, or `nil`/`null` if the seat is empty or the vehicle unknown.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The ped's netId, or `nil`/`null` if the seat is empty or the vehicle unknown.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getVehiclePedIsIn",
              "id": "fn-get-vehicle-ped-is-in",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getVehiclePedIsIn(ped) --> integer?",
                "js": "lsmp.getVehiclePedIsIn(ped: number): number | null"
              },
              "summary": "The vehicle a ped is in.",
              "params": [
                {
                  "name": "ped",
                  "type": "netId",
                  "desc": "The ped (a player's ped too: see `lsmp.getPlayerPed`)."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The vehicle's netId, or `nil`/`null`.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The vehicle's netId, or `nil`/`null`.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Pickups",
              "level": 2,
              "id": "pickups"
            },
            {
              "type": "text",
              "md": "A server pickup is a networked pickup the server grants: when a player collects it, the server fires [`pickupCollect`](#engine-events/ev-pickup-collect) with `serverCreated = true`."
            },
            {
              "type": "function",
              "name": "lsmp.createPickup",
              "id": "fn-create-pickup",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.createPickup(pickupHash, position [, opts]) --> integer?",
                "js": "lsmp.createPickup(pickupHash: number|string, position: Vec3Like, opts?: PickupOptions): number | null"
              },
              "summary": "Creates a pickup owned by the calling resource.",
              "params": [
                {
                  "name": "pickupHash",
                  "type": "hash",
                  "desc": "Pickup type: a `PICKUP_*` name or its hash."
                },
                {
                  "name": "position",
                  "type": "vec3",
                  "desc": "Where to place it."
                },
                {
                  "name": "opts",
                  "type": "PickupOptions",
                  "optional": true,
                  "desc": "See the table below."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The pickup's netId, or `nil`/`null` with `limit` or `permission` (client entities disabled in that dimension).",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The pickup's netId, or `nil`/`null` with `limit` or `permission` (client entities disabled in that dimension).",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local id = lsmp.createPickup(\"PICKUP_MONEY_CASE\", position, { amount = 500, lifetimeMs = 60000 })\nlsmp.on(\"pickupCollect\", function(playerId, netId, pickupHash, amount, serverCreated)\n  if netId == id then giveMoney(playerId, amount) end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const id = lsmp.createPickup(\"PICKUP_MONEY_CASE\", position, { amount: 500, lifetimeMs: 60000 });\nlsmp.on(\"pickupCollect\", (playerId, netId, pickupHash, amount, serverCreated) => {\n  if (netId === id) giveMoney(playerId, amount);\n});"
                  }
                ]
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Option",
                    "Type",
                    "Default",
                    "Description"
                  ],
                  "rows": [
                    [
                      "`amount`",
                      "integer",
                      "`0`",
                      "Amount granted (money, ammo...)."
                    ],
                    [
                      "`dimension`",
                      "dimension",
                      "`0`",
                      "Dimension."
                    ],
                    [
                      "`lifetimeMs`",
                      "ms",
                      "`0`",
                      "Removed after this time (at most 24 h); `0` never expires. Removal happens within one second after the deadline."
                    ],
                    [
                      "`model`",
                      "hash",
                      "the type's model",
                      "Another model to show."
                    ],
                    [
                      "`collectors`",
                      "list of playerId",
                      "anyone",
                      "Only these players (at most 64) may collect it."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.setPickupCollectors",
              "id": "fn-set-pickup-collectors",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setPickupCollectors(netId, players) --> boolean",
                "js": "lsmp.setPickupCollectors(netId: number, players: number[] | null): boolean"
              },
              "summary": "Restricts who may collect a pickup.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The pickup."
                },
                {
                  "name": "players",
                  "type": "list | nil",
                  "desc": "Up to 64 playerIds; `nil`/`null` lets anyone collect it."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `not-found` or `permission` (pickup of another resource without `entities.foreign`)."
              }
            },
            {
              "type": "heading",
              "text": "Constant",
              "level": 2,
              "id": "constant"
            },
            {
              "type": "function",
              "name": "lsmp.EntityType",
              "id": "const-entity-type",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.EntityType",
                "js": "lsmp.EntityType"
              },
              "summary": "Entity type strings.",
              "md": "`lsmp.EntityType.Vehicle` = `\"vehicle\"` · `lsmp.EntityType.Ped` = `\"ped\"` · `lsmp.EntityType.Object` = `\"object\"` · `lsmp.EntityType.PlayerPed` = `\"playerPed\"`"
            }
          ]
        },
        {
          "id": "server-ownership",
          "title": "Ownership and AI intents",
          "eyebrow": "Server · Lua & JS",
          "lead": "Which player simulates an entity, how long it lives, and AI orders that survive ownership changes.",
          "blocks": [
            {
              "type": "text",
              "md": "Every networked entity is **simulated** by one player's game: its **owner**. The owner runs the physics and the AI, and sends the result to the server, which relays it to the others. By default LS:MP picks the owner for you: the nearest player who can simulate the entity **adopts** it, and ownership **migrates** when another player is much closer or when the owner leaves."
            },
            {
              "type": "text",
              "md": "An entity without owner is **orphan**: it is frozen until someone adopts it. The [`entityOwnerChange`](#engine-events/ev-entity-owner-change) event reports every change."
            },
            {
              "type": "table",
              "headers": [
                "Reason",
                "Meaning"
              ],
              "rows": [
                [
                  "`\"adopt\"`",
                  "An orphan entity was taken by a nearby player."
                ],
                [
                  "`\"migrate\"`",
                  "A clearly closer player took over."
                ],
                [
                  "`\"leaseExpired\"`",
                  "The owner stopped sending updates."
                ],
                [
                  "`\"disconnect\"`",
                  "The owner left."
                ],
                [
                  "`\"demand\"`",
                  "A player took it on demand (for example by damaging an orphan entity)."
                ],
                [
                  "`\"script\"`",
                  "A script decided it (`setEntityOwner`)."
                ],
                [
                  "`\"release\"`",
                  "Nobody can take it: it becomes orphan."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Who owns it",
              "level": 2,
              "id": "owner"
            },
            {
              "type": "function",
              "name": "lsmp.getEntityOwner",
              "id": "fn-get-entity-owner",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getEntityOwner(netId) --> integer?",
                "js": "lsmp.getEntityOwner(netId: number): number | null"
              },
              "summary": "The player simulating an entity.",
              "md": "On the server, tell an orphan entity from an unknown one with `lsmp.entityExists`.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "A playerId; `nil`/`null` if the entity is orphan or unknown.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "A playerId; `nil`/`null` if the entity is orphan or unknown.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.setEntityOwner",
              "id": "fn-set-entity-owner",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setEntityOwner(netId, playerId) --> boolean",
                "js": "lsmp.setEntityOwner(netId: number, playerId: number | null): boolean"
              },
              "summary": "Gives the simulation of an entity to a player, or makes it orphan.",
              "md": "With the default `\"auto\"` policy, ownership can migrate again afterwards: set the policy to `\"pinned\"` to keep it on that player.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                },
                {
                  "name": "playerId",
                  "type": "playerId?",
                  "desc": "The new owner, in the same dimension as the entity; `nil`/`null` makes it orphan."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `not-found` (entity or player), `invalid` (other dimension, or the policy forbids it) or `permission`."
              }
            },
            {
              "type": "heading",
              "text": "Owner policies",
              "level": 2,
              "id": "owner-policies"
            },
            {
              "type": "table",
              "headers": [
                "Policy",
                "Who simulates"
              ],
              "rows": [
                [
                  "`\"auto\"` (default)",
                  "The nearest capable player; ownership migrates freely."
                ],
                [
                  "`\"pinned\"`",
                  "One player, set with `setEntityOwner` or `owner` at creation. No automatic migration; when that player leaves, the [life policy](#server-ownership/life-policies) decides."
                ],
                [
                  "`\"server\"`",
                  "Nobody: the entity is never adopted and has no game AI. Use it for entities a server script moves itself."
                ],
                [
                  "`\"frozen\"`",
                  "Nobody, and the entity is never synchronized: static scenery."
                ]
              ]
            },
            {
              "type": "function",
              "name": "lsmp.setEntityOwnerPolicy",
              "id": "fn-set-entity-owner-policy",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setEntityOwnerPolicy(netId, policy) --> boolean",
                "js": "lsmp.setEntityOwnerPolicy(netId: number, policy: string): boolean"
              },
              "summary": "Sets how ownership of an entity may change.",
              "md": "Switching to `\"server\"` or `\"frozen\"` removes the current owner at once.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                },
                {
                  "name": "policy",
                  "type": "string",
                  "desc": "`\"auto\"`, `\"pinned\"`, `\"server\"` or `\"frozen\"`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `not-found`, or `permission` (entity of another resource without `entities.foreign`)."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local car = lsmp.createEntity(\"vehicle\", \"police\", position, { owner = playerId })\nlsmp.setEntityOwnerPolicy(car, \"pinned\") -- stays on this player"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const car = lsmp.createEntity(\"vehicle\", \"police\", position, { owner: playerId });\nlsmp.setEntityOwnerPolicy(car, \"pinned\"); // stays on this player"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Life policies",
              "level": 2,
              "id": "life-policies"
            },
            {
              "type": "table",
              "headers": [
                "Policy",
                "When the entity is deleted"
              ],
              "rows": [
                [
                  "`\"whileRelevant\"` (default)",
                  "When no player has it in range any more."
                ],
                [
                  "`\"keep\"`",
                  "Never automatically. It also survives the stop of the resource that created it."
                ],
                [
                  "`\"withCreator\"`",
                  "When its creator goes away: the player who created it leaves, or the resource that created it stops."
                ]
              ]
            },
            {
              "type": "function",
              "name": "lsmp.setEntityLifePolicy",
              "id": "fn-set-entity-life-policy",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setEntityLifePolicy(netId, policy) --> boolean",
                "js": "lsmp.setEntityLifePolicy(netId: number, policy: string): boolean"
              },
              "summary": "Sets when the engine may delete an entity.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                },
                {
                  "name": "policy",
                  "type": "string",
                  "desc": "`\"whileRelevant\"`, `\"keep\"` or `\"withCreator\"`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `not-found`, or `permission` (entity of another resource without `entities.foreign`)."
              }
            },
            {
              "type": "heading",
              "text": "AI intents",
              "level": 2,
              "id": "intents"
            },
            {
              "type": "text",
              "md": "Game AI tasks live in the owner's game, so they are lost when ownership migrates. An **intent** is a server-side order that travels with the entity and that **every successive owner applies again**: a wandering ped keeps wandering after its owner left. Set it once on the server; LS:MP does the rest."
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Description"
              ],
              "rows": [
                [
                  "`type`",
                  "string",
                  "`\"idle\"` (stay in place), `\"wander\"` (around `position` within `radius`), `\"goTo\"` (go to `position` and stop), `\"follow\"`, `\"flee\"`, `\"combat\"` (relative to `target`), `\"guard\"` (stay within `radius` of `position` and attack what comes close), `\"custom\"` (see below), `\"none\"` (no order)."
                ],
                [
                  "`target`",
                  "netId or string",
                  "For `follow`, `flee`, `combat`: a netId, `\"nearestPlayer\"` or `\"owner\"` (the owner's ped). The strings are resolved again by each owner."
                ],
                [
                  "`position`",
                  "vec3",
                  "Anchor or destination."
                ],
                [
                  "`radius`",
                  "meters",
                  "Wander radius, follow distance, guard radius."
                ],
                [
                  "`group`",
                  "hash",
                  "Relationship group."
                ],
                [
                  "`accuracy`",
                  "integer",
                  "Shooting accuracy, `0..100`."
                ],
                [
                  "`keepTask`",
                  "boolean",
                  "Keep the task even when the game would replace it (recommended for any lasting AI)."
                ],
                [
                  "`mission`",
                  "boolean",
                  "Mark as a mission entity: not cleaned up with the ambient population."
                ],
                [
                  "`run`",
                  "boolean",
                  "Run instead of walk."
                ],
                [
                  "`hatesPlayers`",
                  "boolean",
                  "Hostile to players."
                ]
              ]
            },
            {
              "type": "text",
              "md": "With `\"custom\"`, LS:MP applies no task: the new owner's client receives [`entityAdopt`](#engine-events/ev-entity-adopt) and your client script gives the orders itself. A complete example is in [Recipe: server-spawned AI](#recipe-ai)."
            },
            {
              "type": "function",
              "name": "lsmp.setEntityIntent",
              "id": "fn-set-entity-intent",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setEntityIntent(netId, intent) --> boolean",
                "js": "lsmp.setEntityIntent(netId: number, intent: EntityIntent): boolean"
              },
              "summary": "Sets the replicated AI intent of a ped.",
              "md": "A mistyped or out-of-range field raises.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                },
                {
                  "name": "intent",
                  "type": "EntityIntent",
                  "desc": "See the table above."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `not-found`, or `permission` (entity of another resource without `entities.foreign`)."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local ped = lsmp.createEntity(\"ped\", \"s_m_y_cop_01\", position, { lifePolicy = \"keep\" })\nlsmp.setEntityIntent(ped, {\n  type = \"guard\", position = position, radius = 15.0,\n  accuracy = 60, keepTask = true, mission = true, hatesPlayers = true,\n})"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const ped = lsmp.createEntity(\"ped\", \"s_m_y_cop_01\", position, { lifePolicy: \"keep\" });\nlsmp.setEntityIntent(ped, {\n  type: \"guard\", position, radius: 15,\n  accuracy: 60, keepTask: true, mission: true, hatesPlayers: true,\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.clearEntityIntent",
              "id": "fn-clear-entity-intent",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.clearEntityIntent(netId) --> boolean",
                "js": "lsmp.clearEntityIntent(netId: number): boolean"
              },
              "summary": "Removes the intent of a ped.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `not-found`, or `permission` (entity of another resource without `entities.foreign`)."
              }
            },
            {
              "type": "heading",
              "text": "Constants",
              "level": 2,
              "id": "constants"
            },
            {
              "type": "function",
              "name": "lsmp.OwnerChangeReason",
              "id": "const-owner-change-reason",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.OwnerChangeReason",
                "js": "lsmp.OwnerChangeReason"
              },
              "summary": "The `reason` values of `entityOwnerChange`.",
              "md": "`lsmp.OwnerChangeReason.Adopt` = `\"adopt\"` · `lsmp.OwnerChangeReason.Migrate` = `\"migrate\"` · `lsmp.OwnerChangeReason.LeaseExpired` = `\"leaseExpired\"` · `lsmp.OwnerChangeReason.Disconnect` = `\"disconnect\"` · `lsmp.OwnerChangeReason.Demand` = `\"demand\"` · `lsmp.OwnerChangeReason.Script` = `\"script\"` · `lsmp.OwnerChangeReason.Release` = `\"release\"`"
            },
            {
              "type": "function",
              "name": "lsmp.OwnerPolicy",
              "id": "const-owner-policy",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.OwnerPolicy",
                "js": "lsmp.OwnerPolicy"
              },
              "summary": "Owner policies.",
              "md": "`lsmp.OwnerPolicy.Auto` = `\"auto\"` · `lsmp.OwnerPolicy.Pinned` = `\"pinned\"` · `lsmp.OwnerPolicy.Server` = `\"server\"` · `lsmp.OwnerPolicy.Frozen` = `\"frozen\"`"
            },
            {
              "type": "function",
              "name": "lsmp.LifePolicy",
              "id": "const-life-policy",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.LifePolicy",
                "js": "lsmp.LifePolicy"
              },
              "summary": "Life policies.",
              "md": "`lsmp.LifePolicy.WhileRelevant` = `\"whileRelevant\"` · `lsmp.LifePolicy.Keep` = `\"keep\"` · `lsmp.LifePolicy.WithCreator` = `\"withCreator\"`"
            }
          ]
        },
        {
          "id": "dimensions",
          "title": "Dimensions",
          "eyebrow": "Server · Lua & JS",
          "lead": "Separate copies of the world on one server: instances, arenas, interiors.",
          "blocks": [
            {
              "type": "text",
              "md": "A **dimension** is a separate copy of the world on the same server. Players and entities only see, hear and synchronize with players and entities of their own dimension. Dimension `0` is the default world; every player starts there. Use dimensions for instances: an apartment interior, a race, a deathmatch arena, a tutorial."
            },
            {
              "type": "list",
              "items": [
                "Moving players and entities and changing dimension settings needs the `dimensions.manage` [capability](#capabilities) (granted by default; the operator can refuse it).",
                "Moving a player does **not** move their vehicle or anything else: move entities with `lsmp.setEntityDimension`. A player's ped always follows its player.",
                "Dimension settings (population, client entities) are not restored when the resource that changed them stops, and changing them fires no event.",
                "The current dimension of a player is given by [`lsmp.getPlayerDimension`](#players)."
              ]
            },
            {
              "type": "heading",
              "text": "Moving players and entities",
              "level": 2,
              "id": "moving"
            },
            {
              "type": "function",
              "name": "lsmp.setPlayerDimension",
              "id": "fn-set-player-dimension",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setPlayerDimension(playerId, dimension) --> boolean",
                "js": "lsmp.setPlayerDimension(playerId: number, dimension: number): boolean"
              },
              "summary": "Moves a player (and their ped) to another dimension.",
              "md": "The move is applied asynchronously: `true` means the request was accepted. [`playerDimensionChange`](#engine-events/ev-player-dimension-change) fires on the server and on that player's client once it is done.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "dimension",
                  "type": "dimension",
                  "desc": "The dimension, `0..65535`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `not-found` or `permission`."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local function enterArena(playerId, arena)\n  local car = lsmp.getVehiclePedIsIn(lsmp.getPlayerPed(playerId))\n  lsmp.setPlayerDimension(playerId, arena)\n  if car then lsmp.setEntityDimension(car, arena) end\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "function enterArena(playerId, arena) {\n  const car = lsmp.getVehiclePedIsIn(lsmp.getPlayerPed(playerId));\n  lsmp.setPlayerDimension(playerId, arena);\n  if (car !== null) lsmp.setEntityDimension(car, arena);\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.setEntityDimension",
              "id": "fn-set-entity-dimension",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setEntityDimension(netId, dimension) --> boolean",
                "js": "lsmp.setEntityDimension(netId: number, dimension: number): boolean"
              },
              "summary": "Moves an entity to another dimension.",
              "md": "A player's ped cannot be moved alone: move the player.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                },
                {
                  "name": "dimension",
                  "type": "dimension",
                  "desc": "The dimension, `0..65535`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `not-found`, `invalid` (a player's ped) or `permission`."
              }
            },
            {
              "type": "function",
              "name": "lsmp.getEntityDimension",
              "id": "fn-get-entity-dimension",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getEntityDimension(netId) --> integer?",
                "js": "lsmp.getEntityDimension(netId: number): number | null"
              },
              "summary": "The dimension of an entity.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "`nil`/`null` if the entity is unknown.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "`nil`/`null` if the entity is unknown.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getPlayersInDimension",
              "id": "fn-get-players-in-dimension",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getPlayersInDimension(dimension) --> {integer}",
                "js": "lsmp.getPlayersInDimension(dimension: number): number[]"
              },
              "summary": "The players currently in a dimension.",
              "params": [
                {
                  "name": "dimension",
                  "type": "dimension",
                  "desc": "The dimension, `0..65535`."
                }
              ],
              "returns": [
                {
                  "type": "{integer}",
                  "desc": "A list of playerIds, possibly empty.",
                  "only": "lua"
                },
                {
                  "type": "number[]",
                  "desc": "A list of playerIds, possibly empty.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Dimension settings",
              "level": 2,
              "id": "settings"
            },
            {
              "type": "table",
              "headers": [
                "Setting",
                "Default",
                "Effect"
              ],
              "rows": [
                [
                  "population",
                  "on in dimension 0",
                  "Ambient pedestrians and traffic. Turning it off stops the games of the players in the dimension from creating them."
                ],
                [
                  "client entities",
                  "on (server.cfg `DefaultDimensionClientEntities`)",
                  "Whether the games of the players in the dimension may create their own networked entities (ambient and scripted). Off: only server scripts create entities there."
                ]
              ]
            },
            {
              "type": "function",
              "name": "lsmp.setDimensionPopulation",
              "id": "fn-set-dimension-population",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setDimensionPopulation(dimension, enabled) --> boolean",
                "js": "lsmp.setDimensionPopulation(dimension: number, enabled: boolean): boolean"
              },
              "summary": "Turns ambient population on or off in a dimension.",
              "params": [
                {
                  "name": "dimension",
                  "type": "dimension",
                  "desc": "The dimension, `0..65535`."
                },
                {
                  "name": "enabled",
                  "type": "boolean",
                  "desc": "Required: `true` or `false`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `permission`."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.setDimensionPopulation(12, false)\nlsmp.setDimensionClientEntities(12, false)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.setDimensionPopulation(12, false);\nlsmp.setDimensionClientEntities(12, false);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.isDimensionPopulationEnabled",
              "id": "fn-is-dimension-population-enabled",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.isDimensionPopulationEnabled(dimension) --> boolean?",
                "js": "lsmp.isDimensionPopulationEnabled(dimension: number): boolean | null"
              },
              "summary": "Whether ambient population runs in a dimension.",
              "md": "On a client, only the local player's dimension is known: other dimensions return `nil`/`null`.",
              "params": [
                {
                  "name": "dimension",
                  "type": "dimension",
                  "desc": "The dimension, `0..65535`."
                }
              ],
              "returns": [
                {
                  "type": "boolean?",
                  "only": "lua"
                },
                {
                  "type": "boolean | null",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.setDimensionClientEntities",
              "id": "fn-set-dimension-client-entities",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setDimensionClientEntities(dimension, enabled) --> boolean",
                "js": "lsmp.setDimensionClientEntities(dimension: number, enabled: boolean): boolean"
              },
              "summary": "Lets the players' games create their own networked entities in a dimension, or not.",
              "md": "On by default. Off, every entity a client tries to create in the dimension (ambient traffic and pedestrians, and entities created by client scripts) is refused: only server scripts create entities there. Useful for instanced missions and arenas.",
              "params": [
                {
                  "name": "dimension",
                  "type": "dimension",
                  "desc": "The dimension, `0..65535`."
                },
                {
                  "name": "enabled",
                  "type": "boolean",
                  "desc": "Required: `true` or `false`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `permission`."
              }
            },
            {
              "type": "function",
              "name": "lsmp.isDimensionClientEntitiesEnabled",
              "id": "fn-is-dimension-client-entities-enabled",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.isDimensionClientEntitiesEnabled(dimension) --> boolean",
                "js": "lsmp.isDimensionClientEntitiesEnabled(dimension: number): boolean"
              },
              "summary": "Whether clients may create entities in a dimension.",
              "params": [
                {
                  "name": "dimension",
                  "type": "dimension",
                  "desc": "The dimension, `0..65535`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` by default."
              }
            }
          ]
        },
        {
          "id": "server-moderation",
          "title": "Admission and moderation",
          "eyebrow": "Server · Lua & JS",
          "lead": "Decide who may join, then kick, ban and whitelist from a script.",
          "blocks": [
            {
              "type": "heading",
              "text": "Admission",
              "level": 2,
              "id": "moderation-admission"
            },
            {
              "type": "text",
              "md": "When somebody asks to join, the server first runs its own checks (bans, whitelist, player verification). Then [`playerPreConnection`](#engine-events) gives every resource a say, **before** the player downloads anything: refusing here costs them one round trip, refusing later costs them the whole download.\n\nThe handler receives one object, `p`:"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Description"
              ],
              "rows": [
                [
                  "`name`",
                  "string",
                  "The name they connect with."
                ],
                [
                  "`lsmpId`",
                  "int?",
                  "Their account, `nil`/`null` for a guest."
                ],
                [
                  "`guest`",
                  "boolean",
                  "`true` for a guest."
                ],
                [
                  "`verified`",
                  "boolean",
                  "`true` when the LS:MP network confirmed the account; otherwise it is only what the client says."
                ],
                [
                  "`ip`",
                  "string?",
                  "The address of the connection. Needs the `players.identity` [capability](#capabilities)."
                ],
                [
                  "`hwid`",
                  "string?",
                  "This server's view of the player's machine (64 hex): stable on this server, different on every other one. Needs `players.identity`."
                ],
                [
                  "`deny(reason)`",
                  "function",
                  "Refuse, with the sentence the player reads (256 bytes at most)."
                ]
              ]
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "**Any refusal wins.** A handler that returns without calling `p.deny` lets the player in, and so does a handler that throws (it is logged).",
                "A handler may be asynchronous (a database lookup): the verdict waits for every handler, up to `PreConnectionTimeoutMs` ([server.cfg](#server-cfg), 10 s by default). A handler still running then counts as a **refusal**: put a shorter timeout on your own queries."
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "lsmp.on(\"playerPreConnection\", function(p)\n  if MAINTENANCE and not STAFF[p.lsmpId] then\n    p.deny(\"The server is under maintenance. Come back in a few minutes.\")\n    return\n  end\n  if REQUIRE_ACCOUNT and p.guest then\n    p.deny(\"This server needs an LS:MP account.\")\n  end\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "lsmp.on('playerPreConnection', (p) => {\n  if (MAINTENANCE && !STAFF.has(p.lsmpId)) {\n    p.deny('The server is under maintenance. Come back in a few minutes.');\n    return;\n  }\n  if (REQUIRE_ACCOUNT && p.guest) p.deny('This server needs an LS:MP account.');\n});"
                }
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "Unverified accounts",
              "md": "Without player verification (\"Verify players with LS:MP\" in the admin panel), `lsmpId` is what the client declares. A staff list or a ban list keyed on it can then be bypassed by a modified client. Check `p.verified` when it matters."
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Refusing every guest",
              "md": "No script is needed: turn off \"Allow guest players\" in the **Identity & protection** card of the admin panel (`AllowGuests` in [server.cfg](#server-cfg)). It applies at once, and guests are refused before this event fires."
            },
            {
              "type": "heading",
              "text": "Removing players",
              "level": 2,
              "id": "moderation-kick"
            },
            {
              "type": "function",
              "name": "lsmp.kickPlayer",
              "id": "fn-kick-player",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.kickPlayer(playerId [, reason]) --> boolean",
                "js": "lsmp.kickPlayer(playerId: number, reason?: string): boolean"
              },
              "summary": "Disconnect a player.",
              "md": "[`playerLeave`](#engine-events) fires with the reason `\"kick\"` and your text as `detail`.\n\nNeeds the `players.kick` [capability](#capabilities).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "reason",
                  "type": "string",
                  "desc": "Shown to the player, 256 bytes at most.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the player was connected."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "Unknown player."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `players.kick`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.banPlayer",
              "id": "fn-ban-player",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.banPlayer(playerId [, opts]) --> {string}?",
                "js": "lsmp.banPlayer(playerId: number, opts?: BanOptions): string[] | null"
              },
              "summary": "Ban a connected player, then kick them.",
              "md": "The ban is recorded under each identifier type of `modes` the player has, so that they cannot come back by changing only one (a guest has no `lsmp` identifier). [`playerLeave`](#engine-events) fires with the reason `\"ban\"`. Bans are kept by the server and listed in the admin panel.\n\nNeeds the `players.ban` [capability](#capabilities).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "opts",
                  "type": "BanOptions",
                  "desc": "See [`BanOptions`](#server-moderation/ban-options).",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "{string}?",
                  "desc": "The identifier types actually banned, or `nil`/`null` if the player is unknown or the capability is missing.",
                  "only": "lua"
                },
                {
                  "type": "string[] | null",
                  "desc": "The identifier types actually banned, or `nil`/`null` if the player is unknown or the capability is missing.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "Unknown player."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `players.ban`."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.registerCommand(\"tempban\", {\n  help = \"Ban a player for a week\",\n  params = { { name = \"playerId\" }, { name = \"reason\", optional = true } },\n  permission = \"admin.ban\",\n}, function(args, raw, source)\n  local target = tonumber(args[1])\n  local banned = target and lsmp.banPlayer(target, {\n    reason = args[2] or \"Banned for a week\",\n    durationMs = 7 * 86400000,\n  })\n  lsmp.log(banned and (\"banned under \" .. table.concat(banned, \", \")) or \"no such player\")\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.registerCommand('tempban', {\n  help: 'Ban a player for a week',\n  params: [{ name: 'playerId' }, { name: 'reason', optional: true }],\n  permission: 'admin.ban',\n}, (args, raw, source) => {\n  const target = Number(args[0]);\n  const banned = Number.isInteger(target)\n    ? lsmp.banPlayer(target, { reason: args[1] || 'Banned for a week', durationMs: 7 * 86400000 })\n    : null;\n  lsmp.log(banned ? `banned under ${banned.join(', ')}` : 'no such player');\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.removeBan",
              "id": "fn-remove-ban",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.removeBan(type, value) --> boolean",
                "js": "lsmp.removeBan(type: string, value: string | number): boolean"
              },
              "summary": "Lift a ban.",
              "md": "Needs the `players.ban` [capability](#capabilities).",
              "params": [
                {
                  "name": "type",
                  "type": "string",
                  "desc": "`\"lsmp\"`, `\"hwid\"`, `\"ip\"` or `\"name\"`."
                },
                {
                  "name": "value",
                  "type": "string|int",
                  "desc": "The banned value. For `\"lsmp\"`, the account number is accepted."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if a ban was lifted."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "No such ban."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `players.ban`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "Whitelist",
              "level": 2,
              "id": "moderation-whitelist"
            },
            {
              "type": "text",
              "md": "While the whitelist is on, only the players it lists may join. The admin panel edits the same list."
            },
            {
              "type": "function",
              "name": "lsmp.addToWhitelist",
              "id": "fn-add-to-whitelist",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.addToWhitelist(type, value [, note]) --> boolean",
                "js": "lsmp.addToWhitelist(type: string, value: string | number, note?: string): boolean"
              },
              "summary": "Add an entry to the whitelist.",
              "md": "Needs the `players.whitelist` [capability](#capabilities).",
              "params": [
                {
                  "name": "type",
                  "type": "string",
                  "desc": "`\"lsmp\"`, `\"ip\"` or `\"name\"`."
                },
                {
                  "name": "value",
                  "type": "string|int",
                  "desc": "The value. For `\"lsmp\"`, the account number is accepted."
                },
                {
                  "name": "note",
                  "type": "string",
                  "desc": "Shown in the admin panel.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the entry was added."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`exists`",
                      "The entry is already there."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `players.whitelist`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.removeFromWhitelist",
              "id": "fn-remove-from-whitelist",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.removeFromWhitelist(type, value) --> boolean",
                "js": "lsmp.removeFromWhitelist(type: string, value: string | number): boolean"
              },
              "summary": "Remove an entry from the whitelist.",
              "md": "Needs the `players.whitelist` [capability](#capabilities).",
              "params": [
                {
                  "name": "type",
                  "type": "string",
                  "desc": "`\"lsmp\"`, `\"ip\"` or `\"name\"`."
                },
                {
                  "name": "value",
                  "type": "string|int",
                  "desc": "The value."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the entry was removed."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "No such entry."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `players.whitelist`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.setWhitelistEnabled",
              "id": "fn-set-whitelist-enabled",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setWhitelistEnabled(enabled)",
                "js": "lsmp.setWhitelistEnabled(enabled: boolean): void"
              },
              "summary": "Switch the whitelist on or off.",
              "md": "Players already connected stay.\n\nNeeds the `players.whitelist` [capability](#capabilities).",
              "params": [
                {
                  "name": "enabled",
                  "type": "boolean",
                  "desc": "`true` to switch it on, `false` to switch it off."
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The resource does not hold `players.whitelist`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.isWhitelistEnabled",
              "id": "fn-is-whitelist-enabled",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.isWhitelistEnabled() --> boolean",
                "js": "lsmp.isWhitelistEnabled(): boolean"
              },
              "summary": "Whether the whitelist is on.",
              "returns": {
                "type": "boolean",
                "desc": "`true` while it is on."
              }
            },
            {
              "type": "heading",
              "text": "Developer status",
              "level": 2,
              "id": "moderation-dev"
            },
            {
              "type": "function",
              "name": "lsmp.setPlayerDev",
              "id": "fn-set-player-dev",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setPlayerDev(playerId, dev) --> boolean",
                "js": "lsmp.setPlayerDev(playerId: number, dev: boolean): boolean"
              },
              "summary": "Allow or forbid DevTools to a player on this server.",
              "md": "DevTools let the player inspect this server's web interfaces. The `lsmp.devtools` [permission](#permissions) gives the same right through groups. Read it back with [`isPlayerDev`](#players/fn-is-player-dev).\n\nNeeds the `players.dev` [capability](#capabilities).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "dev",
                  "type": "boolean",
                  "desc": "`true` to allow, `false` to forbid."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the player is connected."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "Unknown player."
                    ],
                    [
                      "`permission`",
                      "The resource does not hold `players.dev`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "BanOptions",
              "level": 3,
              "id": "ban-options"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`modes`",
                  "strings",
                  "`{\"lsmp\", \"hwid\"}`",
                  "Identifier types to ban: `\"lsmp\"`, `\"hwid\"`, `\"ip\"`."
                ],
                [
                  "`reason`",
                  "string",
                  "—",
                  "Shown to the player and in the admin panel."
                ],
                [
                  "`durationMs`",
                  "ms",
                  "permanent",
                  "How long the ban lasts."
                ]
              ]
            }
          ]
        },
        {
          "id": "server-storage",
          "title": "Persistent storage",
          "eyebrow": "Server · Lua & JS",
          "lead": "A persistent key/value store private to each resource, with no setup.",
          "blocks": [
            {
              "type": "text",
              "md": "`lsmp.storage` is a small persistent key/value store, private to each resource and kept on the server's disk across restarts. It needs no setup: use it for settings, counters, small player records. For large or relational data, use [MySQL](#server-mysql); to compare the options, see [Storing data](#data-guide)."
            },
            {
              "type": "list",
              "items": [
                "Each resource has **its own store**: two resources never see each other's keys. The store follows the resource's identity: an operator resource and a marketplace mod with the same folder name never share it.",
                "Values are any [transportable value](#conventions/transportable-values): numbers (integers and floats stay distinct), strings, booleans, bytes, vectors, lists and maps. A value is at most 64 KiB encoded, and a store at most 16 MiB, each entry counting 64 bytes on top of its key and value (about 260 000 entries at most).",
                "Reads and writes are immediate (in memory). Changes reach the disk within about 750 ms; `lsmp.storage.flush()` waits until they are written. Stores are also flushed when the server stops.",
                "If a store file cannot be read, the resource's calls fail with `io` and the file is never overwritten, so nothing is lost."
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "local function addPlaytime(account, minutes)\n  local key = \"playtime:\" .. account\n  local total = (lsmp.storage.get(key) or 0) + minutes\n  lsmp.storage.set(key, total)\n  return total\nend\n\nfor _, key in ipairs(lsmp.storage.keys(\"playtime:\")) do\n  lsmp.log(key, lsmp.storage.get(key))\nend"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "function addPlaytime(account, minutes) {\n  const key = `playtime:${account}`;\n  const total = (lsmp.storage.get(key) ?? 0) + minutes;\n  lsmp.storage.set(key, total);\n  return total;\n}\n\nfor (const key of lsmp.storage.keys(\"playtime:\")) lsmp.log(key, lsmp.storage.get(key));"
                }
              ]
            },
            {
              "type": "callout",
              "variant": "tip",
              "md": "Prefix keys by kind (`\"player:\"`, `\"house:\"`) so `lsmp.storage.keys` can list one kind. Key players on their account (`lsmp.getPlayerLsmpId`), never on their playerId or name.",
              "title": "Keys"
            },
            {
              "type": "heading",
              "text": "Functions",
              "level": 2,
              "id": "functions"
            },
            {
              "type": "function",
              "name": "lsmp.storage.get",
              "id": "fn-storage-get",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.storage.get(key) --> any?",
                "js": "lsmp.storage.get(key: string): Value | null"
              },
              "summary": "Reads a stored value.",
              "params": [
                {
                  "name": "key",
                  "type": "string",
                  "desc": "Key: 1 to 256 bytes, any content."
                }
              ],
              "returns": [
                {
                  "type": "any?",
                  "desc": "The value, or `nil`/`null` if the key is absent; `nil, \"io\"` (JavaScript: `null` and `getLastError()` = `\"io\"`) if the store is unreadable.",
                  "only": "lua"
                },
                {
                  "type": "Value | null",
                  "desc": "The value, or `nil`/`null` if the key is absent; `nil, \"io\"` (JavaScript: `null` and `getLastError()` = `\"io\"`) if the store is unreadable.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.storage.set",
              "id": "fn-storage-set",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.storage.set(key, value) --> boolean",
                "js": "lsmp.storage.set(key: string, value: Value): boolean"
              },
              "summary": "Stores a value, or deletes the key when the value is `nil`/`null`.",
              "md": "A value over 64 KiB encoded raises.",
              "params": [
                {
                  "name": "key",
                  "type": "string",
                  "desc": "Key: 1 to 256 bytes, any content."
                },
                {
                  "name": "value",
                  "type": "value",
                  "desc": "The value; `nil`/`null` deletes the key."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `limit` (the store would exceed 16 MiB) or `io` (unreadable store)."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local ok, err = lsmp.storage.set(\"house:12\", { owner = 4211, price = 250000, locked = true })\nif not ok then lsmp.error(\"cannot save house: \" .. err) end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "if (!lsmp.storage.set(\"house:12\", { owner: 4211, price: 250000, locked: true })) {\n  lsmp.error(`cannot save house: ${lsmp.getLastError()}`);\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.storage.delete",
              "id": "fn-storage-delete",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.storage.delete(key) --> boolean",
                "js": "lsmp.storage.delete(key: string): boolean"
              },
              "summary": "Deletes a key.",
              "params": [
                {
                  "name": "key",
                  "type": "string",
                  "desc": "Key: 1 to 256 bytes, any content."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` if the key was absent."
              }
            },
            {
              "type": "function",
              "name": "lsmp.storage.keys",
              "id": "fn-storage-keys",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.storage.keys([prefix]) --> {string}",
                "js": "lsmp.storage.keys(prefix: string = \"\"): string[]"
              },
              "summary": "The keys that start with a prefix, sorted.",
              "params": [
                {
                  "name": "prefix",
                  "type": "string",
                  "optional": true,
                  "default": "\"\"",
                  "desc": "Prefix; empty lists every key."
                }
              ],
              "returns": [
                {
                  "type": "{string}",
                  "desc": "The keys.",
                  "only": "lua"
                },
                {
                  "type": "string[]",
                  "desc": "The keys.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.storage.flush",
              "id": "fn-storage-flush",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.storage.flush([cb]) --> boolean, err",
                "js": "lsmp.storage.flush(): Promise<boolean>"
              },
              "summary": "Writes this resource's pending changes to disk now. Asynchronous.",
              "md": "Call it before an operation that must not lose a recent write, for example in `resourceStop`.",
              "returns": [
                {
                  "type": "boolean, err",
                  "desc": "`true` once the store is on disk; fails with `io` if the write failed.",
                  "only": "lua"
                },
                {
                  "type": "Promise<boolean>",
                  "desc": "`true` once the store is on disk; fails with `io` if the write failed.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.storage.set(\"config:motd\", \"Welcome!\")\nlsmp.storage.flush(function(ok, err)\n  if not ok then lsmp.error(\"flush failed: \" .. err) end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.storage.set(\"config:motd\", \"Welcome!\");\nlsmp.storage.flush().catch((e) => lsmp.error(`flush failed: ${e.code}`));"
                  }
                ]
              }
            }
          ]
        },
        {
          "id": "server-mysql",
          "title": "MySQL",
          "eyebrow": "Server · Lua & JS",
          "lead": "Asynchronous queries to a MySQL or MariaDB database through a connection pool.",
          "blocks": [
            {
              "type": "text",
              "md": "Resources can use a MySQL or MariaDB database through a connection **pool**. Queries are asynchronous: the server never waits for the database. Results use the same values in Lua and JavaScript."
            },
            {
              "type": "callout",
              "variant": "warn",
              "md": "A database reaches outside the server, so a [sandboxed](#capabilities/sandbox) resource cannot create a pool: `createPool` fails with `permission`. The operator trusts a resource with `\"sandbox\": false` in [`resources.json`](#operator-settings).",
              "title": "Sandbox"
            },
            {
              "type": "list",
              "items": [
                "Connections open on demand, up to `connectionLimit`, and are reused.",
                "Always pass values as **parameters** (`?`), never by building SQL text: parameters cannot be used for SQL injection.",
                "SQL `NULL` is `lsmp.null` in Lua and `null` in JavaScript, in results and in parameters. Integers beyond 2^53 are `BigInt` in JavaScript.",
                "Pools of a resource are closed when it stops; queries already sent complete first (within the stop grace time)."
              ]
            },
            {
              "type": "heading",
              "text": "Creating a pool",
              "level": 2,
              "id": "pool"
            },
            {
              "type": "function",
              "name": "lsmp.mysql.createPool",
              "id": "fn-mysql-create-pool",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.mysql.createPool(opts) --> MysqlPool?",
                "js": "lsmp.mysql.createPool(opts: MysqlPoolOptions): MysqlPool | null"
              },
              "summary": "Creates a connection pool.",
              "params": [
                {
                  "name": "opts",
                  "type": "MysqlPoolOptions",
                  "desc": "Connection settings (table below)."
                }
              ],
              "returns": [
                {
                  "type": "MysqlPool?",
                  "desc": "The pool, or `nil`/`null` with `permission` (sandboxed resource) or `limit` (8 pools per resource).",
                  "only": "lua"
                },
                {
                  "type": "MysqlPool | null",
                  "desc": "The pool, or `nil`/`null` with `permission` (sandboxed resource) or `limit` (8 pools per resource).",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local db = lsmp.mysql.createPool({\n  host = \"127.0.0.1\", user = \"game\", password = \"secret\", database = \"lsmp\",\n  connectionLimit = 4, queryTimeoutMs = 5000,\n})"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const db = lsmp.mysql.createPool({\n  host: \"127.0.0.1\", user: \"game\", password: \"secret\", database: \"lsmp\",\n  connectionLimit: 4, queryTimeoutMs: 5000,\n});"
                  }
                ]
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Option",
                    "Type",
                    "Default",
                    "Description"
                  ],
                  "rows": [
                    [
                      "`host`",
                      "string",
                      "`\"127.0.0.1\"`",
                      "Server address."
                    ],
                    [
                      "`port`",
                      "integer",
                      "`3306`",
                      "Server port."
                    ],
                    [
                      "`user`",
                      "string",
                      "required",
                      "User name."
                    ],
                    [
                      "`password`",
                      "string",
                      "`\"\"`",
                      "Password."
                    ],
                    [
                      "`database`",
                      "string",
                      "—",
                      "Default database."
                    ],
                    [
                      "`charset`",
                      "string",
                      "`\"utf8mb4\"`",
                      "`\"utf8mb4\"`, `\"utf8\"`, `\"latin1\"` or `\"binary\"`."
                    ],
                    [
                      "`connectionLimit`",
                      "integer",
                      "`8`",
                      "Connections at most, `1..64`."
                    ],
                    [
                      "`connectTimeoutMs`",
                      "ms",
                      "`10000`",
                      "Deadline to open a connection."
                    ],
                    [
                      "`queryTimeoutMs`",
                      "ms",
                      "`0`",
                      "A query running longer fails with `timeout` and its connection is closed. `0` = no limit."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "Queries",
              "level": 2,
              "id": "queries"
            },
            {
              "type": "text",
              "md": "Failures: `error` (SQL error), `io` (connection problem), `timeout` (`queryTimeoutMs`), `cancelled` (pool closed). An SQL error comes with details `{ errno, sqlState, message }`: the third value in Lua, fields of the `Error` in JavaScript."
            },
            {
              "type": "function",
              "name": "pool.query",
              "id": "fn-pool-query",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "pool:query(sql [, params] [, cb]) --> MysqlResult, err",
                "js": "pool.query(sql: string, params?: Value[]): Promise<MysqlResult>"
              },
              "summary": "Runs one statement. Asynchronous.",
              "md": "A `SELECT` returns the list of rows, each row a table keyed by column name. Other statements return `{ affectedRows, insertId, warningCount }`.",
              "params": [
                {
                  "name": "sql",
                  "type": "string",
                  "desc": "The statement, with `?` placeholders."
                },
                {
                  "name": "params",
                  "type": "list",
                  "optional": true,
                  "desc": "Values for the placeholders, in order: numbers, strings, booleans, `lsmp.null`/`null`."
                }
              ],
              "returns": [
                {
                  "type": "MysqlResult, err",
                  "desc": "The rows, or the write summary.",
                  "only": "lua"
                },
                {
                  "type": "Promise<MysqlResult>",
                  "desc": "The rows, or the write summary.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- inside a host coroutine (event handler, file body, lsmp.createThread)\nlocal rows, err, details = db:query(\"SELECT name, money FROM players WHERE account = ?\", { account })\nif not rows then\n  lsmp.error(\"query failed: \" .. err .. \" \" .. (details and details.message or \"\"))\nelseif rows[1] then\n  lsmp.log(rows[1].name .. \" has $\" .. rows[1].money)\nend\n\nlocal res = db:query(\"UPDATE players SET money = money + ? WHERE account = ?\", { 100, account })"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "async function loadPlayer(account) {\n  try {\n    const rows = await db.query(\"SELECT name, money FROM players WHERE account = ?\", [account]);\n    if (rows.length) lsmp.log(`${rows[0].name} has $${rows[0].money}`);\n    const res = await db.query(\"UPDATE players SET money = money + ? WHERE account = ?\", [100, account]);\n    lsmp.log(`${res.affectedRows} row(s) changed`);\n  } catch (e) {\n    lsmp.error(`query failed: ${e.code} ${e.message}`);\n  }\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "pool.transaction",
              "id": "fn-pool-transaction",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "pool:transaction(fn [, cb]) --> any, err",
                "js": "pool.transaction(fn: Function): Promise<Value>"
              },
              "summary": "Runs several statements in one transaction. Asynchronous.",
              "md": "`fn(tx)` runs inside the transaction; use `tx:query(sql, params)` / `tx.query(sql, params)` like `pool.query`. When `fn` returns, the transaction is committed and its result is the result of `transaction`. When `fn` raises or rejects, it is rolled back and the error is passed on.",
              "params": [
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "`fn(tx)`; in Lua it may suspend on `tx:query`."
                }
              ],
              "returns": [
                {
                  "type": "any, err",
                  "desc": "What `fn` returned.",
                  "only": "lua"
                },
                {
                  "type": "Promise<Value>",
                  "desc": "What `fn` returned.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local ok, err = pcall(function()\n  return db:transaction(function(tx)\n    tx:query(\"UPDATE accounts SET balance = balance - ? WHERE id = ?\", { 50, from })\n    tx:query(\"UPDATE accounts SET balance = balance + ? WHERE id = ?\", { 50, to })\n    return true\n  end)\nend)\nif not ok then lsmp.error(\"transfer failed: \" .. tostring(err)) end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "async function transfer(from, to, amount) {\n  await db.transaction(async (tx) => {\n    await tx.query(\"UPDATE accounts SET balance = balance - ? WHERE id = ?\", [amount, from]);\n    await tx.query(\"UPDATE accounts SET balance = balance + ? WHERE id = ?\", [amount, to]);\n  });\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "pool.close",
              "id": "fn-pool-close",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "pool:close([cb]) --> boolean, err",
                "js": "pool.close(): Promise<boolean>"
              },
              "summary": "Lets queued queries finish, then closes the pool. Asynchronous.",
              "md": "Queries sent after the call fail with `cancelled`. Pools are also closed automatically when the resource stops.",
              "returns": [
                {
                  "type": "boolean, err",
                  "desc": "`true` when closed.",
                  "only": "lua"
                },
                {
                  "type": "Promise<boolean>",
                  "desc": "`true` when closed.",
                  "only": "js"
                }
              ]
            }
          ]
        },
        {
          "id": "server-files",
          "title": "Files",
          "eyebrow": "Server · Lua & JS",
          "lead": "Asynchronous file access on the server, with a private data folder for each resource.",
          "blocks": [
            {
              "type": "text",
              "md": "`lsmp.fs` reads and writes files on the server machine. Every call is asynchronous: the disk work happens in the background and the server keeps running. To read files shipped **inside** your resource, use [`lsmp.readResourceFile`](#core-utils/fn-read-resource-file) instead."
            },
            {
              "type": "list",
              "items": [
                "Every resource has a private **data folder**, [`lsmp.getDataPath()`](#server-files/fn-get-data-path), always readable and writable, sandboxed or not. Store your files there.",
                "A [sandboxed](#capabilities/sandbox) resource can only reach its data folder and the folders the operator lists in `SandboxFsRead` / `SandboxFsWrite` ([server.cfg](#server-cfg)). Anything else fails with `permission`.",
                "Use `/` in paths on every system."
              ]
            },
            {
              "type": "table",
              "headers": [
                "Code",
                "When"
              ],
              "rows": [
                [
                  "`not-found`",
                  "The file or folder does not exist."
                ],
                [
                  "`exists`",
                  "`mkdir` on an existing path, `writeFile` with `exclusive` on an existing file."
                ],
                [
                  "`permission`",
                  "Refused by the sandbox or by the system."
                ],
                [
                  "`invalid`",
                  "Malformed path, a folder where a file is expected, a folder that is not empty, `append` with `exclusive`."
                ],
                [
                  "`limit`",
                  "File larger than 512 MiB to read, or not enough memory."
                ],
                [
                  "`io`",
                  "Any other disk error."
                ]
              ]
            },
            {
              "type": "text",
              "md": "Failures come with details `{ message }` (third value in Lua, `message` of the `Error` in JavaScript)."
            },
            {
              "type": "heading",
              "text": "Data folder",
              "level": 2,
              "id": "data-folder"
            },
            {
              "type": "function",
              "name": "lsmp.getDataPath",
              "id": "fn-get-data-path",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getDataPath() --> string",
                "js": "lsmp.getDataPath(): string"
              },
              "summary": "The absolute path of the resource's private data folder, created on first call.",
              "md": "The folder follows the resource's identity: an operator resource and a marketplace mod with the same folder name never share it.",
              "returns": [
                {
                  "type": "string",
                  "desc": "The path, without a trailing `/`.",
                  "only": "lua"
                },
                {
                  "type": "string",
                  "desc": "The path, without a trailing `/`.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local file = lsmp.getDataPath() .. \"/scores.json\""
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const file = `${lsmp.getDataPath()}/scores.json`;"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Files",
              "level": 2,
              "id": "files"
            },
            {
              "type": "function",
              "name": "lsmp.fs.readFile",
              "id": "fn-fs-read-file",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.fs.readFile(path [, opts] [, cb]) --> string|string, err",
                "js": "lsmp.fs.readFile(path: string, opts?: ReadFileOptions): Promise<string | Uint8Array>"
              },
              "summary": "Reads a whole file (512 MiB at most). Asynchronous.",
              "params": [
                {
                  "name": "path",
                  "type": "string",
                  "desc": "Absolute, or relative to the server folder."
                },
                {
                  "name": "opts",
                  "type": "ReadFileOptions",
                  "optional": true,
                  "desc": "`{ binary = true }` returns bytes (`Uint8Array` in JavaScript); text (UTF-8) by default."
                }
              ],
              "returns": [
                {
                  "type": "string, err",
                  "desc": "The content.",
                  "only": "lua"
                },
                {
                  "type": "Promise<string | Uint8Array>",
                  "desc": "The content.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.fs.readFile(lsmp.getDataPath() .. \"/scores.json\", function(text, err)\n  if not text then\n    if err ~= \"not-found\" then lsmp.warn(\"cannot read scores: \" .. err) end\n    return\n  end\n  scores = lsmp.json.decode(text)\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "async function loadScores() {\n  try {\n    return JSON.parse(await lsmp.fs.readFile(`${lsmp.getDataPath()}/scores.json`));\n  } catch (e) {\n    if (e.code !== \"not-found\") lsmp.warn(`cannot read scores: ${e.code}`);\n    return {};\n  }\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.fs.writeFile",
              "id": "fn-fs-write-file",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.fs.writeFile(path, data [, opts] [, cb]) --> boolean, err",
                "js": "lsmp.fs.writeFile(path: string, data: string|Uint8Array|ArrayBuffer, opts?: WriteFileOptions): Promise<boolean>"
              },
              "summary": "Writes a file, replacing it or appending to it. Asynchronous.",
              "params": [
                {
                  "name": "path",
                  "type": "string",
                  "desc": "Absolute, or relative to the server folder."
                },
                {
                  "name": "data",
                  "type": "data",
                  "desc": "A string, or bytes (`lsmp.bytes`/string in Lua; `Uint8Array` or `ArrayBuffer` in JavaScript)."
                },
                {
                  "name": "opts",
                  "type": "WriteFileOptions",
                  "optional": true,
                  "desc": "`{ append = false, exclusive = false }`: `append` adds at the end; `exclusive` fails with `exists` if the file exists. Not both."
                }
              ],
              "returns": [
                {
                  "type": "boolean, err",
                  "desc": "`true` when written.",
                  "only": "lua"
                },
                {
                  "type": "Promise<boolean>",
                  "desc": "`true` when written.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.fs.writeFile(lsmp.getDataPath() .. \"/chat.log\", line .. \"\\n\", { append = true }, function(ok, err)\n  if not ok then lsmp.warn(\"log write failed: \" .. err) end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.fs.writeFile(`${lsmp.getDataPath()}/chat.log`, `${line}\\n`, { append: true })\n  .catch((e) => lsmp.warn(`log write failed: ${e.code}`));"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.fs.rename",
              "id": "fn-fs-rename",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.fs.rename(from, to [, cb]) --> boolean, err",
                "js": "lsmp.fs.rename(from: string, to: string): Promise<boolean>"
              },
              "summary": "Renames or moves a file or folder. Asynchronous.",
              "params": [
                {
                  "name": "from",
                  "type": "string",
                  "desc": "Current path."
                },
                {
                  "name": "to",
                  "type": "string",
                  "desc": "New path."
                }
              ],
              "returns": [
                {
                  "type": "boolean, err",
                  "only": "lua"
                },
                {
                  "type": "Promise<boolean>",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.fs.remove",
              "id": "fn-fs-remove",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.fs.remove(path [, opts] [, cb]) --> boolean, err",
                "js": "lsmp.fs.remove(path: string, opts?: RemoveOptions): Promise<boolean>"
              },
              "summary": "Removes a file or a folder. Asynchronous.",
              "md": "A folder must be empty unless `recursive` is set. Removing a path that does not exist succeeds.",
              "params": [
                {
                  "name": "path",
                  "type": "string",
                  "desc": "Absolute, or relative to the server folder."
                },
                {
                  "name": "opts",
                  "type": "RemoveOptions",
                  "optional": true,
                  "desc": "`{ recursive = false }`."
                }
              ],
              "returns": [
                {
                  "type": "boolean, err",
                  "only": "lua"
                },
                {
                  "type": "Promise<boolean>",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Folders",
              "level": 2,
              "id": "folders"
            },
            {
              "type": "function",
              "name": "lsmp.fs.mkdir",
              "id": "fn-fs-mkdir",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.fs.mkdir(path [, opts] [, cb]) --> boolean, err",
                "js": "lsmp.fs.mkdir(path: string, opts?: MkdirOptions): Promise<boolean>"
              },
              "summary": "Creates a folder. Asynchronous.",
              "md": "Without `recursive`, the parent must exist and the folder must not (`exists`). With `recursive`, missing parents are created and an existing folder is fine.",
              "params": [
                {
                  "name": "path",
                  "type": "string",
                  "desc": "Absolute, or relative to the server folder."
                },
                {
                  "name": "opts",
                  "type": "MkdirOptions",
                  "optional": true,
                  "desc": "`{ recursive = false }`."
                }
              ],
              "returns": [
                {
                  "type": "boolean, err",
                  "only": "lua"
                },
                {
                  "type": "Promise<boolean>",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.fs.list",
              "id": "fn-fs-list",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.fs.list(path [, cb]) --> {DirEntry}, err",
                "js": "lsmp.fs.list(path: string): Promise<DirEntry[]>"
              },
              "summary": "The entries of a folder, sorted by name. Asynchronous.",
              "params": [
                {
                  "name": "path",
                  "type": "string",
                  "desc": "Absolute, or relative to the server folder."
                }
              ],
              "returns": [
                {
                  "type": "{DirEntry}, err",
                  "desc": "A list of `{ name, isDir, size, mtimeMs }` (`size` 0 for folders).",
                  "only": "lua"
                },
                {
                  "type": "Promise<DirEntry[]>",
                  "desc": "A list of `{ name, isDir, size, mtimeMs }` (`size` 0 for folders).",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.createThread(function()\n  local entries, err = lsmp.fs.list(lsmp.getDataPath())\n  for _, e in ipairs(entries or {}) do\n    lsmp.log(e.name, e.isDir and \"dir\" or e.size .. \" bytes\")\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "(async () => {\n  for (const e of await lsmp.fs.list(lsmp.getDataPath())) {\n    lsmp.log(e.name, e.isDir ? \"dir\" : `${e.size} bytes`);\n  }\n})();"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.fs.stat",
              "id": "fn-fs-stat",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.fs.stat(path [, cb]) --> FileStat?, err",
                "js": "lsmp.fs.stat(path: string): Promise<FileStat | null>"
              },
              "summary": "Information about a path. Asynchronous.",
              "md": "A path that does not exist is not a failure: the result is `nil`/`null`.",
              "params": [
                {
                  "name": "path",
                  "type": "string",
                  "desc": "Absolute, or relative to the server folder."
                }
              ],
              "returns": [
                {
                  "type": "FileStat?, err",
                  "desc": "`{ isDir, isFile, size, mtimeMs }`, or `nil`/`null` if nothing is there.",
                  "only": "lua"
                },
                {
                  "type": "Promise<FileStat | null>",
                  "desc": "`{ isDir, isFile, size, mtimeMs }`, or `nil`/`null` if nothing is there.",
                  "only": "js"
                }
              ]
            }
          ]
        },
        {
          "id": "server-http-serve",
          "title": "HTTP routes",
          "eyebrow": "Server · Lua & JS",
          "lead": "Answer HTTP requests under /res/<resource>/ on the server's HTTP port.",
          "blocks": [
            {
              "type": "text",
              "md": "A resource can answer HTTP requests on the server's HTTP port (`HttpPort` in [server.cfg](#server-cfg)), under its own path: `http://<server>:<HttpPort>/res/<resource name>/...`. Use it for webhooks, a small JSON API for your website, or files generated on the fly. Pages shown in game load their files from the resource package, not from here (see [Web interfaces](#web-ui))."
            },
            {
              "type": "list",
              "items": [
                "**One route per resource**, covering every path under `/res/<name>/`. It is removed when the resource stops; requests not answered yet get `503`. At most 256 requests are handled at once for one route (more get `503`) and 64 from one client address (more get `429`; the loopback is not counted).",
                "Requests are public: anyone who can reach the port can call your route. Check a secret or a signature for anything that is not public.",
                "A request body over `maxBodyBytes` is answered `413` without calling the handler. A handler that does not answer within `timeoutMs` leaves the client with `504`. A handler that raises gets the client a `500`, and the error is logged."
              ]
            },
            {
              "type": "heading",
              "text": "Serving",
              "level": 2,
              "id": "serve"
            },
            {
              "type": "function",
              "name": "lsmp.http.serve",
              "id": "fn-http-serve",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.http.serve(fn [, opts]) --> function",
                "js": "lsmp.http.serve(fn: Function, opts?: HttpServeOptions): () => boolean"
              },
              "summary": "Serves `/res/<resource name>/...` with a handler function.",
              "md": "The handler receives a request and **returns** the response: a string (sent as `200`, `text/plain`), or a response table. In JavaScript it may return a Promise. A second call while the route exists raises.",
              "params": [
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "`fn(req) -> response`."
                },
                {
                  "name": "opts",
                  "type": "HttpServeOptions",
                  "optional": true,
                  "desc": "`{ maxBodyBytes = 1048576, timeoutMs = 10000 }`: largest accepted body (at most 16 MiB) and answer deadline (at most 300 000 ms)."
                }
              ],
              "returns": [
                {
                  "type": "function",
                  "desc": "The function that removes the route.",
                  "only": "lua"
                },
                {
                  "type": "() => boolean",
                  "desc": "The function that removes the route.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.http.serve(function(req)\n  if req.method == \"GET\" and req.path == \"/status\" then\n    return {\n      status = 200,\n      headers = { [\"content-type\"] = \"application/json\" },\n      body = lsmp.json.encode({ players = #lsmp.getPlayers() }),\n    }\n  end\n  return { status = 404, body = \"not found\" }\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.http.serve(async (req) => {\n  if (req.method === \"GET\" && req.path === \"/status\") {\n    return { json: { players: lsmp.getPlayers().length } };\n  }\n  return { status: 404, body: \"not found\" };\n});"
                  }
                ]
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Request field",
                    "Type",
                    "Description"
                  ],
                  "rows": [
                    [
                      "`method`",
                      "string",
                      "Upper case: `\"GET\"`, `\"POST\"`..."
                    ],
                    [
                      "`path`",
                      "string",
                      "The path after `/res/<name>`, starting with `/`."
                    ],
                    [
                      "`query`",
                      "table",
                      "Query parameters, decoded: `{ page = \"2\" }`."
                    ],
                    [
                      "`headers`",
                      "table",
                      "Header names in lower case; repeated headers joined with `\", \"`."
                    ],
                    [
                      "`body`",
                      "string or bytes",
                      "The body; bytes (`Uint8Array` in JavaScript) when it is not valid UTF-8."
                    ],
                    [
                      "`address`",
                      "string",
                      "The client's IP address."
                    ]
                  ]
                },
                {
                  "type": "table",
                  "headers": [
                    "Response field",
                    "Type",
                    "Default",
                    "Description"
                  ],
                  "rows": [
                    [
                      "`status`",
                      "integer",
                      "`200`",
                      "`100..599`."
                    ],
                    [
                      "`headers`",
                      "table",
                      "—",
                      "Header values are strings. `Content-Length`, `Transfer-Encoding` and `Connection` are set by the server and refused; a value with a line break raises."
                    ],
                    [
                      "`body`",
                      "string or bytes",
                      "`\"\"`",
                      "The body."
                    ],
                    [
                      "`json`",
                      "value",
                      "—",
                      "Sent as JSON with `Content-Type: application/json`. Not with `body`."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "Example: a webhook",
              "level": 2,
              "id": "webhook"
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "local SECRET = \"change-me\"\n\nlsmp.http.serve(function(req)\n  if req.method ~= \"POST\" or req.headers[\"x-secret\"] ~= SECRET then\n    return { status = 403, body = \"forbidden\" }\n  end\n  local data = lsmp.json.decode(req.body)\n  if not data then return { status = 400, body = \"bad json\" } end\n  lsmp.emitAllClients(\"news:flash\", data.text)\n  return { status = 204 }\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "const SECRET = \"change-me\";\n\nlsmp.http.serve((req) => {\n  if (req.method !== \"POST\" || req.headers[\"x-secret\"] !== SECRET) return { status: 403, body: \"forbidden\" };\n  let data;\n  try { data = JSON.parse(req.body); } catch { return { status: 400, body: \"bad json\" }; }\n  lsmp.emitAllClients(\"news:flash\", data.text);\n  return { status: 204 };\n});"
                }
              ]
            },
            {
              "type": "text",
              "md": "To call other web services from a script, see the [HTTP client](#http)."
            }
          ]
        },
        {
          "id": "server-commands",
          "title": "Console commands",
          "eyebrow": "Server · Lua & JS",
          "lead": "Add commands to the server console and the admin panel, and let players run them with the right permission.",
          "blocks": [
            {
              "type": "text",
              "md": "A command registered by a server script answers in the server terminal and in the admin panel console. The [built-in commands](#console) (`start`, `stop`, `kick`, `say`...) come first and cannot be replaced.\n\nPlayers do not type server commands directly: a resource passes their line to [`executeCommand`](#server-commands/fn-execute-command), usually from the chat (the bundled `chat` resource runs every line that starts with `/`). The player's permissions then decide which handlers run."
            },
            {
              "type": "table",
              "headers": [
                "Option",
                "Who may run the command"
              ],
              "rows": [
                [
                  "(no `permission`)",
                  "The console, and players holding `command.<name>`."
                ],
                [
                  "`permission = \"admin.kick\"`",
                  "The console, and players holding that permission."
                ],
                [
                  "`permission = false`",
                  "The console and every player."
                ],
                [
                  "`restricted = true`",
                  "The console only, never a player."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Registering",
              "level": 2,
              "id": "commands-register"
            },
            {
              "type": "function",
              "name": "lsmp.registerCommand",
              "id": "fn-register-command",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.registerCommand(name [, opts], fn) --> off",
                "js": "lsmp.registerCommand(name: string, opts: CommandOptions | undefined, fn: Function): () => boolean  // also (name, fn)"
              },
              "summary": "Add a command to the server console.",
              "md": "The handler receives `(args, raw, source, invoker)`:\n\n- `args`: the words after the command name, split on spaces; a word that starts with `\"` runs to the next `\"` (no escapes);\n- `raw`: the rest of the line as typed, leading spaces removed;\n- `source`: the playerId when a player runs it, `nil`/`null` from the console or the admin panel;\n- `invoker`: who ran it: the admin user, the player's name, or `resource:<name>` for a script.\n\nSeveral handlers may share a name, in any resource and either language: they all run, each filtered by its own permission. Names are 1 to 64 characters (`A-Z a-z 0-9 _ . : -`), case-insensitive, with an optional leading `/`.",
              "params": [
                {
                  "name": "name",
                  "type": "string",
                  "desc": "The command name."
                },
                {
                  "name": "opts",
                  "type": "CommandOptions",
                  "desc": "See [`CommandOptions`](#server-commands/command-options).",
                  "optional": true
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The handler."
                }
              ],
              "returns": [
                {
                  "type": "function",
                  "desc": "A function that unregisters this handler and returns `true` if it was registered.",
                  "only": "lua"
                },
                {
                  "type": "() => boolean",
                  "desc": "A function that unregisters this handler and returns `true` if it was registered.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "callout",
                  "variant": "info",
                  "title": "Answering a player",
                  "md": "`lsmp.log` writes to the server log. To answer a player who ran the command, send them a message (for example the chat's `chat:message` event) when `source` is not `nil`/`null`."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.perms.declare(\"admin.announce\", \"Use /announce\")\n\nlsmp.registerCommand(\"announce\", {\n  help = \"Show a message to every player\",\n  params = { { name = \"text\", help = \"What to say\" } },\n  permission = \"admin.announce\",\n}, function(args, raw, source, invoker)\n  if raw == \"\" then\n    lsmp.log(\"usage: announce <text>\")\n    return\n  end\n  lsmp.emitAllClients(\"announce\", raw)\n  lsmp.log(invoker .. \" announced: \" .. raw)\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.perms.declare('admin.announce', 'Use /announce');\n\nlsmp.registerCommand('announce', {\n  help: 'Show a message to every player',\n  params: [{ name: 'text', help: 'What to say' }],\n  permission: 'admin.announce',\n}, (args, raw, source, invoker) => {\n  if (!raw) {\n    lsmp.log('usage: announce <text>');\n    return;\n  }\n  lsmp.emitAllClients('announce', raw);\n  lsmp.log(`${invoker} announced: ${raw}`);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.unregisterCommand",
              "id": "fn-unregister-command",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.unregisterCommand(name, fn) --> boolean",
                "js": "lsmp.unregisterCommand(name: string, fn: Function): boolean"
              },
              "summary": "Remove a command handler of this resource.",
              "md": "The same as calling the function `registerCommand` returned. A resource's commands are removed when it stops. Works for server and [client commands](#client-commands).",
              "params": [
                {
                  "name": "name",
                  "type": "string",
                  "desc": "The command name."
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The handler that was registered."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the handler was registered."
              }
            },
            {
              "type": "heading",
              "text": "Running a command for a player",
              "level": 2,
              "id": "commands-execute"
            },
            {
              "type": "function",
              "name": "lsmp.executeCommand",
              "id": "fn-execute-command",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.executeCommand(source, line) --> \"ok\" | \"unknown\" | \"denied\" | \"invalid\"",
                "js": "lsmp.executeCommand(source: number | null, line: string): \"ok\" | \"unknown\" | \"denied\" | \"invalid\""
              },
              "summary": "Run a console line on behalf of a player, or with console rights.",
              "md": "With a playerId, the player must hold the permission of a handler for it to run; handlers marked `restricted` never run. With `nil`/`null`, every handler runs, as from the console. Built-in commands are not reachable this way. Handlers run on the next server tick, after the call returns.\n\nNeeds the `commands.execute` [capability](#capabilities) for a player, `commands.console` for console rights.",
              "params": [
                {
                  "name": "source",
                  "type": "playerId?",
                  "desc": "The player, or `nil`/`null` for console rights."
                },
                {
                  "name": "line",
                  "type": "string",
                  "desc": "The line, command name first, with or without a leading `/`."
                }
              ],
              "returns": {
                "type": "string",
                "desc": "`\"ok\"` (handlers will run), `\"unknown\"` (no such command), `\"denied\"` (the player may not run it, or left) or `\"invalid\"` (no command name in the line); `nil`/`null` when the capability is missing."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The resource does not hold the capability."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- In a chat resource: a line starting with \"/\" is a command.\nlsmp.onClient(\"chat:say\", function(source, text)\n  if text:sub(1, 1) ~= \"/\" then return end\n  local verdict = lsmp.executeCommand(source, text:sub(2))\n  if verdict == \"unknown\" then\n    lsmp.emitClient(source, \"chat:message\", { name = \"\", text = \"Unknown command.\", system = true })\n  elseif verdict == \"denied\" then\n    lsmp.emitClient(source, \"chat:message\", { name = \"\", text = \"Not allowed.\", system = true })\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// In a chat resource: a line starting with \"/\" is a command.\nlsmp.onClient('chat:say', (source, text) => {\n  if (typeof text !== 'string' || text[0] !== '/') return;\n  const verdict = lsmp.executeCommand(source, text.slice(1));\n  if (verdict === 'unknown') lsmp.emitClient(source, 'chat:message', { name: '', text: 'Unknown command.', system: true });\n  else if (verdict === 'denied') lsmp.emitClient(source, 'chat:message', { name: '', text: 'Not allowed.', system: true });\n});"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "CommandOptions",
              "level": 3,
              "id": "command-options"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`help`",
                  "string",
                  "—",
                  "One line shown by `help` in the console and in completions."
                ],
                [
                  "`params`",
                  "list",
                  "—",
                  "Parameters shown while typing: `{ name, help, type, optional }` each. Display only: the handler still receives strings."
                ],
                [
                  "`permission`",
                  "string | boolean",
                  "`\"command.<name>\"`",
                  "The permission a player needs; `false` for every player."
                ],
                [
                  "`restricted`",
                  "boolean",
                  "`false`",
                  "`true`: the console only, never a player."
                ]
              ]
            }
          ]
        },
        {
          "id": "server-lifecycle",
          "title": "Server and resource lifecycle",
          "eyebrow": "Server · Lua & JS",
          "lead": "When your scripts start and stop, and what they can still do on the way out.",
          "blocks": [
            {
              "type": "heading",
              "text": "Resource states",
              "level": 2,
              "id": "lifecycle-states"
            },
            {
              "type": "text",
              "md": "A resource is in one state at a time, the same for its Lua and its JavaScript scripts: `stopped` → `starting` → `started` or `failed`; `started` → `stopping` → `stopped`. On the server, every enabled resource starts **once**, with the server, and runs until the server stops: nothing starts, stops or restarts a resource in between, neither the console nor a script. A `failed` resource stays failed until the next server start. [`lsmp.getResourceState`](#core-utils) and the `resources` console command show it."
            },
            {
              "type": "heading",
              "text": "Starting a resource",
              "level": 2,
              "id": "lifecycle-start"
            },
            {
              "type": "list",
              "ordered": true,
              "items": [
                "Its [dependencies](#resource-layout) start first. A dependency that is missing, disabled in [`resources.json`](#operator-settings) or failed makes the resource `failed`, with the reason in the log.",
                "Its server scripts run in manifest order, JavaScript files before Lua files. In JavaScript, a module-level `await` is waited for before the next file and before the resource counts as started, up to `ResourceStartTimeoutMs` ([server.cfg](#server-cfg), 30 s by default). A Lua file runs until it ends or first waits (a `while true do lsmp.wait(...) end` loop is fine).",
                "A script that throws, or a module-level Promise that rejects, makes the resource `failed`: what it already registered or created is removed, the error and the file are logged, and the resources that depend on it do not start.",
                "Otherwise the resource is `started` and [`resourceStart`](#engine-events) `(name)` fires in every resource, itself included."
              ]
            },
            {
              "type": "heading",
              "text": "Stopping a resource",
              "level": 2,
              "id": "lifecycle-stop"
            },
            {
              "type": "list",
              "ordered": true,
              "items": [
                "It happens when the server shuts down ([below](#server-lifecycle/lifecycle-server)). The resources that depend on it stop first.",
                "[`resourceStop`](#engine-events) `(name)` fires, in the stopping resource first, then in the others. Its handlers may wait (a Promise in JS, a suspended handler in Lua) up to `ResourceStopGraceMs` (2 s by default): this is the moment to save. Everything the resource owns still works during the handlers.",
                "Then the resource is cleaned up: event handlers, commands, timers and pending waits, its HTTP route, its MySQL pools (queries already queued finish first), its storage is written to disk, the entities and pickups it created (except `lifePolicy = \"keep\"`), its synchronized scenes, its voice channels, its declared permissions, and the weather it forced is restored."
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "lsmp.on(\"resourceStop\", function(name)\n  if name ~= lsmp.getResourceName() then return end\n  for playerId, data in pairs(sessions) do\n    lsmp.storage.set(\"session:\" .. data.account, data)\n  end\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "lsmp.on('resourceStop', async (name) => {\n  if (name !== lsmp.getResourceName()) return;\n  for (const data of sessions.values()) lsmp.storage.set(`session:${data.account}`, data);\n  await lsmp.storage.flush();\n});"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Changing a resource",
              "level": 2,
              "id": "lifecycle-changes"
            },
            {
              "type": "text",
              "md": "The server reads its resources **once**, when it starts. To apply a change (an edited file, a new or removed resource, [`resources.json`](#operator-settings)), restart the server: players are disconnected with the shutdown message and join again. No console command and no function starts, stops or restarts a resource while the server runs.\n\nOn the client, a script can still mount and unmount resources while the game runs: see [Hot resources](#client-resources)."
            },
            {
              "type": "heading",
              "text": "Server start and shutdown",
              "level": 2,
              "id": "lifecycle-server"
            },
            {
              "type": "table",
              "headers": [
                "Moment",
                "What happens"
              ],
              "rows": [
                [
                  "Start",
                  "Every enabled resource starts, in dependency order: the only start of the server's resources. Then [`serverStart`](#engine-events) fires once, when they all reached `started` or `failed` and the game port listens."
                ],
                [
                  "Shutdown",
                  "`quit`, the admin panel, an update, or a stop signal: no new connection; [`playerLeave`](#engine-events) with the reason `\"shutdown\"` for every player, who is then disconnected (no event or call from that player reaches a handler afterwards); [`serverStop`](#engine-events), whose handlers may wait up to `ShutdownGraceMs` (5 s by default); every resource stops (as above, within what is left of that time); storage and permissions are written; the process exits."
                ],
                [
                  "Crash",
                  "Nothing of the above runs. Save important data as it changes, not only at shutdown."
                ]
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "lsmp.on(\"serverStop\", function()\n  local res, err = db:query(\"UPDATE servers SET online = 0 WHERE id = ?\", { SERVER_ID })\n  if not res then lsmp.warn(\"could not mark the server offline: \" .. err) end\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "lsmp.on('serverStop', async () => {\n  try {\n    await db.query('UPDATE servers SET online = 0 WHERE id = ?', [SERVER_ID]);\n  } catch (err) {\n    lsmp.warn(`could not mark the server offline: ${err.code}`);\n  }\n});"
                }
              ]
            },
            {
              "type": "heading",
              "text": "On the client",
              "level": 2,
              "id": "lifecycle-client"
            },
            {
              "type": "text",
              "md": "A client starts the server's resources when it joins (those mounted automatically, in dependency order) and stops them all when it leaves. [`resourceStart`](#engine-events) and [`resourceStop`](#engine-events) fire there too; a client's `resourceStop` handlers get 1 s. In between, a client script can mount and unmount resources with [`lsmp.mountResource`](#client-resources/fn-mount-resource) and [`lsmp.unmountResource`](#client-resources/fn-unmount-resource): the only change made to resources while connected."
            }
          ]
        },
        {
          "id": "capabilities",
          "title": "Resource capabilities and sandbox",
          "eyebrow": "Server · Lua & JS",
          "lead": "What a resource is allowed to do: sensitive functions (capabilities) and access to the machine (sandbox).",
          "blocks": [
            {
              "type": "text",
              "md": "Two independent protections let a server owner run resources they did not write, including marketplace mods:"
            },
            {
              "type": "list",
              "items": [
                "**Capabilities** decide which sensitive `lsmp` functions a resource may use: kicking players, moving them between dimensions, deleting other resources' entities...",
                "The **sandbox** decides what a resource may do on the machine: files, network, databases, processes."
              ]
            },
            {
              "type": "text",
              "md": "Both are set by the operator, never by the resource itself."
            },
            {
              "type": "heading",
              "text": "Capabilities",
              "level": 2,
              "id": "list"
            },
            {
              "type": "text",
              "md": "Operator resources get every capability by default. Marketplace mods get them too, except the four marked \"refused\". The operator changes them per resource in the admin panel (see [Console and admin panel](#console))."
            },
            {
              "type": "table",
              "headers": [
                "Capability",
                "Covers",
                "Operator resource",
                "Marketplace mod"
              ],
              "rows": [
                [
                  "`perms.manage`",
                  "Writes of [`lsmp.perms`](#permissions) (groups, members, rules)",
                  "granted",
                  "granted"
                ],
                [
                  "`commands.execute`",
                  "`lsmp.executeCommand(playerId, line)`: run a command for a player (their permissions still apply)",
                  "granted",
                  "granted"
                ],
                [
                  "`commands.console`",
                  "`lsmp.executeCommand(nil, line)`: run a command with console rights",
                  "granted",
                  "granted"
                ],
                [
                  "`players.kick`",
                  "`lsmp.kickPlayer`",
                  "granted",
                  "granted"
                ],
                [
                  "`players.ban`",
                  "`lsmp.banPlayer`, `lsmp.removeBan`",
                  "granted",
                  "granted"
                ],
                [
                  "`players.whitelist`",
                  "Whitelist functions",
                  "granted",
                  "granted"
                ],
                [
                  "`players.dev`",
                  "`lsmp.setPlayerDev`",
                  "granted",
                  "granted"
                ],
                [
                  "`players.identity`",
                  "IP address and hardware id (`getPlayerIdentifier(s)`, `playerPreConnection`)",
                  "granted",
                  "granted"
                ],
                [
                  "`dimensions.manage`",
                  "`setPlayerDimension`, `setEntityDimension`, `setDimensionPopulation`, `setDimensionLockdown`",
                  "granted",
                  "granted"
                ],
                [
                  "`voice.manage`",
                  "Writes of `lsmp.voice` (channels, members, muting)",
                  "granted",
                  "granted"
                ],
                [
                  "`benefits.consume`",
                  "`lsmp.benefits.consume`, `consumeRevocation`",
                  "granted",
                  "granted"
                ],
                [
                  "`benefits.read`",
                  "`lsmp.benefits.fetch`, events `benefitGrant` and `benefitRevoke`",
                  "granted",
                  "**refused**"
                ],
                [
                  "`world.weather`",
                  "`lsmp.weather.set`, `resumeCycle`, `setSeed`",
                  "granted",
                  "**refused**"
                ],
                [
                  "`entities.foreign`",
                  "Acting on entities, pickups and synchronized scenes created by another resource or by a client",
                  "granted",
                  "**refused**"
                ]
              ]
            },
            {
              "type": "text",
              "md": "A refused capability is never an error: the function fails with the code `permission` (`false`/`nil` with the code in Lua, `false`/`null` and `lsmp.getLastError()` in JavaScript, a rejected Promise for asynchronous functions). Events reserved to a capability are simply not delivered. The server log shows one warning per resource and capability at most once a minute, with the capability name; the admin panel counts the refusals."
            },
            {
              "type": "callout",
              "variant": "tip",
              "md": "Test the result of capability-protected calls and tell the operator what is missing, rather than assuming success. A mod that needs `world.weather` can log once \"grant world.weather to enable weather control\" and keep working without it.",
              "title": "Write resources that degrade well"
            },
            {
              "type": "heading",
              "text": "Sandbox",
              "level": 2,
              "id": "sandbox"
            },
            {
              "type": "text",
              "md": "Server resources run in a sandbox by default (`Sandbox` in [server.cfg](#server-cfg)). The operator trusts one resource with `\"sandbox\": false` in [`resources.json`](#operator-settings); an unsandboxed resource has full access to the machine, and the server log says so when it starts."
            },
            {
              "type": "table",
              "headers": [
                "Area",
                "Sandboxed resource"
              ],
              "rows": [
                [
                  "Files",
                  "Its [data folder](#server-files/fn-get-data-path) (read and write) and its own package (`lsmp.readResourceFile`). Other folders only when listed in `SandboxFsRead` / `SandboxFsWrite`. Elsewhere: `permission`."
                ],
                [
                  "Outgoing network",
                  "As allowed by `SandboxNetConnect` (default: everything). Refused: `permission`."
                ],
                [
                  "Listening sockets",
                  "Only what `SandboxNetListen` allows (default: nothing). Use [`lsmp.http.serve`](#server-http-serve) instead."
                ],
                [
                  "Databases",
                  "`lsmp.mysql.createPool` fails with `permission`."
                ],
                [
                  "Environment variables",
                  "Only those listed in `SandboxEnv` (default `NODE_ENV`, `TZ`, `LANG`, `LC_ALL`)."
                ],
                [
                  "Processes and native code",
                  "Refused: no child processes, no native modules, no access to the server process."
                ],
                [
                  "Lua standard library",
                  "Functions that reach outside (`io`, `os.execute`, `load`, `debug`...) raise an error that names the `lsmp` alternative."
                ],
                [
                  "Blocking code",
                  "Lua or JavaScript code that runs longer than `SandboxWatchdogSec` (default 10 s) without suspending is interrupted."
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "md": "Unsandboxing a resource gives it the machine, not extra capabilities, and granting a capability does not open the sandbox.",
              "title": "Capabilities and the sandbox are separate"
            },
            {
              "type": "function",
              "name": "lsmp.isSandboxed",
              "id": "fn-is-sandboxed",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.isSandboxed() --> boolean",
                "js": "lsmp.isSandboxed(): boolean"
              },
              "summary": "Whether the calling resource runs in the sandbox.",
              "returns": {
                "type": "boolean"
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "if lsmp.isSandboxed() then\n  lsmp.warn(\"MySQL disabled: set \\\"sandbox\\\": false for this resource in resources.json\")\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "if (lsmp.isSandboxed()) {\n  lsmp.warn('MySQL disabled: set \"sandbox\": false for this resource in resources.json');\n}"
                  }
                ]
              }
            }
          ]
        },
        {
          "id": "sync-scenes",
          "title": "Synchronized scenes",
          "eyebrow": "Server · Lua & JS",
          "lead": "Animations played together by several entities, the same on every client.",
          "blocks": [
            {
              "type": "text",
              "md": "A **synchronized scene** plays animations on several entities at once, aligned to one origin, and every client sees the same thing: two peds shaking hands, a ped sitting on a bench, a character getting into a car with a door animation. The server starts it; every client of the dimension plays it, including players who stream the entities in later."
            },
            {
              "type": "list",
              "items": [
                "Participants are networked entities (peds, objects, vehicles), **1 to 8** per scene, in the same dimension and within 50 m of each other.",
                "A resource stops its own scenes; acting on a scene of another resource, or using entities created by another resource as participants, needs the `entities.foreign` [capability](#capabilities). Players' peds can always take part.",
                "Scenes of a resource stop when it stops. A scene also stops when a participant disappears.",
                "Clients receive [`syncSceneStart`](#engine-events/ev-sync-scene-start) and [`syncSceneStop`](#engine-events/ev-sync-scene-stop) for each participant."
              ]
            },
            {
              "type": "heading",
              "text": "Scene definition",
              "level": 2,
              "id": "definition"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`position`",
                  "vec3",
                  "required",
                  "Origin of the scene."
                ],
                [
                  "`rotation`",
                  "rotation",
                  "`{0, 0, 0}`",
                  "Rotation of the origin, in degrees."
                ],
                [
                  "`rotationOrder`",
                  "integer",
                  "`2`",
                  "Euler order of `rotation`, `0..5` (the game's usual order is 2)."
                ],
                [
                  "`phase`",
                  "number",
                  "`0`",
                  "Starting point, `0..1` of the animation."
                ],
                [
                  "`rate`",
                  "number",
                  "`1`",
                  "Playback speed."
                ],
                [
                  "`holdLastFrame`",
                  "boolean",
                  "`false`",
                  "Stay on the last frame at the end."
                ],
                [
                  "`looped`",
                  "boolean",
                  "`false`",
                  "Loop."
                ],
                [
                  "`durationMs`",
                  "ms",
                  "`0`",
                  "Stop the scene after this time; `0` = no limit."
                ],
                [
                  "`participants`",
                  "list",
                  "required",
                  "1 to 8 participants (below)."
                ]
              ]
            },
            {
              "type": "table",
              "headers": [
                "Participant field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`netId`",
                  "netId",
                  "required",
                  "The entity."
                ],
                [
                  "`dict`",
                  "string",
                  "required",
                  "Animation dictionary (1 to 63 bytes)."
                ],
                [
                  "`clip`",
                  "string",
                  "required",
                  "Animation name (1 to 63 bytes)."
                ],
                [
                  "`blendIn`",
                  "number",
                  "`8`",
                  "Blend-in speed."
                ],
                [
                  "`blendOut`",
                  "number",
                  "`-8`",
                  "Blend-out speed."
                ],
                [
                  "`flags`",
                  "integer",
                  "`0`",
                  "Game scene flags."
                ],
                [
                  "`ikFlags`",
                  "integer",
                  "`0`",
                  "Game IK flags."
                ],
                [
                  "`offset`",
                  "table",
                  "—",
                  "`{ x, y, z, heading }` offset of this participant from the origin."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Functions",
              "level": 2,
              "id": "functions"
            },
            {
              "type": "function",
              "name": "lsmp.startSyncScene",
              "id": "fn-start-sync-scene",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.startSyncScene(def) --> integer?",
                "js": "lsmp.startSyncScene(def: SyncSceneDef): number | null"
              },
              "summary": "Starts a synchronized scene played by every client.",
              "md": "A malformed definition (missing field, wrong type, more than 8 participants) raises.",
              "params": [
                {
                  "name": "def",
                  "type": "SyncSceneDef",
                  "desc": "The scene definition (tables above)."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The scene id, or `nil`/`null` with `not-found` (a participant does not exist), `invalid` (participants in different dimensions or too far apart), `limit` (too many scenes) or `permission`.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The scene id, or `nil`/`null` with `not-found` (a participant does not exist), `invalid` (participants in different dimensions or too far apart), `limit` (too many scenes) or `permission`.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local scene = lsmp.startSyncScene({\n  position = { x = -1037.0, y = -2737.0, z = 20.17 },\n  rotation = { x = 0, y = 0, z = 150 },\n  participants = {\n    { netId = pedA, dict = \"mp_common\", clip = \"givetake1_a\" },\n    { netId = pedB, dict = \"mp_common\", clip = \"givetake1_b\" },\n  },\n})\nif not scene then lsmp.warn(\"scene refused: \" .. lsmp.getLastError()) end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const scene = lsmp.startSyncScene({\n  position: { x: -1037, y: -2737, z: 20.17 },\n  rotation: { x: 0, y: 0, z: 150 },\n  participants: [\n    { netId: pedA, dict: \"mp_common\", clip: \"givetake1_a\" },\n    { netId: pedB, dict: \"mp_common\", clip: \"givetake1_b\" },\n  ],\n});\nif (scene === null) lsmp.warn(`scene refused: ${lsmp.getLastError()}`);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.stopSyncScene",
              "id": "fn-stop-sync-scene",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.stopSyncScene(sceneId) --> boolean",
                "js": "lsmp.stopSyncScene(sceneId: number): boolean"
              },
              "summary": "Stops a scene.",
              "params": [
                {
                  "name": "sceneId",
                  "type": "integer",
                  "desc": "The scene, as returned by `startSyncScene`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `not-found` or `permission` (scene of another resource)."
              }
            },
            {
              "type": "function",
              "name": "lsmp.setSyncScenePhase",
              "id": "fn-set-sync-scene-phase",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setSyncScenePhase(sceneId, phase [, rate]) --> boolean",
                "js": "lsmp.setSyncScenePhase(sceneId: number, phase: number, rate?: number): boolean"
              },
              "summary": "Moves a running scene to another point, and optionally changes its speed.",
              "params": [
                {
                  "name": "sceneId",
                  "type": "integer",
                  "desc": "The scene, as returned by `startSyncScene`."
                },
                {
                  "name": "phase",
                  "type": "number",
                  "desc": "`0..1`."
                },
                {
                  "name": "rate",
                  "type": "number",
                  "optional": true,
                  "desc": "New speed (`>= 0`); unchanged when absent."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` with `not-found` or `permission`."
              }
            },
            {
              "type": "function",
              "name": "lsmp.isSyncSceneActive",
              "id": "fn-is-sync-scene-active",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.isSyncSceneActive(sceneId) --> boolean",
                "js": "lsmp.isSyncSceneActive(sceneId: number): boolean"
              },
              "summary": "Whether a scene is running.",
              "params": [
                {
                  "name": "sceneId",
                  "type": "integer",
                  "desc": "The scene, as returned by `startSyncScene`."
                }
              ],
              "returns": {
                "type": "boolean"
              }
            },
            {
              "type": "function",
              "name": "lsmp.getEntitySyncScene",
              "id": "fn-get-entity-sync-scene",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getEntitySyncScene(netId) --> SyncSceneInfo?",
                "js": "lsmp.getEntitySyncScene(netId: number): SyncSceneInfo | null"
              },
              "summary": "The synchronized scene an entity is playing.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": [
                {
                  "type": "SyncSceneInfo?",
                  "desc": "`{ sceneId, dict, clip }`, or `nil`/`null` if it plays none.",
                  "only": "lua"
                },
                {
                  "type": "SyncSceneInfo | null",
                  "desc": "`{ sceneId, dict, clip }`, or `nil`/`null` if it plays none.",
                  "only": "js"
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "id": "api-client",
      "title": "Client API",
      "icon": "🎮",
      "pages": [
        {
          "id": "local-player",
          "title": "Local player, spawn and death",
          "eyebrow": "Client · Lua & JS",
          "lead": "Who the local player is, when and where they appear, what happens when they die, and how to leave the server.",
          "blocks": [
            {
              "type": "text",
              "md": "When a player joins, their ped exists but stays hidden behind the LS:MP loading screen: frozen, invisible, without collision. **LS:MP never places the player by itself**, and never respawns them after a death. A client script decides both: that is what makes character selection, spawn menus, death screens and timers possible."
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Resources start",
                  "md": "Every client resource of the server runs its top-level code."
                },
                {
                  "title": "Auto spawn",
                  "md": "Once they all ran, the **auto-spawn handler** is called, once: the resource that set it with [`setAutoSpawnHandler`](#local-player/fn-set-auto-spawn-handler) picks a place and calls [`lsmp.spawn`](#local-player/fn-spawn). A gamemode that spawns players itself turns this off with [`setAutoSpawn(false)`](#local-player/fn-set-auto-spawn)."
                },
                {
                  "title": "Spawn",
                  "md": "`lsmp.spawn` loads the world around the point, places the ped, closes the loading screen, and fires [`playerSpawn`](#engine-events) on this client and on the server."
                }
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "A server needs a spawn resource",
              "md": "If nothing spawns the player, the loading screen stays. After 30 s a warning is logged; after 60 s the client leaves the server cleanly instead of hanging. A gamemode that needs more time (a character creator) calls [`closeLoadingScreen`](#local-player/fn-close-loading-screen) to show its own interface: the timer then stops. The bundled `spawn-mgr` resource is a complete spawn manager ([examples](#examples))."
            },
            {
              "type": "heading",
              "text": "Identity",
              "level": 2,
              "id": "local-identity"
            },
            {
              "type": "function",
              "name": "lsmp.getLocalPlayer",
              "id": "fn-get-local-player",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getLocalPlayer() --> integer?",
                "js": "lsmp.getLocalPlayer(): number | null"
              },
              "summary": "The playerId of the local player.",
              "md": "The same number the server uses for this player. It is not the game's `playerId()` native, which is a local slot. [`playerJoin`](#engine-events) is not fired for the local player: read this at start instead.",
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The playerId, or `nil`/`null` outside a session.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The playerId, or `nil`/`null` outside a session.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.getGameScreen",
              "id": "fn-get-game-screen",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getGameScreen() --> ScreenSize?",
                "js": "lsmp.getGameScreen(): ScreenSize | null"
              },
              "summary": "The size of the game image, in pixels.",
              "md": "To convert pixel positions into the normalized `0..1` coordinates used by [`worldToScreen`](#world/fn-world-to-screen) and the drawing natives.",
              "returns": [
                {
                  "type": "ScreenSize?",
                  "desc": "`{ width, height }`, or `nil`/`null` before the game window exists.",
                  "only": "lua"
                },
                {
                  "type": "ScreenSize | null",
                  "desc": "`{ width, height }`, or `nil`/`null` before the game window exists.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Spawning",
              "level": 2,
              "id": "local-spawn"
            },
            {
              "type": "function",
              "name": "lsmp.spawn",
              "id": "fn-spawn",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.spawn(position [, opts]) --> boolean",
                "js": "lsmp.spawn(position: Vec3Like, opts?: SpawnOptions): boolean"
              },
              "summary": "Make the local player appear at a position.",
              "md": "The world around the point is loaded first, then the ped is placed with its feet at `position`, made visible and given back its controls; the loading screen closes on the first spawn. [`playerSpawn`](#engine-events) fires when it is done. Also works later, to move a living player with a full reload of the area.",
              "params": [
                {
                  "name": "position",
                  "type": "vec3",
                  "desc": "Where the feet go."
                },
                {
                  "name": "opts",
                  "type": "SpawnOptions",
                  "desc": "`{ heading, model }`: heading in degrees (default `0`), ped model as a hash or name (default: the current model).",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the spawn was started."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`disconnected`",
                      "Not in a session."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local POINTS = {\n  { x = 195.0, y = -933.7, z = 30.7, h = 145.0 },\n  { x = -1037.6, y = -2737.6, z = 20.2, h = 330.0 },\n}\n\nlsmp.setAutoSpawnHandler(function()\n  local p = POINTS[math.random(#POINTS)]\n  lsmp.spawn({ x = p.x, y = p.y, z = p.z }, { heading = p.h, model = \"mp_m_freemode_01\" })\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const POINTS = [\n  { x: 195.0, y: -933.7, z: 30.7, h: 145.0 },\n  { x: -1037.6, y: -2737.6, z: 20.2, h: 330.0 },\n];\n\nlsmp.setAutoSpawnHandler(() => {\n  const p = POINTS[Math.floor(Math.random() * POINTS.length)];\n  lsmp.spawn({ x: p.x, y: p.y, z: p.z }, { heading: p.h, model: 'mp_m_freemode_01' });\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.setAutoSpawnHandler",
              "id": "fn-set-auto-spawn-handler",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setAutoSpawnHandler(fn)",
                "js": "lsmp.setAutoSpawnHandler(fn: Function | null): void"
              },
              "summary": "Set the function that spawns the player when they join.",
              "md": "Called once per session, after every client resource ran its top-level code, if auto spawn is still on and nothing spawned the player yet. When several resources set one, the last call wins; it is removed when its resource stops.",
              "params": [
                {
                  "name": "fn",
                  "type": "fn?",
                  "desc": "The handler, or `nil`/`null` to remove this resource's."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.setAutoSpawn",
              "id": "fn-set-auto-spawn",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.setAutoSpawn(enabled)",
                "js": "lsmp.setAutoSpawn(enabled: boolean): void"
              },
              "summary": "Turn the auto spawn on or off.",
              "md": "A gamemode with its own arrival (character selection, a lobby) calls `lsmp.setAutoSpawn(false)` at the top of its client script, then calls `lsmp.spawn` when it is ready. The setting belongs to the resource: the last writer wins, and it is restored when that resource stops.",
              "params": [
                {
                  "name": "enabled",
                  "type": "boolean",
                  "desc": "`false` to keep the player hidden until a script spawns them."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.closeLoadingScreen",
              "id": "fn-close-loading-screen",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.closeLoadingScreen()",
                "js": "lsmp.closeLoadingScreen(): void"
              },
              "summary": "Lift the loading screen without spawning the player.",
              "md": "For an arrival that shows its own interface first (character creator, rules to accept). The ped stays hidden until `lsmp.spawn`."
            },
            {
              "type": "heading",
              "text": "Death and respawn",
              "level": 2,
              "id": "local-death"
            },
            {
              "type": "text",
              "md": "[`playerDeath`](#engine-events) `(playerId, killerId, weaponHash, position, flags, killerEntity)` fires on every client for every player who dies. Compare `playerId` with `lsmp.getLocalPlayer()` to react to your own death. The dead player stays down until a script resurrects them."
            },
            {
              "type": "function",
              "name": "lsmp.resurrect",
              "id": "fn-resurrect",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resurrect(position [, opts]) --> boolean",
                "js": "lsmp.resurrect(position: Vec3Like, opts?: ResurrectOptions): boolean"
              },
              "summary": "Bring the dead local player back to life at a position.",
              "md": "The ped is revived in place and moved, keeping its netId: nothing is streamed again for the other players. Call it whenever you like: after a timer, a death screen, a key press.",
              "params": [
                {
                  "name": "position",
                  "type": "vec3",
                  "desc": "Where the feet go."
                },
                {
                  "name": "opts",
                  "type": "ResurrectOptions",
                  "desc": "`{ heading }` in degrees (default `0`).",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the player was resurrected."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`disconnected`",
                      "Not in a session."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local RESPAWN_DELAY_MS = 5000\n\nlsmp.on(\"playerDeath\", function(playerId, killerId, weaponHash, position)\n  if playerId ~= lsmp.getLocalPlayer() then return end\n  lsmp.wait(RESPAWN_DELAY_MS)\n  lsmp.resurrect({ x = position.x, y = position.y, z = position.z + 0.5 }, { heading = 0 })\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const RESPAWN_DELAY_MS = 5000;\n\nlsmp.on('playerDeath', async (playerId, killerId, weaponHash, position) => {\n  if (playerId !== lsmp.getLocalPlayer()) return;\n  await lsmp.wait(RESPAWN_DELAY_MS);\n  lsmp.resurrect({ x: position.x, y: position.y, z: position.z + 0.5 }, { heading: 0 });\n});"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Leaving",
              "level": 2,
              "id": "local-leave"
            },
            {
              "type": "function",
              "name": "lsmp.disconnect",
              "id": "fn-disconnect",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.disconnect([reason]) --> boolean",
                "js": "lsmp.disconnect(reason?: string): boolean"
              },
              "summary": "Leave the server.",
              "md": "The server sees [`playerLeave`](#engine-events) with the reason `\"quit\"` and your text as `detail`.",
              "params": [
                {
                  "name": "reason",
                  "type": "string",
                  "desc": "Why, 127 bytes at most.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the client was in a session."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`disconnected`",
                      "Not in a session."
                    ]
                  ]
                }
              ]
            }
          ]
        },
        {
          "id": "client-entities",
          "title": "Entities and streaming",
          "eyebrow": "Client · Lua & JS",
          "lead": "Networked entities on the client: netIds against game handles, what is streamed in, and who simulates what.",
          "blocks": [
            {
              "type": "text",
              "md": "A networked entity (a vehicle, a ped, an object the server knows) has two names:"
            },
            {
              "type": "table",
              "headers": [
                "Name",
                "What it is",
                "Used by"
              ],
              "rows": [
                [
                  "**netId**",
                  "The same number on the server and every client, for the entity's whole life.",
                  "`lsmp` functions, events, network messages, [meta](#meta)."
                ],
                [
                  "**Handle**",
                  "The game's own number for the entity on this client. It exists only while the entity is built here.",
                  "Game [natives](#natives), [outlines](#outline-selection)."
                ]
              ]
            },
            {
              "type": "text",
              "md": "A client builds only the entities **near its player** (streaming). An entity far away is known by its netId but has no handle here. Never store handles: store netIds and convert when you need a native."
            },
            {
              "type": "heading",
              "text": "Converting",
              "level": 2,
              "id": "entities-convert"
            },
            {
              "type": "function",
              "name": "lsmp.getEntityFromNetId",
              "id": "fn-get-entity-from-net-id",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getEntityFromNetId(netId) --> integer?",
                "js": "lsmp.getEntityFromNetId(netId: number): number | null"
              },
              "summary": "The game handle of a networked entity.",
              "md": "Right after the server creates an entity, its netId is known at once but the game builds it over the next frames: retry for a moment before giving up.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The handle, or `nil`/`null` while the entity is not built on this client.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The handle, or `nil`/`null` while the entity is not built on this client.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "The entity is not built on this client."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local function waitForEntity(netId, timeoutMs)\n  local deadline = lsmp.getTickCount() + timeoutMs\n  while lsmp.getTickCount() < deadline do\n    local handle = lsmp.getEntityFromNetId(netId)\n    if handle then return handle end\n    lsmp.wait(100)\n  end\n  return nil\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "async function waitForEntity(netId, timeoutMs) {\n  const deadline = lsmp.getTickCount() + timeoutMs;\n  while (lsmp.getTickCount() < deadline) {\n    const handle = lsmp.getEntityFromNetId(netId);\n    if (handle !== null) return handle;\n    await lsmp.wait(100);\n  }\n  return null;\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.getNetIdFromEntity",
              "id": "fn-get-net-id-from-entity",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getNetIdFromEntity(entity) --> integer?",
                "js": "lsmp.getNetIdFromEntity(entity: number): number | null"
              },
              "summary": "The netId of a game handle.",
              "params": [
                {
                  "name": "entity",
                  "type": "handle",
                  "desc": "A game handle."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The netId, or `nil`/`null` for an entity LS:MP does not network (a local prop, ambient traffic of this client only).",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The netId, or `nil`/`null` for an entity LS:MP does not network (a local prop, ambient traffic of this client only).",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "The entity is not networked."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "Simulation (ownership)",
              "level": 2,
              "id": "entities-ownership"
            },
            {
              "type": "text",
              "md": "Each networked entity is **simulated** by one client, its owner: that client runs its physics and AI, and the others follow. Ownership moves on its own as players come and go. [`lsmp.getEntityOwner`](#spatial) tells who it is; the [server](#server-ownership) can pin it."
            },
            {
              "type": "function",
              "name": "lsmp.requestEntityOwnership",
              "id": "fn-request-entity-ownership",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.requestEntityOwnership(netId) --> boolean",
                "js": "lsmp.requestEntityOwnership(netId: number): boolean"
              },
              "summary": "Ask to simulate an entity.",
              "md": "Useful before driving or moving something another player simulates. The server decides: when it accepts, [`entityAdopt`](#engine-events) fires on this client. An entity pinned by the server is not handed over.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the request was sent."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "Unknown entity."
                    ],
                    [
                      "`disconnected`",
                      "Not in a session."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "Events",
              "level": 2,
              "id": "entities-events"
            },
            {
              "type": "table",
              "headers": [
                "Event",
                "Arguments",
                "When"
              ],
              "rows": [
                [
                  "[`entityStreamIn`](#engine-events)",
                  "`(netId, entity)`",
                  "An entity was built on this client; the handle is valid in the handler. Other players' peds come through here; your own never does."
                ],
                [
                  "[`entityStreamOut`](#engine-events)",
                  "`(netId)`",
                  "The entity was removed from this client; its handle is no longer valid."
                ],
                [
                  "[`entityAdopt`](#engine-events)",
                  "`(netId)`",
                  "This client started simulating the entity."
                ],
                [
                  "[`entityRelease`](#engine-events)",
                  "`(netId)`",
                  "This client stopped simulating it."
                ]
              ]
            },
            {
              "type": "text",
              "md": "Events are not replayed: entities already in range when a script starts are found with [`lsmp.getEntitiesInRadius`](#spatial) or [`lsmp.getGamePool`](#world/fn-get-game-pool)."
            }
          ]
        },
        {
          "id": "world",
          "title": "World helpers (raycast, ground, screen, pools)",
          "eyebrow": "Client · Lua & JS",
          "lead": "Ready-made answers to common questions about the game world: what a line hits, where the ground is, where a point appears on screen, what exists around you.",
          "blocks": [
            {
              "type": "text",
              "md": "Each of these wraps one or two game natives with a single call, vectors in and out, and no output parameters. They answer for **this client's** game: only what is loaded around the local player exists here."
            },
            {
              "type": "function",
              "name": "lsmp.raycast",
              "id": "fn-raycast",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.raycast(from, to [, opts]) --> RaycastResult",
                "js": "lsmp.raycast(from: Vec3Like, to: Vec3Like, opts?: RaycastOptions): RaycastResult"
              },
              "summary": "What a straight line from `from` to `to` hits first.",
              "md": "It tests collision, not pixels: glass, fences and objects without collision can be crossed. To know what is **drawn** at a point of the screen, use the [picker](#outline-selection).",
              "params": [
                {
                  "name": "from",
                  "type": "vec3",
                  "desc": "Start of the line."
                },
                {
                  "name": "to",
                  "type": "vec3",
                  "desc": "End of the line."
                },
                {
                  "name": "opts",
                  "type": "RaycastOptions",
                  "desc": "See [`RaycastOptions`](#world/raycast-options).",
                  "optional": true
                }
              ],
              "returns": {
                "type": "RaycastResult",
                "desc": "A [`RaycastResult`](#world/raycast-result)."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- What is the player looking at, up to 50 m?\nlocal cam = getGameplayCamCoord()\nlocal rot = getGameplayCamRot(2)\nlocal pitch, yaw = math.rad(rot.x), math.rad(rot.z)\nlocal dir = { x = -math.sin(yaw) * math.cos(pitch), y = math.cos(yaw) * math.cos(pitch), z = math.sin(pitch) }\nlocal hit = lsmp.raycast(cam, { x = cam.x + dir.x * 50, y = cam.y + dir.y * 50, z = cam.z + dir.z * 50 },\n  { ignore = playerPedId() })\nif hit.hit and hit.entity then\n  lsmp.log(\"looking at entity \" .. hit.entity)\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// What is the player looking at, up to 50 m?\nconst cam = getGameplayCamCoord();\nconst rot = getGameplayCamRot(2);\nconst pitch = rot.x * Math.PI / 180, yaw = rot.z * Math.PI / 180;\nconst dir = { x: -Math.sin(yaw) * Math.cos(pitch), y: Math.cos(yaw) * Math.cos(pitch), z: Math.sin(pitch) };\nconst hit = lsmp.raycast(cam, { x: cam.x + dir.x * 50, y: cam.y + dir.y * 50, z: cam.z + dir.z * 50 },\n  { ignore: playerPedId() });\nif (hit.hit && hit.entity !== null) lsmp.log(`looking at entity ${hit.entity}`);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.getGroundZ",
              "id": "fn-get-ground-z",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getGroundZ(position [, opts]) --> number?",
                "js": "lsmp.getGroundZ(position: Vec3Like, opts?: GroundOptions): number | null"
              },
              "summary": "The height of the ground below a point.",
              "md": "The game looks down from `position`. Far from the player the map's collision is not loaded and there is no answer: bring the player (or the camera) closer first, or request the collision with the natives and retry.",
              "params": [
                {
                  "name": "position",
                  "type": "vec3",
                  "desc": "The point to look down from."
                },
                {
                  "name": "opts",
                  "type": "GroundOptions",
                  "desc": "`{ water }`: `true` counts the water surface as ground (default `false`).",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "number?",
                  "desc": "The height, or `nil`/`null` when no ground was found.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The height, or `nil`/`null` when no ground was found.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local p = getEntityCoords(playerPedId(), true)\nlocal ground = lsmp.getGroundZ({ x = p.x + 10, y = p.y, z = p.z + 50 })\nif ground then lsmp.log((\"ground at %.2f\"):format(ground)) end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const p = getEntityCoords(playerPedId(), true);\nconst ground = lsmp.getGroundZ({ x: p.x + 10, y: p.y, z: p.z + 50 });\nif (ground !== null) lsmp.log(`ground at ${ground.toFixed(2)}`);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.worldToScreen",
              "id": "fn-world-to-screen",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.worldToScreen(position) --> ScreenPoint",
                "js": "lsmp.worldToScreen(position: Vec3Like): ScreenPoint"
              },
              "summary": "Where a world position appears on the screen.",
              "md": "`x` and `y` are normalized: `0,0` is the top-left corner, `1,1` the bottom-right. They match the drawing natives (`drawRect`, text) directly; multiply by [`getGameScreen`](#local-player/fn-get-game-screen) for pixels. Call it every frame, from [`lsmp.onTick`](#core-utils), to follow a moving point.",
              "params": [
                {
                  "name": "position",
                  "type": "vec3",
                  "desc": "The world position."
                }
              ],
              "returns": {
                "type": "ScreenPoint",
                "desc": "`{ x, y, onScreen }`; `onScreen` is `false` behind the camera or outside the screen."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.onTick(function()\n  local p = getEntityCoords(playerPedId(), true)\n  local s = lsmp.worldToScreen({ x = p.x, y = p.y, z = p.z + 1.2 })\n  if s.onScreen then drawRect(s.x, s.y, 0.01, 0.015, 255, 200, 0, 200, false) end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.onTick(() => {\n  const p = getEntityCoords(playerPedId(), true);\n  const s = lsmp.worldToScreen({ x: p.x, y: p.y, z: p.z + 1.2 });\n  if (s.onScreen) drawRect(s.x, s.y, 0.01, 0.015, 255, 200, 0, 200, false);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.getGamePool",
              "id": "fn-get-game-pool",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getGamePool([opts]) --> {integer}",
                "js": "lsmp.getGamePool(opts?: QueryOptions): Uint32Array"
              },
              "summary": "The game handles of the networked entities that exist on this client.",
              "md": "Networked entities only: those of the session that have a game instance here. Entities your script creates with natives for this client alone are not listed; keep their handles. To find entities around a point by netId, see [`getEntitiesInRadius`](#spatial).",
              "params": [
                {
                  "name": "opts",
                  "type": "QueryOptions",
                  "desc": "`{ types }`: entity types to include, among `\"vehicle\"`, `\"ped\"`, `\"object\"` and `\"playerPed\"` ([`lsmp.EntityType`](#server-entities)); by default every type except player peds.",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "{integer}",
                  "desc": "The handles (JS: `Uint32Array`).",
                  "only": "lua"
                },
                {
                  "type": "Uint32Array",
                  "desc": "The handles (JS: `Uint32Array`).",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local vehicles = lsmp.getGamePool({ types = { \"vehicle\" } })\nlsmp.log(#vehicles .. \" vehicles on this client\")"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const vehicles = lsmp.getGamePool({ types: [lsmp.EntityType.Vehicle] });\nlsmp.log(`${vehicles.length} vehicles on this client`);"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Shapes",
              "level": 2,
              "id": "world-shapes"
            },
            {
              "type": "heading",
              "text": "RaycastOptions",
              "level": 3,
              "id": "raycast-options"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`flags`",
                  "int",
                  "`-1` (everything)",
                  "What the line can hit, as the game's shape test flags: `1` map, `2` vehicles, `4` peds (`8` ped capsules), `16` objects, `256` vegetation."
                ],
                [
                  "`ignore`",
                  "handle",
                  "—",
                  "An entity the line goes through, usually the player's ped or vehicle."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "RaycastResult",
              "level": 3,
              "id": "raycast-result"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`hit`",
                  "boolean",
                  "—",
                  "`true` if the line hit something."
                ],
                [
                  "`position`",
                  "vec3?",
                  "—",
                  "Where."
                ],
                [
                  "`normal`",
                  "vec3?",
                  "—",
                  "The surface direction at that point."
                ],
                [
                  "`entity`",
                  "handle?",
                  "—",
                  "The entity hit; absent for the map."
                ]
              ]
            }
          ]
        },
        {
          "id": "hud",
          "title": "HUD, blips and money",
          "eyebrow": "Client · Lua & JS",
          "lead": "The money shown in the game HUD, and the parts of the HUD LS:MP lets scripts adjust. Blips use the game's natives.",
          "blocks": [
            {
              "type": "heading",
              "text": "Money",
              "level": 2,
              "id": "hud-money"
            },
            {
              "type": "text",
              "md": "The game shows a wallet and a bank amount in the top-right corner. LS:MP lets a script set them, so the HUD matches your server's own economy. The amounts are display only: your money lives in your scripts and your database, on the server."
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "One resource at a time",
              "md": "The displayed money is a setting owned by the resource that set it: the last writer wins, and the game's values come back when that resource stops."
            },
            {
              "type": "function",
              "name": "lsmp.hud.setMoney",
              "id": "fn-hud-set-money",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.hud.setMoney(wallet, bank) --> boolean",
                "js": "lsmp.hud.setMoney(wallet: number, bank: number): boolean"
              },
              "summary": "Show these amounts in the HUD.",
              "params": [
                {
                  "name": "wallet",
                  "type": "int",
                  "desc": "Cash, `0` to `2147483647`."
                },
                {
                  "name": "bank",
                  "type": "int",
                  "desc": "Bank, `0` to `2147483647`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the amounts are shown."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`unavailable`",
                      "The HUD cannot be changed at this moment (no session)."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.onServer(\"economy:balance\", function(wallet, bank)\n  lsmp.hud.setMoney(wallet, bank)\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.onServer('economy:balance', (wallet, bank) => {\n  lsmp.hud.setMoney(wallet, bank);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.hud.resetMoney",
              "id": "fn-hud-reset-money",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.hud.resetMoney() --> boolean",
                "js": "lsmp.hud.resetMoney(): boolean"
              },
              "summary": "Give the money display back to the game.",
              "returns": {
                "type": "boolean",
                "desc": "`true` if this resource had set the money."
              }
            },
            {
              "type": "function",
              "name": "lsmp.hud.getMoney",
              "id": "fn-hud-get-money",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.hud.getMoney() --> HudMoney?",
                "js": "lsmp.hud.getMoney(): HudMoney | null"
              },
              "summary": "The amounts the HUD shows.",
              "returns": [
                {
                  "type": "HudMoney?",
                  "desc": "`{ wallet, bank }`, or `nil`/`null` when no script sets them.",
                  "only": "lua"
                },
                {
                  "type": "HudMoney | null",
                  "desc": "`{ wallet, bank }`, or `nil`/`null` when no script sets them.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Replay recording",
              "level": 2,
              "id": "hud-replay"
            },
            {
              "type": "function",
              "name": "lsmp.hud.hideReplayRecordingThisFrame",
              "id": "fn-hud-hide-replay-recording-this-frame",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.hud.hideReplayRecordingThisFrame()",
                "js": "lsmp.hud.hideReplayRecordingThisFrame(): void"
              },
              "summary": "Hide the replay recording indicator for this frame.",
              "md": "Call it every frame, from [`lsmp.onTick`](#core-utils), while your own interface covers that corner of the screen."
            },
            {
              "type": "heading",
              "text": "Blips",
              "level": 2,
              "id": "hud-blips"
            },
            {
              "type": "text",
              "md": "LS:MP draws no player blips by itself. Use the game's blip natives (`addBlipForEntity`, `addBlipForCoord`, `setBlipSprite`...) from a client script. Blips attached to an entity go away with it when it is streamed out. The bundled `player-blips` resource puts a blip on every player near you ([examples](#examples))."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "lsmp.on(\"entityStreamIn\", function(netId, entity)\n  if not isEntityAPed(entity) or not isPedAPlayer(entity) then return end\n  local blip = addBlipForEntity(entity)\n  setBlipSprite(blip, 1)\n  setBlipColour(blip, 0)\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "lsmp.on('entityStreamIn', (netId, entity) => {\n  if (!isEntityAPed(entity) || !isPedAPlayer(entity)) return;\n  const blip = addBlipForEntity(entity);\n  setBlipSprite(blip, 1);\n  setBlipColour(blip, 0);\n});"
                }
              ]
            }
          ]
        },
        {
          "id": "nametags",
          "title": "Nametags",
          "eyebrow": "Client · Lua & JS",
          "lead": "The names LS:MP draws above other players: how visible, how far, how large.",
          "blocks": [
            {
              "type": "text",
              "md": "LS:MP draws the name of each nearby player above their head. A client script can change how they look, for every player or for one, without drawing anything itself."
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Owned settings",
              "md": "A style belongs to the resource that set it: the last writer wins, and the previous style comes back when that resource stops. `nil`/`null` removes this resource's style."
            },
            {
              "type": "function",
              "name": "lsmp.nametags.setStyle",
              "id": "fn-nametags-set-style",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.nametags.setStyle(style)",
                "js": "lsmp.nametags.setStyle(style: NametagStyle | null): void"
              },
              "summary": "Set the style of every nametag.",
              "md": "Fields not given keep their default.",
              "params": [
                {
                  "name": "style",
                  "type": "NametagStyle?",
                  "desc": "A [`NametagStyle`](#nametags/nametag-style), or `nil`/`null` to remove this resource's."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- Names only within 15 m, a bit smaller.\nlsmp.nametags.setStyle({ distance = 15, scale = 0.8 })"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// Names only within 15 m, a bit smaller.\nlsmp.nametags.setStyle({ distance: 15, scale: 0.8 });"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.nametags.setPlayerStyle",
              "id": "fn-nametags-set-player-style",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.nametags.setPlayerStyle(playerId, style)",
                "js": "lsmp.nametags.setPlayerStyle(playerId: number, style: NametagStyle | null): void"
              },
              "summary": "Set the style of one player's nametag.",
              "md": "It wins over the general style for that player. For example, always show your teammates, and hide the others.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "style",
                  "type": "NametagStyle?",
                  "desc": "A [`NametagStyle`](#nametags/nametag-style), or `nil`/`null` to remove this resource's."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "for _, id in ipairs(teammates) do\n  lsmp.nametags.setPlayerStyle(id, { visibility = \"always\", beacon = true })\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "for (const id of teammates) {\n  lsmp.nametags.setPlayerStyle(id, { visibility: 'always', beacon: true });\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.nametags.getStyle",
              "id": "fn-nametags-get-style",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.nametags.getStyle() --> NametagStyle",
                "js": "lsmp.nametags.getStyle(): NametagStyle"
              },
              "summary": "The general nametag style in force.",
              "md": "Every field is filled in. A player's own style is read with [`getPlayerStyle`](#nametags/fn-nametags-get-player-style).",
              "returns": {
                "type": "NametagStyle",
                "desc": "A [`NametagStyle`](#nametags/nametag-style)."
              }
            },
            {
              "type": "function",
              "name": "lsmp.nametags.getPlayerStyle",
              "id": "fn-nametags-get-player-style",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.nametags.getPlayerStyle(playerId) --> NametagStyle?",
                "js": "lsmp.nametags.getPlayerStyle(playerId: number): NametagStyle | null"
              },
              "summary": "The style in force for one player's nametag.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ],
              "returns": [
                {
                  "type": "NametagStyle?",
                  "desc": "A [`NametagStyle`](#nametags/nametag-style), or `nil`/`null` for an unknown player.",
                  "only": "lua"
                },
                {
                  "type": "NametagStyle | null",
                  "desc": "A [`NametagStyle`](#nametags/nametag-style), or `nil`/`null` for an unknown player.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "Unknown player."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "NametagStyle",
              "level": 3,
              "id": "nametag-style"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`alpha`",
                  "number",
                  "`1`",
                  "Opacity, `0` to `1`. `0` hides the name."
                ],
                [
                  "`scale`",
                  "number",
                  "`1`",
                  "Size factor, greater than `0`."
                ],
                [
                  "`distance`",
                  "meters",
                  "`256`",
                  "Shown up to this distance from the camera."
                ],
                [
                  "`visibility`",
                  "string",
                  "`\"auto\"`",
                  "`\"auto\"` (shown when the player's ped is visible), `\"always\"` (even when it is not) or `\"never\"`."
                ],
                [
                  "`beacon`",
                  "boolean",
                  "`false`",
                  "Draw a marker above the name."
                ]
              ]
            }
          ]
        },
        {
          "id": "outline-selection",
          "title": "Outlines and picking",
          "eyebrow": "Client · Lua & JS",
          "lead": "Draw a line around an entity or a piece of the map, and find out exactly what is drawn under a point of the screen.",
          "blocks": [
            {
              "type": "heading",
              "text": "Outlines",
              "level": 2,
              "id": "outlines"
            },
            {
              "type": "text",
              "md": "An outline is drawn around an entity, as thick at 200 m as at 2 m, and hidden by walls like the entity itself. It takes a game **handle**, not a netId (see [Entities and streaming](#client-entities)).\n\nOutlines belong to the resource that drew them: a resource cannot change or remove another resource's outline, and its outlines go away when it stops. At most **32** outlines exist at once, shared by every resource: outline what matters, and take down what you put up."
            },
            {
              "type": "function",
              "name": "lsmp.outline.showEntity",
              "id": "fn-outline-show-entity",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.outline.showEntity(entity [, opts]) --> boolean",
                "js": "lsmp.outline.showEntity(entity: number, opts?: OutlineOptions): boolean"
              },
              "summary": "Outline an entity, or change the style of this resource's outline on it.",
              "params": [
                {
                  "name": "entity",
                  "type": "handle",
                  "desc": "A game handle."
                },
                {
                  "name": "opts",
                  "type": "OutlineOptions",
                  "desc": "See [`OutlineOptions`](#outline-selection/outline-options).",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the outline is drawn."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "The handle is not usable, or the 32 outlines are taken."
                    ],
                    [
                      "`permission`",
                      "Another resource outlines this entity."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local vehicle = getVehiclePedIsIn(playerPedId(), false)\nif vehicle ~= 0 then\n  lsmp.outline.showEntity(vehicle, { color = \"#40beff\", width = 3 })\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const vehicle = getVehiclePedIsIn(playerPedId(), false);\nif (vehicle) lsmp.outline.showEntity(vehicle, { color: '#40beff', width: 3 });"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.outline.hideEntity",
              "id": "fn-outline-hide-entity",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.outline.hideEntity(entity) --> boolean",
                "js": "lsmp.outline.hideEntity(entity: number): boolean"
              },
              "summary": "Remove this resource's outline from an entity.",
              "params": [
                {
                  "name": "entity",
                  "type": "handle",
                  "desc": "A game handle."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if this resource outlined it."
              }
            },
            {
              "type": "function",
              "name": "lsmp.outline.hasEntity",
              "id": "fn-outline-has-entity",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.outline.hasEntity(entity) --> boolean",
                "js": "lsmp.outline.hasEntity(entity: number): boolean"
              },
              "summary": "Whether this resource outlines an entity.",
              "params": [
                {
                  "name": "entity",
                  "type": "handle",
                  "desc": "A game handle."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` while the outline is drawn."
              }
            },
            {
              "type": "function",
              "name": "lsmp.outline.showGeometry",
              "id": "fn-outline-show-geometry",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.outline.showGeometry(entity, geomKey [, opts]) --> boolean",
                "js": "lsmp.outline.showGeometry(entity: number | null, geomKey: number, opts?: OutlineOptions): boolean"
              },
              "summary": "Outline one piece of geometry: a door, a window, one wall of a building.",
              "md": "The geometry key comes from the [picker](#outline-selection/fn-selection-get) (`geometry.key`). Buildings and terrain are not entities: pass `nil`/`null` as the entity for map geometry.",
              "params": [
                {
                  "name": "entity",
                  "type": "handle?",
                  "desc": "The entity the piece belongs to, or `nil`/`null` for the map."
                },
                {
                  "name": "geomKey",
                  "type": "uint",
                  "desc": "The geometry key."
                },
                {
                  "name": "opts",
                  "type": "OutlineOptions",
                  "desc": "See [`OutlineOptions`](#outline-selection/outline-options); `position` helps to find map geometry again.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the outline is drawn."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`not-found`",
                      "No such geometry, or the 32 outlines are taken."
                    ],
                    [
                      "`permission`",
                      "Another resource outlines this geometry."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.outline.hideGeometry",
              "id": "fn-outline-hide-geometry",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.outline.hideGeometry(entity, geomKey) --> boolean",
                "js": "lsmp.outline.hideGeometry(entity: number | null, geomKey: number): boolean"
              },
              "summary": "Remove this resource's outline from a piece of geometry.",
              "params": [
                {
                  "name": "entity",
                  "type": "handle?",
                  "desc": "The entity, or `nil`/`null` for the map."
                },
                {
                  "name": "geomKey",
                  "type": "uint",
                  "desc": "The geometry key."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if this resource outlined it."
              }
            },
            {
              "type": "function",
              "name": "lsmp.outline.hasGeometry",
              "id": "fn-outline-has-geometry",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.outline.hasGeometry(entity, geomKey) --> boolean",
                "js": "lsmp.outline.hasGeometry(entity: number | null, geomKey: number): boolean"
              },
              "summary": "Whether this resource outlines a piece of geometry.",
              "params": [
                {
                  "name": "entity",
                  "type": "handle?",
                  "desc": "The entity, or `nil`/`null` for the map."
                },
                {
                  "name": "geomKey",
                  "type": "uint",
                  "desc": "The geometry key."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` while the outline is drawn."
              }
            },
            {
              "type": "function",
              "name": "lsmp.outline.clear",
              "id": "fn-outline-clear",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.outline.clear() --> integer",
                "js": "lsmp.outline.clear(): number"
              },
              "summary": "Remove every outline of this resource.",
              "returns": [
                {
                  "type": "integer",
                  "desc": "How many were removed.",
                  "only": "lua"
                },
                {
                  "type": "number",
                  "desc": "How many were removed.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.outline.count",
              "id": "fn-outline-count",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.outline.count() --> integer",
                "js": "lsmp.outline.count(): number"
              },
              "summary": "How many outlines this resource draws.",
              "returns": [
                {
                  "type": "integer",
                  "desc": "The number of outlines.",
                  "only": "lua"
                },
                {
                  "type": "number",
                  "desc": "The number of outlines.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "OutlineOptions",
              "level": 3,
              "id": "outline-options"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`color`",
                  "color",
                  "`\"#ffffff\"`",
                  "Any [color](#conventions) form. An alpha below 255 makes it translucent."
                ],
                [
                  "`width`",
                  "number",
                  "`2`",
                  "Thickness in pixels, up to `64`."
                ],
                [
                  "`mode`",
                  "string",
                  "`\"outline\"`",
                  "`\"outline\"`, `\"fill\"` (the whole silhouette) or `\"dashed\"`."
                ],
                [
                  "`softness`",
                  "number",
                  "`0`",
                  "Blur of the edge, `0` to `1`."
                ],
                [
                  "`dashPeriod`",
                  "number",
                  "—",
                  "Length of a dash and its gap, in pixels (`\"dashed\"`)."
                ],
                [
                  "`dashSpeed`",
                  "number",
                  "—",
                  "How fast the dashes move, in pixels per second (`\"dashed\"`)."
                ],
                [
                  "`position`",
                  "vec3",
                  "—",
                  "`showGeometry` only: a point of the piece."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Picking",
              "level": 2,
              "id": "picking"
            },
            {
              "type": "text",
              "md": "The picker answers \"what is drawn at this point of the screen?\" from the image itself. No collision is involved: it also finds what a [raycast](#world/fn-raycast) goes through (a fence, leaves, an object without collision), and it gives the exact piece of geometry under the point, not only the entity.\n\nIt costs an extra render pass while it runs: turn it on when you need it. Each resource holds it on its own account, and it runs while at least one resource holds it."
            },
            {
              "type": "function",
              "name": "lsmp.selection.setEnabled",
              "id": "fn-selection-set-enabled",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.selection.setEnabled(enabled) --> boolean",
                "js": "lsmp.selection.setEnabled(enabled: boolean): boolean"
              },
              "summary": "Hold the picker on, or release this resource's hold.",
              "params": [
                {
                  "name": "enabled",
                  "type": "boolean",
                  "desc": "`true` to hold it, `false` to release."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if this resource's hold changed."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`unavailable`",
                      "The picker is not available on this client."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.selection.isEnabled",
              "id": "fn-selection-is-enabled",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.selection.isEnabled() --> boolean",
                "js": "lsmp.selection.isEnabled(): boolean"
              },
              "summary": "Whether the picker runs (for any resource).",
              "returns": {
                "type": "boolean",
                "desc": "`true` while it runs."
              }
            },
            {
              "type": "function",
              "name": "lsmp.selection.setPoint",
              "id": "fn-selection-set-point",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.selection.setPoint(point)",
                "js": "lsmp.selection.setPoint(point: Vec2Like | null): void"
              },
              "summary": "Pick at a fixed point of the screen.",
              "md": "Without a point, the picker follows the mouse cursor. `{ x = 0.5, y = 0.5 }` picks at the centre, under a crosshair. Like other owned settings, the last resource to set it wins until it stops.",
              "params": [
                {
                  "name": "point",
                  "type": "vec2?",
                  "desc": "`{ x, y }`, normalized `0..1`, or `nil`/`null` to follow the cursor again."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.selection.setPointPixel",
              "id": "fn-selection-set-point-pixel",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.selection.setPointPixel(x, y)",
                "js": "lsmp.selection.setPointPixel(x: number, y: number): void"
              },
              "summary": "Pick at a fixed point of the screen, in pixels.",
              "params": [
                {
                  "name": "x",
                  "type": "number",
                  "desc": "From the left edge."
                },
                {
                  "name": "y",
                  "type": "number",
                  "desc": "From the top edge."
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.selection.get",
              "id": "fn-selection-get",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.selection.get() --> Selection?",
                "js": "lsmp.selection.get(): Selection | null"
              },
              "summary": "What is under the pick point.",
              "md": "See [`Selection`](#outline-selection/selection). Already up to date inside a [`selectionChange`](#engine-events) handler.",
              "returns": [
                {
                  "type": "Selection?",
                  "desc": "The selection, or `nil`/`null` while the picker is off.",
                  "only": "lua"
                },
                {
                  "type": "Selection | null",
                  "desc": "The selection, or `nil`/`null` while the picker is off.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.selection.setEnabled(true)\nlsmp.selection.setPoint({ x = 0.5, y = 0.5 })\n\nlsmp.on(\"selectionChange\", function(entity, geomKey, valid)\n  local hit = lsmp.selection.get()\n  if not valid or not hit then return end\n  if hit.baked then\n    lsmp.log((\"scenery, %.1f m\"):format(hit.distance))\n  else\n    lsmp.log((\"%s, model 0x%x, %.1f m\"):format(hit.type, hit.model, hit.distance))\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.selection.setEnabled(true);\nlsmp.selection.setPoint({ x: 0.5, y: 0.5 });\n\nlsmp.on('selectionChange', (entity, geomKey, valid) => {\n  const hit = lsmp.selection.get();\n  if (!valid || !hit) return;\n  if (hit.baked) lsmp.log(`scenery, ${hit.distance.toFixed(1)} m`);\n  else lsmp.log(`${hit.type}, model 0x${hit.model.toString(16)}, ${hit.distance.toFixed(1)} m`);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.selection.setOutline",
              "id": "fn-selection-set-outline",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.selection.setOutline(enabled [, opts]) --> boolean",
                "js": "lsmp.selection.setOutline(enabled: boolean, opts?: SelectionOutlineOptions): boolean"
              },
              "summary": "Keep an outline on whatever is picked, with no per-frame code.",
              "md": "The entity under the point gets one style, the piece of geometry another. Defaults: a light blue outline for the entity, yellow dashes for the geometry.",
              "params": [
                {
                  "name": "enabled",
                  "type": "boolean",
                  "desc": "`true` to show, `false` to stop."
                },
                {
                  "name": "opts",
                  "type": "SelectionOutlineOptions",
                  "desc": "`{ entity, geometry }`, each an [`OutlineOptions`](#outline-selection/outline-options).",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the setting was applied."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`unavailable`",
                      "The picker is not available on this client."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.selection.setToolOpen",
              "id": "fn-selection-set-tool-open",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.selection.setToolOpen(open) --> boolean",
                "js": "lsmp.selection.setToolOpen(open: boolean): boolean"
              },
              "summary": "Open or close the inspection tool.",
              "md": "The engine's own tool: the camera freezes, the mouse hovers over the world and a panel describes what is under it. It manages the picker by itself.",
              "params": [
                {
                  "name": "open",
                  "type": "boolean",
                  "desc": "`true` to open, `false` to close."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the request was applied."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`unavailable`",
                      "The tool is not available on this client."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.selection.isToolOpen",
              "id": "fn-selection-is-tool-open",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.selection.isToolOpen() --> boolean",
                "js": "lsmp.selection.isToolOpen(): boolean"
              },
              "summary": "Whether the inspection tool is open.",
              "returns": {
                "type": "boolean",
                "desc": "`true` while it is open."
              }
            },
            {
              "type": "text",
              "md": "[`selectionChange`](#engine-events) `(entity, geomKey, valid)` fires when what is under the pick point changes, not every frame."
            },
            {
              "type": "heading",
              "text": "Selection",
              "level": 3,
              "id": "selection"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Default",
                "Description"
              ],
              "rows": [
                [
                  "`serial`",
                  "int",
                  "—",
                  "Increases with each new reading."
                ],
                [
                  "`valid`",
                  "boolean",
                  "—",
                  "`false` when nothing is under the point (sky, nothing drawn)."
                ],
                [
                  "`entity`",
                  "handle?",
                  "—",
                  "The entity picked; absent for buildings and terrain."
                ],
                [
                  "`model`",
                  "hash?",
                  "—",
                  "Its model. Read it here: some picked entities have no model information for natives."
                ],
                [
                  "`type`",
                  "string?",
                  "—",
                  "`\"vehicle\"`, `\"ped\"` or `\"object\"`."
                ],
                [
                  "`baked`",
                  "boolean",
                  "—",
                  "`true` for map geometry (buildings, terrain)."
                ],
                [
                  "`distance`",
                  "meters?",
                  "—",
                  "From the camera."
                ],
                [
                  "`position`",
                  "vec3?",
                  "—",
                  "The world position under the point."
                ],
                [
                  "`point`",
                  "vec2",
                  "—",
                  "The pick point, normalized."
                ],
                [
                  "`geometry`",
                  "table?",
                  "—",
                  "The piece of geometry: `key` (for [`showGeometry`](#outline-selection/fn-outline-show-geometry)), and its triangle and vertex counts."
                ]
              ]
            }
          ]
        },
        {
          "id": "client-commands",
          "title": "Console commands and key input",
          "eyebrow": "Client · Lua & JS",
          "lead": "Commands in the player's F8 console, and reacting to keys and buttons.",
          "blocks": [
            {
              "type": "heading",
              "text": "Console commands",
              "level": 2,
              "id": "client-console-commands"
            },
            {
              "type": "text",
              "md": "A client command is typed by the player in the F8 console, with or without a leading `/`. It runs on that player's machine only: anything that must be checked or shared goes to the server (an [event](#events) or a [remote call](#rpc)). For commands in the server console, see [Console commands](#server-commands)."
            },
            {
              "type": "function",
              "name": "lsmp.registerCommand",
              "id": "fn-register-command",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.registerCommand(name [, opts], fn) --> off",
                "js": "lsmp.registerCommand(name: string, opts: CommandOptions | undefined, fn: Function): () => boolean"
              },
              "summary": "Add a command to the F8 console.",
              "md": "The handler receives `(args, raw)`: `args` are the words after the command name, split on spaces (a word that starts with `\"` runs to the next `\"`); `raw` is the rest of the line as typed. `help` and `params` are shown while the player types; they are display only, `args` are always strings.\n\nSeveral handlers may share a name: they all run. Names follow the [server rules](#server-commands/fn-register-command); the built-in client commands (`devtools`, `disconnect`...) cannot be registered. A resource's commands are removed when it stops; [`unregisterCommand`](#server-commands/fn-unregister-command) removes one before.",
              "params": [
                {
                  "name": "name",
                  "type": "string",
                  "desc": "The command name."
                },
                {
                  "name": "opts",
                  "type": "CommandOptions",
                  "desc": "`{ help, params }`: see [`CommandOptions`](#server-commands/command-options) (`permission` and `restricted` are server only).",
                  "optional": true
                },
                {
                  "name": "fn",
                  "type": "fn",
                  "desc": "The handler."
                }
              ],
              "returns": [
                {
                  "type": "function",
                  "desc": "A function that unregisters this handler and returns `true` if it was registered.",
                  "only": "lua"
                },
                {
                  "type": "() => boolean",
                  "desc": "A function that unregisters this handler and returns `true` if it was registered.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.registerCommand(\"heal\", {\n  help = \"Ask the server to heal you\",\n}, function(args, raw)\n  local ok, err = lsmp.callServer(\"medic:heal\")\n  if not ok then lsmp.log(\"no medic available: \" .. tostring(err)) end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.registerCommand('heal', { help: 'Ask the server to heal you' }, async () => {\n  try {\n    await lsmp.callServer('medic:heal');\n  } catch (err) {\n    lsmp.log(`no medic available: ${err.code}`);\n  }\n});"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Key input",
              "level": 2,
              "id": "client-key-input"
            },
            {
              "type": "text",
              "md": "Keys are read with the game's control natives, every frame, from [`lsmp.onTick`](#core-utils). Controls are game actions (`INPUT_...`), not physical keys: a player who rebinds a key in the game settings keeps your feature working. `isControlJustPressed` fires once per press; `isControlPressed` while held."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "local INPUT_MULTIPLAYER_INFO = 20   -- Z on a default layout\n\nlsmp.onTick(function()\n  if isControlJustPressed(0, INPUT_MULTIPLAYER_INFO) then\n    lsmp.emit(\"scoreboard:toggle\")\n  end\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "const INPUT_MULTIPLAYER_INFO = 20;   // Z on a default layout\n\nlsmp.onTick(() => {\n  if (isControlJustPressed(0, INPUT_MULTIPLAYER_INFO)) lsmp.emit('scoreboard:toggle');\n});"
                }
              ]
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "**A focused page takes the keyboard.** While a [browser](#browsers) has the focus (a chat field, a menu), the control natives report nothing: the same key cannot fire twice for one action.",
                "**Disable a game action** while you use its key: `disableControlAction(0, control, true)` every frame.",
                "**Keep the handler short.** It runs every frame; heavy work belongs in a timer or an `async` function."
              ]
            }
          ]
        },
        {
          "id": "browsers",
          "title": "Browsers (2D and 3D)",
          "eyebrow": "Client · Lua & JS",
          "lead": "Show web pages in game: 2D pages drawn over the game, and 3D pages rendered into a texture placed in the world. Each page talks only to the script that opened it.",
          "blocks": [
            {
              "type": "table",
              "headers": [
                "",
                "2D browser",
                "3D browser"
              ],
              "rows": [
                [
                  "Created with",
                  "[`lsmp.createBrowser`](#browsers/fn-create-browser)",
                  "[`lsmp.createBrowser3D`](#browsers/fn-create-browser3d)"
                ],
                [
                  "Shown",
                  "Over the game, in a rectangle of the screen",
                  "Nowhere by itself: its texture replaces a game texture ([`lsmp.replaceTexture`](#textures/fn-replace-texture))"
                ],
                [
                  "Mouse and keyboard",
                  "When it has the focus (both, or one of the two)",
                  "None"
                ],
                [
                  "Addresses",
                  "`https://`, `rsc://<resource>/…`; `http://localhost` outside a server",
                  "`https://`, `rsc://<its own resource>/…`"
                ],
                [
                  "At most",
                  "16 per resource, 128 on the client",
                  "4 per resource, 64 on the client"
                ]
              ]
            },
            {
              "type": "text",
              "md": "A browser belongs to the resource that created it: it closes when the resource stops, and only that resource's handlers hear from it. The page itself uses the [`lsmp` object of a page](#page-api). For a guided start, see [Web interfaces](#web-ui) and the [UI tutorial](#tutorial-ui). A method called on a handle of another resource does nothing and returns `false`, with the code `permission` in `lsmp.getLastError()`."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "client/main.lua",
                  "lang": "lua",
                  "code": "local hud = lsmp.createBrowser(\"rsc://shop/index.html\", {\n  bounds = { x = 0.70, y = 0.10, width = 0.28, height = 0.80 },\n})\n\nhud:on(\"load\", function(url)\n  hud:emit(\"init\", lsmp.getPlayerName(lsmp.getLocalPlayer()))\nend)\n\n-- The page calls lsmp.callServer(\"buy\", itemId); the return value answers it.\nhud:on(\"buy\", function(itemId)\n  local ok, err = lsmp.callServer(\"shop:buy\", itemId)\n  return { ok = ok ~= nil, error = err }\nend)"
                },
                {
                  "label": "client/main.js",
                  "lang": "js",
                  "code": "const hud = lsmp.createBrowser('rsc://shop/index.html', {\n  bounds: { x: 0.70, y: 0.10, width: 0.28, height: 0.80 },\n});\n\nhud.on('load', () => {\n  hud.emit('init', lsmp.getPlayerName(lsmp.getLocalPlayer()));\n});\n\n// The page calls lsmp.callServer('buy', itemId); the return value answers it.\nhud.on('buy', async (itemId) => {\n  try {\n    return { ok: true, result: await lsmp.callServer('shop:buy', itemId) };\n  } catch (err) {\n    return { ok: false, error: err.code };\n  }\n});"
                },
                {
                  "label": "web/index.html (page)",
                  "lang": "js",
                  "web": true,
                  "code": "lsmp.on('init', (name) => {\n  document.querySelector('#hello').textContent = `Hello, ${name}`;\n});\n\nasync function buy(itemId) {\n  const answer = await lsmp.call('buy', itemId);\n  if (!answer.ok) document.querySelector('#error').textContent = answer.error;\n}"
                }
              ]
            },
            {
              "type": "heading",
              "text": "2D browsers",
              "level": 2,
              "id": "browsers-2d"
            },
            {
              "type": "function",
              "name": "lsmp.createBrowser",
              "id": "fn-create-browser",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.createBrowser(url [, opts]) --> Browser?",
                "js": "lsmp.createBrowser(url: string, opts?: BrowserOptions): Browser | null"
              },
              "summary": "Open a 2D page over the game, owned by the calling resource.",
              "md": "The page starts loading at once; messages you `emit` before it is ready are kept and delivered when it is (see [`load`](#browsers/browser-lifecycle)). Without `bounds` the page covers the whole screen, transparent where the page is. Failures return `nil`/`null`; read the code with [`lsmp.getLastError()`](#core-utils): `limit` (16 open 2D browsers for this resource, 128 on the client) or `unavailable` (the game's web engine is not ready). A refused address or out-of-range option raises a `RangeError`.",
              "params": [
                {
                  "name": "url",
                  "type": "string",
                  "desc": "`https://…`, `rsc://<resource>/…` (pages of a resource's [`webui`](#resource-layout/layout-webui) folders), or `http://localhost`, `http://127.0.0.1`, `http://[::1]` **outside** a server session only (local development). See [URL rules](#browsers/browsers-urls)."
                },
                {
                  "name": "opts",
                  "type": "BrowserOptions",
                  "desc": "Options, below.",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "Browser?",
                  "desc": "The handle, or `nil` on failure.",
                  "only": "lua"
                },
                {
                  "type": "Browser | null",
                  "desc": "The handle, or `null` on failure.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "BrowserOptions",
                    "Type",
                    "Default",
                    "Description"
                  ],
                  "rows": [
                    [
                      "`bounds`",
                      "Rect",
                      "full screen",
                      "`{ x, y, width, height }` as fractions of the screen, `0`..`1`. The rectangle must fit on the screen."
                    ],
                    [
                      "`boundsPixel`",
                      "Rect",
                      "",
                      "The same in pixels. Do not give both `bounds` and `boundsPixel`."
                    ],
                    [
                      "`visible`",
                      "boolean",
                      "`true`",
                      "Shown at once."
                    ],
                    [
                      "`focus`",
                      "boolean",
                      "`false`",
                      "Takes the mouse and keyboard at once. See [Focus](#browsers/browsers-focus)."
                    ],
                    [
                      "`cursor`",
                      "boolean",
                      "`true`",
                      "With `focus`: `false` takes the keyboard only, with no cursor (a chat field). Same as the `cursor` option of `browser.setFocus`."
                    ],
                    [
                      "`keepInput`",
                      "boolean",
                      "`false`",
                      "With `focus`: `true` takes the mouse only, the player keeps playing. Same as the `keepInput` option of `browser.setFocus`."
                    ],
                    [
                      "`zIndex`",
                      "integer",
                      "`0`",
                      "Stacking among this server's 2D pages, `-1000`..`1000`; higher is on top."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "browser.destroy",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:destroy()",
                "js": "browser.destroy(): void"
              },
              "summary": "Close the page.",
              "md": "Pending `browser.call`s fail with `cancelled`, and popups the page opened close with it. Afterwards every method of the handle does nothing and returns `false` (or `nil`/`null`). Resources do not need it at stop: their browsers close by themselves."
            },
            {
              "type": "function",
              "name": "browser.isValid",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:isValid() --> boolean",
                "js": "browser.isValid(): boolean"
              },
              "summary": "Whether the browser is still open.",
              "returns": {
                "type": "boolean",
                "desc": "`false` once destroyed, by you or when the resource stopped."
              }
            },
            {
              "type": "function",
              "name": "browser.id",
              "id": "fn-browser-id",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser.id --> integer",
                "js": "browser.id: number"
              },
              "summary": "Read-only field: the 2D browser id given by the client.",
              "md": "Stable for the life of the handle. It is the number shown by DevTools and in the client log for this browser."
            },
            {
              "type": "function",
              "name": "browser.setUrl",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:setUrl(url) --> boolean",
                "js": "browser.setUrl(url: string): boolean"
              },
              "summary": "Load another page, with the same address rules as `createBrowser`.",
              "md": "Pending calls of the old page fail with `cancelled`. `load` fires again when the new page is ready. Also the way to reload a page after a `crash`.",
              "params": [
                {
                  "name": "url",
                  "type": "string",
                  "desc": "The new address. A refused address raises a `RangeError`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` if the browser was destroyed."
              }
            },
            {
              "type": "function",
              "name": "browser.setBounds",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:setBounds(rect) --> boolean",
                "js": "browser.setBounds(rect: Rect): boolean"
              },
              "summary": "Move and resize the page, as fractions of the screen.",
              "params": [
                {
                  "name": "rect",
                  "type": "Rect",
                  "desc": "`{ x, y, width, height }`, `0`..`1`; width and height above `0`, and the rectangle inside the screen. Otherwise `RangeError`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` if the browser was destroyed."
              }
            },
            {
              "type": "function",
              "name": "browser.setBoundsPixel",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:setBoundsPixel(rect) --> boolean",
                "js": "browser.setBoundsPixel(rect: Rect): boolean"
              },
              "summary": "Move and resize the page, in pixels.",
              "md": "Pixel bounds do not follow a change of resolution; fractions do. Use [`lsmp.getGameScreen`](#local-player) to read the screen size.",
              "params": [
                {
                  "name": "rect",
                  "type": "Rect",
                  "desc": "`{ x, y, width, height }` in pixels, non-negative, width and height above `0`, at most 16384 to the far edge."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` if the browser was destroyed."
              }
            },
            {
              "type": "function",
              "name": "browser.setVisible",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:setVisible(visible) --> boolean",
                "js": "browser.setVisible(visible: boolean): boolean"
              },
              "summary": "Show or hide the page.",
              "md": "A hidden page keeps running and keeps its state: hiding is cheaper than destroying and recreating it. A hidden page never takes the mouse.",
              "params": [
                {
                  "name": "visible",
                  "type": "boolean",
                  "desc": "`true` to show."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` if the browser was destroyed."
              }
            },
            {
              "type": "function",
              "name": "browser.isVisible",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:isVisible() --> boolean",
                "js": "browser.isVisible(): boolean"
              },
              "summary": "Whether the page is shown.",
              "returns": {
                "type": "boolean",
                "desc": "`false` when hidden or destroyed."
              }
            },
            {
              "type": "function",
              "name": "browser.setFocus",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:setFocus(focused [, opts]) --> boolean",
                "js": "browser.setFocus(focused: boolean, opts?: FocusOptions): boolean"
              },
              "summary": "Give the page the mouse and keyboard, the keyboard alone or the mouse alone, or take them back.",
              "md": "While a page has the focus, the player's input goes to the page instead of the game. By default the page takes the mouse and the keyboard, and the cursor shows: right for a menu or a form. With `cursor` set to `false`, it takes the **keyboard only**: no cursor, no clicks, and the camera stays still while the player types. Use it for a chat field or any text input that needs no mouse. With `keepInput` set to `true`, it takes the **mouse only**: the cursor shows and clicks reach the page, while the player **keeps playing** with the keyboard and gamepad (walking, driving). The mouse then moves the cursor instead of the camera, and a click does not fire. Use it for a panel that stays usable during play (a radio, a map, a tracker). The keys still go to the game, so a text field in such a page would also move the player: use the default focus for typing. The two options cannot be combined. The player can always take the input back with **Ctrl+Alt+Backspace**; the page then gets `focusLost`. Give the focus only while the player needs it, and remove it when they are done.",
              "params": [
                {
                  "name": "focused",
                  "type": "boolean",
                  "desc": "`true` to take the input, `false` to give it back to the game."
                },
                {
                  "name": "opts",
                  "type": "FocusOptions",
                  "desc": "Options, below.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` if the browser was destroyed."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "FocusOptions",
                    "Type",
                    "Default",
                    "Description"
                  ],
                  "rows": [
                    [
                      "`cursor`",
                      "boolean",
                      "`true`",
                      "`true`: the mouse and the keyboard, with the cursor. `false`: the keyboard only, with no cursor and no clicks. No effect when `focused` is `false`."
                    ],
                    [
                      "`keepInput`",
                      "boolean",
                      "`false`",
                      "`true`: the mouse only. The cursor shows and clicks reach the page; the game keeps the keyboard and gamepad, and the mouse no longer turns the camera. A `RangeError` with `cursor` set to `false`."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local menu = lsmp.createBrowser(\"rsc://shop/menu.html\", { visible = false })\n\nlsmp.registerCommand(\"shop\", function()\n  menu:setVisible(true)\n  menu:setFocus(true)\nend)\n\n-- The page calls lsmp.emit(\"close\") from its close button.\nmenu:on(\"close\", function()\n  menu:setFocus(false)\n  menu:setVisible(false)\nend)\n\n-- The player took the input back with Ctrl+Alt+Backspace.\nmenu:on(\"focusLost\", function()\n  menu:setVisible(false)\nend)\n\n-- A chat field needs the keyboard only: no cursor while the player types.\nlocal chat = lsmp.createBrowser(\"rsc://shop/chat.html\", {\n  bounds = { x = 0.01, y = 0.03, width = 0.32, height = 0.34 },\n})\n\nlsmp.registerCommand(\"say\", function()\n  chat:setFocus(true, { cursor = false })\n  chat:emit(\"open\")\nend)\n\n-- The page gives the line back when the player presses Enter.\nchat:on(\"submit\", function(text)\n  chat:setFocus(false)\nend)\n\n-- A radio panel stays usable while the player drives: mouse only.\nlocal radio = lsmp.createBrowser(\"rsc://shop/radio.html\", {\n  bounds = { x = 0.75, y = 0.70, width = 0.24, height = 0.28 },\n})\n\nlsmp.registerCommand(\"radio\", function()\n  radio:setFocus(not radio:hasFocus(), { keepInput = true })\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const menu = lsmp.createBrowser('rsc://shop/menu.html', { visible: false });\n\nlsmp.registerCommand('shop', () => {\n  menu.setVisible(true);\n  menu.setFocus(true);\n});\n\n// The page calls lsmp.emit('close') from its close button.\nmenu.on('close', () => {\n  menu.setFocus(false);\n  menu.setVisible(false);\n});\n\n// The player took the input back with Ctrl+Alt+Backspace.\nmenu.on('focusLost', () => menu.setVisible(false));\n\n// A chat field needs the keyboard only: no cursor while the player types.\nconst chat = lsmp.createBrowser('rsc://shop/chat.html', {\n  bounds: { x: 0.01, y: 0.03, width: 0.32, height: 0.34 },\n});\n\nlsmp.registerCommand('say', () => {\n  chat.setFocus(true, { cursor: false });\n  chat.emit('open');\n});\n\n// The page gives the line back when the player presses Enter.\nchat.on('submit', (text) => chat.setFocus(false));\n\n// A radio panel stays usable while the player drives: mouse only.\nconst radio = lsmp.createBrowser('rsc://shop/radio.html', {\n  bounds: { x: 0.75, y: 0.70, width: 0.24, height: 0.28 },\n});\n\nlsmp.registerCommand('radio', () => {\n  radio.setFocus(!radio.hasFocus(), { keepInput: true });\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "browser.hasFocus",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:hasFocus() --> boolean",
                "js": "browser.hasFocus(): boolean"
              },
              "summary": "Whether the page holds the focus (the mouse and keyboard, or the keyboard alone).",
              "returns": {
                "type": "boolean",
                "desc": "`false` after `setFocus(false)`, after the player's Ctrl+Alt+Backspace, or once destroyed."
              }
            },
            {
              "type": "function",
              "name": "browser.setZIndex",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:setZIndex(z) --> boolean",
                "js": "browser.setZIndex(z: number): boolean"
              },
              "summary": "Change the stacking order among this server's 2D pages.",
              "md": "LS:MP's own interface (menu, console, payment window) always stays above every server page.",
              "params": [
                {
                  "name": "z",
                  "type": "integer",
                  "desc": "`-1000`..`1000`; higher is on top."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` if the browser was destroyed."
              }
            },
            {
              "type": "heading",
              "text": "Talking to the page",
              "level": 2,
              "id": "browsers-messages"
            },
            {
              "type": "text",
              "md": "The same four methods exist on 2D and 3D handles. Values are those a page understands: see [Values and limits](#browsers/browsers-values)."
            },
            {
              "type": "function",
              "name": "browser.emit",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:emit(event, ...) --> boolean",
                "js": "browser.emit(event: string, ...args: Value[]): boolean"
              },
              "summary": "Send an event to the page's `lsmp.on` handlers.",
              "md": "Before the page is ready, events wait in a queue (256 messages or 1 MiB at most) and are delivered in order right after `load`. A value the page cannot represent, a message over the limit, or more than 32 arguments raises. The names `load`, `loadError`, `focusLost`, `crash` and those starting with `lsmp:` are reserved.",
              "params": [
                {
                  "name": "event",
                  "type": "string",
                  "desc": "Event name, 1 to 128 characters."
                },
                {
                  "name": "...",
                  "type": "Value",
                  "desc": "Up to 32 values.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` if the browser was destroyed or the queue is full (code `limit`)."
              }
            },
            {
              "type": "function",
              "name": "browser.on",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:on(event, fn) --> function",
                "js": "browser.on(event: string, fn: Function): () => boolean"
              },
              "summary": "Handle an event or a call from this browser's page, or one of its lifecycle events.",
              "md": "The handler receives the page's arguments. For a page `lsmp.emit`, every handler of the name runs. For a page `lsmp.call`, handlers run in order until one returns a value: that value is the answer (a JS handler may return a Promise; a Lua handler may wait, it runs in a coroutine). If all return `nil`/`undefined` the answer is `nil`/`null`; a handler that raises answers with the code `error`, and the error is logged in the client console. With no handler, the page gets `no-handler` at once.\n\nThe same function registered twice for one name counts once. Lifecycle events are in the [table below](#browsers/browser-lifecycle).",
              "params": [
                {
                  "name": "event",
                  "type": "string",
                  "desc": "Event name, or `\"load\"`, `\"loadError\"`, `\"focusLost\"`, `\"crash\"`."
                },
                {
                  "name": "fn",
                  "type": "function",
                  "desc": "`fn(...args)`; its return value answers a page call."
                }
              ],
              "returns": [
                {
                  "type": "function",
                  "desc": "Call it to remove the handler; it returns `true` if it was registered.",
                  "only": "lua"
                },
                {
                  "type": "() => boolean",
                  "desc": "Call it to remove the handler; it returns `true` if it was registered.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "browser.off",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:off(event, fn) --> boolean",
                "js": "browser.off(event: string, fn: Function): boolean"
              },
              "summary": "Remove a handler registered with `on`.",
              "params": [
                {
                  "name": "event",
                  "type": "string",
                  "desc": "The event name."
                },
                {
                  "name": "fn",
                  "type": "function",
                  "desc": "The same function that was registered."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if it was registered."
              }
            },
            {
              "type": "function",
              "name": "browser.call",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:call(event, ... [, cb]) --> any, err",
                "js": "browser.call(event: string | CallOptions, ...args: Value[]): Promise<Value>"
              },
              "summary": "Call the page's `lsmp.on` handler and get its answer.",
              "md": "The call waits for the page if it is still loading. Asynchronous: in Lua with a callback or inside a coroutine, see [Conventions](#conventions/async-lua). Failure codes ([Error codes](#error-codes)):",
              "params": [
                {
                  "name": "event",
                  "type": "string | CallOptions",
                  "desc": "The handler's name, or `{ name, timeoutMs }`: `timeoutMs` from `1` to `300000`, default `10000`."
                },
                {
                  "name": "...",
                  "type": "Value",
                  "desc": "Up to 32 values.",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "any, err",
                  "desc": "The page's answer, or `nil` and a code.",
                  "only": "lua"
                },
                {
                  "type": "Promise<Value>",
                  "desc": "Resolves with the page's answer; rejects with an error whose `code` is one of the codes below.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Code",
                    "Meaning"
                  ],
                  "rows": [
                    [
                      "`timeout`",
                      "No answer in time."
                    ],
                    [
                      "`no-handler`",
                      "The page has no `lsmp.on` handler for this name."
                    ],
                    [
                      "`error`",
                      "The page's handler threw, or its answer could not be sent. Details in the page's console ([DevTools](#debugging/debugging-devtools))."
                    ],
                    [
                      "`cancelled`",
                      "The browser was destroyed, or the page navigated away, before answering."
                    ],
                    [
                      "`limit`",
                      "1024 calls are already waiting on this browser."
                    ],
                    [
                      "`unavailable`",
                      "The game's web engine is not running."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local form = lsmp.createBrowser(\"rsc://garage/form.html\")\n\nform:call({ name = \"getColor\", timeoutMs = 5000 }, function(color, err)\n  if err then\n    lsmp.warn(\"no color: \" .. err)\n  else\n    lsmp.log(\"chosen color: \" .. color)\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "const form = lsmp.createBrowser('rsc://garage/form.html');\n\nform.call({ name: 'getColor', timeoutMs: 5000 })\n  .then((color) => lsmp.log(`chosen color: ${color}`))\n  .catch((err) => lsmp.warn(`no color: ${err.code}`));"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Lifecycle events",
              "level": 3,
              "id": "browser-lifecycle"
            },
            {
              "type": "text",
              "md": "Register them with `browser:on`, like page events. They come from LS:MP, never from the page, and only reach that handle's handlers. See also [Engine events](#engine-events)."
            },
            {
              "type": "table",
              "headers": [
                "Event",
                "Arguments",
                "When"
              ],
              "rows": [
                [
                  "`load`",
                  "`url`",
                  "The page's document is ready (its `DOMContentLoaded`). Queued `emit`s are delivered right after. Fires again after each navigation."
                ],
                [
                  "`loadError`",
                  "`url, code`",
                  "The page could not load. `code`: `\"refused-url\"` (address not allowed), `\"network\"`, `\"http-<status>\"` (such as `\"http-404\"`), `\"aborted\"`."
                ],
                [
                  "`focusLost`",
                  "",
                  "2D only. The player took the input back (Ctrl+Alt+Backspace), or another page took the focus. `hasFocus()` is now `false`."
                ],
                [
                  "`crash`",
                  "`reason`",
                  "The page's process crashed. The handle stays valid. A 2D page is reloaded by LS:MP right away and `load` fires again (after repeated crashes it stays down until `setUrl`). For a 3D page, `setUrl` loads a page again."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "3D browsers",
              "level": 2,
              "id": "browsers-3d"
            },
            {
              "type": "text",
              "md": "A 3D browser renders a page off-screen into a texture. Show it in the world by putting that texture in place of a game texture with [`lsmp.replaceTexture`](#textures/fn-replace-texture): a screen in a bar, a billboard, a phone. A 3D page has no mouse or keyboard; drive it with `emit` and `call`."
            },
            {
              "type": "function",
              "name": "lsmp.createBrowser3D",
              "id": "fn-create-browser3d",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.createBrowser3D(url [, opts]) --> Browser3D?",
                "js": "lsmp.createBrowser3D(url: string, opts?: Browser3DOptions): Browser3D | null"
              },
              "summary": "Open an off-screen page that renders into a texture.",
              "md": "Failures return `nil`/`null`, with the code from [`lsmp.getLastError()`](#core-utils): `limit` (4 open 3D browsers for this resource, 64 on the client) or `unavailable`. A refused address or an out-of-range option raises a `RangeError`.",
              "params": [
                {
                  "name": "url",
                  "type": "string",
                  "desc": "`https://…`, or `rsc://<this resource>/…`: a 3D page cannot show another resource's pages."
                },
                {
                  "name": "opts",
                  "type": "Browser3DOptions",
                  "desc": "`width` and `height` of the page and its texture in pixels, `1`..`4096`, default `1024`; `fps`, frames rendered per second, `1`..`60`, default `30`.",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "Browser3D?",
                  "desc": "The handle, or `nil` on failure.",
                  "only": "lua"
                },
                {
                  "type": "Browser3D | null",
                  "desc": "The handle, or `null` on failure.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- Show a web page on an existing world texture.\nlocal screen = lsmp.createBrowser3D(\"rsc://cinema/screen.html\", { width = 1280, height = 720, fps = 30 })\nif not screen then return end\n\nscreen:on(\"load\", function()\n  local texture = screen:getTexture()\n  if not texture then return end\n\n  local bind = lsmp.replaceTexture(texture, {\n    type = \"txd\", container = \"cs4_02_build_1\", name = \"cs4_02_rsl_mr_bb\",\n  })\n  if not bind then\n    lsmp.warn(\"texture not bound: \" .. tostring(lsmp.getLastError()))\n    return\n  end\n  screen:emit(\"play\", \"intro\")\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// Show a web page on an existing world texture.\nconst screen = lsmp.createBrowser3D('rsc://cinema/screen.html', { width: 1280, height: 720, fps: 30 });\n\nscreen?.on('load', () => {\n  const texture = screen.getTexture();\n  if (texture === null) return;\n\n  const bind = lsmp.replaceTexture(texture, {\n    type: 'txd', container: 'cs4_02_build_1', name: 'cs4_02_rsl_mr_bb',\n  });\n  if (bind === null) {\n    lsmp.warn(`texture not bound: ${lsmp.getLastError()}`);\n    return;\n  }\n  screen.emit('play', 'intro');\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "browser3d.destroy",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser3d:destroy()",
                "js": "browser3d.destroy(): void"
              },
              "summary": "Close the page; game textures it replaced are restored.",
              "md": "Pending calls fail with `cancelled`. Resources do not need it at stop: their browsers close by themselves."
            },
            {
              "type": "function",
              "name": "browser3d.isValid",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser3d:isValid() --> boolean",
                "js": "browser3d.isValid(): boolean"
              },
              "summary": "Whether the 3D browser is still open.",
              "returns": {
                "type": "boolean",
                "desc": "`false` once destroyed."
              }
            },
            {
              "type": "function",
              "name": "browser3d.id",
              "id": "fn-browser3d-id",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser3d.id --> integer",
                "js": "browser3d.id: number"
              },
              "summary": "Read-only field: the 3D browser id given by the client.",
              "md": "Stable for the life of the handle. It is the number shown by DevTools and in the client log for this browser."
            },
            {
              "type": "function",
              "name": "browser3d.setUrl",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser3d:setUrl(url) --> boolean",
                "js": "browser3d.setUrl(url: string): boolean"
              },
              "summary": "Load another page, with the same address rules as `createBrowser3D`.",
              "params": [
                {
                  "name": "url",
                  "type": "string",
                  "desc": "The new address. A refused address raises a `RangeError`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` if the browser was destroyed."
              }
            },
            {
              "type": "function",
              "name": "browser3d.setSize",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser3d:setSize(width, height) --> boolean",
                "js": "browser3d.setSize(width: number, height: number): boolean"
              },
              "summary": "Resize the page and its texture.",
              "md": "The texture handle stays the same; bindings made with `replaceTexture` follow.",
              "params": [
                {
                  "name": "width",
                  "type": "integer",
                  "desc": "`1`..`4096` pixels."
                },
                {
                  "name": "height",
                  "type": "integer",
                  "desc": "`1`..`4096` pixels."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` if the browser was destroyed."
              }
            },
            {
              "type": "function",
              "name": "browser3d.getTexture",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser3d:getTexture() --> integer",
                "js": "browser3d.getTexture(): number"
              },
              "summary": "The texture the page renders into, for `lsmp.replaceTexture`.",
              "md": "The handle is stable for the browser's whole life. `nil`/`null` with the code `unavailable` if the texture does not exist yet, `not-found` once destroyed.",
              "returns": {
                "type": "integer",
                "desc": "Texture handle."
              }
            },
            {
              "type": "function",
              "name": "browser3d.emit",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser3d:emit(event, ...) --> boolean",
                "js": "browser3d.emit(event: string, ...args: Value[]): boolean"
              },
              "summary": "Send an event to the page, as [`browser.emit`](#browsers/fn-browser-emit).",
              "params": [
                {
                  "name": "event",
                  "type": "string",
                  "desc": "Event name."
                },
                {
                  "name": "...",
                  "type": "Value",
                  "desc": "Up to 32 values.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` if the browser was destroyed or the queue is full."
              }
            },
            {
              "type": "function",
              "name": "browser3d.on",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser3d:on(event, fn) --> function",
                "js": "browser3d.on(event: string, fn: Function): () => boolean"
              },
              "summary": "Handle an event, a call or a lifecycle event of the page, as [`browser.on`](#browsers/fn-browser-on).",
              "md": "Lifecycle events: `load`, `loadError`, `crash` (no `focusLost`: a 3D page has no focus).",
              "params": [
                {
                  "name": "event",
                  "type": "string",
                  "desc": "Event name or lifecycle event."
                },
                {
                  "name": "fn",
                  "type": "function",
                  "desc": "`fn(...args)`; its return value answers a page call."
                }
              ],
              "returns": [
                {
                  "type": "function",
                  "desc": "Call it to remove the handler.",
                  "only": "lua"
                },
                {
                  "type": "() => boolean",
                  "desc": "Call it to remove the handler.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "browser3d.off",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser3d:off(event, fn) --> boolean",
                "js": "browser3d.off(event: string, fn: Function): boolean"
              },
              "summary": "Remove a handler, as [`browser.off`](#browsers/fn-browser-off).",
              "params": [
                {
                  "name": "event",
                  "type": "string",
                  "desc": "The event name."
                },
                {
                  "name": "fn",
                  "type": "function",
                  "desc": "The same function that was registered."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if it was registered."
              }
            },
            {
              "type": "function",
              "name": "browser3d.call",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser3d:call(event, ... [, cb]) --> any, err",
                "js": "browser3d.call(event: string | CallOptions, ...args: Value[]): Promise<Value>"
              },
              "summary": "Call the page's handler and get its answer, as [`browser.call`](#browsers/fn-browser-call), with the same codes.",
              "params": [
                {
                  "name": "event",
                  "type": "string | CallOptions",
                  "desc": "The handler's name, or `{ name, timeoutMs }`."
                },
                {
                  "name": "...",
                  "type": "Value",
                  "desc": "Up to 32 values.",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "any, err",
                  "desc": "The answer, or `nil` and a code.",
                  "only": "lua"
                },
                {
                  "type": "Promise<Value>",
                  "desc": "Resolves with the answer; rejects with a coded error.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Values and limits",
              "level": 2,
              "id": "browsers-values"
            },
            {
              "type": "table",
              "headers": [
                "Script value",
                "In the page"
              ],
              "rows": [
                [
                  "`nil` / `null`",
                  "`null` (a missing argument too)"
                ],
                [
                  "boolean, string",
                  "the same"
                ],
                [
                  "number",
                  "number. Integers beyond 2^53, `NaN` and infinities raise a `TypeError`."
                ],
                [
                  "table with keys / object",
                  "object"
                ],
                [
                  "sequence / array",
                  "array"
                ],
                [
                  "vector",
                  "`{ x, y, z }`; an `{ x, y, z }` object from the page becomes a `Vector3` in Lua"
                ],
                [
                  "bytes ([`lsmp.bytes`](#core-utils), `Uint8Array`)",
                  "`Uint8Array`, and back"
                ]
              ]
            },
            {
              "type": "list",
              "items": [
                "One message holds at most 32 arguments and 120,000 characters once written as JSON; more raises a `RangeError`, on both sides.",
                "Event names: 1 to 128 characters, no control characters. Names starting with `lsmp:`, and `load`, `loadError`, `focusLost`, `crash`, are reserved.",
                "At most 1024 calls wait on one browser in each direction; the next fails with `limit`. At most 1024 handlers on one browser.",
                "In one frame, a page delivers at most 256 messages and 524 288 characters of JSON to its script; beyond, an `emit` is dropped and a `call` fails with `limit`. A page event no script handler listens to is dropped (a `call` fails with `no-handler`)."
              ]
            },
            {
              "type": "heading",
              "text": "URL rules",
              "level": 2,
              "id": "browsers-urls"
            },
            {
              "type": "list",
              "items": [
                "**`rsc://<resource>/…`** serves the files of a resource's [`webui`](#resource-layout/layout-webui) folders. A 3D browser may only open its own resource's pages.",
                "**`https://`** opens any public web page. The page still gets the `lsmp` object, linked to your script: only open sites you trust.",
                "**`http://`** is refused, except `http://localhost`, `http://127.0.0.1` and `http://[::1]` in a 2D browser **outside** a server session: handy with a dev server (Vite, webpack) in Story mode with [local resources](#local-resources).",
                "Server pages cannot reach the player's local network or machine. LS:MP's own pages cannot be opened."
              ]
            },
            {
              "type": "heading",
              "text": "Focus and input",
              "level": 2,
              "id": "browsers-focus"
            },
            {
              "type": "list",
              "items": [
                "A 2D page without the focus is **click-through**: the mouse and keyboard go to the game. Only focused, visible pages take the mouse, each in its own rectangle.",
                "**The cursor shows only while something needs it**: a page that holds the mouse, LS:MP's menu or console, a loading screen. In game it stays hidden.",
                "**Keyboard only**: a page focused with `cursor` set to `false` takes the keyboard and nothing else. No cursor, no clicks, and the game gets no input until you remove the focus: what a chat field wants.",
                "**Mouse only, the player keeps playing**: a page focused with `keepInput` set to `true` keeps the cursor on screen while the player walks or drives with the keyboard and gamepad. The mouse moves the cursor instead of the camera, clicks go to the page, and the cursor stays inside the game window.",
                "**What a page takes, the game no longer sees**: while a page holds the keyboard, no script reads the keys the player types, not even with `isDisabledControlPressed` or the frontend controls; the same goes for the mouse. Close your page from its own keys (Escape in the page), not from a control read by your script. The key that closes a page (Escape, Enter) does not reach the game either.",
                "**Ctrl+Alt+Backspace** always gives the input back to the player, from every page of the server. Your pages get `focusLost` and stay open; `setFocus(true)` gives them the input again.",
                "LS:MP's own interface always comes first: its menu (F1) and console (F8) open over your pages."
              ]
            },
            {
              "type": "heading",
              "text": "Storage, microphone, camera and limits",
              "level": 2,
              "id": "browsers-sandbox"
            },
            {
              "type": "text",
              "md": "A page runs with its real origin, 2D and 3D alike: `rsc://<resource>` for the files of a resource, or the `https://` site. That gives it the usual web platform:"
            },
            {
              "type": "list",
              "items": [
                "**Storage**: `localStorage`, `sessionStorage` and IndexedDB work, and what a page stores is **kept on the player's disk**: it is there again at the next connection, after a restart of the game too.",
                "**One store per server**: the store belongs to the server the player joined (its address). A page never reads what a page of another server wrote, even at the same origin or with the same resource name. Story Mode has one store for all mods, separated by origin; a Marketplace trial keeps nothing once it ends.",
                "**Microphone and camera**: `navigator.mediaDevices.getUserMedia` shows an LS:MP prompt that names your server, the resource and the page's origin. The player allows or blocks, for the session or for good (remembered for this server and this origin). LS:MP shows an indicator while a page records, and recording stops when the browser is destroyed. Screen capture is always refused.",
                "Web Workers and `BroadcastChannel` work as on the web.",
                "`fetch` and ES modules work for the files of the page's own resource (`rsc://`), and for `https://` servers that allow it (CORS)."
              ]
            },
            {
              "type": "text",
              "md": "What to keep in mind:"
            },
            {
              "type": "list",
              "items": [
                "A 2D page and a 3D page do **not** share storage, even at the same origin: 2D pages are frames of the LS:MP interface, and the browser keeps the storage of frames apart. Pass the value through your script if both need it.",
                "`rsc://` pages have no cookies and the Cache API does not store `rsc://` files: use `localStorage` or IndexedDB. An `https://` 2D page is an embedded frame: its cookies need `SameSite=None; Secure`.",
                "Storage is a convenience, not a database. LS:MP clears the store of a server the player has not visited for 180 days, the least recently visited ones beyond 64 servers or 4 GB, and a store that grows over 1 GB. Keep what matters on your server.",
                "2D pages of the same origin can reach each other (`parent.frames`), like two tabs of one site. Pages of different origins, and the LS:MP interface around them, cannot be read or navigated.",
                "**No dialogs** in 2D pages: `alert`, `confirm` and `prompt` do nothing. Draw your own. No pointer lock, no downloads."
              ]
            },
            {
              "type": "heading",
              "text": "Popups",
              "level": 2,
              "id": "browsers-popups"
            },
            {
              "type": "text",
              "md": "`window.open` and `target=\"_blank\"` links open an LS:MP popup window over the game, with the site's address in its title bar and a close button: useful for a sign-in page that refuses to load in a frame."
            },
            {
              "type": "list",
              "items": [
                "`https://` only, and only right after a click or a key press of the player.",
                "3 popups at most; a popup cannot open another one. The size is fixed (520 × 640).",
                "Popups close with the browser that opened them, and when the player leaves the server."
              ]
            }
          ]
        },
        {
          "id": "scenes",
          "title": "Render scenes",
          "eyebrow": "Client · Lua & JS",
          "lead": "Render peds, vehicles and objects in a private studio, away from the map and from the player's screen: portraits, vehicle thumbnails, item icons, on a transparent background. Shoot still images, or render the scene live on screen or onto a game texture.",
          "blocks": [
            {
              "type": "text",
              "md": "A **scene** is a small world of its own: no map, no sky, no weather, no time of day. It holds the entities you add, a camera and lights. It renders with the game's own renderer, into images of its own: the player's screen is never read or touched.\n\nThe entities stay where they are in the world. The scene only **draws** them, at the place you give them in its own space, with their current look: clothes, pose, damage, paint and mods. An invisible or far away entity renders just as well, so a common pattern is to spawn a hidden entity, shoot it, then delete it."
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Create",
                  "md": "Create the scene with `lsmp.createScene`, at the size of the image you want."
                },
                {
                  "title": "Add entities",
                  "md": "Add peds, vehicles or objects with `scene.addEntity`, each with its own position and rotation."
                },
                {
                  "title": "Frame and light",
                  "md": "Place the camera with `scene.setCamera`, and light the scene with a preset, the ambient light, a key light or your own lights. Every setting has a default that frames a ped standing at the origin."
                },
                {
                  "title": "Shoot or render live",
                  "md": "Call `scene.shot` for an image, or `scene.enableRender` to render continuously into a texture."
                },
                {
                  "title": "Destroy",
                  "md": "Destroy the scene when you are done. The scenes of a resource are destroyed when it stops."
                }
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- A thumbnail of the player's vehicle, on a transparent background.\nlocal scene, err = lsmp.createScene({ width = 512, height = 288, supersample = 2 })\nif not scene then return lsmp.warn(\"no scene: \" .. err) end\n\nscene:setLightPreset(\"studio\")\nscene:addEntity(getVehiclePedIsIn(playerPedId(), false), { rotation = { 0, 0, -35 } })\nscene:setCamera({ position = { 0, 6.5, 1.6 }, lookAt = { 0, 0, 0.2 }, fov = 40 })\n\nlocal shot, shotErr = scene:shot({ format = \"webp\", dataUrl = true })\nscene:destroy()\nif shot then\n  lsmp.emit(\"garage:thumbnail\", shot.dataUrl)\nelse\n  lsmp.warn(\"shot failed: \" .. shotErr)\nend"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// A thumbnail of the player's vehicle, on a transparent background.\nasync function thumbnail() {\n  const scene = lsmp.createScene({ width: 512, height: 288, supersample: 2 });\n  if (!scene) return lsmp.warn(`no scene: ${lsmp.getLastError()}`);\n\n  scene.setLightPreset('studio');\n  scene.addEntity(getVehiclePedIsIn(playerPedId(), false), { rotation: { x: 0, y: 0, z: -35 } });\n  scene.setCamera({ position: { x: 0, y: 6.5, z: 1.6 }, lookAt: { x: 0, y: 0, z: 0.2 }, fov: 40 });\n\n  try {\n    const shot = await scene.shot({ format: 'webp', dataUrl: true });\n    lsmp.emit('garage:thumbnail', shot.dataUrl);\n  } catch (err) {\n    lsmp.warn(`shot failed: ${err.code}`);\n  } finally {\n    scene.destroy();\n  }\n}"
                }
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Scenes or camera capture?",
              "md": "[Camera capture](#capture) photographs the **world** through a scripted camera: the map, the weather, the other players. A scene shows **only** what you put in it, lit the way you choose, and costs the player nothing on screen."
            },
            {
              "type": "heading",
              "text": "Creating a scene",
              "level": 2,
              "id": "scenes-create"
            },
            {
              "type": "function",
              "name": "lsmp.createScene",
              "id": "fn-create-scene",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.createScene([opts]) --> Scene?",
                "js": "lsmp.createScene(opts?: SceneOptions): Scene | null"
              },
              "summary": "Create a render scene owned by this resource.",
              "md": "The scene starts with the `\"headshot\"` light preset, a white ambient light and a camera framed on a ped standing at the origin. Every setting can change afterwards. The handle has a read-only `id`.\n\nFailure codes: `limit` (too many scenes, or too many pixels in total), `unavailable` (the game has not rendered its first frame yet, or this game build has no scenes), `error` (no graphics memory). See [Error codes](#error-codes).",
              "params": [
                {
                  "name": "opts",
                  "type": "SceneOptions",
                  "desc": "See [scene options](#scenes/scenes-options).",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "Scene?",
                  "desc": "The scene, or `nil` and a code.",
                  "only": "lua"
                },
                {
                  "type": "Scene | null",
                  "desc": "The scene, or `null` with the code in `lsmp.getLastError()`.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "scene.configure",
              "id": "fn-scene-configure",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:configure(opts) --> boolean",
                "js": "scene.configure(opts: SceneOptions): boolean"
              },
              "summary": "Change the size, the supersampling or the background.",
              "md": "Options you leave out keep their value. When a new size is refused, the scene keeps its previous size and stays usable. On a scene that renders live, the texture keeps its handle: replacements and the overlay follow.",
              "params": [
                {
                  "name": "opts",
                  "type": "SceneOptions",
                  "desc": "The options to change."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` when applied; `false` otherwise, with the code in [`lsmp.getLastError()`](#core-utils/fn-get-last-error): `limit`, `unavailable`, `error`."
              }
            },
            {
              "type": "heading",
              "text": "Scene options",
              "level": 3,
              "id": "scenes-options"
            },
            {
              "type": "table",
              "headers": [
                "Option",
                "Type",
                "Default",
                "Meaning"
              ],
              "rows": [
                [
                  "`width`, `height`",
                  "int",
                  "`512`",
                  "Size of the images in pixels, `16` to `4096`."
                ],
                [
                  "`supersample`",
                  "int",
                  "`1`",
                  "`1` to `4`. The scene renders at `width × supersample` by `height × supersample`, then scales down: smoother edges, finer hair. `2` is a good balance; `3` or `4` for small icons."
                ],
                [
                  "`background`",
                  "color | boolean",
                  "`false`",
                  "`false`: transparent. `true`: opaque black. A [color](#conventions), with alpha if you want a semi-transparent background. JPEG has no transparency."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Scene space",
              "level": 2,
              "id": "scenes-space"
            },
            {
              "type": "text",
              "md": "Positions are in **meters**, **Z points up**, and **+Y is the front** of the game's entities: a ped faces +Y, a car's nose points to +Y. Rotations are `{ x, y, z }` in degrees, as in the game's rotation natives (`z` is the yaw): a yaw of `180` turns an entity to face -Y. Vectors and colors follow the [Conventions](#conventions).\n\nAn entity is placed by its **origin**, the point the game uses for its position: about 1 m above the feet for a ped, around the middle of the body for a vehicle or an object. The default camera stands at `{ 0, 3, -0.1 }` and looks at `{ 0, 0, -0.1 }`, with a vertical field of view of 40°: a whole ped at the origin, seen from the front."
            },
            {
              "type": "heading",
              "text": "Entities",
              "level": 2,
              "id": "scenes-entities"
            },
            {
              "type": "function",
              "name": "scene.addEntity",
              "id": "fn-scene-add-entity",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:addEntity(entity [, opts]) --> integer?",
                "js": "scene.addEntity(entity: number, opts?: SceneTransform): number | null"
              },
              "summary": "Draw a ped, a vehicle or an object in the scene.",
              "md": "The entity must exist on this client: one your script created, the local player, any handle the natives give you. It is drawn with its current state, so change its clothes, paint or pose with the usual natives before a shot. The same entity can be in several scenes; a scene holds up to 32 entities.\n\nReturns `nil` / `null` with the code `not-found` when the handle is unknown, is not a ped, vehicle or object, or the scene is full.",
              "params": [
                {
                  "name": "entity",
                  "type": "handle",
                  "desc": "A ped, vehicle or object handle."
                },
                {
                  "name": "opts",
                  "type": "SceneTransform",
                  "desc": "`{ position, rotation }` in scene space, both default `{ 0, 0, 0 }`.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "integer?",
                "desc": "An id for this entity in this scene (not the entity handle)."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- A ped next to its car, both turned towards the camera.\nscene:addEntity(car, { position = { 0.6, 0, 0 }, rotation = { 0, 0, -30 } })\nscene:addEntity(ped, { position = { -1.9, 0.6, 0.05 }, rotation = { 0, 0, 20 } })"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// A ped next to its car, both turned towards the camera.\nscene.addEntity(car, { position: { x: 0.6, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: -30 } });\nscene.addEntity(ped, { position: { x: -1.9, y: 0.6, z: 0.05 }, rotation: { x: 0, y: 0, z: 20 } });"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "scene.setEntityTransform",
              "id": "fn-scene-set-entity-transform",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:setEntityTransform(id, opts) --> boolean",
                "js": "scene.setEntityTransform(id: number, opts: SceneTransform): boolean"
              },
              "summary": "Move or turn an entity of the scene.",
              "md": "Only the fields you give change. Takes the id returned by `addEntity`. Handy for turntables: turn, shoot, turn again.",
              "params": [
                {
                  "name": "id",
                  "type": "int",
                  "desc": "The id from `addEntity`."
                },
                {
                  "name": "opts",
                  "type": "SceneTransform",
                  "desc": "`{ position, rotation }`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` when applied; `false` otherwise, with the code in [`lsmp.getLastError()`](#core-utils/fn-get-last-error): `not-found`."
              }
            },
            {
              "type": "function",
              "name": "scene.removeEntity",
              "id": "fn-scene-remove-entity",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:removeEntity(id) --> boolean",
                "js": "scene.removeEntity(id: number): boolean"
              },
              "summary": "Take an entity out of the scene. The entity itself is left as it is.",
              "params": [
                {
                  "name": "id",
                  "type": "int",
                  "desc": "The id from `addEntity`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if it was in the scene."
              }
            },
            {
              "type": "function",
              "name": "scene.clearEntities",
              "id": "fn-scene-clear-entities",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:clearEntities() --> integer",
                "js": "scene.clearEntities(): number"
              },
              "summary": "Take every entity out of the scene.",
              "returns": {
                "type": "integer",
                "desc": "How many were removed."
              }
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Level of detail",
              "md": "A shot waits a few frames at most until the entities are ready: an outfit streamed, a vehicle's high-detail model loaded. An entity deleted after it was added is skipped, and counted in `missing` in the shot result."
            },
            {
              "type": "heading",
              "text": "Camera",
              "level": 2,
              "id": "scenes-camera"
            },
            {
              "type": "function",
              "name": "scene.setCamera",
              "id": "fn-scene-set-camera",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:setCamera(opts) --> boolean",
                "js": "scene.setCamera(opts: SceneCamera): boolean"
              },
              "summary": "Place the camera of the scene.",
              "md": "Only the fields you give change. Give `lookAt` to aim at a point, or `rotation` to set the angles yourself, not both in the same call. Returns `false` with the code `invalid` when the camera would look at its own position.",
              "params": [
                {
                  "name": "opts",
                  "type": "SceneCamera",
                  "desc": "See the table below."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` when applied; `false` otherwise, with the code in [`lsmp.getLastError()`](#core-utils/fn-get-last-error): `invalid`."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- A head-and-shoulders portrait of a ped standing at the origin.\nscene:configure({ width = 256, height = 256 })\nscene:setCamera({ position = { 0, 1.0, 0.62 }, lookAt = { 0, 0, 0.6 }, fov = 30 })"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// A head-and-shoulders portrait of a ped standing at the origin.\nscene.configure({ width: 256, height: 256 });\nscene.setCamera({ position: { x: 0, y: 1.0, z: 0.62 }, lookAt: { x: 0, y: 0, z: 0.6 }, fov: 30 });"
                  }
                ]
              }
            },
            {
              "type": "table",
              "headers": [
                "Option",
                "Type",
                "Default",
                "Meaning"
              ],
              "rows": [
                [
                  "`position`",
                  "vec3",
                  "`{ 0, 3, -0.1 }`",
                  "Where the camera stands."
                ],
                [
                  "`lookAt`",
                  "vec3",
                  "`{ 0, 0, -0.1 }`",
                  "The point it looks at."
                ],
                [
                  "`rotation`",
                  "rotation",
                  "",
                  "Angles in degrees, instead of `lookAt`."
                ],
                [
                  "`fov`",
                  "degrees",
                  "`40`",
                  "Vertical field of view, `1` to `170`."
                ],
                [
                  "`near`, `far`",
                  "meters",
                  "`0.05`, `500`",
                  "Clipping distances. `near` above `0`, `far` above `near`."
                ],
                [
                  "`ortho`",
                  "boolean",
                  "`false`",
                  "Orthographic projection: no perspective, for icons and blueprints."
                ],
                [
                  "`orthoHeight`",
                  "meters",
                  "`2`",
                  "With `ortho`, the height of the visible area."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Lighting",
              "level": 2,
              "id": "scenes-lighting"
            },
            {
              "type": "text",
              "md": "Light in a scene adds up from four sources: a **preset** of lights, the **ambient** light, an optional **key light**, and **your own lights**. The **exposure** scales them all. Nothing else lights the scene: no sun, no street lights, no time of day."
            },
            {
              "type": "function",
              "name": "scene.setLightPreset",
              "id": "fn-scene-set-light-preset",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:setLightPreset(preset) --> boolean",
                "js": "scene.setLightPreset(preset: string): boolean"
              },
              "summary": "Replace the lights of the scene with a ready-made set.",
              "md": "Replaces every light added with `addLight`. The ambient and key lights stay as they are.",
              "params": [
                {
                  "name": "preset",
                  "type": "string",
                  "desc": "`\"headshot\"` (the default: the lights of the game's character portraits, for a ped seen from the front), `\"studio\"` (key, fill and rim lights for a subject of about two meters, for vehicles and objects) or `\"none\"`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` when applied; `false` otherwise, with the code in [`lsmp.getLastError()`](#core-utils/fn-get-last-error)."
              }
            },
            {
              "type": "function",
              "name": "scene.setAmbient",
              "id": "fn-scene-set-ambient",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:setAmbient(opts) --> boolean",
                "js": "scene.setAmbient(opts: SceneAmbient): boolean"
              },
              "summary": "Set the light that comes from everywhere.",
              "md": "Only the fields you give change. Use `intensity = 0` for a pitch black scene lit only by your lights.",
              "params": [
                {
                  "name": "opts",
                  "type": "SceneAmbient",
                  "desc": "`color` (the same from every direction, default white), `topColor` (the light from above, default white), `intensity` (`0` to `64`, default `1`)."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` when applied; `false` otherwise, with the code in [`lsmp.getLastError()`](#core-utils/fn-get-last-error)."
              }
            },
            {
              "type": "function",
              "name": "scene.setKeyLight",
              "id": "fn-scene-set-key-light",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:setKeyLight(opts) --> boolean",
                "js": "scene.setKeyLight(opts: SceneLight | null): boolean"
              },
              "summary": "Turn on the scene's sun, or turn it off.",
              "md": "A light that comes from far away in one direction, like the sun: every entity gets it from the same side. Off by default. `nil`, `null` or `false` turns it off.",
              "params": [
                {
                  "name": "opts",
                  "type": "table?",
                  "desc": "`direction` (the direction the light **travels**, default `{ 0.4, -0.6, -0.7 }`: from the front right of the default camera, from above), `color` (default white), `intensity` (`0` to `256`, default `8`, about daylight)."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` when applied; `false` otherwise, with the code in [`lsmp.getLastError()`](#core-utils/fn-get-last-error)."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "scene:setKeyLight({ direction = { 0.5, -0.5, -0.7 }, color = \"#fff4e0\", intensity = 8 })"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "scene.setKeyLight({ direction: { x: 0.5, y: -0.5, z: -0.7 }, color: '#fff4e0', intensity: 8 });"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "scene.setExposure",
              "id": "fn-scene-set-exposure",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:setExposure(ev) --> boolean",
                "js": "scene.setExposure(ev: number): boolean"
              },
              "summary": "Brighten or darken the whole image.",
              "md": "Every light, ambient included, is multiplied by 2^`ev`: `1` doubles the light, `-1` halves it. Default `0`.",
              "params": [
                {
                  "name": "ev",
                  "type": "number",
                  "desc": "`-16` to `16`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` when applied; `false` otherwise, with the code in [`lsmp.getLastError()`](#core-utils/fn-get-last-error)."
              }
            },
            {
              "type": "function",
              "name": "scene.addLight",
              "id": "fn-scene-add-light",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:addLight([opts]) --> integer?",
                "js": "scene.addLight(opts?: SceneLight): number | null"
              },
              "summary": "Add a point, spot or capsule light.",
              "md": "Lights live in the scene's space, like the entities. A scene holds up to 32 lights; only the first 8 also light glass and other transparent surfaces. Returns `nil` / `null` with the code `limit` when the scene is full.",
              "params": [
                {
                  "name": "opts",
                  "type": "SceneLight",
                  "desc": "See the table below.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "integer?",
                "desc": "The id of the light."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- A warm spot above the car, a cold light behind the ped.\nscene:setLightPreset(\"none\")\nscene:addLight({ type = \"spot\", position = { 0.6, 2.5, 3.5 }, direction = { 0, -0.55, -0.83 },\n  color = \"#ff8030\", intensity = 30, range = 15, innerAngle = 12, outerAngle = 28 })\nscene:addLight({ position = { -2, -1.5, 1.5 }, color = \"#80b0ff\", intensity = 10 })"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// A warm spot above the car, a cold light behind the ped.\nscene.setLightPreset('none');\nscene.addLight({ type: 'spot', position: { x: 0.6, y: 2.5, z: 3.5 }, direction: { x: 0, y: -0.55, z: -0.83 },\n  color: '#ff8030', intensity: 30, range: 15, innerAngle: 12, outerAngle: 28 });\nscene.addLight({ position: { x: -2, y: -1.5, z: 1.5 }, color: '#80b0ff', intensity: 10 });"
                  }
                ]
              }
            },
            {
              "type": "table",
              "headers": [
                "Option",
                "Type",
                "Default",
                "Meaning"
              ],
              "rows": [
                [
                  "`type`",
                  "string",
                  "`\"point\"`",
                  "`\"point\"`, `\"spot\"` or `\"capsule\"` (a light along a segment, like a neon tube)."
                ],
                [
                  "`position`",
                  "vec3",
                  "`{ 0, 2.5, 1.5 }`",
                  "In front of the subject, above it."
                ],
                [
                  "`direction`",
                  "vec3",
                  "towards the origin",
                  "Spot: where it points. Capsule: the axis of the tube."
                ],
                [
                  "`color`",
                  "color",
                  "white",
                  ""
                ],
                [
                  "`intensity`",
                  "number",
                  "`4`",
                  "`0` to `1024`."
                ],
                [
                  "`range`",
                  "meters",
                  "`10`",
                  "Reach, `0.01` to `1000`: nothing is lit beyond it."
                ],
                [
                  "`falloff`",
                  "number",
                  "`8`",
                  "How the light fades towards `range`, `0.01` to `64`: high values keep it strong, then fade it quickly near the edge."
                ],
                [
                  "`innerAngle`, `outerAngle`",
                  "degrees",
                  "`20`, `35`",
                  "Spot: half-angles of the cone, `0` to `89.9`. Full light inside `innerAngle`, none beyond `outerAngle`."
                ],
                [
                  "`length`",
                  "meters",
                  "`1`",
                  "Capsule: length of the tube, `0` to `1000`."
                ]
              ]
            },
            {
              "type": "function",
              "name": "scene.updateLight",
              "id": "fn-scene-update-light",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:updateLight(id, opts) --> boolean",
                "js": "scene.updateLight(id: number, opts: SceneLight): boolean"
              },
              "summary": "Change a light added with `addLight`. Only the fields you give change.",
              "params": [
                {
                  "name": "id",
                  "type": "int",
                  "desc": "The id from `addLight`."
                },
                {
                  "name": "opts",
                  "type": "SceneLight",
                  "desc": "The fields to change."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` when applied; `false` otherwise, with the code in [`lsmp.getLastError()`](#core-utils/fn-get-last-error): `not-found`."
              }
            },
            {
              "type": "function",
              "name": "scene.removeLight",
              "id": "fn-scene-remove-light",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:removeLight(id) --> boolean",
                "js": "scene.removeLight(id: number): boolean"
              },
              "summary": "Remove a light added with `addLight`.",
              "params": [
                {
                  "name": "id",
                  "type": "int",
                  "desc": "The id from `addLight`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if the light existed."
              }
            },
            {
              "type": "function",
              "name": "scene.clearLights",
              "id": "fn-scene-clear-lights",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:clearLights() --> integer",
                "js": "scene.clearLights(): number"
              },
              "summary": "Remove every light, those of the preset included. The ambient and key lights stay.",
              "returns": {
                "type": "integer",
                "desc": "How many lights added with `addLight` were removed."
              }
            },
            {
              "type": "heading",
              "text": "Shots",
              "level": 2,
              "id": "scenes-shots"
            },
            {
              "type": "function",
              "name": "scene.shot",
              "id": "fn-scene-shot",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:shot([opts] [, cb]) --> ShotResult, err",
                "js": "scene.shot(opts?: ShotOptions): Promise<ShotResult>"
              },
              "summary": "Render the scene to an image.",
              "md": "A shot renders the scene **as it is when the frame is drawn**, usually the frame of the request: to shoot several variations (angles, colors, outfits), wait for each result before changing the scene. It usually takes one or two frames. A scene keeps up to 4 shots in flight. Without `width` and `height` the image has the size of the scene ([`configure`](#scenes/fn-scene-configure)). Asynchronous: see [Conventions](#conventions); the Promise carries `promise.jobId`.\n\nFailure codes: `limit` (too many shots in flight), `unavailable` (the game is not ready to render), `cancelled` (the scene was destroyed first), `error` (rendering or encoding failed). See [Error codes](#error-codes).",
              "params": [
                {
                  "name": "opts",
                  "type": "ShotOptions",
                  "desc": "`width` and `height` (`16` to `4096`, default the size of the scene), `format` (`\"png\"`, `\"jpeg\"` or `\"webp\"`, default `\"webp\"`), `quality` (JPEG and WebP, `0` to `100`, default `90`; WebP at `100` is lossless), `dataUrl` (also return a `data:` URL, default `false`), `settleFrames` (frames rendered before the image, `0` to `30`, default `2`).",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "ShotResult, err",
                  "desc": "The result below, or `nil` and a code.",
                  "only": "lua"
                },
                {
                  "type": "Promise<ShotResult>",
                  "desc": "Resolves with the result below; rejects with a code.",
                  "only": "js"
                }
              ],
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Field",
                    "Type",
                    "Meaning"
                  ],
                  "rows": [
                    [
                      "`width`, `height`",
                      "int",
                      "Size of the image."
                    ],
                    [
                      "`format`",
                      "string",
                      "The format of `data`."
                    ],
                    [
                      "`data`",
                      "bytes",
                      "The encoded image: a string in Lua, a `Uint8Array` in JavaScript."
                    ],
                    [
                      "`dataUrl`",
                      "string?",
                      "The data URL when asked for; `nil` / `null` otherwise."
                    ],
                    [
                      "`entities`",
                      "int",
                      "Entities drawn in the image."
                    ],
                    [
                      "`missing`",
                      "int",
                      "Entities of the scene that no longer exist, skipped."
                    ],
                    [
                      "`frames`",
                      "int",
                      "Frames the shot waited before it was rendered."
                    ],
                    [
                      "`ms`",
                      "ms",
                      "Time from the request to the image."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- A turntable: eight angles of the same car, one after the other.\nlocal id = scene:addEntity(car)\nlocal frames = {}\nfor i = 0, 7 do\n  scene:setEntityTransform(id, { rotation = { 0, 0, i * 45 } })\n  local res = scene:shot({ format = \"jpeg\", quality = 90 })\n  if res then frames[#frames + 1] = res.data end\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// A turntable: eight angles of the same car, one after the other.\nasync function turntable(scene, car) {\n  const id = scene.addEntity(car);\n  const frames = [];\n  for (let i = 0; i < 8; i++) {\n    scene.setEntityTransform(id, { rotation: { x: 0, y: 0, z: i * 45 } });\n    const res = await scene.shot({ format: 'jpeg', quality: 90 });\n    frames.push(res.data);\n  }\n  return frames;\n}"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Live rendering",
              "level": 2,
              "id": "scenes-live"
            },
            {
              "type": "text",
              "md": "A scene can also render **continuously**, into a texture that stays on the graphics card: nothing is read back or encoded. Use it for a car turning in a dealership menu, a character preview next to a clothing shop, a security camera on a TV. Two ways to show the image, together or not:"
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "**On the screen**: [`setOverlay`](#scenes/fn-scene-set-overlay) draws it in a rectangle, above the game's HUD and below LS:MP pages.",
                "**As a game texture**: [`getTexture`](#scenes/fn-scene-get-texture) returns a texture for [`lsmp.replaceTexture`](#textures/fn-replace-texture). The image then shows wherever the game draws the texture it replaces: a surface of the world, or a sprite."
              ]
            },
            {
              "type": "text",
              "md": "Every change to the scene shows in the next live frame, and the entities keep the animation they have in the world. The image has **premultiplied alpha**: a transparent background stays transparent."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- A live preview of the player's car, turning, bottom right of the screen.\nlocal scene = lsmp.createScene({ width = 512, height = 288 })\nscene:setLightPreset(\"studio\")\nlocal car = scene:addEntity(getVehiclePedIsIn(playerPedId(), false))\nscene:setCamera({ position = { 0, 6.5, 1.6 }, lookAt = { 0, 0, 0.2 }, fov = 40 })\n\nscene:enableRender(true, { fps = 30 })\nscene:setOverlay({ bounds = { x = 0.73, y = 0.72, width = 0.25, height = 0.25 } })\n\nlsmp.onTick(function()\n  if scene:isValid() then\n    scene:setEntityTransform(car, { rotation = { 0, 0, (lsmp.getTickCount() / 20) % 360 } })\n  end\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// A live preview of the player's car, turning, bottom right of the screen.\nconst scene = lsmp.createScene({ width: 512, height: 288 });\nscene.setLightPreset('studio');\nconst car = scene.addEntity(getVehiclePedIsIn(playerPedId(), false));\nscene.setCamera({ position: { x: 0, y: 6.5, z: 1.6 }, lookAt: { x: 0, y: 0, z: 0.2 }, fov: 40 });\n\nscene.enableRender(true, { fps: 30 });\nscene.setOverlay({ bounds: { x: 0.73, y: 0.72, width: 0.25, height: 0.25 } });\n\nlsmp.onTick(() => {\n  if (scene.isValid()) {\n    scene.setEntityTransform(car, { rotation: { x: 0, y: 0, z: (lsmp.getTickCount() / 20) % 360 } });\n  }\n});"
                }
              ]
            },
            {
              "type": "function",
              "name": "scene.enableRender",
              "id": "fn-scene-enable-render",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:enableRender(enabled [, opts]) --> boolean",
                "js": "scene.enableRender(enabled: boolean, opts?: RenderOptions): boolean"
              },
              "summary": "Start or stop rendering the scene live.",
              "md": "The first call creates the scene's texture; calling it again changes the rate. `enableRender(false)` stops rendering but keeps the last image: the texture and the overlay still show it.",
              "params": [
                {
                  "name": "enabled",
                  "type": "boolean",
                  "desc": "`true` to render, `false` to stop."
                },
                {
                  "name": "opts",
                  "type": "RenderOptions",
                  "desc": "`fps`: frames per second, `1` to `60`, default `30`.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` when applied; `false` otherwise, with the code in [`lsmp.getLastError()`](#core-utils/fn-get-last-error): `limit` (8 scenes already render live), `unavailable`, `error`."
              }
            },
            {
              "type": "function",
              "name": "scene.invalidate",
              "id": "fn-scene-invalidate",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:invalidate() --> boolean",
                "js": "scene.invalidate(): boolean"
              },
              "summary": "Ask for one more live frame as soon as possible.",
              "md": "Useful with a low `fps` when you just changed something and want it on screen at once. Several calls in the same frame render once.",
              "returns": {
                "type": "boolean",
                "desc": "`false` if the scene does not render live."
              }
            },
            {
              "type": "function",
              "name": "scene.getTexture",
              "id": "fn-scene-get-texture",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:getTexture() --> integer?",
                "js": "scene.getTexture(): number | null"
              },
              "summary": "The texture the scene renders into, for `lsmp.replaceTexture`.",
              "md": "Available after the first `enableRender`; it then stays the same for the life of the scene, even when `configure` changes its size. The scene owns it: destroying the scene restores every replacement and frees it.",
              "returns": {
                "type": "integer?",
                "desc": "A texture handle, or `nil` / `null` before `enableRender`."
              }
            },
            {
              "type": "function",
              "name": "scene.setOverlay",
              "id": "fn-scene-set-overlay",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:setOverlay(opts) --> boolean",
                "js": "scene.setOverlay(opts: SceneOverlay | boolean): boolean"
              },
              "summary": "Show the live image on the screen.",
              "md": "LS:MP draws the image in a rectangle, above the game's HUD and below LS:MP pages. `true` / `false` shows or hides it; a table changes the fields it gives, and sets `visible` back to `true` unless it says otherwise. The overlay shows the scene only once it has an image: enable live rendering first.",
              "params": [
                {
                  "name": "opts",
                  "type": "SceneOverlay | boolean",
                  "desc": "`visible` (default `true`), `bounds` (`{ x, y, width, height }` as **fractions of the game's screen**: `0` is the left or top edge, `1` the right or bottom one; default a quarter of the screen at the top left), `zIndex` (between overlays: the highest is drawn on top, default `0`)."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` when applied; `false` otherwise, with the code in [`lsmp.getLastError()`](#core-utils/fn-get-last-error): `limit`, `unavailable`, `error`."
              }
            },
            {
              "type": "function",
              "name": "scene.getRenderInfo",
              "id": "fn-scene-get-render-info",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:getRenderInfo() --> SceneRenderInfo?",
                "js": "scene.getRenderInfo(): SceneRenderInfo | null"
              },
              "summary": "How the live rendering is doing.",
              "returns": {
                "type": "SceneRenderInfo?",
                "desc": "`nil` / `null` when the scene does not render live. Fields: `enabled`, `fps` (frames actually rendered per second), `frames` (live frames since creation), `skipped` (frames where the scene waited its turn because the live scenes together went over the per-frame budget), `gpuMs` (graphics-card time of one render), `texture`, `width`, `height`, `overlay` (shown or not)."
              }
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "What it costs",
              "md": "A live scene costs the graphics card in proportion to its **rendered** pixels, `width × supersample` by `height × supersample`. Pick the smallest size and supersampling that look right, lower `fps` when the image moves slowly, and read `getRenderInfo().gpuMs` for the cost on the player's machine."
            },
            {
              "type": "heading",
              "text": "Destroying a scene",
              "level": 2,
              "id": "scenes-destroy"
            },
            {
              "type": "function",
              "name": "scene.destroy",
              "id": "fn-scene-destroy",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:destroy()",
                "js": "scene.destroy(): void"
              },
              "summary": "Destroy the scene and give its memory back.",
              "md": "Shots still in flight reject with `cancelled`. The entities are left as they are in the world. Live rendering stops: the overlay disappears, and every game texture replaced with the scene's texture gets its original back."
            },
            {
              "type": "function",
              "name": "scene.isValid",
              "id": "fn-scene-is-valid",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "scene:isValid() --> boolean",
                "js": "scene.isValid(): boolean"
              },
              "summary": "`false` once the scene was destroyed, by the script or because its resource stopped.",
              "returns": {
                "type": "boolean",
                "desc": ""
              }
            },
            {
              "type": "text",
              "md": "On a destroyed scene, methods do nothing and return `false`, `nil` / `null` or `0`, with the code `not-found`. A scene of another resource raises an `Error`."
            },
            {
              "type": "heading",
              "text": "Game textures",
              "level": 2,
              "id": "scenes-textures"
            },
            {
              "type": "text",
              "md": "The texture of a scene that renders live ([`scene.getTexture`](#scenes/fn-scene-get-texture)) is a **texture handle** like any other: [`lsmp.replaceTexture`](#textures/fn-replace-texture) shows it in place of a texture of the game. The handle belongs to the scene and goes with it: `lsmp.releaseTexture` refuses it. See [Textures](#textures)."
            },
            {
              "type": "heading",
              "text": "Limits",
              "level": 2,
              "id": "scenes-limits"
            },
            {
              "type": "table",
              "headers": [
                "Limit",
                "Value"
              ],
              "rows": [
                [
                  "Scenes",
                  "8 per resource, 16 on the client"
                ],
                [
                  "Pixels, all scenes together",
                  "About 8 million, counted at the rendered size (`width × supersample` by `height × supersample`)"
                ],
                [
                  "Entities per scene",
                  "32"
                ],
                [
                  "Lights per scene",
                  "32, the key light included; 8 of them light transparent surfaces"
                ],
                [
                  "Shots in flight",
                  "4 per scene"
                ],
                [
                  "Scenes rendering live",
                  "8 on the client; beyond the per-frame pixel budget, live scenes take turns (`skipped`)"
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "When the resource stops",
              "md": "Its scenes are destroyed, its texture replacements are restored, and the Promises or callbacks of pending shots never complete."
            }
          ]
        },
        {
          "id": "textures",
          "title": "Textures",
          "eyebrow": "Client · Lua & JS",
          "lead": "Make a texture from an image file, from downloaded data or from pixels you compute, then show it in place of a texture of the game: a billboard, a poster, a vehicle livery, a sprite on screen.",
          "blocks": [
            {
              "type": "text",
              "md": "A **texture handle** is an image owned by your resource, kept on the graphics card. A handle comes from one of three places:\n\n- [`lsmp.createTexture`](#textures/fn-create-texture): a still image, from a file or from pixels;\n- a [3D browser](#browsers/browsers-3d): a web page, repainted as it changes;\n- a [scene](#scenes/scenes-live) that renders live.\n\nWhatever its origin, [`lsmp.replaceTexture`](#textures/fn-replace-texture) shows it in place of a texture of the game."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- The logo of the server on a billboard of the map.\nlocal logo, err = lsmp.createTexture({ file = \"img/logo.png\" })\nif not logo then return lsmp.warn(\"no texture: \" .. err) end\n\nlsmp.replaceTexture(logo, {\n  type = \"txd\", container = \"cs4_02_build_1\", name = \"cs4_02_rsl_mr_bb\",\n})"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// The logo of the server on a billboard of the map.\nconst logo = lsmp.createTexture({ file: 'img/logo.png' });\nif (logo === null) {\n  lsmp.warn(`no texture: ${lsmp.getLastError()}`);\n} else {\n  lsmp.replaceTexture(logo, {\n    type: 'txd', container: 'cs4_02_build_1', name: 'cs4_02_rsl_mr_bb',\n  });\n}"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Creating a texture",
              "level": 2,
              "id": "textures-create"
            },
            {
              "type": "function",
              "name": "lsmp.createTexture",
              "id": "fn-create-texture",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.createTexture(source) --> integer?",
                "js": "lsmp.createTexture(source: TextureSource): number | null"
              },
              "summary": "Make a texture from an image file, from the content of an image file or from raw pixels.",
              "md": "Give it **exactly one** source:\n\n- `file`: an image file shipped with your resource, with a path relative to the resource root. List the file in `files` of the [manifest](#resource-layout) so that players receive it.\n- `data`: the content of an image file that you already hold, for instance the body of an [HTTP response](#http).\n- `pixels`: pixels that you computed, with `width` and `height`.\n\nThe handle is returned at once, and you can give it to `replaceTexture` right away. The image itself is decoded in the background, so even a large file does not freeze the game. A replacement shows once the image is ready, never a blank texture in the meantime. [`getTextureInfo`](#textures/fn-get-texture-info) tells where the image stands.\n\nFailure codes: `not-found` (no such file in the resource), `invalid` (not a PNG, JPEG, WebP or DDS image that can be read), `limit` (larger than 4096 pixels on a side, over a [limit](#textures/textures-limits) of the resource, or more than the game can upload at once), `unavailable` (the game is not ready yet). See [Error codes](#error-codes).",
              "params": [
                {
                  "name": "source",
                  "type": "TextureSource",
                  "desc": "Where the image comes from: `{ file }`, `{ data }` or `{ pixels, width, height, format }`. See the table below."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The texture handle, or `nil` and a code.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The texture handle, or `null` with the code in `lsmp.getLastError()`.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- An image downloaded while the server runs.\nlsmp.http.get(\"https://example.com/banner.webp\", { responseType = \"bytes\" }, function(res, err)\n  if not res or not res.ok then return lsmp.warn(\"no banner\") end\n  local banner, code = lsmp.createTexture({ data = res.body })\n  if not banner then lsmp.warn(\"banner refused: \" .. code) end\nend)\n\n-- A 64 x 64 checkerboard built pixel by pixel: red, green, blue, alpha.\nlocal size, rows = 64, {}\nfor y = 0, size - 1 do\n  local row = {}\n  for x = 0, size - 1 do\n    local white = (math.floor(x / 8) + math.floor(y / 8)) % 2 == 0\n    row[#row + 1] = white and \"\\255\\255\\255\\255\" or \"\\30\\30\\30\\255\"\n  end\n  rows[#rows + 1] = table.concat(row)\nend\nlocal checker = lsmp.createTexture({ pixels = table.concat(rows), width = size, height = size })"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// An image downloaded while the server runs.\nasync function loadBanner() {\n  const res = await lsmp.http.get('https://example.com/banner.webp', { responseType: 'bytes' });\n  if (!res.ok) return null;\n  const banner = lsmp.createTexture({ data: res.body });\n  if (banner === null) lsmp.warn(`banner refused: ${lsmp.getLastError()}`);\n  return banner;\n}\n\n// A 64 x 64 checkerboard built pixel by pixel: red, green, blue, alpha.\nconst size = 64;\nconst pixels = new Uint8Array(size * size * 4);\nfor (let y = 0; y < size; y++) {\n  for (let x = 0; x < size; x++) {\n    const white = ((x >> 3) + (y >> 3)) % 2 === 0;\n    pixels.set(white ? [255, 255, 255, 255] : [30, 30, 30, 255], (y * size + x) * 4);\n  }\n}\nconst checker = lsmp.createTexture({ pixels, width: size, height: size });"
                  }
                ]
              }
            },
            {
              "type": "table",
              "headers": [
                "Field of the source",
                "Type",
                "Meaning"
              ],
              "rows": [
                [
                  "`file`",
                  "string",
                  "Path of an image file of this resource, relative to its root, with `/` separators and no `..`."
                ],
                [
                  "`data`",
                  "bytes",
                  "The content of a PNG, JPEG, WebP or DDS file: a string in Lua, a `Uint8Array` or an `ArrayBuffer` in JavaScript."
                ],
                [
                  "`pixels`",
                  "bytes",
                  "Raw pixels, 4 bytes each, rows from top to bottom, without padding: exactly `width * height * 4` bytes."
                ],
                [
                  "`width`, `height`",
                  "integer",
                  "Size of `pixels`, `1` to `4096` each. Required with `pixels`, refused otherwise."
                ],
                [
                  "`format`",
                  "string",
                  "Byte order of `pixels`: `\"rgba\"` (the default) or `\"bgra\"`."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Image files",
              "level": 3,
              "id": "textures-formats"
            },
            {
              "type": "text",
              "md": "The type of an image is recognized from its content, not from its file name."
            },
            {
              "type": "table",
              "headers": [
                "Format",
                "What is read"
              ],
              "rows": [
                [
                  "PNG",
                  "Every color type and bit depth, with transparency."
                ],
                [
                  "JPEG",
                  "Baseline and progressive, 8 bits per channel."
                ],
                [
                  "WebP",
                  "Lossy and lossless, with transparency. Animated WebP files are refused."
                ],
                [
                  "DDS",
                  "Uncompressed 8, 16, 24 and 32 bit formats, and the block compressed formats DXT1, DXT3, DXT5 (BC1 to BC3), BC4, BC5 and BC7. Cube maps, volume textures, texture arrays, BC6H and floating point formats are refused."
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "What the game gets",
              "md": "Every image becomes an uncompressed texture, 8 bits per channel with an alpha channel, at the size of the image and **without mipmaps**. Of a DDS file, only the largest level is read. Keep the image close to the size it has on screen: a 4096 pixel image on a small sign takes 64 MiB of video memory and shimmers from far away. Transparency is plain alpha, not premultiplied."
            },
            {
              "type": "function",
              "name": "lsmp.getTextureInfo",
              "id": "fn-get-texture-info",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.getTextureInfo(texture) --> TextureInfo?",
                "js": "lsmp.getTextureInfo(texture: number): TextureInfo | null"
              },
              "summary": "Size and state of a texture of this resource.",
              "md": "Works on every texture handle of the resource, the one of a 3D browser or of a scene included. `state` is:\n\n- `\"loading\"`: the image is still being decoded or sent to the graphics card;\n- `\"ready\"`: the texture shows its image;\n- `\"failed\"`: the image was damaged and could not be decoded. The texture stays valid but is never shown; release it.\n\nThe texture of a 3D browser or of a scene is always `\"ready\"`.",
              "params": [
                {
                  "name": "texture",
                  "type": "int",
                  "desc": "A texture handle of this resource."
                }
              ],
              "returns": [
                {
                  "type": "TextureInfo?",
                  "desc": "`{ width, height, state }`, or `nil` and `not-found` when the handle is unknown or belongs to another resource.",
                  "only": "lua"
                },
                {
                  "type": "TextureInfo | null",
                  "desc": "`{ width, height, state }`, or `null` with `not-found` when the handle is unknown or belongs to another resource.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- Say so when the file shipped with the resource is damaged.\nlocal logo = lsmp.createTexture({ file = \"img/logo.png\" })\nsetTimeout(function()\n  local info = logo and lsmp.getTextureInfo(logo)\n  if info and info.state == \"failed\" then\n    lsmp.warn(\"img/logo.png cannot be read\")\n  end\nend, 3000)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// Say so when the file shipped with the resource is damaged.\nconst logo = lsmp.createTexture({ file: 'img/logo.png' });\nsetTimeout(() => {\n  const info = logo === null ? null : lsmp.getTextureInfo(logo);\n  if (info && info.state === 'failed') lsmp.warn('img/logo.png cannot be read');\n}, 3000);"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.releaseTexture",
              "id": "fn-release-texture",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.releaseTexture(texture) --> boolean",
                "js": "lsmp.releaseTexture(texture: number): boolean"
              },
              "summary": "Free a texture made by `createTexture`, restoring every replacement that used it.",
              "md": "Only the textures you made with `createTexture` can be released. The texture of a 3D browser or of a scene belongs to it and is freed when you destroy the browser or the scene: releasing it is refused with `permission`.\n\nFailure codes: `not-found` (unknown handle, already released, or a texture of another resource), `permission`.",
              "params": [
                {
                  "name": "texture",
                  "type": "int",
                  "desc": "A handle returned by `createTexture`."
                }
              ],
              "returns": [
                {
                  "type": "boolean",
                  "desc": "`true` when the texture was freed; `false` and a code otherwise.",
                  "only": "lua"
                },
                {
                  "type": "boolean",
                  "desc": "`true` when the texture was freed; `false` otherwise, with the code in `lsmp.getLastError()`.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Showing a texture in the game",
              "level": 2,
              "id": "textures-replace"
            },
            {
              "type": "text",
              "md": "A replacement names a texture of the game by its container (the `.ytd`, `.ydr`, `.ydd` or `.yft` file that holds it, without extension) and its name, as a model viewer shows them. Every surface that uses that texture then shows yours."
            },
            {
              "type": "function",
              "name": "lsmp.replaceTexture",
              "id": "fn-replace-texture",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.replaceTexture(texture, target) --> integer?",
                "js": "lsmp.replaceTexture(texture: number, target: TextureTarget): number | null"
              },
              "summary": "Show a texture handle in place of a texture of the game.",
              "md": "The replacement applies whenever the game has the target loaded, and again each time it streams back in. Binding the same texture to the same target twice returns the same id. To draw the image as a sprite, replace a texture of a dictionary that you load and draw yourself.\n\nFailure codes: `not-found` (unknown texture handle, or target that cannot be replaced), `permission` (a texture of another resource). See [Error codes](#error-codes).",
              "params": [
                {
                  "name": "texture",
                  "type": "int",
                  "desc": "A texture handle of this resource."
                },
                {
                  "name": "target",
                  "type": "TextureTarget",
                  "desc": "`{ type, container, name }`: `type` is `\"txd\"` (a texture dictionary, `.ytd`), `\"drawable\"` (`.ydr`), `\"drawabledict\"` (`.ydd`) or `\"fragment\"` (`.yft`); `container` is the name of the file without extension; `name` is the texture inside it."
                }
              ],
              "returns": [
                {
                  "type": "integer?",
                  "desc": "The id of the replacement, or `nil` and a code.",
                  "only": "lua"
                },
                {
                  "type": "number | null",
                  "desc": "The id of the replacement, or `null` with the code in `lsmp.getLastError()`.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- Use a configured scene as a live texture in the world.\nif scene:enableRender(true) then\n  local texture = scene:getTexture()\n  if texture then\n    lsmp.replaceTexture(texture, {\n      type = \"txd\", container = \"cs4_02_build_1\", name = \"cs4_02_rsl_mr_bb\",\n    })\n  end\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// Use a configured scene as a live texture in the world.\nif (scene.enableRender(true)) {\n  const texture = scene.getTexture();\n  if (texture !== null) {\n    lsmp.replaceTexture(texture, {\n      type: 'txd', container: 'cs4_02_build_1', name: 'cs4_02_rsl_mr_bb',\n    });\n  }\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.restoreTexture",
              "id": "fn-restore-texture",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.restoreTexture(bindId) --> boolean",
                "js": "lsmp.restoreTexture(bindId: number): boolean"
              },
              "summary": "Give the game its original texture back.",
              "params": [
                {
                  "name": "bindId",
                  "type": "int",
                  "desc": "The id returned by `replaceTexture`."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`false` when the id is unknown or belongs to another resource."
              }
            },
            {
              "type": "heading",
              "text": "Drawing a texture on screen",
              "level": 2,
              "id": "textures-draw"
            },
            {
              "type": "text",
              "md": "The game draws sprites from texture dictionaries. To draw your own image, ship a small dictionary in your resource (see [Assets and streaming](#streaming)) with a placeholder texture, replace the placeholder, then draw the sprite every frame."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- my_hud.ytd is shipped by the resource and holds a texture named \"slot\".\nlocal badge = lsmp.createTexture({ file = \"img/badge.png\" })\nif badge then\n  requestStreamedTextureDict(\"my_hud\", false)\n  lsmp.replaceTexture(badge, { type = \"txd\", container = \"my_hud\", name = \"slot\" })\n\n  lsmp.onTick(function()\n    if hasStreamedTextureDictLoaded(\"my_hud\") then\n      drawSprite(\"my_hud\", \"slot\", 0.9, 0.12, 0.08, 0.14, 0.0, 255, 255, 255, 255, false, 0)\n    end\n  end)\nend"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// my_hud.ytd is shipped by the resource and holds a texture named 'slot'.\nconst badge = lsmp.createTexture({ file: 'img/badge.png' });\nif (badge !== null) {\n  requestStreamedTextureDict('my_hud', false);\n  lsmp.replaceTexture(badge, { type: 'txd', container: 'my_hud', name: 'slot' });\n\n  lsmp.onTick(() => {\n    if (hasStreamedTextureDictLoaded('my_hud')) {\n      drawSprite('my_hud', 'slot', 0.9, 0.12, 0.08, 0.14, 0.0, 255, 255, 255, 255, false, 0);\n    }\n  });\n}"
                }
              ]
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "A page is often simpler",
              "md": "For an interface, a [web page](#web-ui) drawn over the game does the same with HTML and CSS. A sprite is the right tool when the image must go through the game itself: a marker in the world, or an image drawn behind the HUD."
            },
            {
              "type": "heading",
              "text": "Limits",
              "level": 2,
              "id": "textures-limits"
            },
            {
              "type": "table",
              "headers": [
                "Limit",
                "Value"
              ],
              "rows": [
                [
                  "Size of an image",
                  "4096 pixels on a side"
                ],
                [
                  "Size of an image file (`file`, `data`)",
                  "96 MiB"
                ],
                [
                  "Textures made by `createTexture`",
                  "256 per resource"
                ],
                [
                  "Pixels of those textures",
                  "256 MiB per resource, counted as `width * height * 4` bytes"
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "When the resource stops",
              "md": "Its textures are freed and its replacements are restored: the game shows its own textures again."
            }
          ]
        },
        {
          "id": "capture",
          "title": "Camera capture",
          "eyebrow": "Client · Lua & JS",
          "lead": "Render a scripted camera to an image the player never sees: portraits, thumbnails, a character on a transparent background.",
          "blocks": [
            {
              "type": "text",
              "md": "`lsmp.captureCamera` renders a scripted camera **through the game**, at full quality, during a frame the player does not see: their screen keeps the previous image for that frame. The image is resized, encoded and handed to your script as bytes, or as a data URL ready for a [page](#browsers).\n\nTo shoot only chosen entities in a studio of their own, with no map around them, use [render scenes](#scenes) instead."
            },
            {
              "type": "function",
              "name": "lsmp.captureCamera",
              "id": "fn-capture-camera",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.captureCamera(camera [, opts] [, cb]) --> CaptureResult, err",
                "js": "lsmp.captureCamera(camera: number, opts?: CaptureOptions): Promise<CaptureResult>"
              },
              "summary": "Capture what a scripted camera sees.",
              "md": "The capture takes a few frames. Asynchronous: see [Conventions](#conventions). The Promise carries the capture number in `promise.jobId`; in Lua, the callback form returns it.\n\nFailure codes: `not-found` (unknown or destroyed camera), `limit` (too many captures queued, for this resource or for the client), `cancelled` (the capture was dropped, for instance the resource is stopping), `error` (anything else: the game was paused or loading for too long, the resolution changed, encoding failed, capture switched off in the player's settings). The error message gives the precise reason. See [Error codes](#error-codes).",
              "params": [
                {
                  "name": "camera",
                  "type": "handle",
                  "desc": "A scripted camera, from `createCam`, `createCamWithParams` and the camera natives."
                },
                {
                  "name": "opts",
                  "type": "CaptureOptions",
                  "desc": "See [the options](#capture/capture-options).",
                  "optional": true
                }
              ],
              "returns": [
                {
                  "type": "CaptureResult, err",
                  "desc": "The [result](#capture/capture-result), or `nil` and a code.",
                  "only": "lua"
                },
                {
                  "type": "Promise<CaptureResult>",
                  "desc": "Resolves with the [result](#capture/capture-result); rejects with a code.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- A 256 x 256 portrait of the local player, shown in our page.\nlocal function portrait(browser)\n  local ped = playerPedId()\n  local pos = getEntityCoords(ped, false)\n  local heading = getEntityHeading(ped)\n  local rad = math.rad(heading)\n  local cam = createCamWithParams(\"DEFAULT_SCRIPTED_CAMERA\",\n    pos.x - math.sin(rad) * 1.2, pos.y + math.cos(rad) * 1.2, pos.z + 0.6,\n    0.0, 0.0, heading + 180.0, 35.0, false, 0)\n\n  local res, err = lsmp.captureCamera(cam, { width = 256, height = 256, dataUrl = true })\n  destroyCam(cam, false)\n  if res then\n    browser:emit(\"portrait\", res.dataUrl)\n  else\n    lsmp.warn(\"capture failed: \" .. err)\n  end\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// A 256 x 256 portrait of the local player, shown in our page.\nasync function portrait(browser) {\n  const ped = playerPedId();\n  const pos = getEntityCoords(ped, false);\n  const heading = getEntityHeading(ped);\n  const rad = heading * Math.PI / 180;\n  const cam = createCamWithParams('DEFAULT_SCRIPTED_CAMERA',\n    pos.x - Math.sin(rad) * 1.2, pos.y + Math.cos(rad) * 1.2, pos.z + 0.6,\n    0.0, 0.0, heading + 180.0, 35.0, false, 0);\n\n  try {\n    const res = await lsmp.captureCamera(cam, { width: 256, height: 256, dataUrl: true });\n    browser.emit('portrait', res.dataUrl);\n  } catch (err) {\n    lsmp.warn(`capture failed: ${err.code}`);\n  } finally {\n    destroyCam(cam, false);\n  }\n}"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Options",
              "level": 2,
              "id": "capture-options"
            },
            {
              "type": "table",
              "headers": [
                "Option",
                "Type",
                "Default",
                "Meaning"
              ],
              "rows": [
                [
                  "`width`, `height`",
                  "int",
                  "`512`",
                  "Output size in pixels, `16` to `4096`."
                ],
                [
                  "`format`",
                  "string",
                  "`\"webp\"`",
                  "`\"png\"`, `\"jpeg\"` or `\"webp\"`. WebP keeps the transparency of PNG at a fraction of its size."
                ],
                [
                  "`quality`",
                  "int",
                  "`90`",
                  "JPEG and WebP quality, `0` to `100`. WebP at `100` is lossless."
                ],
                [
                  "`settleFrames`",
                  "int",
                  "`2`",
                  "Frames rendered **before** the shot, `0` to `30`, so that streaming and exposure settle after the camera moved."
                ],
                [
                  "`fov`",
                  "degrees",
                  "the camera's",
                  "Vertical field of view of the image, above `0` and below `180`."
                ],
                [
                  "`dataUrl`",
                  "boolean",
                  "`false`",
                  "Also return a `data:image/...;base64,...` URL, ready for an `<img>` in a page."
                ],
                [
                  "`chromaKey`",
                  "boolean | color | table",
                  "off",
                  "`true` makes a green background transparent. A [color](#conventions) picks the color to remove. A table `{ color, similarity, smoothness, spill }` tunes it: the three numbers are `0` to `1`, defaults `0.4`, `0.08` and `0.1`. Only useful with `png` or `webp`."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Result",
              "level": 2,
              "id": "capture-result"
            },
            {
              "type": "table",
              "headers": [
                "Field",
                "Type",
                "Meaning"
              ],
              "rows": [
                [
                  "`width`, `height`",
                  "int",
                  "Size of the image."
                ],
                [
                  "`format`",
                  "string",
                  "The format of `data`."
                ],
                [
                  "`data`",
                  "bytes",
                  "The encoded image: a string in Lua, a `Uint8Array` in JavaScript."
                ],
                [
                  "`dataUrl`",
                  "string?",
                  "The data URL when `dataUrl` was asked for; `nil` / `null` otherwise."
                ],
                [
                  "`sourceWidth`, `sourceHeight`",
                  "int",
                  "Size of the region of the frame that was read."
                ],
                [
                  "`upscaled`",
                  "boolean",
                  "`true` when the output is larger than that region: ask for a smaller size, or play at a higher resolution, for a sharper image."
                ],
                [
                  "`frames`",
                  "int",
                  "Frames the capture took."
                ],
                [
                  "`ms`",
                  "ms",
                  "Time the capture took."
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "When the resource stops",
              "md": "Its pending captures are dropped: their Promise or callback never completes. The player sees nothing of it."
            }
          ]
        },
        {
          "id": "client-resources",
          "title": "Hot resources, stream sets and archives",
          "eyebrow": "Client · Lua & JS",
          "lead": "Mount and unmount client resources while the game runs, load parts of their streamed assets on demand, take game assets and archives out of the streaming, and quiet the story-mode scripts.",
          "blocks": [
            {
              "type": "text",
              "md": "Everything on this page changes what the game streams. These calls are **jobs**: the call returns at once, and the work runs in order with every other job of the client, whichever resource or language asked for it. A job never blocks the game. Read [Assets and streaming](#streaming) first for the concepts and complete recipes."
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "Jobs run **in the order they were requested**: unregister the old map, *then* mount the resource of the new one, without waiting in between.",
                "A job that **cannot start** (unknown resource, unknown set) fails at once: the Promise rejects, the Lua callback receives the code. Never synchronously: see [Conventions](#conventions).",
                "When a resource stops, the Promises and callbacks it was waiting for are dropped. The jobs themselves run to their end."
              ]
            },
            {
              "type": "heading",
              "text": "Resources",
              "level": 2,
              "id": "client-resources-start"
            },
            {
              "type": "function",
              "name": "lsmp.mountResource",
              "id": "fn-mount-resource",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.mountResource(name [, cb]) --> boolean, err",
                "js": "lsmp.mountResource(name: string): Promise<boolean>"
              },
              "summary": "Mount a client resource the server offers, downloading it if needed, then start its scripts.",
              "md": "For a resource the server lists but does not start on its own, or one that was unmounted earlier. With [`unmountResource`](#client-resources/fn-unmount-resource), the only change made to resources while connected: the server's own resources start with the server and run until it stops. The resources it depends on are started first. Asynchronous: see [Conventions](#conventions). In JavaScript the Promise carries the job number in `promise.jobId`; in Lua, the callback form returns it.\n\nFailure codes: `not-found` (the server offers no client resource of that name), `error` (the job failed: download, a dependency that cannot start). See [Error codes](#error-codes).",
              "params": [
                {
                  "name": "name",
                  "type": "name",
                  "desc": "The resource name."
                }
              ],
              "returns": [
                {
                  "type": "boolean, err",
                  "desc": "`true` once the resource is started; `false` and a [code](#error-codes) otherwise.",
                  "only": "lua"
                },
                {
                  "type": "Promise<boolean>",
                  "desc": "Resolves with `true` once the resource is started; rejects with a [code](#error-codes) otherwise.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local ok, err = lsmp.mountResource(\"island_b\")\nif ok then\n  lsmp.emitServer(\"island:ready\")\nelse\n  lsmp.warn(\"island_b did not start: \" .. err)\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "async function openIsland() {\n  try {\n    await lsmp.mountResource('island_b');\n    lsmp.emitServer('island:ready');\n  } catch (err) {\n    lsmp.warn(`island_b did not start: ${err.code}`);\n  }\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.unmountResource",
              "id": "fn-unmount-resource",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.unmountResource(name [, cb]) --> boolean, err",
                "js": "lsmp.unmountResource(name: string): Promise<boolean>"
              },
              "summary": "Stop a client resource and unmount it: its scripts end, its assets leave the streaming.",
              "md": "The resource receives `resourceStop` first, like every other resource, and keeps a short grace period to clean up. Only this player's copy stops: the server half of the resource keeps running. Asynchronous: see [Conventions](#conventions). In JavaScript the Promise carries the job number in `promise.jobId`; in Lua, the callback form returns it.\n\nA resource can stop **itself**: the call is accepted, and its own Promise or callback never completes, since the resource is gone when the job ends.\n\nFailure codes: `not-found`. See [Error codes](#error-codes).",
              "params": [
                {
                  "name": "name",
                  "type": "name",
                  "desc": "The resource name."
                }
              ],
              "returns": [
                {
                  "type": "boolean, err",
                  "desc": "`true` once the resource is stopped; `false` and a [code](#error-codes) otherwise.",
                  "only": "lua"
                },
                {
                  "type": "Promise<boolean>",
                  "desc": "Resolves with `true` once the resource is stopped; rejects with a [code](#error-codes) otherwise.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "-- Swap two maps, in order.\nlocal ok = lsmp.unmountResource(\"island_a\")\nif ok then lsmp.mountResource(\"island_b\") end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "// Swap two maps, in order.\nasync function swapIslands() {\n  await lsmp.unmountResource('island_a');\n  await lsmp.mountResource('island_b');\n}"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Stream sets",
              "level": 2,
              "id": "client-resources-sets"
            },
            {
              "type": "text",
              "md": "A resource can split its streamed files into named **stream sets**, declared in its manifest (`stream_sets`, see [Resource layout](#resource-layout)). A set declared with `\"load\": \"manual\"` stays out of the streaming until a script loads it. Everything is already in the package: loading a set later downloads nothing."
            },
            {
              "type": "function",
              "name": "lsmp.resources.loadStreamSet",
              "id": "fn-resources-load-stream-set",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.loadStreamSet(resource, set [, cb]) --> boolean, err",
                "js": "lsmp.resources.loadStreamSet(resource: string, set: string): Promise<boolean>"
              },
              "summary": "Put the assets of a stream set in the streaming.",
              "md": "Works on any mounted resource, not only the caller. Loading a set that is already loaded succeeds: the result says the set **is** loaded, not that this call changed it. The call can be queued right behind the `mountResource` of the same resource. Asynchronous: see [Conventions](#conventions). In JavaScript the Promise carries the job number in `promise.jobId`; in Lua, the callback form returns it.\n\nFailure codes: `not-found` (the resource is not mounted and not being mounted, or has no set of that name), `error`. See [Error codes](#error-codes).",
              "params": [
                {
                  "name": "resource",
                  "type": "name",
                  "desc": "A mounted resource."
                },
                {
                  "name": "set",
                  "type": "string",
                  "desc": "The `name` of one of its stream sets. Exact, case-sensitive."
                }
              ],
              "returns": [
                {
                  "type": "boolean, err",
                  "desc": "`true` once the set is loaded; `false` and a [code](#error-codes) otherwise.",
                  "only": "lua"
                },
                {
                  "type": "Promise<boolean>",
                  "desc": "Resolves with `true` once the set is loaded; rejects with a [code](#error-codes) otherwise.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local ok, err = lsmp.resources.loadStreamSet(\"las-venturas\", \"addons\")\nif not ok then lsmp.warn(\"addons: \" .. err) end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.resources.loadStreamSet('las-venturas', 'addons')\n  .catch((err) => lsmp.warn(`addons: ${err.code}`));"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.resources.unloadStreamSet",
              "id": "fn-resources-unload-stream-set",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.unloadStreamSet(resource, set [, cb]) --> boolean, err",
                "js": "lsmp.resources.unloadStreamSet(resource: string, set: string): Promise<boolean>"
              },
              "summary": "Take the assets of a stream set out of the streaming.",
              "md": "Each name the set provided falls back to what is below it: another set, the rest of the resource, another resource, or the game's own file. A model or texture still in use is not taken away from what uses it: it leaves once released, and the job still succeeds. Same rules and codes as [`loadStreamSet`](#client-resources/fn-resources-load-stream-set), except that `error` is the only failure once the job started.",
              "params": [
                {
                  "name": "resource",
                  "type": "name",
                  "desc": "A mounted resource."
                },
                {
                  "name": "set",
                  "type": "string",
                  "desc": "The name of the set."
                }
              ],
              "returns": [
                {
                  "type": "boolean, err",
                  "desc": "`true` once the set is unloaded; `false` and a [code](#error-codes) otherwise.",
                  "only": "lua"
                },
                {
                  "type": "Promise<boolean>",
                  "desc": "Resolves with `true` once the set is unloaded; rejects with a [code](#error-codes) otherwise.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.resources.getStreamSetState",
              "id": "fn-resources-get-stream-set-state",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.getStreamSetState(resource, set) --> string?",
                "js": "lsmp.resources.getStreamSetState(resource: string, set: string): string | null"
              },
              "summary": "The state of a stream set, read at once.",
              "params": [
                {
                  "name": "resource",
                  "type": "name",
                  "desc": "A resource."
                },
                {
                  "name": "set",
                  "type": "string",
                  "desc": "The name of the set."
                }
              ],
              "returns": {
                "type": "string?",
                "desc": "`\"unloaded\"`, `\"loading\"`, `\"loaded\"` or `\"unloading\"`; `nil` / `null` when the resource is not mounted or has no set of that name."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "if lsmp.resources.getStreamSetState(\"las-venturas\", \"addons\") == \"unloaded\" then\n  lsmp.resources.loadStreamSet(\"las-venturas\", \"addons\")\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "if (lsmp.resources.getStreamSetState('las-venturas', 'addons') === 'unloaded') {\n  lsmp.resources.loadStreamSet('las-venturas', 'addons');\n}"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Streaming assets",
              "level": 2,
              "id": "client-resources-assets"
            },
            {
              "type": "text",
              "md": "These functions act on **named assets** of the streaming, the game's and those of every mounted resource. A name is the file name **with its extension**, which says what kind of asset it is: `\"prop_alien_egg_01.ydr\"`, `\"cs1_01.ybn\"`, `\"my_textures.ytd\"`."
            },
            {
              "type": "function",
              "name": "lsmp.resources.unregisterAssets",
              "id": "fn-resources-unregister-assets",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.unregisterAssets(names [, cb]) --> AssetJobResult, err",
                "js": "lsmp.resources.unregisterAssets(names: string[]): Promise<AssetJobResult>"
              },
              "summary": "Take assets out of the streaming.",
              "md": "The whole list is one job. Send one large list rather than many small ones: 100,000 names is one call. A model or texture that something still uses is **refused** and counted in `failed`: it stays as it was. Maps (`.ymap`) and collisions (`.ybn`) are unloaded on the spot, so do it behind a loading screen. Asynchronous: see [Conventions](#conventions). In JavaScript the Promise carries the job number in `promise.jobId`; in Lua, the callback form returns it.\n\nFailure code: `error` (the job could not run). See [Error codes](#error-codes).",
              "params": [
                {
                  "name": "names",
                  "type": "{string}",
                  "desc": "1 to 1,048,576 asset names, each a non-empty string.",
                  "only": "lua"
                },
                {
                  "name": "names",
                  "type": "string[]",
                  "desc": "1 to 1,048,576 asset names, each a non-empty string.",
                  "only": "js"
                }
              ],
              "returns": [
                {
                  "type": "AssetJobResult, err",
                  "desc": "`{ done, failed }`: names processed and names refused. A refused name is **not** a failure of the call.",
                  "only": "lua"
                },
                {
                  "type": "Promise<AssetJobResult>",
                  "desc": "Resolves with `{ done, failed }`: names processed and names refused. A refused name does **not** reject the Promise.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local names = lsmp.json.decode(lsmp.readResourceFile(\"data/base_map.json\"))\nlocal res, err = lsmp.resources.unregisterAssets(names)\nif res then\n  lsmp.log((\"unregistered %d, refused %d\"):format(res.done, res.failed))\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "async function clearBaseMap() {\n  const names = JSON.parse(lsmp.readResourceFile('data/base_map.json'));\n  const res = await lsmp.resources.unregisterAssets(names);\n  lsmp.log(`unregistered ${res.done}, refused ${res.failed}`);\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.resources.registerAssets",
              "id": "fn-resources-register-assets",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.registerAssets(names [, cb]) --> AssetJobResult, err",
                "js": "lsmp.resources.registerAssets(names: string[]): Promise<AssetJobResult>"
              },
              "summary": "Put back assets that a script took out of the streaming.",
              "md": "Same rules and result as [`unregisterAssets`](#client-resources/fn-resources-unregister-assets). Failure codes: `error`, `limit`. See [Error codes](#error-codes).",
              "params": [
                {
                  "name": "names",
                  "type": "{string}",
                  "desc": "1 to 1,048,576 asset names.",
                  "only": "lua"
                },
                {
                  "name": "names",
                  "type": "string[]",
                  "desc": "1 to 1,048,576 asset names.",
                  "only": "js"
                }
              ],
              "returns": [
                {
                  "type": "AssetJobResult, err",
                  "desc": "`{ done, failed }`: names processed and names refused. A refused name is **not** a failure of the call.",
                  "only": "lua"
                },
                {
                  "type": "Promise<AssetJobResult>",
                  "desc": "Resolves with `{ done, failed }`: names processed and names refused. A refused name does **not** reject the Promise.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.resources.getAssetState",
              "id": "fn-resources-get-asset-state",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.getAssetState(name) --> string?",
                "js": "lsmp.resources.getAssetState(name: string): string | null"
              },
              "summary": "The state of one asset, read at once.",
              "params": [
                {
                  "name": "name",
                  "type": "string",
                  "desc": "Asset name, with its extension."
                }
              ],
              "returns": {
                "type": "string?",
                "desc": "`\"registered\"` (in the streaming) or `\"unregistered\"` (taken out by a script); `nil` / `null` when no asset has that name."
              }
            },
            {
              "type": "heading",
              "text": "Game archives",
              "level": 2,
              "id": "client-resources-archives"
            },
            {
              "type": "function",
              "name": "lsmp.resources.invalidateArchives",
              "id": "fn-resources-invalidate-archives",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.invalidateArchives(names [, cb]) --> AssetJobResult, err",
                "js": "lsmp.resources.invalidateArchives(names: string[]): Promise<AssetJobResult>"
              },
              "summary": "Switch whole streaming archives of the game off.",
              "md": "This is what a map DLC does with `filesToInvalidate`: the maps of an invalidated archive are unloaded and ignored, its other assets leave memory once nothing uses them. Nothing is deleted: [`restoreArchives`](#client-resources/fn-resources-restore-archives) gives everything back, and so does stopping the resource that invalidated them, or leaving the server.\n\nSend all the archives in one call: the whole base map is one job. Only **streaming** archives are known here; a data archive is counted in `failed`. Invalidating does not free room in the game's asset stores: to make room for another map, also [unregister](#client-resources/fn-resources-unregister-assets) its models and textures. Asynchronous: see [Conventions](#conventions). In JavaScript the Promise carries the job number in `promise.jobId`; in Lua, the callback form returns it.\n\nFailure code: `error`. See [Error codes](#error-codes).",
              "params": [
                {
                  "name": "names",
                  "type": "{string}",
                  "desc": "Archive names as the game registers them, the strings a DLC `content.xml` lists under `filesToInvalidate`: `\"platform:/levels/gta5/_citye/downtown_01/dt1_01.rpf\"`.",
                  "only": "lua"
                },
                {
                  "name": "names",
                  "type": "string[]",
                  "desc": "Archive names as the game registers them, the strings a DLC `content.xml` lists under `filesToInvalidate`: `\"platform:/levels/gta5/_citye/downtown_01/dt1_01.rpf\"`.",
                  "only": "js"
                }
              ],
              "returns": [
                {
                  "type": "AssetJobResult, err",
                  "desc": "`{ done, failed }`: names processed and names refused. A refused name is **not** a failure of the call.",
                  "only": "lua"
                },
                {
                  "type": "Promise<AssetJobResult>",
                  "desc": "Resolves with `{ done, failed }`: names processed and names refused. A refused name does **not** reject the Promise.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local res = lsmp.resources.invalidateArchives({\n  \"platform:/levels/gta5/_citye/downtown_01/dt1_01.rpf\",\n  \"platform:/levels/gta5/_citye/downtown_01/dt1_02.rpf\",\n})\nif res then lsmp.log(res.done .. \" archives switched off\") end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.resources.invalidateArchives([\n  'platform:/levels/gta5/_citye/downtown_01/dt1_01.rpf',\n  'platform:/levels/gta5/_citye/downtown_01/dt1_02.rpf',\n]).then((res) => lsmp.log(`${res.done} archives switched off`));"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.resources.restoreArchives",
              "id": "fn-resources-restore-archives",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.restoreArchives(names [, cb]) --> AssetJobResult, err",
                "js": "lsmp.resources.restoreArchives(names: string[]): Promise<AssetJobResult>"
              },
              "summary": "Switch archives that this resource invalidated back on.",
              "md": "Same rules and result as [`invalidateArchives`](#client-resources/fn-resources-invalidate-archives). It happens on its own when the resource stops. Failure code: `error`.",
              "params": [
                {
                  "name": "names",
                  "type": "{string}",
                  "desc": "Archive names.",
                  "only": "lua"
                },
                {
                  "name": "names",
                  "type": "string[]",
                  "desc": "Archive names.",
                  "only": "js"
                }
              ],
              "returns": [
                {
                  "type": "AssetJobResult, err",
                  "desc": "`{ done, failed }`: names processed and names refused. A refused name is **not** a failure of the call.",
                  "only": "lua"
                },
                {
                  "type": "Promise<AssetJobResult>",
                  "desc": "Resolves with `{ done, failed }`: names processed and names refused. A refused name does **not** reject the Promise.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.resources.getArchiveState",
              "id": "fn-resources-get-archive-state",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.getArchiveState(name) --> string?",
                "js": "lsmp.resources.getArchiveState(name: string): string | null"
              },
              "summary": "The state of one game archive, read at once.",
              "params": [
                {
                  "name": "name",
                  "type": "string",
                  "desc": "Archive name as the game registers it."
                }
              ],
              "returns": {
                "type": "string?",
                "desc": "`\"active\"` or `\"invalidated\"`; `nil` / `null` when no streaming archive has that name."
              }
            },
            {
              "type": "heading",
              "text": "Story-mode scripts",
              "level": 2,
              "id": "client-resources-story"
            },
            {
              "type": "text",
              "md": "The story-mode scripts of the game keep running in a session, and some of them load map pieces (IPLs) or start activities of their own. These calls quiet them. Each one is an **owned setting**: the last resource that calls it wins, and what it changed is restored when that resource stops."
            },
            {
              "type": "function",
              "name": "lsmp.resources.suspendScriptIpls",
              "id": "fn-resources-suspend-script-ipls",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.suspendScriptIpls([cb]) --> AssetJobResult, err",
                "js": "lsmp.resources.suspendScriptIpls(): Promise<AssetJobResult>"
              },
              "summary": "Unload the map pieces (IPLs) that the story scripts load, and keep them from loading again.",
              "md": "For a server that replaces the map, or needs the world as the base game ships it, without the extra buildings and interiors the story adds. Asynchronous: see [Conventions](#conventions). In JavaScript the Promise carries the job number in `promise.jobId`; in Lua, the callback form returns it.\n\nFailure code: `error`.",
              "returns": [
                {
                  "type": "AssetJobResult, err",
                  "desc": "`{ done, failed }`: names processed and names refused. A refused name is **not** a failure of the call.",
                  "only": "lua"
                },
                {
                  "type": "Promise<AssetJobResult>",
                  "desc": "Resolves with `{ done, failed }`: names processed and names refused. A refused name does **not** reject the Promise.",
                  "only": "js"
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local res, err = lsmp.resources.suspendScriptIpls()\nif not res then lsmp.warn(\"IPLs: \" .. err) end"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.resources.suspendScriptIpls().catch((err) => lsmp.warn(`IPLs: ${err.code}`));"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.resources.resumeScriptIpls",
              "id": "fn-resources-resume-script-ipls",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.resumeScriptIpls([cb]) --> AssetJobResult, err",
                "js": "lsmp.resources.resumeScriptIpls(): Promise<AssetJobResult>"
              },
              "summary": "Give the story scripts their map pieces back.",
              "md": "Undoes [`suspendScriptIpls`](#client-resources/fn-resources-suspend-script-ipls). Failure code: `error`.",
              "returns": [
                {
                  "type": "AssetJobResult, err",
                  "desc": "`{ done, failed }`: names processed and names refused. A refused name is **not** a failure of the call.",
                  "only": "lua"
                },
                {
                  "type": "Promise<AssetJobResult>",
                  "desc": "Resolves with `{ done, failed }`: names processed and names refused. A refused name does **not** reject the Promise.",
                  "only": "js"
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.resources.suspendStoryScript",
              "id": "fn-resources-suspend-story-script",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.suspendStoryScript(name) --> string",
                "js": "lsmp.resources.suspendStoryScript(name: string): string"
              },
              "summary": "Stop one story-mode script and keep it from starting again.",
              "md": "Synchronous. Some scripts of the game cannot be stopped this way: the result is then `\"refused\"`.",
              "params": [
                {
                  "name": "name",
                  "type": "string",
                  "desc": "The name of the game script, for example `\"blip_controller\"`."
                }
              ],
              "returns": {
                "type": "string",
                "desc": "`\"stopped\"`, `\"loading\"`, `\"running\"` (the state the script is in now), or `\"refused\"`."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "if lsmp.resources.suspendStoryScript(\"blip_controller\") == \"refused\" then\n  lsmp.warn(\"blip_controller cannot be stopped\")\nend"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "if (lsmp.resources.suspendStoryScript('blip_controller') === 'refused') {\n  lsmp.warn('blip_controller cannot be stopped');\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.resources.resumeStoryScript",
              "id": "fn-resources-resume-story-script",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.resources.resumeStoryScript(name) --> string",
                "js": "lsmp.resources.resumeStoryScript(name: string): string"
              },
              "summary": "Allow a story script to run again.",
              "md": "Undoes [`suspendStoryScript`](#client-resources/fn-resources-suspend-story-script) for this resource. The game starts the script again when it needs it.",
              "params": [
                {
                  "name": "name",
                  "type": "string",
                  "desc": "The name of the game script."
                }
              ],
              "returns": {
                "type": "string",
                "desc": "Same values as `suspendStoryScript`."
              }
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Everything is undone when the player leaves",
              "md": "Going to another server or back to story mode stops every resource, gives back every game asset a script unregistered, and switches invalidated archives back on."
            }
          ]
        },
        {
          "id": "discord",
          "title": "Discord presence",
          "eyebrow": "Client · Lua & JS",
          "lead": "What a player's Discord profile shows while they play on your server.",
          "blocks": [
            {
              "type": "text",
              "md": "While a player is on a server and Discord runs on their machine, their Discord profile shows a card. By default its two lines are the server's name and the player count. A client script can replace them, and with a custom presence, the images, the buttons and the application."
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "**Players decide.** A player who turned the presence off in their LS:MP settings shows nothing, and every call returns `false` with the code `permission`.",
                "**Owned settings.** Each field belongs to the resource that set it: the last writer wins, and the default comes back when that resource stops.",
                "**Change rarely.** Discord limits how often a presence may change: update on a real change (a new area, a new vehicle), not every frame.",
                "Texts are 128 bytes at most. `nil`/`null` puts the default back."
              ]
            },
            {
              "type": "function",
              "name": "lsmp.discord.setDetails",
              "id": "fn-discord-set-details",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.discord.setDetails(text) --> boolean",
                "js": "lsmp.discord.setDetails(text: string | null): boolean"
              },
              "summary": "Set the first line of the card.",
              "params": [
                {
                  "name": "text",
                  "type": "string?",
                  "desc": "The text, or `nil`/`null` for the default."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if applied."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The player turned the presence off."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "local last = nil\nlsmp.onTick(function()\n  local vehicle = getVehiclePedIsIn(playerPedId(), false)\n  local text = vehicle ~= 0 and \"Driving\" or \"On foot\"\n  if text ~= last then\n    last = text\n    lsmp.discord.setDetails(text)\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "let last = null;\nlsmp.onTick(() => {\n  const text = getVehiclePedIsIn(playerPedId(), false) ? 'Driving' : 'On foot';\n  if (text !== last) {\n    last = text;\n    lsmp.discord.setDetails(text);\n  }\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.discord.setState",
              "id": "fn-discord-set-state",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.discord.setState(text) --> boolean",
                "js": "lsmp.discord.setState(text: string | null): boolean"
              },
              "summary": "Set the second line of the card.",
              "params": [
                {
                  "name": "text",
                  "type": "string?",
                  "desc": "The text, or `nil`/`null` for the default."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if applied."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The player turned the presence off."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.discord.setAsset",
              "id": "fn-discord-set-asset",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.discord.setAsset(slot, key [, hoverText]) --> boolean",
                "js": "lsmp.discord.setAsset(slot: string, key: string | null, hoverText?: string): boolean"
              },
              "summary": "Set the large or the small image of the card.",
              "md": "Needs a custom presence: the images are assets of your own Discord application (see [`setAppId`](#discord/fn-discord-set-app-id)), or `https://` addresses from the hosts LS:MP accepts.",
              "params": [
                {
                  "name": "slot",
                  "type": "string",
                  "desc": "`\"large\"` or `\"small\"`."
                },
                {
                  "name": "key",
                  "type": "string?",
                  "desc": "The asset key or image address, or `nil`/`null` for none."
                },
                {
                  "name": "hoverText",
                  "type": "string",
                  "desc": "Text shown when the image is hovered, 128 bytes at most.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if applied."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The player turned the presence off, or the server has no custom presence."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.discord.setButton",
              "id": "fn-discord-set-button",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.discord.setButton(index, label [, url]) --> boolean",
                "js": "lsmp.discord.setButton(index: number, label: string | null, url?: string): boolean"
              },
              "summary": "Set one of the two buttons of the card.",
              "md": "Needs a custom presence. A button opens its address in the browser of whoever clicks it.",
              "params": [
                {
                  "name": "index",
                  "type": "int",
                  "desc": "`0` or `1`."
                },
                {
                  "name": "label",
                  "type": "string?",
                  "desc": "The button text, or `nil`/`null` to remove the button."
                },
                {
                  "name": "url",
                  "type": "string",
                  "desc": "An `https://` address; required with a label.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if applied."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The player turned the presence off, or the server has no custom presence."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.discord.setAppId",
              "id": "fn-discord-set-app-id",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.discord.setAppId(appId) --> boolean",
                "js": "lsmp.discord.setAppId(appId: string): boolean"
              },
              "summary": "Show the card under your own Discord application.",
              "md": "Its name becomes the card's title and its assets become available to [`setAsset`](#discord/fn-discord-set-asset). Needs a custom presence.",
              "params": [
                {
                  "name": "appId",
                  "type": "string",
                  "desc": "The application id from the Discord developer portal: 17 to 20 digits, as a string."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if applied."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Failure code",
                    "When"
                  ],
                  "rows": [
                    [
                      "`permission`",
                      "The player turned the presence off, or the server has no custom presence."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "lsmp.discord.clear",
              "id": "fn-discord-clear",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.discord.clear()",
                "js": "lsmp.discord.clear(): void"
              },
              "summary": "Remove everything this resource set.",
              "md": "The card goes back to what other resources set, or to the default."
            }
          ]
        }
      ]
    },
    {
      "id": "page-api",
      "title": "Page API",
      "icon": "🖥",
      "pages": [
        {
          "id": "page-api",
          "title": "The `lsmp` object in a page",
          "eyebrow": "Page · JavaScript",
          "lead": "What a web page opened by your resource can call: events and calls to and from the script that owns its browser, and a few read-only facts about the game.",
          "blocks": [
            {
              "type": "text",
              "md": "Every page opened with [`lsmp.createBrowser`](#browsers/fn-create-browser) or [`lsmp.createBrowser3D`](#browsers/fn-create-browser3d) finds a global `lsmp` object, ready before the page's first script runs. It talks to **one** party: the client script that owns this browser, through that browser's handle (`browser:on`, `browser:emit`, `browser:call`). Two browsers never hear each other, and no page can reach another resource."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "web/index.html",
                  "lang": "html",
                  "web": true,
                  "code": "<!doctype html>\n<html>\n<body>\n  <h1 id=\"hello\">…</h1>\n  <button id=\"buy\">Buy a soda</button>\n  <script>\n    // The script sends 'init' once the page is loaded.\n    lsmp.on('init', (name) => {\n      document.getElementById('hello').textContent = `Hello, ${name}`;\n    });\n\n    // Ask the script, and wait for its answer.\n    document.getElementById('buy').addEventListener('click', async () => {\n      try {\n        const answer = await lsmp.call('buy', 'soda', 1);\n        document.getElementById('hello').textContent = answer.ok ? 'Enjoy!' : answer.error;\n      } catch (err) {\n        console.error('buy failed:', err.code);\n      }\n    });\n\n    // Answer the script's calls.\n    lsmp.on('getSelection', () => ({ item: 'soda', quantity: 1 }));\n  </script>\n</body>\n</html>"
                },
                {
                  "label": "client/main.lua",
                  "lang": "lua",
                  "code": "local page = lsmp.createBrowser(\"rsc://shop/index.html\", { focus = true })\n\npage:on(\"load\", function()\n  page:emit(\"init\", lsmp.getPlayerName(lsmp.getLocalPlayer()))\nend)\n\npage:on(\"buy\", function(item, quantity)\n  local ok, err = lsmp.callServer(\"shop:buy\", item, quantity)\n  return { ok = ok ~= nil, error = err }\nend)"
                },
                {
                  "label": "client/main.js",
                  "lang": "js",
                  "code": "const page = lsmp.createBrowser('rsc://shop/index.html', { focus: true });\n\npage.on('load', () => {\n  page.emit('init', lsmp.getPlayerName(lsmp.getLocalPlayer()));\n});\n\npage.on('buy', async (item, quantity) => {\n  try {\n    return { ok: true, result: await lsmp.callServer('shop:buy', item, quantity) };\n  } catch (err) {\n    return { ok: false, error: err.code };\n  }\n});"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Which documents get it",
              "level": 2,
              "id": "page-api-who"
            },
            {
              "type": "table",
              "headers": [
                "Document",
                "`lsmp`"
              ],
              "rows": [
                [
                  "The page loaded in a 2D or 3D browser of a resource",
                  "Yes, linked to that browser."
                ],
                [
                  "An `<iframe>` of that page from the **same origin** (same `rsc://` resource, or same site)",
                  "Yes, linked to the same browser."
                ],
                [
                  "An `<iframe>` from another origin (video, ads, widget)",
                  "No."
                ],
                [
                  "A popup opened by the page",
                  "No."
                ],
                [
                  "The page opened in an ordinary web browser, outside the game",
                  "No: see [Developing outside the game](#page-api/page-api-outside)."
                ]
              ]
            },
            {
              "type": "text",
              "md": "The object is frozen: a page cannot replace or extend it, and a `lsmp` global the page declares itself is ignored."
            },
            {
              "type": "heading",
              "text": "Functions",
              "level": 2,
              "id": "page-api-functions"
            },
            {
              "type": "function",
              "name": "lsmp.emit",
              "id": "fn-page-emit",
              "side": "page",
              "engines": [
                "js"
              ],
              "signature": {
                "js": "lsmp.emit(event: string, ...args: any[]): void"
              },
              "summary": "Send an event to the owning script's `browser:on` handlers.",
              "md": "Every handler of that name runs. If the script has none, the event is dropped silently. Throws a `TypeError` for a value that cannot travel (function, symbol, `BigInt`, `NaN`, `Infinity`, integer beyond 2^53), a `RangeError` for more than 32 arguments or a message over 120,000 characters of JSON, and an `Error` for a reserved name.",
              "params": [
                {
                  "name": "event",
                  "type": "string",
                  "desc": "Event name, 1 to 128 characters, no control characters. `load`, `loadError`, `focusLost`, `crash` and names starting with `lsmp:` are reserved."
                },
                {
                  "name": "...args",
                  "type": "any",
                  "desc": "Up to 32 JSON-compatible values; `Uint8Array`, `ArrayBuffer` and `DataView` travel as bytes.",
                  "optional": true
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Page",
                    "lang": "js",
                    "web": true,
                    "code": "document.querySelector('#close').addEventListener('click', () => {\n  lsmp.emit('close');\n});\n\ndocument.querySelector('form').addEventListener('submit', (e) => {\n  e.preventDefault();\n  lsmp.emit('form:submit', Object.fromEntries(new FormData(e.target)));\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.on",
              "id": "fn-page-on",
              "side": "page",
              "engines": [
                "js"
              ],
              "signature": {
                "js": "lsmp.on(event: string, fn: (...args) => any): () => boolean"
              },
              "summary": "Handle an event or a call from the owning script.",
              "md": "For `browser:emit`, every handler runs. For `browser:call`, handlers run in order until one returns something other than `undefined` (a value, `null`, or a Promise): that is the answer, and a Promise is awaited. If they all return `undefined`, the answer is `null`. A handler that throws, or a Promise that rejects, answers with the code `error` (the error is printed in the page's console). With no handler, the script gets `no-handler`.\n\nThe same function registered twice for one name counts once.",
              "params": [
                {
                  "name": "event",
                  "type": "string",
                  "desc": "Event name, same rules as `lsmp.emit`."
                },
                {
                  "name": "fn",
                  "type": "function",
                  "desc": "`fn(...args)`; its return value (or Promise) answers a script call."
                }
              ],
              "returns": {
                "type": "() => boolean",
                "desc": "Call it to remove the handler."
              },
              "examples": {
                "tabs": [
                  {
                    "label": "Page",
                    "lang": "js",
                    "web": true,
                    "code": "// Event from browser:emit('money', 1500)\nlsmp.on('money', (amount) => {\n  document.querySelector('#money').textContent = `$${amount}`;\n});\n\n// Call from browser:call('confirm', 'Sell your car?'): answers true or false\nlsmp.on('confirm', (question) => askPlayer(question));\n\nfunction askPlayer(question) {\n  return new Promise((resolve) => {\n    document.querySelector('#question').textContent = question;\n    document.querySelector('#yes').onclick = () => resolve(true);\n    document.querySelector('#no').onclick = () => resolve(false);\n  });\n}"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "lsmp.off",
              "id": "fn-page-off",
              "side": "page",
              "engines": [
                "js"
              ],
              "signature": {
                "js": "lsmp.off(event: string, fn: Function): boolean"
              },
              "summary": "Remove a handler registered with `lsmp.on`.",
              "params": [
                {
                  "name": "event",
                  "type": "string",
                  "desc": "The event name."
                },
                {
                  "name": "fn",
                  "type": "function",
                  "desc": "The same function that was registered."
                }
              ],
              "returns": {
                "type": "boolean",
                "desc": "`true` if it was registered."
              }
            },
            {
              "type": "function",
              "name": "lsmp.call",
              "id": "fn-page-call",
              "side": "page",
              "engines": [
                "js"
              ],
              "signature": {
                "js": "lsmp.call(event: string | { name: string, timeoutMs?: number }, ...args: any[]): Promise<any>"
              },
              "summary": "Call the owning script's `browser:on` handler and get its answer.",
              "md": "Same argument rules as `lsmp.emit`. The Promise rejects with an `Error` whose `code` says why:",
              "params": [
                {
                  "name": "event",
                  "type": "string | { name, timeoutMs }",
                  "desc": "The handler's name, or an object with `name` and `timeoutMs` (`1` to `300000`, default `10000`)."
                },
                {
                  "name": "...args",
                  "type": "any",
                  "desc": "Up to 32 values.",
                  "optional": true
                }
              ],
              "returns": {
                "type": "Promise<any>",
                "desc": "Resolves with the script's answer (`null` when it returned nothing)."
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "`err.code`",
                    "Meaning"
                  ],
                  "rows": [
                    [
                      "`timeout`",
                      "No answer in time."
                    ],
                    [
                      "`no-handler`",
                      "The script has no `browser:on` handler for this name."
                    ],
                    [
                      "`error`",
                      "The script's handler raised, or its answer could not be sent. The details are in the client console (F8), never in the page."
                    ],
                    [
                      "`cancelled`",
                      "The browser was destroyed or the page navigated away."
                    ],
                    [
                      "`limit`",
                      "1024 calls are already waiting."
                    ]
                  ]
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Page",
                    "lang": "js",
                    "web": true,
                    "code": "async function loadInventory() {\n  try {\n    const items = await lsmp.call({ name: 'inventory:list', timeoutMs: 5000 });\n    render(items);\n  } catch (err) {\n    if (err.code === 'timeout') showMessage('The server is slow, try again.');\n    else console.error('inventory:list failed', err.code);\n  }\n}"
                  }
                ]
              }
            },
            {
              "type": "heading",
              "text": "Constants",
              "level": 2,
              "id": "page-api-constants"
            },
            {
              "type": "function",
              "name": "lsmp.version",
              "id": "const-lsmp-version",
              "side": "page",
              "engines": [
                "js"
              ],
              "signature": {
                "js": "lsmp.version: string"
              },
              "summary": "The LS:MP version, such as `\"0.6.254\"`."
            },
            {
              "type": "function",
              "name": "lsmp.gameVersion",
              "id": "const-lsmp-gameversion",
              "side": "page",
              "engines": [
                "js"
              ],
              "signature": {
                "js": "lsmp.gameVersion: string"
              },
              "summary": "The game version, such as `\"1.0.1158.16\"`."
            },
            {
              "type": "function",
              "name": "lsmp.gameBuild",
              "id": "const-lsmp-gamebuild",
              "side": "page",
              "engines": [
                "js"
              ],
              "signature": {
                "js": "lsmp.gameBuild: number"
              },
              "summary": "The game build number, such as `1158`."
            },
            {
              "type": "function",
              "name": "lsmp.language",
              "id": "const-lsmp-language",
              "side": "page",
              "engines": [
                "js"
              ],
              "signature": {
                "js": "lsmp.language: string"
              },
              "summary": "The language of the player's LS:MP interface, as a BCP 47 tag such as `\"fr-FR\"`: use it to translate your page."
            },
            {
              "type": "function",
              "name": "lsmp.resource",
              "id": "const-lsmp-resource",
              "side": "page",
              "engines": [
                "js"
              ],
              "signature": {
                "js": "lsmp.resource: string"
              },
              "summary": "The name of the resource that owns this browser, such as `\"shop\"`."
            },
            {
              "type": "heading",
              "text": "Good to know",
              "level": 2,
              "id": "page-api-good-to-know"
            },
            {
              "type": "list",
              "items": [
                "**Order**: the script's `load` handler runs once the page's document is ready (`DOMContentLoaded`). Register your `lsmp.on` handlers at the top of your scripts, not in a later callback, and they will be there for the first events.",
                "Events the script sends **before** the page is ready are kept and delivered, in order, right after.",
                "A page that navigates (or reloads) loses its handlers and its pending calls (`cancelled`); the script gets `load` again.",
                "Never trust what a page sends: a page is code running on the player's machine. Check every value in the client script, and anything that matters on the server.",
                "`localStorage`, IndexedDB, the microphone and the camera are available to pages, with a few rules: see [Storage, microphone, camera and limits](#browsers/browsers-sandbox)."
              ]
            },
            {
              "type": "heading",
              "text": "Developing outside the game",
              "level": 2,
              "id": "page-api-outside"
            },
            {
              "type": "text",
              "md": "A page opened in Chrome or in your framework's dev server has no `lsmp`. A small stand-in keeps it working while you design it; in game, the real object is already there and the stand-in does nothing."
            },
            {
              "type": "code",
              "lang": "js",
              "title": "web/lsmp-stub.js (load it first)",
              "web": true,
              "code": "if (!('lsmp' in window)) {\n  const handlers = new Map();\n  window.lsmp = {\n    version: 'dev', gameVersion: 'dev', gameBuild: 0, language: navigator.language, resource: 'dev',\n    emit: (event, ...args) => console.log('[lsmp.emit]', event, ...args),\n    on: (event, fn) => { handlers.set(event, fn); return () => handlers.delete(event); },\n    off: (event) => handlers.delete(event),\n    call: async (event, ...args) => { console.log('[lsmp.call]', event, ...args); return null; },\n    // From the DevTools console: lsmp.fake('init', 'Jane')\n    fake: (event, ...args) => handlers.get(event)?.(...args),\n  };\n}"
            },
            {
              "type": "text",
              "md": "In game, inspect your pages with [DevTools](#debugging/debugging-devtools). With [local resources](#local-resources), a 2D browser can also open your dev server (`http://localhost:5173`) for hot reload."
            },
            {
              "type": "code",
              "lang": "ts",
              "title": "lsmp.d.ts (for TypeScript projects)",
              "web": true,
              "code": "declare const lsmp: Readonly<{\n  emit(event: string, ...args: unknown[]): void;\n  on(event: string, fn: (...args: any[]) => unknown): () => boolean;\n  off(event: string, fn: (...args: any[]) => unknown): boolean;\n  call<T = unknown>(event: string | { name: string; timeoutMs?: number }, ...args: unknown[]): Promise<T>;\n  version: string;\n  gameVersion: string;\n  gameBuild: number;\n  language: string;\n  resource: string;\n}>;"
            }
          ]
        }
      ]
    },
    {
      "id": "engine",
      "title": "Natives",
      "icon": "🔧",
      "pages": [
        {
          "id": "natives",
          "title": "Game natives",
          "eyebrow": "Client · Lua & JS",
          "lead": "The game's natives are global functions in client scripts. Most work as they do in the game, some are checked first, and some are blocked.",
          "blocks": [
            {
              "type": "text",
              "md": "About 6,700 game natives are **global functions** in client scripts, under the same names in Lua and JavaScript. They work on the game's own **handles**: convert a `netId` first with [`lsmp.getEntityFromNetId`](#client-entities)."
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "Look one up",
              "md": "The [natives reference](/resources/natives) lists each native with its arguments, its results, and what LS:MP does about it. Its **Checked** and **Blocked** filters list the natives described below. This page explains the rules they all follow."
            },
            {
              "type": "heading",
              "text": "Calling convention",
              "level": 2,
              "id": "natives-conv"
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "Names are **camelCase**, always starting with a lowercase letter: `SET_ENTITY_COORDS` is `setEntityCoords`, `_GET_LAST_ENTITY_HIT_BY_ENTITY` is `getLastEntityHitByEntity`.",
                "**Out-params come back to you**: skip them in the call and read them from the result. See [Out-params](#natives/natives-out).",
                "**Hashes come back unsigned**, equal to [`lsmp.hash`](#core-utils/fn-hash) for the same name: `getHashKey(\"adder\") == lsmp.hash(\"adder\")`. As an argument, a hash can be given signed or unsigned.",
                "A missing argument counts as `0`, extra arguments are ignored, and an argument of the wrong type raises a `TypeError` that names the native and the argument."
              ]
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "A vector **argument** is three numbers, or one `Vector3`, which fills the same three slots: `setEntityCoordsNoOffset(ped, pos, false, false, false)`.",
                "A native that **returns** a vector gives a `Vector3`: `local pos = getEntityCoords(ped, true)`."
              ],
              "only": "lua"
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "A vector **argument** is three numbers, or one `{ x, y, z }` object or `[x, y, z]` array, which fills the same three slots: `setEntityCoordsNoOffset(ped, pos, false, false, false)`.",
                "A native that **returns** a vector gives a plain `{ x, y, z }` object: `const { x, y, z } = getEntityCoords(ped, true)`."
              ],
              "only": "js"
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "local ped = playerPedId()\nsetEntityHealth(ped, 200, 0)\n\nlocal pos = getEntityCoords(ped, true)   -- a Vector3\nlocal ahead = pos + getEntityForwardVector(ped) * 5.0\nsetEntityCoordsNoOffset(ped, ahead, false, false, false)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "const ped = playerPedId();\nsetEntityHealth(ped, 200, 0);\n\nconst pos = getEntityCoords(ped, true);   // { x, y, z }\nconst fwd = getEntityForwardVector(ped);\nsetEntityCoordsNoOffset(ped, { x: pos.x + fwd.x * 5, y: pos.y + fwd.y * 5, z: pos.z }, false, false, false);"
                }
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "Input while LS:MP has the focus",
              "md": "While the LS:MP menu, the console or a focused page holds the keyboard and mouse, the input natives (`isControlPressed` and the like) report no input, so your key bindings do not fire while the player types."
            },
            {
              "type": "heading",
              "text": "Out-params",
              "level": 2,
              "id": "natives-out"
            },
            {
              "type": "text",
              "md": "Many natives do not return their useful value: the game **writes it through a pointer**, such as a ground height, a screen size or a hit position. LS:MP allocates that pointer for you. Skip those arguments in the call, and read the values from the result, after the native's own return value."
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "The contract",
              "md": "A native returns its own value first, if it has one, then its out-params in parameter order, as **multiple return values**.",
              "only": "lua"
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "The contract",
              "md": "The results are the native's own value first, if it has one, then its out-params in parameter order. No result gives `undefined`, one gives the bare value, and two or more give an `Array`.",
              "only": "js"
            },
            {
              "type": "table",
              "headers": [
                "Out-param",
                "You receive"
              ],
              "rows": [
                [
                  "`float*`",
                  "`number`"
                ],
                [
                  "`BOOL*`",
                  "`boolean`"
                ],
                [
                  "`int*`",
                  "`integer`, signed 32-bit"
                ],
                [
                  "`Hash*`",
                  "`integer`, unsigned"
                ],
                [
                  "`Entity*`, `Ped*`, `Vehicle*`, `Object*`, `Blip*`",
                  "`integer`, a game handle"
                ],
                [
                  "`scrVector3*`",
                  "`Vector3`"
                ]
              ],
              "only": "lua"
            },
            {
              "type": "table",
              "headers": [
                "Out-param",
                "You receive"
              ],
              "rows": [
                [
                  "`float*`",
                  "`number`"
                ],
                [
                  "`BOOL*`",
                  "`boolean`"
                ],
                [
                  "`int*`",
                  "`number`, signed 32-bit"
                ],
                [
                  "`Hash*`",
                  "`number`, unsigned"
                ],
                [
                  "`Entity*`, `Ped*`, `Vehicle*`, `Object*`, `Blip*`",
                  "`number`, a game handle"
                ],
                [
                  "`scrVector3*`",
                  "`{ x, y, z }`"
                ]
              ],
              "only": "js"
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "local ped = playerPedId()\nlocal pos = getEntityCoords(ped, true)\n\n-- BOOL return + float* out\nlocal found, groundZ = getGroundZFor3dCoord(pos.x, pos.y, pos.z + 1.0, false, 0)\n\n-- no return value + two vector outs\nlocal mn, mx = getModelDimensions(getHashKey(\"adder\"))\nlocal size = mx - mn                     -- Vector3 arithmetic\n\n-- no return value + two int outs\nlocal w, h = getActualScreenResolution()\n\n-- int return + BOOL* + two vector outs + Entity* out\nlocal probe = startExpensiveSynchronousShapeTestLosProbe(pos.x, pos.y, pos.z, pos.x, pos.y, pos.z - 10.0, -1, ped, 7)\nlocal result, hit, coords, normal, entity = getShapeTestResult(probe)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "const ped = playerPedId();\nconst pos = getEntityCoords(ped, true);\n\n// BOOL return + float* out\nconst [found, groundZ] = getGroundZFor3dCoord(pos.x, pos.y, pos.z + 1.0, false, 0);\n\n// no return value + two vector outs: [{ x, y, z }, { x, y, z }]\nconst [mn, mx] = getModelDimensions(getHashKey('adder'));\nconst height = mx.z - mn.z;\n\n// no return value + two int outs\nconst [w, h] = getActualScreenResolution();\n\n// int return + BOOL* + two vector outs + Entity* out\nconst probe = startExpensiveSynchronousShapeTestLosProbe(pos, { x: pos.x, y: pos.y, z: pos.z - 10.0 }, -1, ped, 7);\nconst [result, hit, coords, normal, entity] = getShapeTestResult(probe);"
                }
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "Pointers the game only reads",
              "md": "Some natives take a value through a pointer only to **read** it: `DELETE_PED(Ped* ped)`, `DELETE_VEHICLE`, `REMOVE_BLIP`, `DELETE_ENTITY`, the `SET_*_AS_NO_LONGER_NEEDED` family, the rope natives. LS:MP treats these pointers as outputs, so the value you give does not reach the game and the call has no effect on your handle. Each one carries a **Known issue** note in the [natives reference](/resources/natives)."
            },
            {
              "type": "heading",
              "text": "Checked natives",
              "level": 2,
              "id": "natives-checked"
            },
            {
              "type": "text",
              "md": "The game trusts its arguments: an index out of range or a broken float can bring it down. LS:MP checks the arguments of the natives concerned **before the game sees them**, in both languages: an index must be in range, a float that must be a real number cannot be `NaN` or infinite, a handle must designate something alive, a required name must be given.\n\nA refused call is **silent**: it does not raise, the native does not run, and it returns its neutral value (`false`, `0`, `0.0` or a zero vector). If such a native seems to do nothing, check the accepted range on its entry in the [natives reference](/resources/natives)."
            },
            {
              "type": "table",
              "headers": [
                "Family",
                "Natives",
                "Accepted"
              ],
              "rows": [
                [
                  "HUD colors",
                  "`replaceHudColour`, `replaceHudColourWithRgba`",
                  "color `0` to `234`"
                ],
                [
                  "HUD components",
                  "`showHudComponentThisFrame`, `hideHudComponentThisFrame`, `setHudComponentPosition` and related",
                  "`0` to `160`, scripted components `0` to `29`"
                ],
                [
                  "Vehicle windows",
                  "`rollDownWindow`, `smashVehicleWindow`, `isVehicleWindowIntact` and related",
                  "`0` to `7`"
                ],
                [
                  "Vehicle doors",
                  "`isVehicleDoorFullyOpen`, `getIsDoorValid`, `getVehicleIndividualDoorLockStatus`",
                  "`0` to `6`"
                ],
                [
                  "Tyres",
                  "`setVehicleTyreFixed`, `getTyreHealth`, `setTyreHealth` and related",
                  "`0` to `7`"
                ],
                [
                  "Vehicle classes",
                  "`getVehicleClassMaxBraking`, `getVehicleClassMaxTraction` and related",
                  "`0` to `22`"
                ],
                [
                  "Ped components",
                  "`getPedDrawableVariation`, `getPedTextureVariation`, `getPedPaletteVariation`",
                  "`0` to `11`"
                ],
                [
                  "Combat attributes",
                  "`setPedCombatAttributes`",
                  "`0` to `90`"
                ],
                [
                  "TV",
                  "`setTvChannel`, `setTvChannelPlaylist`, `setTvChannelPlaylistAtHour`",
                  "channel `-1` (off, for `setTvChannel`) or `0` to `4`, hour `0` to `23`"
                ],
                [
                  "Text blocks",
                  "`requestAdditionalText`, `hasAdditionalTextLoaded` and related",
                  "slot `0` to `21`, `0` to `22` to query"
                ],
                [
                  "Markers",
                  "`drawMarker`, `drawMarkerEx`",
                  "type `0` to `44`, finite position, size and rotation"
                ],
                [
                  "Clock",
                  "`setClockTime`, `advanceClockTimeTo`, `networkOverrideClockTime`, `setClockDate`",
                  "hours `0`–`23`, minutes and seconds `0`–`59`, or a valid Gregorian date with a zero-based month and year `1898`–`2499`"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Enhanced 1158.16 adapters",
              "level": 2,
              "id": "natives-enhanced-adapters"
            },
            {
              "type": "text",
              "md": "These 17 client natives are available on GTA V Enhanced **1158.16**. Calls on another build raise an error. LS:MP builds the game's structures from named script fields and returns ordinary Lua tables or JavaScript objects and arrays. Invalid arguments or incompatible target entities raise an error. Check the leading success value on query results that return one."
            },
            {
              "type": "table",
              "headers": ["Calls", "Result or scope"],
              "rows": [
                ["`getClosestRoad`", "Success, south and north endpoints, south and north lane counts, and median width."],
                ["`getGroupSize`", "Leader present as `0` or `1`, then the number of followers."],
                ["`getMpOutfitDataFromMetadata`", "Pass `{ male, index }` with a zero-based index. Returns success and a record with `componentDrawables`, `componentTextures`, `propDrawables`, `propTextures` and `tattooOverlays`."],
                ["`getPedHeadBlendData`", "Success and a record with six shape and skin IDs, three blend weights and Boolean `isParent`."],
                ["`getPedNearbyPeds`, `getPedNearbyVehicles`, `getAllVehicles`", "Count and a dense array of up to 256 game handles. Lua starts at index 1, and JavaScript at index 0."],
                ["`getPosFromFiredEvent`", "Success and the source position of the selected event type."],
                ["`getWeaponHudStats`, `getWeaponComponentHudStats`", "Success and a record with `damage`, `speed`, `capacity`, `accuracy` and `range`."],
                ["`addRope`, `attachEntitiesToRope`", "Load rope textures before creation. Each resource can create up to 32 live ropes on this client. Attachments require a rope and two distinct local entities with physics instances owned by that resource."],
                ["`taskScriptedAnimation`, `playEntityScriptedAnim`", "Scripted animation on a resource-owned local ped, vehicle or object. Load each clip dictionary first."],
                ["`taskMoveNetworkByNameWithInitParams`, `taskMoveNetworkAdvancedByNameWithInitParams`", "Movement graphs on a resource-owned local ped. Clone override must be false. Flags may use only bits `0x04` and `0x08`."],
                ["`createMissionTrain`", "Returns the local locomotive handle or `0`. Preload the models for the selected variation. Pass `false` for both network flags."]
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                { "label": "Lua", "lang": "lua", "code": "local pos = getEntityCoords(playerPedId(), true)\nlocal found, south, north, lanesSouth, lanesNorth, median = getClosestRoad(pos, 0, 1, true)\nif found then\n    print(lanesSouth, lanesNorth, median)\nend" },
                { "label": "JavaScript", "lang": "js", "code": "const pos = getEntityCoords(playerPedId(), true);\nconst [found, south, north, lanesSouth, lanesNorth, median] = getClosestRoad(pos, 0, 1, true);\nif (found) console.log(lanesSouth, lanesNorth, median);" }
              ]
            },
            {
              "type": "text",
              "md": "For a scripted animation, pass a record per priority slot. Omit the record or use `state: 0` for an empty slot, `state: 1` for a clip, or `state: 2` for three blended clips. Set `dictionary`, `clip`, `phase`, `rate` and `weight`, with the suffixes `2` and `3` for the other two clips. Phase and weight are `0`–`1`, rate is `0`–`10`, and rate and weight default to `1`. The slot also accepts `filter`, `blendIn` and `blendOut` (`0`–`60`, default `0.25`), `duration` (default `-1`), `flags` (bits `1`, `2`, `16`, `32`, `128` and `256`) and `ikFlags` (must be zero)."
            },
            {
              "type": "text",
              "md": "For a movement graph, pass a record with optional hash pairs `clipSetHash` and `variableClipSetHash` and their `2` variants. Use `floatName`, `floatValue`, `floatLerp` for a float signal and `boolName`, `boolValue` for a Boolean signal. Add the suffix `2` for a second signal of either type. Float lerp defaults to `-1`. Structured parameter names and clip names support up to 127 UTF-8 bytes each. The [natives reference](/resources/natives) lists the arguments and bounds for each call."
            },
            {
              "type": "heading",
              "text": "Blocked natives",
              "level": 2,
              "id": "natives-blocked"
            },
            {
              "type": "text",
              "md": "Calling a blocked native raises an error before the game sees the call. The **Blocked** filter in the [natives reference](/resources/natives) lists the current policy. Three camera and entity calls also enforce resource scope: pass `false` or `0` for the scope flag documented on `destroyCam`, `destroyAllCams` and `setEntityAsMissionEntity`."
            },
            {
              "type": "table",
              "headers": [
                "Family",
                "What it covers",
                "Instead"
              ],
              "rows": [
                [
                  "Rockstar accounts and commerce",
                  "`MONEY`, `NETSHOPPING`, `SOCIALCLUB`, `APP`, `SAVEMIGRATION`",
                  "Keep your economy and profiles on your server, with [storage](#server-storage)."
                ],
                [
                  "Rockstar online sessions and content",
                  "`LOBBY`, `LANDINGPAGE`, `NETWORK_SESSION_*`, `NETWORK_TRANSITION_*`, UGC, remote textures and Rockstar network authority changes",
                  "LS:MP runs the session: use [events](#events) and [remote calls](#rpc)."
                ],
                [
                  "Game script threads",
                  "`START_NEW_SCRIPT`, `TERMINATE_THREAD`, the `BRAIN` namespace",
                  "Your code runs as a [resource](#quick-start). To quiet a story script, see [`suspendStoryScript`](#client-resources/fn-resources-suspend-story-script)."
                ],
                [
                  "Saves and game flow",
                  "Save data, `STAT_SAVE`, `RESTART_GAME`",
                  "Store data with [storage](#server-storage)."
                ],
                [
                  "Rockstar Editor",
                  "`RECORDING`, `REPLAY`",
                  "Not available to resources."
                ],
                [
                  "Raw memory and structures",
                  "`DATAFILE`, raw pointers and game structures without a typed adapter",
                  "For entity lists, [`lsmp.getGamePool`](#world/fn-get-game-pool). For JSON, your language's own JSON functions."
                ],
                [
                  "Shared menus and input",
                  "The game's frontend and pause menu, on-screen keyboard and input layout",
                  "Use the LS:MP page and input APIs for your resource UI."
                ],
                [
                  "Managed world state",
                  "Shared weather changes and unchecked clock increments",
                  "Use the documented LS:MP world APIs and checked clock setters."
                ],
                [
                  "Replaced by the language",
                  "Bit helpers and string conversions",
                  "Your language's own operators and functions."
                ]
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "local ok, err = pcall(startNewScript, \"cellphone_flashhand\", 1424)\nlsmp.log(tostring(ok) .. \" \" .. tostring(err))   --> false ... not available to scripts"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "try {\n  startNewScript('cellphone_flashhand', 1424);\n} catch (err) {\n  lsmp.log(err.message);   // startNewScript: this native is not available to scripts\n}"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Any* pointers",
              "level": 2,
              "id": "natives-any"
            },
            {
              "type": "text",
              "md": "An `Any*` parameter is a pointer whose size no signature gives: nothing tells how much the game will read or write there. A script cannot supply one safely, so **every native with an `Any*` parameter is blocked**, whatever you pass. This includes the natives that fill a script array, like `getPedNearbyVehicles` and `getAllVehicles`: use [`lsmp.getGamePool`](#world/fn-get-game-pool) instead."
            },
            {
              "type": "heading",
              "text": "Coverage",
              "level": 2,
              "id": "natives-coverage"
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "**About 220 names are not in the current game build.** The global exists, does nothing, returns nothing, and never raises.",
                "**Some natives are not exposed at all**, so the global does not exist. The notable gap is the interior room and portal cluster: `getInteriorRoomCount`, `getInteriorPortalCount`, `getInteriorRoomName` and the like. Basic interior lookups are present: `isValidInterior`, `getInteriorFromEntity`, `getInteriorAtCoords`, `refreshInterior`, and the entity-set natives.",
                "**One is left out on purpose:** the game's `WAIT`. It only works inside the game's own compiled scripts and cannot pause an LS:MP script. Pause with [`lsmp.wait`](#core-utils/fn-wait)."
              ]
            },
            {
              "type": "callout",
              "variant": "info",
              "title": "When a native seems to do nothing",
              "md": "Look it up in the [natives reference](/resources/natives) before debugging your own code. It may not be in this build, it may have refused an argument out of range, or it may be blocked."
            },
            {
              "type": "callout",
              "variant": "danger",
              "title": "One native can crash the game",
              "md": "`getEntityModel` reads the entity's archetype without checking that it exists. On an entity whose archetype is missing, the game goes down on the spot, and `doesEntityExist` does **not** protect you. Do not call it on a handle from a shape test or [`lsmp.raycast`](#world/fn-raycast). The type natives (`isEntityAPed`, `isEntityAVehicle`, `isEntityAnObject`) read the entity itself and are safe."
            },
            {
              "type": "heading",
              "text": "Coming from FiveM",
              "level": 2,
              "id": "natives-fivem"
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "Same contract",
              "md": "Out-params work the FiveM way, so scripts port easily: `GetGroundZFor_3dCoord(x, y, z, water)` gives a boolean and a number in FiveM, and `getGroundZFor3dCoord(x, y, z, water, 0)` gives the same here."
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "LS:MP names are **camelCase**; FiveM's are PascalCase.",
                "There are no `_i` / `_f` / `_v` pointer sentinels and no `Citizen.InvokeNative`. You never declare an out-param: skip the argument.",
                "A `BOOL*` out-param comes back as a real boolean, where FiveM gives an integer. A hash comes back unsigned.",
                "In JavaScript, a vector comes back as an `{ x, y, z }` object, not an array.",
                "Parameter lists come from a natives database that sometimes includes parameters FiveM omits: `getGroundZFor3dCoord` takes a trailing `p5`, for instance."
              ]
            }
          ]
        }
      ]
    },
    {
      "id": "reference",
      "title": "Reference",
      "icon": "📖",
      "pages": [
        {
          "id": "conventions",
          "title": "Conventions (types, errors, units, colors, vectors, hashes, async, subscriptions)",
          "eyebrow": "Reference",
          "lead": "The rules every lsmp function follows: types, errors and failures, absent values, colors, vectors, hashes, units, transportable values, asynchronous calls and subscriptions.",
          "blocks": [
            {
              "type": "text",
              "md": "These rules hold for **every** `lsmp` function, on the server and on the client, in Lua and in JavaScript. Function pages do not repeat them: they only say what is specific to the function."
            },
            {
              "type": "heading",
              "text": "Types used in signatures",
              "level": 2,
              "id": "types"
            },
            {
              "type": "text",
              "md": "Signatures use a few names for common values. They are plain numbers, strings or tables: there is no special class to create."
            },
            {
              "type": "table",
              "headers": [
                "Type",
                "Lua",
                "JavaScript",
                "Meaning"
              ],
              "rows": [
                [
                  "`playerId`",
                  "integer",
                  "number",
                  "A connected player, `0..65534`. Valid for one session and reused after the player leaves. See [Players](#players)."
                ],
                [
                  "`netId`",
                  "integer",
                  "number",
                  "A networked entity, `1..65535`, the same number on the server and on every client. Reused after the entity is deleted."
                ],
                [
                  "`handle`",
                  "integer",
                  "number",
                  "Client only: the game's own handle of an entity, valid on this client only. Turn a `netId` into a handle with `lsmp.getEntityFromNetId`."
                ],
                [
                  "`dimension`",
                  "integer",
                  "number",
                  "A dimension, `0..65535`. `0` is the default world. See [Dimensions](#dimensions)."
                ],
                [
                  "`vec3` (input)",
                  "`Vector3`, `{x, y, z}` or `{x = .., y = .., z = ..}`",
                  "`{x, y, z}` or `[x, y, z]`",
                  "A position or a direction, in meters, always **one** argument."
                ],
                [
                  "`Vector3` / `Vec3` (output)",
                  "`Vector3`",
                  "`{x, y, z}`",
                  "What functions return."
                ],
                [
                  "`rotation`",
                  "`{x, y, z}`",
                  "`{x, y, z}`",
                  "Degrees: `x` = pitch, `y` = roll, `z` = yaw."
                ],
                [
                  "`heading`",
                  "number",
                  "number",
                  "Degrees, yaw only."
                ],
                [
                  "`hash`",
                  "integer or string",
                  "number or string",
                  "A 32-bit game hash. A string is hashed with [`lsmp.hash`](#core-utils/fn-hash)."
                ],
                [
                  "`ms`",
                  "integer",
                  "number",
                  "A duration in milliseconds."
                ],
                [
                  "`epochMs`",
                  "integer",
                  "number",
                  "A point in time: milliseconds since the Unix epoch (`lsmp.nowMs()`)."
                ],
                [
                  "`meters`",
                  "number",
                  "number",
                  "A distance."
                ],
                [
                  "`color`",
                  "see [Colors](#conventions/colors)",
                  "see [Colors](#conventions/colors)",
                  "A color, read in four forms."
                ],
                [
                  "`value`",
                  "see [Transportable values](#conventions/transportable-values)",
                  "see [Transportable values](#conventions/transportable-values)",
                  "Any value that can travel between resources, engines and machines."
                ],
                [
                  "`event`",
                  "string",
                  "string",
                  "An event or RPC name: 1 to 128 bytes of UTF-8, no NUL, case-sensitive. See [Reserved names](#conventions/reserved-names)."
                ],
                [
                  "`name`",
                  "string",
                  "string",
                  "A resource name (its folder name)."
                ],
                [
                  "`ids`",
                  "sequence of integers",
                  "`Uint32Array`",
                  "A list of netIds that can be large (`getEntities`, `getEntitiesInRadius`)."
                ],
                [
                  "`fn`",
                  "function",
                  "function",
                  "A function you provide (handler, callback)."
                ]
              ]
            },
            {
              "type": "text",
              "md": "A `?` after a type (`string?`, `integer?`) or `| null` means the value may be absent: `nil` in Lua, `null` in JavaScript."
            },
            {
              "type": "heading",
              "text": "Errors and failures",
              "level": 2,
              "id": "errors"
            },
            {
              "type": "text",
              "md": "A call can go wrong in two ways that never overlap: a **programming error** raises, a **run-time failure** returns a failure value."
            },
            {
              "type": "table",
              "headers": [
                "Situation",
                "Lua",
                "JavaScript"
              ],
              "rows": [
                [
                  "Programming error: wrong type, missing required argument, a function expected and not given",
                  "raises `lsmp.fn: <text>`",
                  "`TypeError`"
                ],
                [
                  "Value out of its domain: number out of range, unknown name in a fixed list, path leaving the resource, size over a documented limit, reserved name",
                  "raises `lsmp.fn: <text>`",
                  "`RangeError` (reserved name: `Error`)"
                ],
                [
                  "Run-time failure of a synchronous call: player gone, unknown entity, quota reached, capability refused, object of another resource",
                  "action: `false, \"code\"`; read: `nil, \"code\"`",
                  "action: `false`; read: `null`; the code with [`lsmp.getLastError()`](#core-utils/fn-get-last-error)"
                ],
                [
                  "Run-time failure of an asynchronous call",
                  "`cb(nil, \"code\", details?)`, or `nil, \"code\", details?` in a coroutine",
                  "the Promise rejects with an `Error` whose `code` is the failure code"
                ]
              ]
            },
            {
              "type": "list",
              "items": [
                "Every message starts with the function name: `lsmp.setEntityMeta: arg 2 'key' ...`. A method says `browser:emit:` in Lua and `browser.emit:` in JavaScript.",
                "A value that cannot be sent names its path: `lsmp.emitServer: args[2].inventory[4].icon: function is not transportable`. Indices follow the language: `args[1]` is the first argument in Lua, `args[0]` in JavaScript.",
                "A **refused capability** is a failure with the code `permission`, never an error. The server log gets one warning per resource and capability at most once a minute, naming the capability and where the operator grants it. See [Capabilities](#capabilities).",
                "Nothing is silently converted: a number is never taken for a string (or the reverse), `undefined` is never stored as `\"undefined\"`, a boolean is never a number, a string that is too long is never cut.",
                "In an asynchronous JavaScript function, a programming error throws **synchronously** (at the call); everything else rejects the Promise. In Lua, a programming error raises at the call, before any callback.",
                "`details` (third Lua value, extra fields of the JavaScript `Error`) only exists where a function says so (MySQL, HTTP, files)."
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "local ok, err = lsmp.setEntityOwner(netId, playerId)\nif not ok then\n  lsmp.warn(\"cannot give the entity: \" .. err) -- \"not-found\", \"permission\"...\nend"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "if (!lsmp.setEntityOwner(netId, playerId)) {\n  lsmp.warn(`cannot give the entity: ${lsmp.getLastError()}`);\n}"
                }
              ]
            },
            {
              "type": "text",
              "md": "The codes form a closed list: see [Error codes](#error-codes)."
            },
            {
              "type": "heading",
              "text": "Absent values",
              "level": 2,
              "id": "absent"
            },
            {
              "type": "list",
              "items": [
                "Absent is `nil` in Lua and `null` in JavaScript, **everywhere**: return values, fields of returned tables, event arguments (`killerId`, `oldOwner`...). A business value (`0` for the default dimension) is never used to mean \"absent\".",
                "A field that is absent from a returned table does not exist in Lua; in JavaScript it is present and `null` when the shape documents it.",
                "\"Unknown\" and \"empty\" are told apart by an existence function: `lsmp.entityExists`, `lsmp.playerExists`.",
                "In JavaScript, `undefined` and `null` passed as an argument both mean \"absent\" (the documented default applies), except where `nil` has an explicit meaning, such as \"nil deletes\" for meta and storage."
              ]
            },
            {
              "type": "heading",
              "text": "Booleans",
              "level": 2,
              "id": "booleans"
            },
            {
              "type": "list",
              "items": [
                "Functions and events return real booleans.",
                "Arguments and option fields take `true` or `false`; `nil` or absent selects the documented default. A number, a string or a table in place of a boolean is a programming error: `0` is not `false`.",
                "Some sensitive settings have **no default** and need the boolean explicitly, for example `lsmp.setDimensionPopulation(dimension, enabled)`."
              ]
            },
            {
              "type": "heading",
              "text": "Colors",
              "level": 2,
              "id": "colors"
            },
            {
              "type": "text",
              "md": "Every function that takes a color reads it the same way:"
            },
            {
              "type": "table",
              "headers": [
                "Form",
                "Example",
                "Meaning"
              ],
              "rows": [
                [
                  "number `0xRRGGBB`",
                  "`0xFF0000`",
                  "Opaque. A number above `0xFFFFFF` is an error (use one of the forms below for transparency)."
                ],
                [
                  "named fields",
                  "`{ r = 255, g = 0, b = 0, a = 128 }`",
                  "Integers `0..255`; `a` defaults to 255."
                ],
                [
                  "list",
                  "`{255, 0, 0}` / `[255, 0, 0, 128]`",
                  "Same, in order r, g, b, a."
                ],
                [
                  "string",
                  "`\"#ff0000\"`, `\"#ff000080\"`",
                  "Hexadecimal, case-insensitive."
                ]
              ]
            },
            {
              "type": "text",
              "md": "Colors are returned as `\"#rrggbb\"` when opaque, otherwise `\"#rrggbbaa\"`."
            },
            {
              "type": "heading",
              "text": "Vectors and rotations",
              "level": 2,
              "id": "vectors"
            },
            {
              "type": "list",
              "items": [
                "A position is always **one** argument, never three numbers: Lua `Vector3`, `{x, y, z}` or `{x = .., y = .., z = ..}`; JavaScript `{x, y, z}` or `[x, y, z]`. A component that is not a finite number is an error.",
                "Functions return a `Vector3` in Lua and a plain `{x, y, z}` object in JavaScript.",
                "Screen points use `{x, y}` (Lua table `{x = .., y = ..}`).",
                "A rotation is `{x, y, z}` in degrees: `x` = pitch, `y` = roll, `z` = yaw, in the game's usual rotation order. Where only the facing matters, functions take a `heading` (degrees)."
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "local pos = lsmp.getEntityCoords(netId)       -- Vector3\nlocal car = lsmp.createEntity(\"vehicle\", \"adder\", pos, { heading = 90.0 })\nlsmp.createEntity(\"object\", \"prop_barrier_work05\", { x = 10, y = 20, z = 30 })"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "const pos = lsmp.getEntityCoords(netId);       // { x, y, z }\nconst car = lsmp.createEntity(\"vehicle\", \"adder\", pos, { heading: 90 });\nlsmp.createEntity(\"object\", \"prop_barrier_work05\", [10, 20, 30]);"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Hashes",
              "level": 2,
              "id": "hashes"
            },
            {
              "type": "list",
              "items": [
                "Hashes are **unsigned** 32-bit integers everywhere, game natives included: `lsmp.getEntityModel(car) == lsmp.hash(\"adder\")`.",
                "As input, a hash may be an integer in `-2^31 .. 2^32-1` (signed or unsigned form of the same bits) or a string, which is hashed with `lsmp.hash` (ASCII letters are lower-cased first). Anything else is an error."
              ]
            },
            {
              "type": "heading",
              "text": "Units",
              "level": 2,
              "id": "units"
            },
            {
              "type": "table",
              "headers": [
                "Quantity",
                "Unit",
                "Naming"
              ],
              "rows": [
                [
                  "duration",
                  "milliseconds, integer",
                  "suffix `Ms`: `timeoutMs`, `transitionMs`, `durationMs`, `lifetimeMs`"
                ],
                [
                  "point in time",
                  "milliseconds since the Unix epoch",
                  "suffix `Ms`: `untilMs`, `atMs`, `mtimeMs`, `purchasedAtMs`"
                ],
                [
                  "distance",
                  "meters",
                  "explicit name, no suffix: `radius`, `range`, `maxRadius`"
                ],
                [
                  "angle",
                  "degrees",
                  "`heading`, `rotation`, `fov`"
                ],
                [
                  "screen position",
                  "normalized `0..1`",
                  "except functions whose name contains `Pixel`"
                ]
              ]
            },
            {
              "type": "text",
              "md": "There are no seconds or days in the API. `server.cfg` keys follow their own naming (see [server.cfg](#server-cfg))."
            },
            {
              "type": "heading",
              "text": "Transportable values",
              "level": 2,
              "id": "transportable-values"
            },
            {
              "type": "text",
              "md": "Event arguments, RPC arguments and results, meta values and stored values all use the same rules. A value is copied when it crosses a resource, an engine or the network: consider it **copied**, never shared."
            },
            {
              "type": "table",
              "headers": [
                "Lua",
                "JavaScript",
                "Travels as"
              ],
              "rows": [
                [
                  "`nil` (argument), `lsmp.null`",
                  "`undefined`, `null`",
                  "nothing (absent)"
                ],
                [
                  "boolean",
                  "boolean",
                  "boolean"
                ],
                [
                  "integer",
                  "integer `number` within ±(2^53-1), `bigint` within 64 bits",
                  "integer"
                ],
                [
                  "float (even `3.0`)",
                  "any other `number` (`NaN`, `Infinity` included)",
                  "float"
                ],
                [
                  "string (valid UTF-8)",
                  "string",
                  "string"
                ],
                [
                  "non-UTF-8 string, or `lsmp.bytes(s)`",
                  "`Uint8Array`, `Buffer`, `ArrayBuffer`, `DataView`",
                  "bytes"
                ],
                [
                  "`Vector3`",
                  "object whose only own keys are numeric `x`, `y`, `z`",
                  "vector"
                ],
                [
                  "sequence with keys exactly `1..n`; an empty table",
                  "`Array` (holes become `null`)",
                  "list"
                ],
                [
                  "table whose keys are all strings",
                  "plain object (own string keys)",
                  "map"
                ]
              ]
            },
            {
              "type": "text",
              "md": "Received values become: integers within ±(2^53-1) a JavaScript `number`, larger ones a `bigint`; bytes a Lua string or a JavaScript `Uint8Array`; a vector a Lua `Vector3` or a JavaScript `{x, y, z}`."
            },
            {
              "type": "text",
              "md": "**Not transportable** (the call raises before anything is sent): functions, coroutines, userdata, handles, Lua tables with mixed or non-string keys or holes, `Vector2`/`Vector4`/`Quaternion` (send `{x = .., y = ..}`), JavaScript `Map`, `Set`, `Date`, `RegExp`, `Promise`, `Error`, class instances, symbols, typed arrays other than `Uint8Array` (wrap them: `new Uint8Array(x.buffer, x.byteOffset, x.byteLength)`), strings with a lone surrogate, nesting deeper than 32 levels."
            },
            {
              "type": "callout",
              "variant": "warn",
              "md": "- An empty Lua table travels as a **list**: a JavaScript `{}` sent to Lua and back returns `[]`.\n- A map entry whose value is absent disappears in Lua (`{ a = nil }` has no key `a`). Inside a list, an absent element arrives as `lsmp.null` in Lua so the length is kept.\n- A JavaScript object with only numeric `x`, `y`, `z` keys becomes a `Vector3` in Lua. To send a business object with these keys, add another key.\n- Lua floats are 32-bit: a vector sent from JavaScript to Lua loses precision beyond about 7 digits.\n- The order of keys of a map built in Lua is not fixed.",
              "title": "Good to know"
            },
            {
              "type": "text",
              "md": "Size limits (per direction, per meta value, per stored value) are in [Limits and quotas](#limits)."
            },
            {
              "type": "heading",
              "text": "Asynchronous functions",
              "level": 2,
              "id": "async"
            },
            {
              "type": "text",
              "md": "Functions that wait for the disk, the database, the network or another machine are asynchronous. Their pages say so."
            },
            {
              "type": "heading",
              "text": "JavaScript: Promises",
              "level": 3,
              "id": "async-js"
            },
            {
              "type": "text",
              "md": "An asynchronous function returns a Promise. It resolves with the result, or rejects with an `Error` whose `message` is `\"lsmp.fn: <code>: <detail>\"` and whose `code` is one of the [error codes](#error-codes). When an operation has a job id, it is exposed as `promise.jobId`."
            },
            {
              "type": "heading",
              "text": "Lua: callback or coroutine",
              "level": 3,
              "id": "async-lua"
            },
            {
              "type": "list",
              "items": [
                "**Callback**: pass a function as the last argument, after the declared parameters (`lsmp.fs.readFile(path, cb)` and `lsmp.fs.readFile(path, opts, cb)` both work). It is called **later**, never during the call, exactly once, with `cb(result, nil)` on success and `cb(nil, \"code\", details)` on failure (`false` instead of `nil` when the normal result is a boolean). An error raised inside the callback is logged and goes no further.",
                "**Coroutine**: without a callback, inside a **host coroutine**, the call suspends and returns `result, err, details`. The rest of the server keeps running.",
                "Without a callback outside a host coroutine, the call raises `lsmp.fn: needs a callback here (not inside a coroutine)`.",
                "Host coroutines are: the body of every script file, every handler of `lsmp.on`, `lsmp.once`, `lsmp.onServer`, `lsmp.onClient` and `lsmp.onCall`, `playerPreConnection` handlers, and every `lsmp.createThread` function. A suspended handler blocks neither the next event nor the other handlers. When the resource stops, its pending waits end with `cancelled`.",
                "`lsmp.onTick` handlers, and functions called by Lua itself (a `table.sort` comparator, a metamethod), cannot suspend."
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- Coroutine form: inside an event handler\nlsmp.on(\"resourceStart\", function(name)\n  if name ~= lsmp.getResourceName() then return end\n  local text, err = lsmp.fs.readFile(lsmp.getDataPath() .. \"/motd.txt\")\n  if text then lsmp.log(text) else lsmp.warn(\"no motd: \" .. err) end\nend)\n\n-- Callback form: works anywhere\nlsmp.storage.flush(function(ok, err)\n  if not ok then lsmp.warn(\"flush failed: \" .. err) end\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "lsmp.on(\"resourceStart\", async (name) => {\n  if (name !== lsmp.getResourceName()) return;\n  try {\n    const text = await lsmp.fs.readFile(lsmp.getDataPath() + \"/motd.txt\");\n    lsmp.log(text);\n  } catch (e) {\n    lsmp.warn(`no motd: ${e.code}`);\n  }\n});"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Subscriptions",
              "level": 2,
              "id": "subscriptions"
            },
            {
              "type": "list",
              "items": [
                "`lsmp.on`, `once`, `onServer`, `onClient`, `onCall`, `onTick`, `registerCommand`, `browser:on` and `lsmp.http.serve` return an **unsubscribe function** `off()`, which returns `true` if it removed something. Each also has a symmetric `off*` function (`off`, `offServer`, `offClient`, `offCall`, `offTick`, `unregisterCommand`, `browser:off`).",
                "The same `(name, fn)` pair registered twice is registered once; the second call returns the same `off`.",
                "A handler that raises is isolated and logged as `[resource] lsmp: handler of '<name>' raised: ...`; the other handlers still run. It stays registered (only `onTick` handlers are disabled after 8 consecutive errors).",
                "Adding or removing a handler during a dispatch takes effect at the next dispatch.",
                "Everything a resource registered is removed when it stops.",
                "Handlers of one event run in registration order (resources in load order). When both engines of a side listen, JavaScript handlers run before Lua handlers. In JavaScript, `this` is `undefined` in every handler."
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "local off = lsmp.on(\"playerJoin\", function(playerId, name)\n  lsmp.log(name .. \" joined\")\nend)\n-- later\noff()"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "const off = lsmp.on(\"playerJoin\", (playerId, name) => {\n  lsmp.log(`${name} joined`);\n});\n// later\noff();"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Handles",
              "level": 2,
              "id": "handles"
            },
            {
              "type": "list",
              "items": [
                "Objects returned by `createBrowser`, `createScene`, `lsmp.mysql.createPool`... are **handles**: call their methods with `obj:m()` in Lua and `obj.m()` in JavaScript. Their `id` field, when they have one, is read-only.",
                "A method of a destroyed handle does nothing and returns `false` or `nil`; `isValid()` returns `false`. It never raises.",
                "Handles belong to the resource that created them and cannot be sent to another resource (they are not transportable). Passing the id of another resource's object fails with `permission`.",
                "Game identifiers (client entity handles, netIds, playerIds) stay integers."
              ]
            },
            {
              "type": "heading",
              "text": "Isolation and restore",
              "level": 2,
              "id": "isolation"
            },
            {
              "type": "list",
              "items": [
                "**Objects**: a resource only acts on what it created. Browsers, scenes, outlines, captures, MySQL pools, voice channels, HTTP routes, commands, handlers and timers belong to their resource and are destroyed when it stops. Acting on another resource's object fails with `permission`.",
                "**Server entities**: the entities and pickups a resource creates belong to it. Acting on others needs the `entities.foreign` capability. When the resource stops, its entities and pickups are deleted (except `lifePolicy = \"keep\"`) and its synchronized scenes stop.",
                "**Global settings** that a resource changes are restored when it stops: the last writer wins, and when it stops the value of the previous writer comes back (or the engine default). This covers the synchronized weather on the server, and on the client the voice settings, nametag styles, Discord presence, local weather, auto spawn, HUD money and player blips, picking and outlines.",
                "Not restored: the whitelist, bans, permissions and groups, meta, storage, and dimension settings (population, client entities). They are data or operator policy.",
                "The log level, memory and time budgets are per resource."
              ]
            },
            {
              "type": "heading",
              "text": "Reserved names",
              "level": 2,
              "id": "reserved-names"
            },
            {
              "type": "list",
              "items": [
                "**Engine event names** (see [Engine events](#engine-events)) can be listened to with `lsmp.on`, but `emit`, `emitServer`, `emitClient`, `emitAllClients`, `emitDimensionClients`, `onServer`, `onClient`, `onCall` and `browser:emit` with these names raise `Error` (`lsmp.emit: 'playerDeath' is an engine event`).",
                "The prefix **`lsmp:`** is reserved for event names, RPC names and meta keys (storage keys are not concerned).",
                "Browser lifecycle names (`load`, `loadError`, `focusLost`, `crash`) are reserved on a browser handle: a page cannot emit them.",
                "Built-in console commands (`help`, `status`, `players`, `resources`, `kick`, `say`, `quit` on the server) cannot be registered by a script.",
                "Meta keys starting with `lsmp:` read as absent and raise on write."
              ]
            },
            {
              "type": "heading",
              "text": "Lists, identifiers and seats",
              "level": 2,
              "id": "lists"
            },
            {
              "type": "list",
              "items": [
                "Lists are Lua sequences `{...}` and JavaScript arrays. Lists of netIds that can be large are a `Uint32Array` in JavaScript (`getEntities`, `getEntitiesInRadius`).",
                "Lists of pairs are lists of objects: `{ seat, ped }`, `{ playerId, role }`.",
                "Seats: `0` is the driver, `1` and up are passengers, everywhere.",
                "Entity types are strings: `\"vehicle\"`, `\"ped\"`, `\"object\"`, `\"playerPed\"` ([`lsmp.EntityType`](#server-entities/const-entity-type)).",
                "Identifiers are strict integers: a numeric string is not a playerId. Out-of-range identifiers are errors."
              ]
            },
            {
              "type": "heading",
              "text": "Lua and JavaScript differences",
              "level": 2,
              "id": "lua-js"
            },
            {
              "type": "text",
              "md": "The API is the same in both languages. These differences are deliberate, and are the only ones:"
            },
            {
              "type": "table",
              "headers": [
                "Subject",
                "Lua",
                "JavaScript"
              ],
              "rows": [
                [
                  "method call",
                  "`obj:m()`",
                  "`obj.m()`"
                ],
                [
                  "asynchronous call",
                  "final callback or coroutine, `result, err`",
                  "Promise"
                ],
                [
                  "reason of a synchronous failure",
                  "second return value `\"code\"`",
                  "`lsmp.getLastError()`"
                ],
                [
                  "vector returned",
                  "`Vector3`",
                  "`{x, y, z}`"
                ],
                [
                  "bytes",
                  "string (send binary explicitly with `lsmp.bytes(s)`)",
                  "`Uint8Array`"
                ],
                [
                  "explicit null in a list, JSON or SQL",
                  "`lsmp.null`",
                  "`null`"
                ],
                [
                  "JSON",
                  "`lsmp.json.encode/decode/array`",
                  "`JSON`"
                ],
                [
                  "thread",
                  "`lsmp.createThread(fn, ...)`",
                  "`async` function"
                ],
                [
                  "print",
                  "`print` = `lsmp.log`",
                  "`console.*` routed to `lsmp.log/warn/error/debug`"
                ],
                [
                  "timers",
                  "integer ids",
                  "client: integer ids; server: Node `Timeout` objects"
                ],
                [
                  "integers beyond 2^53",
                  "64-bit Lua integers",
                  "`BigInt`"
                ],
                [
                  "indices in error paths",
                  "from 1 (`args[1]` = first argument)",
                  "from 0 (`args[0]`)"
                ]
              ]
            },
            {
              "type": "function",
              "name": "lsmp.null",
              "id": "const-null",
              "side": "shared",
              "engines": [
                "lua"
              ],
              "signature": {
                "lua": "lsmp.null"
              },
              "summary": "Lua only: an explicit null. It stands for JSON `null`, SQL `NULL` and an absent element inside a list.",
              "md": "Test it with `v == lsmp.null` (it is not falsy). Received lists keep their length with it: `{1, lsmp.null, 3}`. In a map, an absent value is simply a missing key. JavaScript uses `null`."
            }
          ]
        },
        {
          "id": "engine-events",
          "title": "Engine events (table)",
          "eyebrow": "Reference",
          "lead": "Every event LS:MP fires for your scripts: when it fires, on which side, with which arguments, and what is guaranteed.",
          "blocks": [
            {
              "type": "text",
              "md": "Engine events tell your scripts what happens in the game and on the server: a player joins, an entity changes owner, a resource stops. Listen to them with [`lsmp.on`](#events/fn-on) like any local event. Their names are [reserved](#conventions/reserved-names): a script can listen to them but never emit them."
            },
            {
              "type": "text",
              "md": "One fact has **the same name and the same arguments** on the server and on the client. When an event exists on both sides, the table says \"server, client\"."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "lsmp.on(\"playerJoin\", function(playerId, name)\n  lsmp.log(name .. \" joined as player \" .. playerId)\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "lsmp.on(\"playerJoin\", (playerId, name) => {\n  lsmp.log(`${name} joined as player ${playerId}`);\n});"
                }
              ]
            },
            {
              "type": "heading",
              "text": "Guarantees",
              "level": 2,
              "id": "guarantees"
            },
            {
              "type": "text",
              "md": "Unless an event says otherwise, these rules hold for every engine event:"
            },
            {
              "type": "list",
              "items": [
                "**Asynchronous**: an engine event is never delivered inside the `lsmp` call that caused it. `lsmp.setPlayerDimension` returns first, then `playerDimensionChange` arrives.",
                "**Both engines** of the side receive it: JavaScript handlers first, then Lua handlers, each in registration order (resources in load order).",
                "**Order**: two events coming from the same part of the engine arrive in the order they happened. There is no order between unrelated parts (voice and dimensions, for example).",
                "**Types**: real booleans, `nil`/`null` for absent values, unsigned hashes, vectors (`Vector3` in Lua, `{x, y, z}` in JavaScript), strings for reasons and kinds.",
                "**No replay**: a resource that starts does not receive past events. Read the current state instead: `lsmp.getPlayers()`, `lsmp.getResources()`, `lsmp.weather.get()`...",
                "A handler may suspend (Lua coroutine, `async` function) without delaying the other handlers."
              ]
            },
            {
              "type": "heading",
              "text": "All engine events",
              "level": 2,
              "id": "table"
            },
            {
              "type": "table",
              "headers": [
                "Event",
                "Sides",
                "Arguments",
                "When"
              ],
              "rows": [
                [
                  "[`resourceStart`](#engine-events/ev-resource-start)",
                  "server, client",
                  "`name`",
                  "After a resource's entry scripts (and module-level awaits) completed."
                ],
                [
                  "[`resourceStop`](#engine-events/ev-resource-stop)",
                  "server, client",
                  "`name`",
                  "Before a resource is torn down: its own handlers run first, then other resources'."
                ],
                [
                  "[`serverStart`](#engine-events/ev-server-start)",
                  "server",
                  "—",
                  "Once, after every resource of the boot set has started and the game port listens."
                ],
                [
                  "[`serverStop`](#engine-events/ev-server-stop)",
                  "server",
                  "—",
                  "On graceful shutdown (console quit, admin panel restart/stop, update, SIGTERM/CTRL+C): after playerLeave(..., \"shutdown\") for every player, before resources stop."
                ],
                [
                  "[`playerPreConnection`](#engine-events/ev-player-pre-connection)",
                  "server",
                  "`p`",
                  "When an admitted client asks to join, before any slot is given."
                ],
                [
                  "[`playerJoin`](#engine-events/ev-player-join)",
                  "server, client",
                  "`playerId`, `name`",
                  "Server: the player has a slot and is in the session (after admission)."
                ],
                [
                  "[`playerLeave`](#engine-events/ev-player-leave)",
                  "server, client",
                  "`playerId`, `name`, `reason`, `detail`, `client`",
                  "The player left the session."
                ],
                [
                  "[`playerSpawn`](#engine-events/ev-player-spawn)",
                  "server, client",
                  "`playerId`, `position`, `heading`, `model`, `first`",
                  "Client: the local player spawned (lsmp.spawn, auto spawn, respawn)."
                ],
                [
                  "[`playerDeath`](#engine-events/ev-player-death)",
                  "server, client",
                  "`playerId`, `killerId`, `weaponHash`, `position`, `flags`, `killerEntity`",
                  "Server: the victim's client reported its death (deduplicated, rate-limited, killer resolved by the server)."
                ],
                [
                  "[`playerDimensionChange`](#engine-events/ev-player-dimension-change)",
                  "server, client",
                  "`playerId`, `oldDimension`, `newDimension`",
                  "A player changed dimension."
                ],
                [
                  "[`entityDimensionChange`](#engine-events/ev-entity-dimension-change)",
                  "server",
                  "`netId`, `oldDimension`, `newDimension`",
                  "An entity changed dimension."
                ],
                [
                  "[`entityOwnerChange`](#engine-events/ev-entity-owner-change)",
                  "server",
                  "`netId`, `oldOwner`, `newOwner`, `reason`",
                  "Simulation of an entity moved."
                ],
                [
                  "[`entityAdopt`](#engine-events/ev-entity-adopt)",
                  "client",
                  "`netId`",
                  "The local client starts simulating an entity."
                ],
                [
                  "[`entityRelease`](#engine-events/ev-entity-release)",
                  "client",
                  "`netId`",
                  "The local client stops simulating an entity."
                ],
                [
                  "[`entityStreamIn`](#engine-events/ev-entity-stream-in)",
                  "client",
                  "`netId`, `entity`",
                  "A networked entity got a game instance here."
                ],
                [
                  "[`entityStreamOut`](#engine-events/ev-entity-stream-out)",
                  "client",
                  "`netId`",
                  "A networked entity lost its game instance here (its handle is already invalid)."
                ],
                [
                  "[`voiceStart`](#engine-events/ev-voice-start)",
                  "server, client",
                  "`playerId`",
                  "A player starts transmitting."
                ],
                [
                  "[`voiceStop`](#engine-events/ev-voice-stop)",
                  "server, client",
                  "`playerId`",
                  "A player stops transmitting."
                ],
                [
                  "[`pickupCollect`](#engine-events/ev-pickup-collect)",
                  "server",
                  "`playerId`, `netId`, `pickupHash`, `amount`, `serverCreated`",
                  "The server granted a pickup to a player."
                ],
                [
                  "[`playerPermsChange`](#engine-events/ev-player-perms-change)",
                  "server, client",
                  "`playerId`",
                  "Server: a player's effective permissions changed."
                ],
                [
                  "[`weatherChange`](#engine-events/ev-weather-change)",
                  "server, client",
                  "`type`, `previous`, `transitionMs`",
                  "The target synchronized weather type changed (client: also when a local override starts/ends)."
                ],
                [
                  "[`benefitGrant`](#engine-events/ev-benefit-grant)",
                  "server",
                  "`lsmpId`, `benefit`",
                  "A connected account has a benefit to apply (once per session until consumed)."
                ],
                [
                  "[`benefitRevoke`](#engine-events/ev-benefit-revoke)",
                  "server",
                  "`lsmpId`, `benefit`",
                  "A benefit was revoked and must be taken back."
                ],
                [
                  "[`metaChange`](#engine-events/ev-meta-change)",
                  "server, client",
                  "`scope`, `target`, `key`, `value`, `source`, `client`",
                  "A script-visible meta value changed (server: any writer; client: replicated change received, own writes included)."
                ],
                [
                  "[`selectionChange`](#engine-events/ev-selection-change)",
                  "client",
                  "`entity`, `geomKey`, `valid`",
                  "The picked entity/geometry changed."
                ],
                [
                  "[`syncSceneStart`](#engine-events/ev-sync-scene-start)",
                  "client",
                  "`sceneId`, `netId`",
                  "An entity of the session starts a synchronized scene."
                ],
                [
                  "[`syncSceneStop`](#engine-events/ev-sync-scene-stop)",
                  "client",
                  "`sceneId`, `netId`",
                  "It stops."
                ],
                [
                  "[`serverMessage`](#engine-events/ev-server-message)",
                  "client",
                  "`text`",
                  "The server console ran `say`."
                ],
                [
                  "[`browser:load`](#engine-events/ev-browser-on-load)",
                  "client",
                  "`url`",
                  "The page (main frame) finished loading."
                ],
                [
                  "[`browser:loadError`](#engine-events/ev-browser-on-load-error)",
                  "client",
                  "`url`, `code`",
                  "Navigation failed or the URL was refused."
                ],
                [
                  "[`browser:focusLost`](#engine-events/ev-browser-on-focus-lost)",
                  "client",
                  "—",
                  "The player took focus back (escape hatch) or another page took it."
                ],
                [
                  "[`browser:crash`](#engine-events/ev-browser-on-crash)",
                  "client",
                  "`reason`",
                  "The page renderer crashed."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Resources and server",
              "level": 2,
              "id": "resources"
            },
            {
              "type": "function",
              "name": "resourceStart",
              "id": "ev-resource-start",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"resourceStart\", function(name) end)",
                "js": "lsmp.on(\"resourceStart\", (name) => {})"
              },
              "summary": "A resource has just reached the `\"started\"` state.",
              "md": "Fired after the resource's entry scripts ran (and, in JavaScript, after their module-level `await`s completed). The resource receives its own `resourceStart` too: handlers it registered while loading are called. This is the usual place to initialize.\n\nA resource that starts later only sees later starts; use [`lsmp.getResources()`](#core-utils/fn-get-resources) for the current set.",
              "params": [
                {
                  "name": "name",
                  "type": "name",
                  "desc": "The resource that started."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.on(\"resourceStart\", function(name)\n  if name == lsmp.getResourceName() then\n    lsmp.log(\"ready\")\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.on(\"resourceStart\", (name) => {\n  if (name === lsmp.getResourceName()) lsmp.log(\"ready\");\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "resourceStop",
              "id": "ev-resource-stop",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"resourceStop\", function(name) end)",
                "js": "lsmp.on(\"resourceStop\", (name) => {})"
              },
              "summary": "A resource is about to stop.",
              "md": "The stopping resource's own handlers run first, then those of the other resources. During the dispatch, the stopping resource's objects (entities, browsers, storage, MySQL pools) are still alive: save what you need here.\n\nHandlers may suspend or `await`, for up to `ResourceStopGraceMs` on the server (default 2000 ms) and 1000 ms on the client. Then the resource is torn down anyway.",
              "params": [
                {
                  "name": "name",
                  "type": "name",
                  "desc": "The resource that stops."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.on(\"resourceStop\", function(name)\n  if name ~= lsmp.getResourceName() then return end\n  lsmp.storage.set(\"lastStop\", lsmp.nowMs())\n  lsmp.storage.flush() -- suspends until the store is on disk\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.on(\"resourceStop\", async (name) => {\n  if (name !== lsmp.getResourceName()) return;\n  lsmp.storage.set(\"lastStop\", lsmp.nowMs());\n  await lsmp.storage.flush();\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "serverStart",
              "id": "ev-server-start",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"serverStart\", function() end)",
                "js": "lsmp.on(\"serverStart\", () => {})"
              },
              "summary": "Once, when every resource has started (or failed) and the game port listens.",
              "md": "Every resource receives it: on the server, resources start only with the server."
            },
            {
              "type": "function",
              "name": "serverStop",
              "id": "ev-server-stop",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"serverStop\", function() end)",
                "js": "lsmp.on(\"serverStop\", () => {})"
              },
              "summary": "The server is shutting down gracefully.",
              "md": "Fired on console `quit`, a stop or restart from the admin panel, an update, or a termination signal (CTRL+C). It comes after `playerLeave(..., \"shutdown\")` for every player, before the resources stop.\n\nHandlers may suspend or `await`: the server waits until they all finish, or until `ShutdownGraceMs` (default 5000 ms). MySQL queries started before or during this time complete; storage stores are flushed afterwards. It is not fired when the server crashes."
            },
            {
              "type": "heading",
              "text": "Players",
              "level": 2,
              "id": "players"
            },
            {
              "type": "function",
              "name": "playerPreConnection",
              "id": "ev-player-pre-connection",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"playerPreConnection\", function(p) end)",
                "js": "lsmp.on(\"playerPreConnection\", (p) => {})"
              },
              "summary": "A player asks to join, before getting a slot. Your handlers can refuse them.",
              "md": "This is the only engine event whose outcome depends on the handlers:\n\n- Every handler of every resource runs. Any `p.deny(reason)` refuses the player; the reason (256 bytes at most) is shown to them.\n- A handler answers when it returns (Lua: when its coroutine ends; JavaScript: when the Promise it returns settles). Returning without denying means no objection. A handler can therefore wait for a database before deciding.\n- A handler that raises or rejects counts as no objection (and is logged).\n- The verdict is given when all handlers answered, or after `PreConnectionTimeoutMs` (default 10000 ms). Late handlers then **refuse** the player (\"server check timed out\"), and the log names them.",
              "params": [
                {
                  "name": "p",
                  "type": "PreConnection",
                  "desc": "The connecting player (fields below). JavaScript: a frozen object."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.on(\"playerPreConnection\", function(p)\n  if p.guest then\n    p.deny(\"This server needs an LS:MP account.\")\n    return\n  end\n  local banned = lsmp.storage.get(\"ban:\" .. p.lsmpId)\n  if banned then p.deny(\"You are banned: \" .. banned) end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.on(\"playerPreConnection\", async (p) => {\n  if (p.guest) return p.deny(\"This server needs an LS:MP account.\");\n  const banned = lsmp.storage.get(`ban:${p.lsmpId}`);\n  if (banned) p.deny(`You are banned: ${banned}`);\n});"
                  }
                ]
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Field",
                    "Type",
                    "Description"
                  ],
                  "rows": [
                    [
                      "`lsmpId`",
                      "integer?",
                      "LS:MP account; `nil`/`null` for a guest."
                    ],
                    [
                      "`name`",
                      "string",
                      "The name the player connects with."
                    ],
                    [
                      "`verified`",
                      "boolean",
                      "`true` when the server verified the account with LS:MP."
                    ],
                    [
                      "`guest`",
                      "boolean",
                      "`true` for a player without an account."
                    ],
                    [
                      "`ip`",
                      "string?",
                      "IP address. `nil`/`null` unless the resource holds the `players.identity` [capability](#capabilities)."
                    ],
                    [
                      "`hwid`",
                      "string?",
                      "Hardware identifier. Same rule as `ip`."
                    ],
                    [
                      "`deny(reason)`",
                      "function",
                      "Refuses the connection. In Lua, call it as `p.deny(reason)` (no colon)."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "function",
              "name": "playerJoin",
              "id": "ev-player-join",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"playerJoin\", function(playerId, name) end)",
                "js": "lsmp.on(\"playerJoin\", (playerId, name) => {})"
              },
              "summary": "A player is in the session.",
              "md": "Server: the player was admitted and has a slot. Client: another player appears in the local session. It is **not** fired for the local player: at resource start, read [`lsmp.getLocalPlayer()`](#local-player/fn-get-local-player) and [`lsmp.getPlayers()`](#players/fn-get-players), which also lists the players already present (they are not announced).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The new player."
                },
                {
                  "name": "name",
                  "type": "string",
                  "desc": "Their name."
                }
              ]
            },
            {
              "type": "function",
              "name": "playerLeave",
              "id": "ev-player-leave",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"playerLeave\", function(playerId, name, reason, detail, client) end)",
                "js": "lsmp.on(\"playerLeave\", (playerId, name, reason, detail, client) => {})"
              },
              "summary": "A player left the session.",
              "md": "During the dispatch the leaving player is **still readable**: `getPlayerName`, `getPlayerLsmpId`, `isPlayerGuest`, `getPlayerDimension`, `getPlayerMeta` and `getPlayerIdentifier(s)` answer as just before the departure. `playerExists` already returns `false`, and writes to the player (`setPlayerMeta`, `emitClient`, `callClient`...) return `false`. The playerId is given to a new player only after every handler ran. Pending [`callClient`](#rpc/fn-call-client) calls to the player fail with `disconnected`.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player who left."
                },
                {
                  "name": "name",
                  "type": "string",
                  "desc": "Their name."
                },
                {
                  "name": "reason",
                  "type": "string",
                  "desc": "`\"quit\"`, `\"kick\"`, `\"ban\"`, `\"timeout\"`, `\"shutdown\"` or `\"error\"` (`lsmp.LeaveReason`)."
                },
                {
                  "name": "detail",
                  "type": "string?",
                  "desc": "Server: the text given to the kick, the ban or the client's disconnect, if any. Always `nil`/`null` on the client."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.on(\"playerLeave\", function(playerId, name, reason, detail)\n  local money = lsmp.getPlayerMeta(playerId, \"money\") -- still readable here\n  local account = lsmp.getPlayerLsmpId(playerId)\n  if account and money then lsmp.storage.set(\"money:\" .. account, money) end\n  lsmp.log(name .. \" left (\" .. reason .. \")\")\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.on(\"playerLeave\", (playerId, name, reason, detail) => {\n  const money = lsmp.getPlayerMeta(playerId, \"money\"); // still readable here\n  const account = lsmp.getPlayerLsmpId(playerId);\n  if (account !== null && money !== null) lsmp.storage.set(`money:${account}`, money);\n  lsmp.log(`${name} left (${reason})`);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "playerSpawn",
              "id": "ev-player-spawn",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"playerSpawn\", function(playerId, position, heading, model, first) end)",
                "js": "lsmp.on(\"playerSpawn\", (playerId, position, heading, model, first) => {})"
              },
              "summary": "A player spawned.",
              "md": "Client: the local player spawned (`lsmp.spawn`, automatic spawn, respawn); only the local player. Server: the client reported its spawn. On the server this is what the client declares: use it for information, not for trust.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "position",
                  "type": "Vector3",
                  "desc": "Spawn position."
                },
                {
                  "name": "heading",
                  "type": "heading",
                  "desc": "Spawn heading, in degrees."
                },
                {
                  "name": "model",
                  "type": "hash",
                  "desc": "Ped model (unsigned)."
                },
                {
                  "name": "first",
                  "type": "boolean",
                  "desc": "`true` for the first spawn of the session."
                }
              ]
            },
            {
              "type": "function",
              "name": "playerDeath",
              "id": "ev-player-death",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"playerDeath\", function(playerId, killerId, weaponHash, position, flags, killerEntity) end)",
                "js": "lsmp.on(\"playerDeath\", (playerId, killerId, weaponHash, position, flags, killerEntity) => {})"
              },
              "summary": "A player died.",
              "md": "Server: the victim's client reported its death; duplicates are dropped and the killer is resolved by the server. Client: the server relays it to every client.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The victim."
                },
                {
                  "name": "killerId",
                  "type": "playerId?",
                  "desc": "The killing player; `nil`/`null` when not killed by a player."
                },
                {
                  "name": "weaponHash",
                  "type": "hash",
                  "desc": "Weapon (unsigned); `0` if unknown."
                },
                {
                  "name": "position",
                  "type": "Vector3",
                  "desc": "Where the victim died."
                },
                {
                  "name": "flags",
                  "type": "integer",
                  "desc": "Bits of `lsmp.DeathFlag` (`Headshot` = 1)."
                },
                {
                  "name": "killerEntity",
                  "type": "netId?",
                  "desc": "The entity that killed (ped, vehicle); `nil`/`null` for the environment."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.on(\"playerDeath\", function(victim, killerId, weaponHash, position, flags)\n  if killerId then\n    local headshot = (flags & lsmp.DeathFlag.Headshot) ~= 0\n    lsmp.log(lsmp.getPlayerName(killerId) .. \" killed \" .. lsmp.getPlayerName(victim) .. (headshot and \" (headshot)\" or \"\"))\n  end\nend)"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.on(\"playerDeath\", (victim, killerId, weaponHash, position, flags) => {\n  if (killerId === null) return;\n  const headshot = (flags & lsmp.DeathFlag.Headshot) !== 0;\n  lsmp.log(`${lsmp.getPlayerName(killerId)} killed ${lsmp.getPlayerName(victim)}${headshot ? \" (headshot)\" : \"\"}`);\n});"
                  }
                ]
              }
            },
            {
              "type": "function",
              "name": "playerDimensionChange",
              "id": "ev-player-dimension-change",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"playerDimensionChange\", function(playerId, oldDimension, newDimension) end)",
                "js": "lsmp.on(\"playerDimensionChange\", (playerId, oldDimension, newDimension) => {})"
              },
              "summary": "A player changed dimension.",
              "md": "Client: local player only. See [Dimensions](#dimensions).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                },
                {
                  "name": "oldDimension",
                  "type": "dimension",
                  "desc": "Before."
                },
                {
                  "name": "newDimension",
                  "type": "dimension",
                  "desc": "After."
                }
              ]
            },
            {
              "type": "function",
              "name": "playerPermsChange",
              "id": "ev-player-perms-change",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"playerPermsChange\", function(playerId) end)",
                "js": "lsmp.on(\"playerPermsChange\", (playerId) => {})"
              },
              "summary": "A player's permissions changed.",
              "md": "Server: the effective permissions of a player changed. Client: the local permission snapshot changed (`lsmp.perms.isReady` and `isComplete` give its state). See [Permissions](#permissions).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ]
            },
            {
              "type": "heading",
              "text": "Entities",
              "level": 2,
              "id": "entities"
            },
            {
              "type": "function",
              "name": "entityDimensionChange",
              "id": "ev-entity-dimension-change",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"entityDimensionChange\", function(netId, oldDimension, newDimension) end)",
                "js": "lsmp.on(\"entityDimensionChange\", (netId, oldDimension, newDimension) => {})"
              },
              "summary": "An entity changed dimension.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                },
                {
                  "name": "oldDimension",
                  "type": "dimension",
                  "desc": "Before."
                },
                {
                  "name": "newDimension",
                  "type": "dimension",
                  "desc": "After."
                }
              ]
            },
            {
              "type": "function",
              "name": "entityOwnerChange",
              "id": "ev-entity-owner-change",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"entityOwnerChange\", function(netId, oldOwner, newOwner, reason) end)",
                "js": "lsmp.on(\"entityOwnerChange\", (netId, oldOwner, newOwner, reason) => {})"
              },
              "summary": "The player simulating an entity changed.",
              "md": "See [Ownership and AI intents](#server-ownership).",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                },
                {
                  "name": "oldOwner",
                  "type": "playerId?",
                  "desc": "Previous owner; `nil`/`null` if it was orphan."
                },
                {
                  "name": "newOwner",
                  "type": "playerId?",
                  "desc": "New owner; `nil`/`null` if it becomes orphan."
                },
                {
                  "name": "reason",
                  "type": "string",
                  "desc": "One of [`lsmp.OwnerChangeReason`](#server-ownership/const-owner-change-reason): `\"adopt\"`, `\"migrate\"`, `\"leaseExpired\"`, `\"disconnect\"`, `\"demand\"`, `\"script\"`, `\"release\"`."
                }
              ]
            },
            {
              "type": "function",
              "name": "entityAdopt",
              "id": "ev-entity-adopt",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"entityAdopt\", function(netId) end)",
                "js": "lsmp.on(\"entityAdopt\", (netId) => {})"
              },
              "summary": "The local client starts simulating an entity.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ]
            },
            {
              "type": "function",
              "name": "entityRelease",
              "id": "ev-entity-release",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"entityRelease\", function(netId) end)",
                "js": "lsmp.on(\"entityRelease\", (netId) => {})"
              },
              "summary": "The local client stops simulating an entity.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ]
            },
            {
              "type": "function",
              "name": "entityStreamIn",
              "id": "ev-entity-stream-in",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"entityStreamIn\", function(netId, entity) end)",
                "js": "lsmp.on(\"entityStreamIn\", (netId, entity) => {})"
              },
              "summary": "A networked entity got a game instance on this client.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                },
                {
                  "name": "entity",
                  "type": "handle",
                  "desc": "Its game handle, valid during the dispatch (it can disappear later)."
                }
              ]
            },
            {
              "type": "function",
              "name": "entityStreamOut",
              "id": "ev-entity-stream-out",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"entityStreamOut\", function(netId) end)",
                "js": "lsmp.on(\"entityStreamOut\", (netId) => {})"
              },
              "summary": "A networked entity lost its game instance on this client.",
              "md": "Its handle is already invalid when the event arrives.",
              "params": [
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The entity."
                }
              ]
            },
            {
              "type": "function",
              "name": "pickupCollect",
              "id": "ev-pickup-collect",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"pickupCollect\", function(playerId, netId, pickupHash, amount, serverCreated) end)",
                "js": "lsmp.on(\"pickupCollect\", (playerId, netId, pickupHash, amount, serverCreated) => {})"
              },
              "summary": "The server granted a pickup to a player.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The collector."
                },
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The pickup."
                },
                {
                  "name": "pickupHash",
                  "type": "hash",
                  "desc": "Pickup type (unsigned)."
                },
                {
                  "name": "amount",
                  "type": "integer",
                  "desc": "Amount granted."
                },
                {
                  "name": "serverCreated",
                  "type": "boolean",
                  "desc": "`true` for a pickup created by [`lsmp.createPickup`](#server-entities/fn-create-pickup); `false` for one dropped by the game on a client, whose amount is what the client declares."
                }
              ]
            },
            {
              "type": "function",
              "name": "syncSceneStart",
              "id": "ev-sync-scene-start",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"syncSceneStart\", function(sceneId, netId) end)",
                "js": "lsmp.on(\"syncSceneStart\", (sceneId, netId) => {})"
              },
              "summary": "An entity of the session starts a synchronized scene.",
              "md": "See [Synchronized scenes](#sync-scenes).",
              "params": [
                {
                  "name": "sceneId",
                  "type": "integer",
                  "desc": "The scene."
                },
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The participating entity."
                }
              ]
            },
            {
              "type": "function",
              "name": "syncSceneStop",
              "id": "ev-sync-scene-stop",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"syncSceneStop\", function(sceneId, netId) end)",
                "js": "lsmp.on(\"syncSceneStop\", (sceneId, netId) => {})"
              },
              "summary": "An entity stops playing a synchronized scene.",
              "params": [
                {
                  "name": "sceneId",
                  "type": "integer",
                  "desc": "The scene."
                },
                {
                  "name": "netId",
                  "type": "netId",
                  "desc": "The participating entity."
                }
              ]
            },
            {
              "type": "function",
              "name": "selectionChange",
              "id": "ev-selection-change",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"selectionChange\", function(entity, geomKey, valid) end)",
                "js": "lsmp.on(\"selectionChange\", (entity, geomKey, valid) => {})"
              },
              "summary": "The picked entity or geometry changed.",
              "md": "See [Outlines and picking](#outline-selection).",
              "params": [
                {
                  "name": "entity",
                  "type": "handle?",
                  "desc": "The picked entity; `nil`/`null` if none."
                },
                {
                  "name": "geomKey",
                  "type": "integer?",
                  "desc": "The picked geometry, if any."
                },
                {
                  "name": "valid",
                  "type": "boolean",
                  "desc": "Whether the selection is valid."
                }
              ]
            },
            {
              "type": "heading",
              "text": "Meta",
              "level": 2,
              "id": "meta"
            },
            {
              "type": "function",
              "name": "metaChange",
              "id": "ev-meta-change",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"metaChange\", function(scope, target, key, value, source) end)",
                "js": "lsmp.on(\"metaChange\", (scope, target, key, value, source) => {})"
              },
              "summary": "A meta value changed.",
              "md": "Server: any write, by a script or by a client. Client: a replicated change was received, the client's own writes included. A write with the same value as before does not fire.\n\nPass a **filter** as third argument of `lsmp.on` to receive only what you need: the engine does not even decode the value for handlers whose filter does not match. Fields present in the filter must match; a mistyped field raises. See [Meta](#meta).",
              "params": [
                {
                  "name": "scope",
                  "type": "string",
                  "desc": "`\"global\"`, `\"player\"` or `\"entity\"`."
                },
                {
                  "name": "target",
                  "type": "integer?",
                  "desc": "The playerId or netId; `nil`/`null` for a global value."
                },
                {
                  "name": "key",
                  "type": "string",
                  "desc": "The key."
                },
                {
                  "name": "value",
                  "type": "value?",
                  "desc": "The new value; `nil`/`null` when it was deleted."
                },
                {
                  "name": "source",
                  "type": "playerId?",
                  "desc": "Server: the player who wrote it, `nil`/`null` when a server script wrote it. Always `nil`/`null` on the client, which does not know the writer."
                }
              ],
              "examples": {
                "tabs": [
                  {
                    "label": "Lua",
                    "lang": "lua",
                    "code": "lsmp.on(\"metaChange\", function(scope, target, key, value, source)\n  lsmp.log(\"player \" .. target .. \" has \" .. tostring(value) .. \" money\")\nend, { scope = \"player\", key = \"money\" })"
                  },
                  {
                    "label": "JavaScript",
                    "lang": "js",
                    "code": "lsmp.on(\"metaChange\", (scope, target, key, value, source) => {\n  lsmp.log(`player ${target} has ${value} money`);\n}, { scope: \"player\", key: \"money\" });"
                  }
                ]
              },
              "notes": [
                {
                  "type": "table",
                  "headers": [
                    "Filter field",
                    "Type",
                    "Matches"
                  ],
                  "rows": [
                    [
                      "`scope`",
                      "string",
                      "`\"global\"`, `\"player\"` or `\"entity\"`."
                    ],
                    [
                      "`key`",
                      "string",
                      "One key."
                    ],
                    [
                      "`target`",
                      "integer",
                      "One playerId or netId."
                    ]
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "Voice, weather, benefits",
              "level": 2,
              "id": "misc"
            },
            {
              "type": "function",
              "name": "voiceStart",
              "id": "ev-voice-start",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"voiceStart\", function(playerId) end)",
                "js": "lsmp.on(\"voiceStart\", (playerId) => {})"
              },
              "summary": "A player starts transmitting voice.",
              "md": "See [Voice](#voice).",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The talking player."
                }
              ]
            },
            {
              "type": "function",
              "name": "voiceStop",
              "id": "ev-voice-stop",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"voiceStop\", function(playerId) end)",
                "js": "lsmp.on(\"voiceStop\", (playerId) => {})"
              },
              "summary": "A player stops transmitting voice.",
              "params": [
                {
                  "name": "playerId",
                  "type": "playerId",
                  "desc": "The player."
                }
              ]
            },
            {
              "type": "function",
              "name": "weatherChange",
              "id": "ev-weather-change",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"weatherChange\", function(type, previous, transitionMs) end)",
                "js": "lsmp.on(\"weatherChange\", (type, previous, transitionMs) => {})"
              },
              "summary": "The target synchronized weather changed.",
              "md": "On the client it also fires when a local override starts or ends. See [Weather and time](#weather).",
              "params": [
                {
                  "name": "type",
                  "type": "string",
                  "desc": "The new weather type."
                },
                {
                  "name": "previous",
                  "type": "string?",
                  "desc": "The previous type; `nil`/`null` if unchanged."
                },
                {
                  "name": "transitionMs",
                  "type": "ms",
                  "desc": "Duration of the transition."
                }
              ]
            },
            {
              "type": "function",
              "name": "benefitGrant",
              "id": "ev-benefit-grant",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"benefitGrant\", function(lsmpId, benefit) end)",
                "js": "lsmp.on(\"benefitGrant\", (lsmpId, benefit) => {})"
              },
              "summary": "A connected account has an in-game benefit to apply.",
              "md": "Fired once per session until the benefit is consumed. Delivered only to resources holding the `benefits.read` [capability](#capabilities). See [In-game benefits](#benefits).",
              "params": [
                {
                  "name": "lsmpId",
                  "type": "integer",
                  "desc": "The account."
                },
                {
                  "name": "benefit",
                  "type": "Benefit",
                  "desc": "`{ id, key, quantity, purchasedAtMs, status }`."
                }
              ]
            },
            {
              "type": "function",
              "name": "benefitRevoke",
              "id": "ev-benefit-revoke",
              "side": "server",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"benefitRevoke\", function(lsmpId, benefit) end)",
                "js": "lsmp.on(\"benefitRevoke\", (lsmpId, benefit) => {})"
              },
              "summary": "A benefit was revoked and must be taken back.",
              "md": "Delivered only to resources holding `benefits.read`.",
              "params": [
                {
                  "name": "lsmpId",
                  "type": "integer",
                  "desc": "The account."
                },
                {
                  "name": "benefit",
                  "type": "Benefit",
                  "desc": "`{ id, key, quantity, purchasedAtMs, status }`."
                }
              ]
            },
            {
              "type": "function",
              "name": "serverMessage",
              "id": "ev-server-message",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.on(\"serverMessage\", function(text) end)",
                "js": "lsmp.on(\"serverMessage\", (text) => {})"
              },
              "summary": "The server console ran `say`.",
              "md": "When no client resource listens to it, LS:MP shows the text in its notification feed.",
              "params": [
                {
                  "name": "text",
                  "type": "string",
                  "desc": "The message."
                }
              ]
            },
            {
              "type": "heading",
              "text": "Browser events",
              "level": 2,
              "id": "browser"
            },
            {
              "type": "text",
              "md": "These four events are received on a browser handle with `browser:on` (Lua) or `browser.on` (JavaScript), not with `lsmp.on`. Only that handle receives them, and a page cannot emit them. See [Browsers](#browsers)."
            },
            {
              "type": "function",
              "name": "browser:load",
              "id": "ev-browser-on-load",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:on(\"load\", function(url) end)",
                "js": "browser.on(\"load\", (url) => {})"
              },
              "summary": "The page (main frame) finished loading.",
              "md": "Events emitted to the page before this point are delivered right after it.",
              "params": [
                {
                  "name": "url",
                  "type": "string",
                  "desc": "The loaded address."
                }
              ]
            },
            {
              "type": "function",
              "name": "browser:loadError",
              "id": "ev-browser-on-load-error",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:on(\"loadError\", function(url, code) end)",
                "js": "browser.on(\"loadError\", (url, code) => {})"
              },
              "summary": "Navigation failed or the address was refused.",
              "params": [
                {
                  "name": "url",
                  "type": "string",
                  "desc": "The address."
                },
                {
                  "name": "code",
                  "type": "string",
                  "desc": "`\"refused-url\"`, `\"network\"`, `\"http-<status>\"` or `\"aborted\"`."
                }
              ]
            },
            {
              "type": "function",
              "name": "browser:focusLost",
              "id": "ev-browser-on-focus-lost",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:on(\"focusLost\", function() end)",
                "js": "browser.on(\"focusLost\", () => {})"
              },
              "summary": "The player took the focus back, or another page took it (2D browsers)."
            },
            {
              "type": "function",
              "name": "browser:crash",
              "id": "ev-browser-on-crash",
              "side": "client",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "browser:on(\"crash\", function(reason) end)",
                "js": "browser.on(\"crash\", (reason) => {})"
              },
              "summary": "The page renderer crashed.",
              "md": "The browser stays valid: `setUrl` loads it again.",
              "params": [
                {
                  "name": "reason",
                  "type": "string",
                  "desc": "What happened."
                }
              ]
            },
            {
              "type": "heading",
              "text": "Constants",
              "level": 2,
              "id": "constants"
            },
            {
              "type": "function",
              "name": "lsmp.LeaveReason",
              "id": "const-leave-reason",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.LeaveReason",
                "js": "lsmp.LeaveReason"
              },
              "summary": "The `reason` values of `playerLeave`.",
              "md": "`lsmp.LeaveReason.Quit` = `\"quit\"` · `lsmp.LeaveReason.Kick` = `\"kick\"` · `lsmp.LeaveReason.Ban` = `\"ban\"` · `lsmp.LeaveReason.Timeout` = `\"timeout\"` · `lsmp.LeaveReason.Shutdown` = `\"shutdown\"` · `lsmp.LeaveReason.Error` = `\"error\"`"
            },
            {
              "type": "function",
              "name": "lsmp.DeathFlag",
              "id": "const-death-flag",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.DeathFlag",
                "js": "lsmp.DeathFlag"
              },
              "summary": "Bits of the `flags` argument of `playerDeath`.",
              "md": "`lsmp.DeathFlag.Headshot` = `1`"
            }
          ]
        },
        {
          "id": "error-codes",
          "title": "Error codes",
          "eyebrow": "Reference",
          "lead": "The closed list of run-time failure codes, what each one means and what usually causes it.",
          "blocks": [
            {
              "type": "text",
              "md": "When a call fails at run time (the player left, the file is missing, the quota is reached), it does not raise: it returns a failure, and the failure carries one of the codes below. The list is closed: no function invents its own code. Programming errors (wrong types, out-of-range values) raise instead; see [Errors and failures](#conventions/errors)."
            },
            {
              "type": "heading",
              "text": "Reading the code",
              "level": 2,
              "id": "reading"
            },
            {
              "type": "table",
              "headers": [
                "Call",
                "Lua",
                "JavaScript"
              ],
              "rows": [
                [
                  "synchronous action",
                  "`local ok, code = lsmp.fn(...)`",
                  "`if (!lsmp.fn(...)) code = lsmp.getLastError()`"
                ],
                [
                  "synchronous read",
                  "`local v, code = lsmp.fn(...)`",
                  "`if (lsmp.fn(...) === null) code = lsmp.getLastError()`"
                ],
                [
                  "asynchronous, callback",
                  "`lsmp.fn(..., function(result, code, details) end)`",
                  "—"
                ],
                [
                  "asynchronous, coroutine",
                  "`local result, code, details = lsmp.fn(...)`",
                  "`try { await lsmp.fn(...) } catch (e) { e.code }`"
                ]
              ]
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- server\nlsmp.onCall(\"bank:balance\", function(source)\n  local account = lsmp.getPlayerLsmpId(source)\n  if not account then return nil end\n  return lsmp.storage.get(\"balance:\" .. account) or 0\nend)\n\n-- client, in a host coroutine\nlocal balance, code = lsmp.callServer(\"bank:balance\")\nif code == lsmp.ErrorCode.NoHandler then\n  lsmp.warn(\"the bank resource is not running\")\nend"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// server\nlsmp.onCall(\"bank:balance\", (source) => {\n  const account = lsmp.getPlayerLsmpId(source);\n  if (account === null) return null;\n  return lsmp.storage.get(`balance:${account}`) ?? 0;\n});\n\n// client\nasync function readBalance() {\n  try {\n    return await lsmp.callServer(\"bank:balance\");\n  } catch (e) {\n    if (e.code === lsmp.ErrorCode.NoHandler) lsmp.warn(\"the bank resource is not running\");\n    return null;\n  }\n}"
                }
              ]
            },
            {
              "type": "heading",
              "text": "The codes",
              "level": 2,
              "id": "codes"
            },
            {
              "type": "table",
              "headers": [
                "Code",
                "`lsmp.ErrorCode`",
                "Meaning",
                "Typical causes"
              ],
              "rows": [
                [
                  "`not-found`",
                  "`NotFound`",
                  "The target does not exist.",
                  "Unknown player, entity, resource, scene, file or product; `callClient` to a player who is not connected."
                ],
                [
                  "`timeout`",
                  "`Timeout`",
                  "No answer within the deadline.",
                  "An RPC handler slower than `timeoutMs`; an HTTP request or a MySQL query over its timeout; `playerPreConnection` handlers too slow."
                ],
                [
                  "`no-handler`",
                  "`NoHandler`",
                  "Nobody handles that name on the other side.",
                  "A call (`call`, `callServer`, `callClient`) to a name without `onCall` on the side it reaches (resource not started, typo, wrong side); a page call without a handler."
                ],
                [
                  "`error`",
                  "`Error`",
                  "The operation failed on the other end.",
                  "The remote RPC handler raised or returned a value that cannot be sent; SQL error; a resource failed to start; invalid JSON in an HTTP response read as `json`. The details stay in the other side's log; a client never receives a server error message."
                ],
                [
                  "`permission`",
                  "`Permission`",
                  "Not allowed.",
                  "A [capability](#capabilities) refused to the resource, a sandbox rule, an object or entity that belongs to another resource, a client meta write on an entity it does not own."
                ],
                [
                  "`limit`",
                  "`Limit`",
                  "A quota, size, rate or count limit is reached.",
                  "Too many pending RPC calls, a resource storage that is full, too many entities, a file too large, a rate limit. See [Limits and quotas](#limits)."
                ],
                [
                  "`disconnected`",
                  "`Disconnected`",
                  "Not in a session, or the player left.",
                  "Client call while not connected; the player left before answering a `callClient`."
                ],
                [
                  "`invalid`",
                  "`Invalid`",
                  "Refused by the current state.",
                  "Entity and player in different dimensions, a stale cursor, an empty cart, a directory where a file was expected, conflicting options."
                ],
                [
                  "`unavailable`",
                  "`Unavailable`",
                  "The service is off or not ready.",
                  "LS:MP network services disabled on the server, renderer not ready, store disabled."
                ],
                [
                  "`cancelled`",
                  "`Cancelled`",
                  "Stopped before the end.",
                  "The calling resource stops while it waits; the owner of the operation was destroyed; a MySQL pool closed."
                ],
                [
                  "`io`",
                  "`Io`",
                  "Disk or network transport failure.",
                  "Unreadable file or store, connection lost, write failed."
                ],
                [
                  "`exists`",
                  "`Exists`",
                  "It already exists.",
                  "`fs.mkdir` on an existing folder, `fs.writeFile` with `exclusive`."
                ],
                [
                  "`denied`",
                  "`Denied`",
                  "The player refused.",
                  "A purchase or a permission prompt declined by the player."
                ]
              ]
            },
            {
              "type": "text",
              "md": "Each function lists the codes it can return. A code you do not handle can be logged as is: it is a short stable string."
            },
            {
              "type": "heading",
              "text": "Details",
              "level": 2,
              "id": "details"
            },
            {
              "type": "list",
              "items": [
                "Some asynchronous failures come with details: a third value in Lua, extra fields of the `Error` in JavaScript. Functions that provide them say so (for example MySQL `{ errno, sqlState, message }`, files and HTTP `{ message }`).",
                "In JavaScript the rejection message reads `lsmp.fn: <code>: <detail>`; always test `e.code`, not the message.",
                "[`lsmp.getLastError()`](#core-utils/fn-get-last-error) returns the code of the last synchronous call of the resource that failed, or `nil`/`null` when the last such call succeeded."
              ]
            },
            {
              "type": "heading",
              "text": "Constant",
              "level": 2,
              "id": "constant"
            },
            {
              "type": "function",
              "name": "lsmp.ErrorCode",
              "id": "const-error-code",
              "side": "shared",
              "engines": [
                "lua",
                "js"
              ],
              "signature": {
                "lua": "lsmp.ErrorCode",
                "js": "lsmp.ErrorCode"
              },
              "summary": "Every failure code, by name: `lsmp.ErrorCode.NotFound == \"not-found\"`.",
              "md": "`lsmp.ErrorCode.NotFound` = `\"not-found\"` · `lsmp.ErrorCode.Timeout` = `\"timeout\"` · `lsmp.ErrorCode.NoHandler` = `\"no-handler\"` · `lsmp.ErrorCode.Error` = `\"error\"` · `lsmp.ErrorCode.Permission` = `\"permission\"` · `lsmp.ErrorCode.Limit` = `\"limit\"` · `lsmp.ErrorCode.Disconnected` = `\"disconnected\"` · `lsmp.ErrorCode.Invalid` = `\"invalid\"` · `lsmp.ErrorCode.Unavailable` = `\"unavailable\"` · `lsmp.ErrorCode.Cancelled` = `\"cancelled\"` · `lsmp.ErrorCode.Io` = `\"io\"` · `lsmp.ErrorCode.Exists` = `\"exists\"` · `lsmp.ErrorCode.Denied` = `\"denied\"`"
            }
          ]
        },
        {
          "id": "limits",
          "title": "Limits and quotas",
          "eyebrow": "Reference",
          "lead": "Sizes, counts, rates and timeouts a script can reach, and what happens beyond them.",
          "blocks": [
            {
              "type": "text",
              "md": "Every limit a script can reach, with what happens when it is reached. Sizes of values are measured **encoded**, in the compact form used to send and store them: about one byte per small integer, the length of a string plus one or two bytes, nine bytes per float."
            },
            {
              "type": "text",
              "md": "\"Raises\" means a programming error ([`RangeError`](#conventions/errors) in JavaScript, a Lua error), nothing is sent or stored. \"`limit`\" means the [failure code](#error-codes) `limit`. Keys marked `server.cfg` can be changed by the operator (see [server.cfg](#server-cfg))."
            },
            {
              "type": "heading",
              "text": "Names",
              "level": 2,
              "id": "names"
            },
            {
              "type": "table",
              "headers": [
                "What",
                "Limit",
                "Beyond"
              ],
              "rows": [
                [
                  "Event and RPC name",
                  "1 to 128 bytes of UTF-8, no NUL; `lsmp:` prefix reserved",
                  "raises"
                ],
                [
                  "Meta key",
                  "1 to 128 bytes of UTF-8, no NUL; `lsmp:` prefix reserved",
                  "raises"
                ],
                [
                  "Storage key",
                  "1 to 256 bytes",
                  "raises"
                ],
                [
                  "Command name",
                  "1 to 64 characters among `A-Z a-z 0-9 _ . : -` (a leading `/` is ignored), case-insensitive",
                  "raises"
                ],
                [
                  "Lua module name (`require`)",
                  "1 to 128 characters among `A-Z a-z 0-9 _ - .`",
                  "raises"
                ],
                [
                  "Synchronized scene `dict` and `clip`",
                  "1 to 63 bytes",
                  "the scene is refused"
                ],
                [
                  "`playerPreConnection` deny reason",
                  "256 bytes",
                  "cut to fit"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Events and remote calls",
              "level": 2,
              "id": "events"
            },
            {
              "type": "table",
              "headers": [
                "What",
                "Limit",
                "Beyond"
              ],
              "rows": [
                [
                  "Arguments of `emit`, `emitServer`, `emitClient*`, `call`, `callServer`, `callClient`, `browser:emit`/`call`, page `lsmp.emit`/`call`",
                  "32",
                  "raises"
                ],
                [
                  "Nesting of lists and maps in a value",
                  "32 levels",
                  "raises"
                ],
                [
                  "One map key",
                  "4096 bytes",
                  "raises"
                ],
                [
                  "`emit` and local `call` (same side), arguments and result",
                  "16 MiB encoded",
                  "raises"
                ],
                [
                  "Server → client (`emitClient`, `emitAllClients`, `emitDimensionClients`, `callClient` request, answer to a `callServer`)",
                  "16 MiB encoded",
                  "`emitClient*` raises; a `callClient` request fails with `limit`; an answer that does not fit makes the caller fail with `error`"
                ],
                [
                  "Client → server (`emitServer`, `callServer`, answer to a `callClient`)",
                  "4 MiB − 1 KiB encoded",
                  "raises"
                ],
                [
                  "Lists, maps and byte arrays in one client → server message",
                  "65 536 in total",
                  "the message is dropped, a line is logged"
                ],
                [
                  "Script ↔ page message",
                  "120 000 UTF-16 code units of JSON",
                  "raises"
                ],
                [
                  "Nested synchronous `emit` calls",
                  "32",
                  "raises `lsmp.emit: recursion limit (32) reached`"
                ],
                [
                  "Handlers per resource (`on`, `once`, `onServer`, `onClient`)",
                  "4096",
                  "raises"
                ],
                [
                  "RPC handlers",
                  "one per name per side, for all resources and both engines",
                  "a second `onCall` raises"
                ],
                [
                  "Pending outgoing calls per resource (`call`, `callServer`, `callClient`)",
                  "4096",
                  "`limit`"
                ],
                [
                  "Calls from one player being handled at the same time",
                  "1024",
                  "the client's call fails with `limit`"
                ],
                [
                  "Calls being answered at the same time by one resource on the client (`callClient` requests and local `call`)",
                  "4096",
                  "the call fails with `limit`; a server call not answered within 300 s is dropped"
                ],
                [
                  "Call names (`onCall`) per resource on the client",
                  "256",
                  "raises"
                ],
                [
                  "RPC `timeoutMs`",
                  "1 to 300 000 ms, default 10 000 ms",
                  "raises; at the deadline the caller gets `timeout`"
                ],
                [
                  "Client → server script traffic per player (`emitServer` and `callServer`)",
                  "`ScriptEventBytesPerSec` (`server.cfg`, default 1 MiB/s, four-second burst)",
                  "events dropped on the server, warning in the log (once a minute per player)"
                ],
                [
                  "Queued output to one client",
                  "`MaxClientSendQueueBytes` (`server.cfg`, default 64 MiB)",
                  "the client is disconnected"
                ]
              ]
            },
            {
              "type": "callout",
              "variant": "tip",
              "md": "For large or frequent data, send what changed rather than the whole state, or serve files over [HTTP routes](#server-http-serve) and send their address.",
              "title": "Large data"
            },
            {
              "type": "heading",
              "text": "Meta and storage",
              "level": 2,
              "id": "storage"
            },
            {
              "type": "table",
              "headers": [
                "What",
                "Limit",
                "Beyond"
              ],
              "rows": [
                [
                  "One meta value",
                  "8192 bytes encoded",
                  "raises"
                ],
                [
                  "Meta keys per player or entity, written by clients",
                  "`MetaMaxKeys` (`server.cfg`, default 256)",
                  "the client write is refused"
                ],
                [
                  "Meta bytes per player or entity, written by clients",
                  "`MetaMaxBlobBytes` (`server.cfg`, default 64 KiB)",
                  "the client write is refused"
                ],
                [
                  "Client meta write rate",
                  "`MetaWriteBytesPerSec` (`server.cfg`, default 64 KiB/s, four-second burst)",
                  "`limit`"
                ],
                [
                  "One stored value",
                  "64 KiB encoded",
                  "raises"
                ],
                [
                  "Storage of one resource",
                  "16 MiB; each entry counts 64 bytes on top of its key and value (about 260 000 entries at most)",
                  "`limit`"
                ],
                [
                  "Storage write to disk",
                  "within about 750 ms of the change",
                  "use `lsmp.storage.flush()` to wait for it"
                ],
                [
                  "`lsmp.fs.readFile`",
                  "512 MiB per file",
                  "`limit`"
                ],
                [
                  "`lsmp.readResourceFile`",
                  "64 MiB per file",
                  "`limit`"
                ],
                [
                  "`lsmp.randomBytes`",
                  "1 to 65 536 bytes",
                  "raises"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Databases and HTTP",
              "level": 2,
              "id": "db-http"
            },
            {
              "type": "table",
              "headers": [
                "What",
                "Limit",
                "Beyond"
              ],
              "rows": [
                [
                  "MySQL pools per resource",
                  "8 (JavaScript)",
                  "`limit`"
                ],
                [
                  "MySQL `connectionLimit`",
                  "1 to 64",
                  "raises"
                ],
                [
                  "MySQL `queryTimeoutMs`",
                  "default 0 (none)",
                  "the query fails with `timeout` and its connection is closed"
                ],
                [
                  "HTTP route per resource (`lsmp.http.serve`)",
                  "one",
                  "a second route replaces or is refused, see [HTTP routes](#server-http-serve)"
                ],
                [
                  "HTTP route request body (`maxBodyBytes`)",
                  "default 1 MiB, at most 16 MiB",
                  "the request is answered `413` without calling the handler"
                ],
                [
                  "HTTP route answer time (`timeoutMs`)",
                  "default 10 000 ms, at most 300 000 ms",
                  "the client gets `504`"
                ],
                [
                  "HTTP requests being handled, whole server",
                  "1024",
                  "the client gets `503`"
                ],
                [
                  "HTTP requests being handled by one resource's route",
                  "256",
                  "the client gets `503`"
                ],
                [
                  "HTTP requests being handled from one client address",
                  "64 (loopback not counted)",
                  "the client gets `429`"
                ],
                [
                  "Outgoing HTTP requests in flight, sandboxed server resource",
                  "256",
                  "`limit`"
                ],
                [
                  "`lsmp.fs` operations waiting, sandboxed server resource",
                  "128 operations or 64 MiB of data",
                  "`limit`"
                ]
              ]
            },
            {
              "type": "text",
              "md": "Limits of the HTTP client (`lsmp.http.get`...) are on the [HTTP client](#http) page."
            },
            {
              "type": "heading",
              "text": "Entities and scenes",
              "level": 2,
              "id": "entities"
            },
            {
              "type": "table",
              "headers": [
                "What",
                "Limit",
                "Beyond"
              ],
              "rows": [
                [
                  "Pickup `lifetimeMs`",
                  "0 (never) to 86 400 000 ms (24 h); removed at most 1 s after expiry",
                  "raises"
                ],
                [
                  "Pickup collectors",
                  "64 players",
                  "raises"
                ],
                [
                  "Synchronized scene participants",
                  "1 to 8",
                  "the scene is refused"
                ],
                [
                  "Distance between the participants of a scene",
                  "50 m",
                  "`invalid`"
                ],
                [
                  "Synchronized scenes running at once",
                  "1024",
                  "`limit`"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Client resources",
              "level": 2,
              "id": "client"
            },
            {
              "type": "table",
              "headers": [
                "What",
                "Limit",
                "Beyond"
              ],
              "rows": [
                [
                  "2D browsers",
                  "16 per resource, 128 on the client",
                  "`nil`/`null` with `limit`"
                ],
                [
                  "3D browsers",
                  "4 per resource, 64 on the client",
                  "`nil`/`null` with `limit`"
                ],
                [
                  "Handlers on one browser (`browser:on`)",
                  "1024",
                  "raises"
                ],
                [
                  "Messages from one page in one frame",
                  "256 messages and 524 288 characters of JSON",
                  "an `emit` is dropped, a `call` fails with `limit`; logged once a minute"
                ],
                [
                  "`lsmp.http` on the client",
                  "8 requests in flight and 20 per second per resource; 32 in flight and 128 MiB of response bodies for the whole client",
                  "`limit`"
                ],
                [
                  "Names given to `lsmp.resources.invalidateArchives` / `restoreArchives`",
                  "1 to 4096 per call, each 1 to 512 bytes; 8192 archives invalidated at once on the client",
                  "raises (count, length); `error` beyond 8192"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Time and memory",
              "level": 2,
              "id": "time-memory"
            },
            {
              "type": "table",
              "headers": [
                "What",
                "Limit",
                "Beyond"
              ],
              "rows": [
                [
                  "Lua and JavaScript on the server: one run (handler, timer, file body) without suspending",
                  "`SandboxWatchdogSec` (`server.cfg`, default 10 s; `0` turns it off)",
                  "sandboxed resources are interrupted with `script interrupted: time budget exceeded`, logged with the resource name; unsandboxed resources only get warnings"
                ],
                [
                  "Lua and JavaScript on the client: one run (handler, timer, tick)",
                  "250 ms",
                  "the run is interrupted, the error is logged with the resource name"
                ],
                [
                  "Script time of one resource per frame (client)",
                  "100 ms in total",
                  "the remaining timers and wake-ups wait for the next frame; 30 frames over budget within 10 s stop the resource (logged)"
                ],
                [
                  "Timers per resource (`setTimeout`, `setInterval`)",
                  "65 536",
                  "raises `too many timers in this resource (65536)`"
                ],
                [
                  "Waiting coroutines per resource (Lua) / pending `lsmp.wait` per resource (JS)",
                  "65 536",
                  "raises"
                ],
                [
                  "Lua memory per resource (server)",
                  "`LuaMemoryLimitMiB` (`server.cfg`, default 256 MiB)",
                  "the allocation fails with a memory error in the resource"
                ],
                [
                  "JavaScript heap (server, all resources together)",
                  "`JsHeapLimitMiB` (`server.cfg`, default: chosen by the engine)",
                  "an out-of-memory error in the script that allocates"
                ],
                [
                  "`resourceStop` handlers",
                  "`ResourceStopGraceMs` (`server.cfg`, default 2000 ms); 1000 ms on the client",
                  "the resource is torn down anyway"
                ],
                [
                  "`serverStop` handlers",
                  "`ShutdownGraceMs` (`server.cfg`, default 5000 ms)",
                  "resources are stopped anyway"
                ],
                [
                  "Module-level awaits of a starting resource",
                  "`ResourceStartTimeoutMs` (`server.cfg`, default 30 000 ms)",
                  "the resource is marked `failed`"
                ],
                [
                  "`playerPreConnection` verdict",
                  "`PreConnectionTimeoutMs` (`server.cfg`, default 10 000 ms)",
                  "the player is refused"
                ],
                [
                  "`setInterval` period",
                  "at least 1 ms",
                  "a smaller period is raised to 1 ms"
                ],
                [
                  "`onTick` errors (client)",
                  "8 in a row",
                  "the tick handler is disabled"
                ]
              ]
            }
          ]
        }
      ]
    },
    {
      "id": "tutorials",
      "title": "Tutorials",
      "icon": "💡",
      "pages": [
        {
          "id": "tutorial-car",
          "title": "Tutorial: a /car command",
          "eyebrow": "Tutorial · Lua & JS",
          "lead": "A complete small feature: a player types /car adder, the server checks and creates the vehicle, and the player sits in it.",
          "blocks": [
            {
              "type": "text",
              "md": "You will write one resource with a client script and a server script, talking through a [remote call](#rpc), and protect the command with a [permission](#permissions). It takes about fifteen minutes. The bundled `vehicle-spawner` resource is a fuller version of the same idea."
            },
            {
              "type": "heading",
              "text": "What happens",
              "level": 2,
              "id": "car-flow"
            },
            {
              "type": "list",
              "ordered": true,
              "items": [
                "The **client** checks that the name is a vehicle model (only the game knows) and computes a spot in front of the player.",
                "It **asks the server** with `lsmp.callServer`. Network entities are created by the server: every player nearby sees the same car.",
                "The **server** checks the permission and the distance (a client chooses what it sends), creates the vehicle owned by the player, and answers with its netId.",
                "The client waits for the car to exist in its game, then puts the player in the driver seat."
              ]
            },
            {
              "type": "heading",
              "text": "1. The resource folder",
              "level": 2,
              "id": "car-folder"
            },
            {
              "type": "tree",
              "tree": "resources/\n└─ car/\n   ├─ manifest.json\n   ├─ client/\n   │  └─ main.lua        # or main.js\n   └─ server/\n      └─ main.lua        # or main.js"
            },
            {
              "type": "code",
              "lang": "json",
              "title": "resources/car/manifest.json",
              "code": "{\n  \"title\": \"Car spawner\",\n  \"description\": \"/car <model> spawns a vehicle in front of you.\",\n  \"client_scripts\": \"client/main.lua\",\n  \"server_scripts\": \"server/main.lua\"\n}"
            },
            {
              "type": "text",
              "md": "For JavaScript, name the files `main.js` and list them instead. The folder name, `car`, is the resource name. See [Resource layout and manifest](#resource-layout)."
            },
            {
              "type": "heading",
              "text": "2. The server script",
              "level": 2,
              "id": "car-server"
            },
            {
              "type": "text",
              "md": "The server owns the decision. It declares the permission so that the server owner finds it in the admin panel, and answers each request with `{ netId }` or `{ error }`."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- resources/car/server/main.lua\nlocal MAX_DISTANCE = 15\nlocal spawned = {}   -- playerId -> netId of the car we made for them\n\nlsmp.perms.declare(\"car.spawn\", \"Spawn a vehicle with /car\")\n\nlsmp.onCall(\"car:spawn\", function(source, model, position, heading)\n  if source == nil then return { error = \"For players only.\" } end\n  if not lsmp.perms.has(source, \"car.spawn\") then return { error = \"You may not spawn vehicles.\" } end\n  if math.type(model) ~= \"integer\" or type(position) ~= \"table\" or type(heading) ~= \"number\" then\n    return { error = \"Bad request.\" }\n  end\n\n  -- The position comes from the client: compare it with where the server knows the player is.\n  local ped = lsmp.getPlayerPed(source)\n  local here = ped and lsmp.getEntityCoords(ped)\n  if not here then return { error = \"You have not spawned yet.\" } end\n  local dx, dy, dz = here.x - position.x, here.y - position.y, here.z - position.z\n  if math.sqrt(dx * dx + dy * dy + dz * dz) > MAX_DISTANCE then\n    return { error = \"Too far from you.\" }\n  end\n\n  -- One car per player.\n  if spawned[source] then lsmp.deleteEntity(spawned[source]) end\n\n  local netId = lsmp.createEntity(lsmp.EntityType.Vehicle, model, position, {\n    heading = heading,\n    owner = source,                          -- simulated by this player from the first frame\n    dimension = lsmp.getPlayerDimension(source),\n    lifePolicy = lsmp.LifePolicy.WithCreator, -- removed when the player leaves\n  })\n  if not netId then return { error = \"Could not create the vehicle (\" .. lsmp.getLastError() .. \").\" } end\n\n  spawned[source] = netId\n  return { netId = netId }\nend)\n\nlsmp.on(\"playerLeave\", function(playerId)\n  spawned[playerId] = nil\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// resources/car/server/main.js\nconst MAX_DISTANCE = 15;\nconst spawned = new Map();   // playerId -> netId of the car we made for them\n\nlsmp.perms.declare('car.spawn', 'Spawn a vehicle with /car');\n\nconst isVec3 = (v) => v !== null && typeof v === 'object' && [v.x, v.y, v.z].every(Number.isFinite);\n\nlsmp.onCall('car:spawn', (source, model, position, heading) => {\n  if (source === null) return { error: 'For players only.' };\n  if (!lsmp.perms.has(source, 'car.spawn')) return { error: 'You may not spawn vehicles.' };\n  if (!Number.isInteger(model) || !isVec3(position) || !Number.isFinite(heading)) return { error: 'Bad request.' };\n\n  // The position comes from the client: compare it with where the server knows the player is.\n  const ped = lsmp.getPlayerPed(source);\n  const here = ped !== null ? lsmp.getEntityCoords(ped) : null;\n  if (!here || Math.hypot(here.x - position.x, here.y - position.y, here.z - position.z) > MAX_DISTANCE)\n    return { error: 'Too far from you.' };\n\n  // One car per player.\n  if (spawned.has(source)) lsmp.deleteEntity(spawned.get(source));\n\n  const netId = lsmp.createEntity(lsmp.EntityType.Vehicle, model, position, {\n    heading,\n    owner: source,                            // simulated by this player from the first frame\n    dimension: lsmp.getPlayerDimension(source),\n    lifePolicy: lsmp.LifePolicy.WithCreator,  // removed when the player leaves\n  });\n  if (netId === null) return { error: `Could not create the vehicle (${lsmp.getLastError()}).` };\n\n  spawned.set(source, netId);\n  return { netId };\n});\n\nlsmp.on('playerLeave', (playerId) => {\n  spawned.delete(playerId);\n});"
                }
              ]
            },
            {
              "type": "heading",
              "text": "3. The client script",
              "level": 2,
              "id": "car-client"
            },
            {
              "type": "text",
              "md": "The client registers `/car` in the F8 console, asks the server, and waits for the vehicle: the netId is valid at once, but the game builds the car over the next frames."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- resources/car/client/main.lua\nlocal DRIVER_SEAT = -1\n\nlsmp.registerCommand(\"car\", {\n  help = \"Spawn a vehicle in front of you\",\n  params = { { name = \"model\", help = \"Vehicle model, such as adder\", optional = true } },\n}, function(args)\n  local name = (args[1] or \"sultan\"):lower()\n  local model = lsmp.hash(name)\n  if not isModelInCdimage(model) or not isModelAVehicle(model) then\n    lsmp.log(name .. \" is not a vehicle model\")\n    return\n  end\n\n  local ped = playerPedId()\n  local pos = getEntityCoords(ped, true)\n  local fwd = getEntityForwardVector(ped)\n  local spot = { x = pos.x + fwd.x * 5, y = pos.y + fwd.y * 5, z = pos.z + 0.5 }\n\n  local answer, err = lsmp.callServer(\"car:spawn\", model, spot, getEntityHeading(ped))\n  if not answer then\n    lsmp.log(\"the server did not answer: \" .. err)\n    return\n  end\n  if answer.error then\n    lsmp.log(answer.error)\n    return\n  end\n\n  for _ = 1, 50 do\n    local vehicle = lsmp.getEntityFromNetId(answer.netId)\n    if vehicle then\n      setPedIntoVehicle(playerPedId(), vehicle, DRIVER_SEAT)\n      return\n    end\n    lsmp.wait(100)\n  end\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// resources/car/client/main.js\nconst DRIVER_SEAT = -1;\n\nlsmp.registerCommand('car', {\n  help: 'Spawn a vehicle in front of you',\n  params: [{ name: 'model', help: 'Vehicle model, such as adder', optional: true }],\n}, async (args) => {\n  const name = (args[0] || 'sultan').toLowerCase();\n  const model = lsmp.hash(name);\n  if (!isModelInCdimage(model) || !isModelAVehicle(model)) {\n    lsmp.log(`${name} is not a vehicle model`);\n    return;\n  }\n\n  const ped = playerPedId();\n  const pos = getEntityCoords(ped, true);\n  const fwd = getEntityForwardVector(ped);\n  const spot = { x: pos.x + fwd.x * 5, y: pos.y + fwd.y * 5, z: pos.z + 0.5 };\n\n  let answer;\n  try {\n    answer = await lsmp.callServer('car:spawn', model, spot, getEntityHeading(ped));\n  } catch (err) {\n    lsmp.log(`the server did not answer: ${err.code}`);\n    return;\n  }\n  if (answer.error) {\n    lsmp.log(answer.error);\n    return;\n  }\n\n  for (let i = 0; i < 50; i++) {\n    const vehicle = lsmp.getEntityFromNetId(answer.netId);\n    if (vehicle !== null) {\n      setPedIntoVehicle(playerPedId(), vehicle, DRIVER_SEAT);\n      return;\n    }\n    await lsmp.wait(100);\n  }\n});"
                }
              ]
            },
            {
              "type": "heading",
              "text": "4. Give the permission and test",
              "level": 2,
              "id": "car-test"
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Load the resource",
                  "md": "Restart the server (`quit` in its console, then start it again): resources are loaded when the server starts."
                },
                {
                  "title": "Give the permission",
                  "md": "In the admin panel, Permissions tab, allow `car.spawn` to a group you are in (or to `default` for every player). A script can do it too: `lsmp.perms.allow(\"group:default\", \"car.spawn\")`."
                },
                {
                  "title": "Try it",
                  "md": "In game, open the F8 console and type `/car adder`. Without the permission, the server answers \"You may not spawn vehicles.\""
                }
              ]
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "Going further",
              "md": "Add a `/dv` command that deletes the player's car through another `lsmp.onCall`, and a cooldown per player on the server. The bundled `vehicle-spawner` resource does both: see [Bundled example resources](#examples)."
            }
          ]
        },
        {
          "id": "tutorial-ui",
          "title": "Tutorial: your first web UI",
          "eyebrow": "Tutorials",
          "lead": "Build an ATM in twenty minutes: a web page in game that shows the player's balance and lets them withdraw cash, with the server deciding every amount.",
          "blocks": [
            {
              "type": "text",
              "md": "You need a [running server](#install) and to have done the [Quick start](#quick-start). We build a resource named `atm`. Its three parts talk in a line, never around it: **page ⇄ client script ⇄ server script**. The page asks the client script, which asks the server, which decides."
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Create the folder and the manifest",
                  "md": "`web/` is served to your pages at `rsc://atm/`.",
                  "blocks": [
                    {
                      "type": "tree",
                      "tree": "resources/\n└─ atm/\n   ├─ manifest.json\n   ├─ server/\n   │  └─ main.lua\n   ├─ client/\n   │  └─ main.lua\n   └─ web/\n      ├─ index.html\n      ├─ style.css\n      └─ app.js",
                      "only": "lua"
                    },
                    {
                      "type": "tree",
                      "tree": "resources/\n└─ atm/\n   ├─ manifest.json\n   ├─ server/\n   │  └─ main.js\n   ├─ client/\n   │  └─ main.js\n   └─ web/\n      ├─ index.html\n      ├─ style.css\n      └─ app.js",
                      "only": "js"
                    },
                    {
                      "type": "code",
                      "lang": "json",
                      "title": "manifest.json",
                      "code": "{\n  \"title\": \"ATM\",\n  \"server_scripts\": \"server/main.lua\",\n  \"client_scripts\": \"client/main.lua\",\n  \"webui\": \"web\"\n}",
                      "only": "lua"
                    },
                    {
                      "type": "code",
                      "lang": "json",
                      "title": "manifest.json",
                      "code": "{\n  \"title\": \"ATM\",\n  \"server_scripts\": \"server/main.js\",\n  \"client_scripts\": \"client/main.js\",\n  \"webui\": \"web\"\n}",
                      "only": "js"
                    }
                  ]
                },
                {
                  "title": "The server owns the money",
                  "md": "Two remote calls: one reads the balance, one withdraws. The server checks the amount: a page or a client can send anything. The balance lives in memory to keep the tutorial short; [Storing data](#data-guide) shows how to keep it.",
                  "codetabs": [
                    {
                      "label": "server/main.lua",
                      "lang": "lua",
                      "code": "local balances = {}   -- playerId -> dollars\n\nlsmp.on(\"playerJoin\", function(playerId)\n  balances[playerId] = 5000\nend)\n\nlsmp.on(\"playerLeave\", function(playerId)\n  balances[playerId] = nil\nend)\n\nlsmp.onCall(\"atm:balance\", function(source)\n  return balances[source] or 0\nend)\n\nlsmp.onCall(\"atm:withdraw\", function(source, amount)\n  local balance = balances[source] or 0\n  if math.type(amount) ~= \"integer\" or amount < 1 or amount > 2000 then\n    return { ok = false, reason = \"Choose between $1 and $2,000.\" }\n  end\n  if amount > balance then\n    return { ok = false, reason = \"Not enough money.\" }\n  end\n  balances[source] = balance - amount\n  lsmp.log(lsmp.getPlayerName(source) .. \" withdrew $\" .. amount)\n  return { ok = true, balance = balances[source] }\nend)"
                    },
                    {
                      "label": "server/main.js",
                      "lang": "js",
                      "code": "const balances = new Map();   // playerId -> dollars\n\nlsmp.on('playerJoin', (playerId) => balances.set(playerId, 5000));\nlsmp.on('playerLeave', (playerId) => balances.delete(playerId));\n\nlsmp.onCall('atm:balance', (source) => balances.get(source) ?? 0);\n\nlsmp.onCall('atm:withdraw', (source, amount) => {\n  const balance = balances.get(source) ?? 0;\n  if (!Number.isInteger(amount) || amount < 1 || amount > 2000) {\n    return { ok: false, reason: 'Choose between $1 and $2,000.' };\n  }\n  if (amount > balance) return { ok: false, reason: 'Not enough money.' };\n  balances.set(source, balance - amount);\n  lsmp.log(`${lsmp.getPlayerName(source)} withdrew $${amount}`);\n  return { ok: true, balance: balance - amount };\n});"
                    }
                  ]
                },
                {
                  "title": "The page",
                  "md": "A small panel in the middle of a transparent, full-screen page. It asks for the balance when it opens, and for a withdrawal when the player presses the button. It never decides anything.",
                  "codetabs": [
                    {
                      "label": "web/index.html",
                      "lang": "html",
                      "web": true,
                      "code": "<!doctype html>\n<html>\n<head>\n  <meta charset=\"utf-8\">\n  <link rel=\"stylesheet\" href=\"style.css\">\n</head>\n<body>\n  <main class=\"atm\">\n    <h1>ATM</h1>\n    <p class=\"balance\">Balance: <b id=\"balance\">…</b></p>\n    <input id=\"amount\" type=\"number\" min=\"1\" max=\"2000\" value=\"100\">\n    <button id=\"withdraw\">Withdraw</button>\n    <p id=\"message\"></p>\n    <button id=\"close\" class=\"ghost\">Close</button>\n  </main>\n  <script src=\"app.js\"></script>\n</body>\n</html>"
                    },
                    {
                      "label": "web/style.css",
                      "lang": "css",
                      "web": true,
                      "code": "html, body { margin: 0; height: 100%; background: transparent; font-family: system-ui, sans-serif; }\nbody { display: grid; place-items: center; }\n.atm {\n  width: 22rem; padding: 1.5rem; border-radius: 12px;\n  background: rgba(12, 16, 24, .92); color: #fff; box-shadow: 0 10px 40px #0008;\n}\n.atm h1 { margin: 0 0 1rem; font-size: 1.3rem; }\n.atm input, .atm button { width: 100%; box-sizing: border-box; padding: .7rem; margin-top: .6rem; font: inherit; border-radius: 8px; border: 0; }\n.atm button { background: #2e9d5b; color: #fff; cursor: pointer; }\n.atm button.ghost { background: transparent; color: #aaa; }\n#message { min-height: 1.2em; color: #ffcf5a; }"
                    },
                    {
                      "label": "web/app.js",
                      "lang": "js",
                      "web": true,
                      "code": "const $ = (id) => document.getElementById(id);\nconst dollars = (n) => `$${n.toLocaleString(lsmp.language)}`;\n\n// The client script sends 'open' each time the ATM opens.\nlsmp.on('open', async () => {\n  $('message').textContent = '';\n  $('balance').textContent = dollars(await lsmp.call('balance'));\n  $('amount').focus();\n});\n\n$('withdraw').addEventListener('click', async () => {\n  try {\n    const result = await lsmp.call('withdraw', Number($('amount').value));\n    if (result.ok) {\n      $('balance').textContent = dollars(result.balance);\n      $('message').textContent = 'Take your cash.';\n    } else {\n      $('message').textContent = result.reason;\n    }\n  } catch (err) {\n    $('message').textContent = `The bank is unavailable (${err.code}).`;\n  }\n});\n\n$('close').addEventListener('click', () => lsmp.emit('close'));\ndocument.addEventListener('keydown', (e) => { if (e.key === 'Escape') lsmp.emit('close'); });"
                    }
                  ]
                },
                {
                  "title": "The client script connects them",
                  "md": "It opens the page hidden, shows it on the `/atm` command, and forwards the page's calls to the server. In Lua, the handler may wait for the server: it runs in a coroutine. In JavaScript, it returns a Promise.",
                  "codetabs": [
                    {
                      "label": "client/main.lua",
                      "lang": "lua",
                      "code": "local atm = lsmp.createBrowser(\"rsc://atm/index.html\", { visible = false })\n\nlocal function setOpen(open)\n  atm:setVisible(open)\n  atm:setFocus(open)\n  if open then atm:emit(\"open\") end\nend\n\nlsmp.registerCommand(\"atm\", { help = \"open the ATM\" }, function()\n  setOpen(true)\nend)\n\n-- Page -> client -> server, and the answer goes back the same way.\natm:on(\"balance\", function()\n  local balance = lsmp.callServer(\"atm:balance\")\n  return balance or 0\nend)\n\natm:on(\"withdraw\", function(amount)\n  local result, err = lsmp.callServer(\"atm:withdraw\", amount)\n  if not result then\n    return { ok = false, reason = \"The bank did not answer (\" .. err .. \").\" }\n  end\n  return result\nend)\n\natm:on(\"close\", function() setOpen(false) end)\natm:on(\"focusLost\", function() setOpen(false) end)   -- Ctrl+Alt+Backspace"
                    },
                    {
                      "label": "client/main.js",
                      "lang": "js",
                      "code": "const atm = lsmp.createBrowser('rsc://atm/index.html', { visible: false });\n\nfunction setOpen(open) {\n  atm.setVisible(open);\n  atm.setFocus(open);\n  if (open) atm.emit('open');\n}\n\nlsmp.registerCommand('atm', { help: 'open the ATM' }, () => setOpen(true));\n\n// Page -> client -> server, and the answer goes back the same way.\natm.on('balance', () => lsmp.callServer('atm:balance'));\n\natm.on('withdraw', async (amount) => {\n  try {\n    return await lsmp.callServer('atm:withdraw', amount);\n  } catch (err) {\n    return { ok: false, reason: `The bank did not answer (${err.code}).` };\n  }\n});\n\natm.on('close', () => setOpen(false));\natm.on('focusLost', () => setOpen(false));   // Ctrl+Alt+Backspace"
                    }
                  ]
                },
                {
                  "title": "Start it and try",
                  "md": "Restart the server so it loads `atm`, then join. In game, open the client console (**F8**) and type `atm`. Withdraw $100: the balance drops, and the server console prints the withdrawal. Try $99999: the server refuses, and the page shows why.",
                  "code": {
                    "lang": "text",
                    "title": "server console",
                    "code": "[atm] Jane withdrew $100"
                  }
                },
                {
                  "title": "Change and reload",
                  "md": "Edit the page or a script, then restart the server and join again. To iterate faster on the page and the client scripts, run them as [local resources](#local-resources) in Story mode. To inspect the page (elements, console, network), open [DevTools](#debugging/debugging-devtools)."
                }
              ]
            },
            {
              "type": "callout",
              "variant": "tip",
              "title": "What you used",
              "md": "`webui` and `rsc://` ([Resource layout](#resource-layout/layout-webui)), `createBrowser`, `setVisible`, `setFocus`, `emit` and `on` ([Browsers](#browsers)), the page's `lsmp.on`, `lsmp.call` and `lsmp.emit` ([Page API](#page-api)), and server calls ([Events and RPC](#events-guide))."
            },
            {
              "type": "list",
              "items": [
                "Keep the balance across restarts with [storage](#server-storage).",
                "Open the ATM when the player stands at a real ATM prop instead of a command: [World helpers](#world).",
                "Translate the page with `lsmp.language`.",
                "Read [Web interfaces](#web-ui) for frameworks, hot reload and 3D screens."
              ]
            }
          ]
        },
        {
          "id": "tutorial-shop",
          "title": "Tutorial: a shop with remote calls and storage",
          "eyebrow": "Tutorial · Lua & JS",
          "lead": "A weapon shop where the server keeps each account's money, answers the client's questions with remote calls, and saves everything across restarts.",
          "blocks": [
            {
              "type": "text",
              "md": "Two rules shape this tutorial:\n\n- **Money lives on the server.** The client asks, the server decides. A client can be modified; the server cannot.\n- **Saved data is keyed on the account** (`lsmpId`), never on the playerId, which the next player gets when this one leaves. Guests have no account, so they cannot buy.\n\nWe use [calls](#rpc) for the questions (`lsmp.callServer` on the client, `lsmp.onCall` on the server) and [storage](#server-storage) for the wallets."
            },
            {
              "type": "tree",
              "tree": "resources/\n└─ shop/\n   ├─ manifest.json      # client_scripts: client/main.lua, server_scripts: server/main.lua\n   ├─ client/\n   │  └─ main.lua        # or main.js\n   └─ server/\n      └─ main.lua        # or main.js"
            },
            {
              "type": "heading",
              "text": "1. The server: catalogue, wallets, purchases",
              "level": 2,
              "id": "shop-server"
            },
            {
              "type": "text",
              "md": "The catalogue is a table on the server: the client never sends a price. Each wallet is one storage entry, `wallet:<lsmpId>`, holding a number. `lsmp.storage.set` is visible to the next `get` at once and written to disk shortly after."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- resources/shop/server/main.lua\nlocal START_MONEY = 5000\n\nlocal ITEMS = {\n  pistol  = { label = \"Pistol\",       price = 800,  weapon = \"WEAPON_PISTOL\",       ammo = 60 },\n  smg     = { label = \"SMG\",          price = 2500, weapon = \"WEAPON_SMG\",          ammo = 120 },\n  carbine = { label = \"Carbine rifle\", price = 4200, weapon = \"WEAPON_CARBINERIFLE\", ammo = 180 },\n}\n\nlocal function walletKey(source)\n  local account = lsmp.getPlayerLsmpId(source)\n  return account and (\"wallet:\" .. account)\nend\n\nlocal function balanceOf(key)\n  return lsmp.storage.get(key) or START_MONEY\nend\n\n-- What the shop sells, and what this player has.\nlsmp.onCall(\"shop:list\", function(source)\n  local key = source and walletKey(source)\n  local list = {}\n  for id, item in pairs(ITEMS) do\n    list[#list + 1] = { id = id, label = item.label, price = item.price }\n  end\n  table.sort(list, function(a, b) return a.price < b.price end)\n  return { items = list, balance = key and balanceOf(key) }\nend)\n\n-- A purchase: everything is checked here.\nlsmp.onCall(\"shop:buy\", function(source, id)\n  local key = source and walletKey(source)\n  if not key then return { error = \"Only players with an LS:MP account can buy.\" } end\n  local item = type(id) == \"string\" and ITEMS[id]\n  if not item then return { error = \"No such item.\" } end\n\n  local balance = balanceOf(key)\n  if balance < item.price then return { error = \"Not enough money.\", balance = balance } end\n\n  balance = balance - item.price\n  lsmp.storage.set(key, balance)\n  lsmp.log((\"%s bought %s, %d left\"):format(lsmp.getPlayerName(source), id, balance))\n  return { balance = balance, weapon = item.weapon, ammo = item.ammo }\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// resources/shop/server/main.js\nconst START_MONEY = 5000;\n\nconst ITEMS = {\n  pistol:  { label: 'Pistol',        price: 800,  weapon: 'WEAPON_PISTOL',       ammo: 60 },\n  smg:     { label: 'SMG',           price: 2500, weapon: 'WEAPON_SMG',          ammo: 120 },\n  carbine: { label: 'Carbine rifle', price: 4200, weapon: 'WEAPON_CARBINERIFLE', ammo: 180 },\n};\n\nfunction walletKey(source) {\n  const account = lsmp.getPlayerLsmpId(source);\n  return account !== null ? `wallet:${account}` : null;\n}\n\nconst balanceOf = (key) => lsmp.storage.get(key) ?? START_MONEY;\n\n// What the shop sells, and what this player has.\nlsmp.onCall('shop:list', (source) => {\n  const key = source !== null ? walletKey(source) : null;\n  const items = Object.entries(ITEMS)\n    .map(([id, item]) => ({ id, label: item.label, price: item.price }))\n    .sort((a, b) => a.price - b.price);\n  return { items, balance: key ? balanceOf(key) : null };\n});\n\n// A purchase: everything is checked here.\nlsmp.onCall('shop:buy', (source, id) => {\n  const key = source !== null ? walletKey(source) : null;\n  if (!key) return { error: 'Only players with an LS:MP account can buy.' };\n  const item = typeof id === 'string' && Object.hasOwn(ITEMS, id) ? ITEMS[id] : null;\n  if (!item) return { error: 'No such item.' };\n\n  let balance = balanceOf(key);\n  if (balance < item.price) return { error: 'Not enough money.', balance };\n\n  balance -= item.price;\n  lsmp.storage.set(key, balance);\n  lsmp.log(`${lsmp.getPlayerName(source)} bought ${id}, ${balance} left`);\n  return { balance, weapon: item.weapon, ammo: item.ammo };\n});"
                }
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "Check what the client sends",
              "md": "Arguments of a remote call keep their type, but the client chooses them. Here `id` is looked up in the server's own table; a string such as `toString` or `__index` finds nothing. Never trust a price, an amount or a position coming from a client."
            },
            {
              "type": "heading",
              "text": "2. The client: /shop and /buy",
              "level": 2,
              "id": "shop-client"
            },
            {
              "type": "text",
              "md": "The client only displays and asks. When the server accepts a purchase it answers with the weapon to give, and the client gives it to its own ped."
            },
            {
              "type": "codetabs",
              "tabs": [
                {
                  "label": "Lua",
                  "lang": "lua",
                  "code": "-- resources/shop/client/main.lua\nlsmp.registerCommand(\"shop\", { help = \"List what the shop sells\" }, function()\n  local res, err = lsmp.callServer(\"shop:list\")\n  if not res then\n    lsmp.log(\"the shop is closed: \" .. err)\n    return\n  end\n  for _, item in ipairs(res.items) do\n    lsmp.log((\"%-8s %-14s $%d\"):format(item.id, item.label, item.price))\n  end\n  lsmp.log(res.balance and (\"you have $\" .. res.balance) or \"guests cannot buy\")\nend)\n\nlsmp.registerCommand(\"buy\", {\n  help = \"Buy an item: /buy pistol\",\n  params = { { name = \"item\" } },\n}, function(args)\n  local res, err = lsmp.callServer(\"shop:buy\", args[1])\n  if not res then\n    lsmp.log(\"the shop did not answer: \" .. err)\n  elseif res.error then\n    lsmp.log(res.error)\n  else\n    giveWeaponToPed(playerPedId(), lsmp.hash(res.weapon), res.ammo, false, true)\n    lsmp.log(\"bought, $\" .. res.balance .. \" left\")\n  end\nend)"
                },
                {
                  "label": "JavaScript",
                  "lang": "js",
                  "code": "// resources/shop/client/main.js\nlsmp.registerCommand('shop', { help: 'List what the shop sells' }, async () => {\n  try {\n    const res = await lsmp.callServer('shop:list');\n    for (const item of res.items) lsmp.log(`${item.id.padEnd(8)} ${item.label.padEnd(14)} $${item.price}`);\n    lsmp.log(res.balance !== null ? `you have $${res.balance}` : 'guests cannot buy');\n  } catch (err) {\n    lsmp.log(`the shop is closed: ${err.code}`);\n  }\n});\n\nlsmp.registerCommand('buy', {\n  help: 'Buy an item: /buy pistol',\n  params: [{ name: 'item' }],\n}, async (args) => {\n  let res;\n  try {\n    res = await lsmp.callServer('shop:buy', args[0]);\n  } catch (err) {\n    lsmp.log(`the shop did not answer: ${err.code}`);\n    return;\n  }\n  if (res.error) {\n    lsmp.log(res.error);\n    return;\n  }\n  giveWeaponToPed(playerPedId(), lsmp.hash(res.weapon), res.ammo, false, true);\n  lsmp.log(`bought, $${res.balance} left`);\n});"
                }
              ]
            },
            {
              "type": "heading",
              "text": "3. Try it",
              "level": 2,
              "id": "shop-try"
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Load the resource",
                  "md": "Restart the server: resources are loaded when it starts."
                },
                {
                  "title": "Shop",
                  "md": "In game, F8 console: `/shop`, then `/buy pistol`."
                },
                {
                  "title": "Restart and check",
                  "md": "Restart the server, join again and type `/shop`: the balance is still there, read back from the storage."
                }
              ]
            },
            {
              "type": "heading",
              "text": "Going further",
              "level": 2,
              "id": "shop-further"
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "Give money: a server command that adds to a wallet (`lsmp.storage.set(key, balanceOf(key) + amount)`), protected by a [permission](#server-commands).",
                "Show the shop in a [web interface](#tutorial-ui) instead of the console: the page calls the client script, which calls the server the same way.",
                "Sell real benefits, bought on Summum from your store or in game: see [In-game benefits](#benefits).",
                "Many items or many players: move the wallets to [MySQL](#server-mysql) and do the check and the update in one transaction."
              ]
            }
          ]
        },
        {
          "id": "recipe-ai",
          "title": "Recipe: server-spawned AI",
          "eyebrow": "Tutorials",
          "lead": "Spawn AI peds from the server and keep their behaviour when another player takes over their simulation.",
          "blocks": [
            {
              "type": "text",
              "md": "This recipe spawns AI peds from the server and keeps them behaving the same way whoever simulates them: guards around a building, and a ped driven by your own client code. It uses [entities](#server-entities), [ownership and intents](#server-ownership), [meta](#meta) and the [`entityAdopt`](#engine-events/ev-entity-adopt) event."
            },
            {
              "type": "callout",
              "variant": "info",
              "md": "A ped's AI runs in the game of the player who simulates it. When that player walks away or leaves, another player takes over and the game task is lost. An intent is stored with the entity on the server, and every new owner applies it again.",
              "title": "Why intents"
            },
            {
              "type": "heading",
              "text": "Guards with a built-in intent",
              "level": 2,
              "id": "guards"
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Spawn the peds",
                  "md": "`lifePolicy = \"keep\"` keeps the guards alive when nobody is around. They are deleted with the resource when it stops.",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "local POST = { x = -1037.0, y = -2737.0, z = 20.17 }\nlocal guards = {}\n\nlsmp.on(\"resourceStart\", function(name)\n  if name ~= lsmp.getResourceName() then return end\n  for i = 1, 3 do\n    local pos = { x = POST.x + i * 2.0, y = POST.y, z = POST.z }\n    local ped, err = lsmp.createEntity(\"ped\", \"s_m_m_security_01\", pos, { heading = 180.0, lifePolicy = \"keep\" })\n    if ped then guards[#guards + 1] = ped else lsmp.warn(\"guard not created: \" .. err) end\n  end\nend)"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "const POST = { x: -1037, y: -2737, z: 20.17 };\nconst guards = [];\n\nlsmp.on(\"resourceStart\", (name) => {\n  if (name !== lsmp.getResourceName()) return;\n  for (let i = 1; i <= 3; i++) {\n    const pos = { x: POST.x + i * 2, y: POST.y, z: POST.z };\n    const ped = lsmp.createEntity(\"ped\", \"s_m_m_security_01\", pos, { heading: 180, lifePolicy: \"keep\" });\n    if (ped !== null) guards.push(ped);\n    else lsmp.warn(`guard not created: ${lsmp.getLastError()}`);\n  }\n});"
                    }
                  ]
                },
                {
                  "title": "Give them an intent",
                  "md": "A `\"guard\"` intent keeps each ped within `radius` of `position` and makes it attack what comes close. `keepTask` stops ambient events from replacing the task; `mission` keeps the game from cleaning the ped up.",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "for _, ped in ipairs(guards) do\n  lsmp.setEntityIntent(ped, {\n    type = \"guard\", position = POST, radius = 12.0,\n    accuracy = 40, keepTask = true, mission = true, hatesPlayers = true,\n  })\nend"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "for (const ped of guards) {\n  lsmp.setEntityIntent(ped, {\n    type: \"guard\", position: POST, radius: 12,\n    accuracy: 40, keepTask: true, mission: true, hatesPlayers: true,\n  });\n}"
                    }
                  ]
                },
                {
                  "title": "Change orders later",
                  "md": "Set a new intent at any time; the current owner applies it, and so will the next ones.",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "lsmp.registerCommand(\"alarm\", function(args, raw, source)\n  for _, ped in ipairs(guards) do\n    lsmp.setEntityIntent(ped, { type = \"combat\", target = \"nearestPlayer\", accuracy = 60, keepTask = true, run = true })\n  end\nend)"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "lsmp.registerCommand(\"alarm\", (args, raw, source) => {\n  for (const ped of guards) {\n    lsmp.setEntityIntent(ped, { type: \"combat\", target: \"nearestPlayer\", accuracy: 60, keepTask: true, run: true });\n  }\n});"
                    }
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "Your own AI with a custom intent",
              "level": 2,
              "id": "custom"
            },
            {
              "type": "text",
              "md": "With `type = \"custom\"`, LS:MP applies no task. The client that takes over the ped receives `entityAdopt` and gives the orders itself, with game natives. Store what the client needs in the entity's meta."
            },
            {
              "type": "steps",
              "items": [
                {
                  "title": "Server: mark the ped",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "local ped = lsmp.createEntity(\"ped\", \"a_m_y_hipster_01\", { x = 200.0, y = -930.0, z = 30.7 }, { lifePolicy = \"keep\" })\nif ped then\n  lsmp.setEntityMeta(ped, \"ai:scenario\", \"WORLD_HUMAN_MUSICIAN\")\n  lsmp.setEntityIntent(ped, { type = \"custom\", keepTask = true, mission = true })\nend"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "const ped = lsmp.createEntity(\"ped\", \"a_m_y_hipster_01\", { x: 200, y: -930, z: 30.7 }, { lifePolicy: \"keep\" });\nif (ped !== null) {\n  lsmp.setEntityMeta(ped, \"ai:scenario\", \"WORLD_HUMAN_MUSICIAN\");\n  lsmp.setEntityIntent(ped, { type: \"custom\", keepTask: true, mission: true });\n}"
                    }
                  ]
                },
                {
                  "title": "Client: apply it when adopting",
                  "md": "`entityAdopt` fires on the client that starts simulating the entity, each time ownership moves to it.",
                  "codetabs": [
                    {
                      "label": "Lua",
                      "lang": "lua",
                      "code": "lsmp.on(\"entityAdopt\", function(netId)\n  local scenario = lsmp.getEntityMeta(netId, \"ai:scenario\")\n  if not scenario then return end\n  local ped = lsmp.getEntityFromNetId(netId)\n  if ped then taskStartScenarioInPlace(ped, scenario, 0, true) end\nend)"
                    },
                    {
                      "label": "JavaScript",
                      "lang": "js",
                      "code": "lsmp.on(\"entityAdopt\", (netId) => {\n  const scenario = lsmp.getEntityMeta(netId, \"ai:scenario\");\n  if (!scenario) return;\n  const ped = lsmp.getEntityFromNetId(netId);\n  if (ped) taskStartScenarioInPlace(ped, scenario, 0, true);\n});"
                    }
                  ]
                }
              ]
            },
            {
              "type": "heading",
              "text": "Good to know",
              "level": 2,
              "id": "notes"
            },
            {
              "type": "list",
              "items": [
                "Owners change: never keep AI state only in one client. Keep it in the intent or in meta.",
                "To keep one ped on one player (an escort, a pet), create it with `owner = playerId` and set its owner policy to `\"pinned\"`.",
                "A ped you move only from the server (no game AI) uses the owner policy `\"server\"`.",
                "Peds of other resources need the `entities.foreign` [capability](#capabilities) to be given intents."
              ]
            }
          ]
        },
        {
          "id": "examples",
          "title": "Bundled example resources",
          "eyebrow": "Tutorial · Lua & JS",
          "lead": "The resources shipped with the server: what each one does, which part of the API it shows, and how to install them.",
          "blocks": [
            {
              "type": "text",
              "md": "The server download holds two folders: `lsmp-server/`, the server itself, and `resource_samples/`, the resources of this page. Each script starts with a few lines that say what it does, and is commented where it matters. Some are **essentials** a server needs (arrival, chat, death, voice), others are **samples** of one part of the API each, and two are **tools**. Most are written in JavaScript; four also exist in Lua."
            },
            {
              "type": "heading",
              "text": "Installing them",
              "level": 2,
              "id": "examples-enable"
            },
            {
              "type": "list",
              "ordered": false,
              "items": [
                "Nothing in `resource_samples/` runs by itself. Copy the folders you want into the `resources/` folder of your server, then restart the server: every folder of `resources/` starts with it.",
                "To turn one off without deleting it, use [`resources.json`](#operator-settings) or the admin panel's Resources tab, then restart the server: `{ \"resources\": { \"emptymap\": { \"enabled\": false } } }`.",
                "They are yours to edit. Rename the folder if you turn one into something of your own: the folder name is the resource's name.",
                "Commands written `/like this` are typed in the game's F8 console; the others in the server console. With the `chat` resource, a line that starts with `/` in the chat runs a server command with the player's permissions."
              ]
            },
            {
              "type": "callout",
              "variant": "warn",
              "title": "One resource must spawn the players",
              "md": "A server with an empty `resources/` folder lets players in, but nothing places them in the world: they stay on the loading screen. Install `spawn-mgr`, or a resource of your own that spawns players. See [Local player, spawn and death](#local-player)."
            },
            {
              "type": "heading",
              "text": "Essentials",
              "level": 2,
              "id": "examples-essentials"
            },
            {
              "type": "table",
              "headers": [
                "Resource",
                "What it does",
                "Shows"
              ],
              "rows": [
                [
                  "`spawn-mgr`",
                  "Places each arriving player at a random point of `shared/config.js`. `/spawn [number|list]` to move.",
                  "The auto spawn handler, `lsmp.spawn`, the `playerSpawn` event, shared scripts."
                ],
                [
                  "`chat`",
                  "Text chat: T to type, Enter to send. Lines starting with `/` run server commands with the player's permissions. `/shout`, `/clearchat`.",
                  "A [web interface](#web-ui) with `browser.emit/on`, rate limiting on the server, `executeCommand`."
                ],
                [
                  "`death-mgr`",
                  "Respawn near the place of death after a few seconds, and a kill feed for the players of the same dimension.",
                  "`playerDeath` on both sides, `lsmp.resurrect`, `emitDimensionClients`."
                ],
                [
                  "`voice-mgr`",
                  "Proximity voice with whisper, normal and shout ranges (K), and radio frequencies with `/radio <1-999>` (Caps Lock to talk).",
                  "The whole [Voice](#voice) API: channels, roles, ranges, mutes (`vmute`, `vunmute`, `vchannels` in the server console)."
                ],
                [
                  "`admin-tools`",
                  "Moderation commands for the server console and, with permissions, the chat: `online`, `ids`, `kickplayer`, `ban`, `unban`, `whitelist`, `announce`.",
                  "[Admission and moderation](#server-moderation), [commands](#server-commands) with permissions."
                ],
                [
                  "`scoreboard`",
                  "Kills and deaths of every player; hold Z to see them.",
                  "Global [meta](#meta) as shared state, `metaChange` on the client."
                ],
                [
                  "`player-blips`",
                  "A map blip on every player streamed near you. `/blips` toggles them.",
                  "`getEntitiesInRadius`, the `entityStreamOut` event, blip natives."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Samples",
              "level": 2,
              "id": "examples-samples"
            },
            {
              "type": "table",
              "headers": [
                "Resource",
                "Try it",
                "Shows"
              ],
              "rows": [
                [
                  "`hello-world`",
                  "Join, then `/hello`; `hello some words` in the server console.",
                  "The smallest complete resource: a shared file, events both ways, a [remote call](#rpc), a command on each side. Start here."
                ],
                [
                  "`admission-sample`",
                  "Edit `server/config.json` (maintenance, name rules), then connect.",
                  "The `playerPreConnection` event and `p.deny`."
                ],
                [
                  "`browser3d-sample`",
                  "`/screen3d on`, `/screen3d say <text>`, `/screen3d off`.",
                  "A web page rendered into a texture and shown in place of a texture of the map ([3D browsers](#browsers), `replaceTexture`)."
                ],
                [
                  "`death-respawn`",
                  "Run it without `death-mgr`, then die.",
                  "A client-driven respawn at the closest point of a list, game notifications. Steps aside while `death-mgr` runs."
                ],
                [
                  "`dimensions-sample`",
                  "`/dim <n>`, `/instance`, `/dimwho`, `/dim 0`.",
                  "Moving players and their vehicle between [dimensions](#dimensions), a private dimension without traffic."
                ],
                [
                  "`discord-sample`",
                  "Look at your Discord profile while playing. `/presence off`.",
                  "The Discord presence functions ([Discord presence](#discord))."
                ],
                [
                  "`event-logger`",
                  "`evlog` in the server console, `/evlog` in F8.",
                  "Every [engine event](#engine-events) on both sides, with its arguments."
                ],
                [
                  "`events-sample`",
                  "`/rpc 2 3`, `/blob`, `/bigdata`, `/localevent hello`.",
                  "[Remote calls](#rpc), bytes, a large payload, local events."
                ],
                [
                  "`http-sample`",
                  "`/httpget`, `/httppost`; `http-test` in the server console; open `/res/http-sample/status` on the server's HTTP port.",
                  "The [HTTP client](#http) on both sides and an [HTTP route](#server-http-serve)."
                ],
                [
                  "`hud-sample`",
                  "Look at the bottom right corner. `/hud` hides it.",
                  "A HUD drawn by a web page fed by the client script ([Web interfaces](#web-ui))."
                ],
                [
                  "`identity-sample`",
                  "`/whoami`, `/who <playerId>`.",
                  "playerId against lsmpId, guests, avatars, identifiers ([Players](#players))."
                ],
                [
                  "`in-game-benefit`",
                  "First create its two products in your Summum store (see `shared/config.js`). Then `/shop vip`, `/shop cash 3`, `/wallet`; `benefit-pending <lsmpId>` in the server console.",
                  "[In-game benefits](#benefits): a cart opened in game, each purchase applied exactly once and confirmed, refunds taken back."
                ],
                [
                  "`metasync-sample`",
                  "`/status <text>`, `/label <text>` in a vehicle, `/motd`.",
                  "Player, entity and global [meta](#meta), checked by the server with `metaChange`."
                ],
                [
                  "`modules-sample`",
                  "`tip` in the server console.",
                  "Local modules, JSON files, Node core modules and resource files ([runtimes](#runtimes))."
                ],
                [
                  "`nametags-sample`",
                  "`/nametags far`, `near`, `off`, `reset`, `info`; `/beacon <playerId>`.",
                  "Styling the names above players, for everybody or for one player ([Nametags](#nametags))."
                ],
                [
                  "`npc-sample`",
                  "`/npc wander`, `follow`, `flee`, `hostile`, `idle`, `/npc clear`.",
                  "Server-spawned peds with AI intents that survive owner changes ([Ownership and AI intents](#server-ownership))."
                ],
                [
                  "`outline-sample`",
                  "`/highlight vehicles`, `/highlight peds`, `/highlight off`.",
                  "Entity outlines coloured by owner ([Outlines and picking](#outline-selection))."
                ],
                [
                  "`ownership-sample`",
                  "Stand next to a vehicle: `/owner`, `/fix`.",
                  "Asking for the ownership of an entity before changing it ([Client entities](#client-entities))."
                ],
                [
                  "`perms-sample`",
                  "`/myperms`, `/can <permission>`, `/perk` in F8; `/whoami`, `/promote <playerId>` in the chat.",
                  "Groups, rules, session memberships, the client copy ([Permissions](#permissions))."
                ],
                [
                  "`picker-sample`",
                  "`/picker`, `/pickertool`.",
                  "Picking what is under the crosshair ([Outlines and picking](#outline-selection))."
                ],
                [
                  "`pickups-sample`",
                  "Go to Legion Square and walk over the pickups.",
                  "`createPickup` and the `pickupCollect` event ([Entities and pickups](#server-entities))."
                ],
                [
                  "`spatial-sample`",
                  "`/near`, `/aim`, `/labels`; `near <playerId>` in the server console.",
                  "Queries around a point on both sides, a raycast from the camera, netIds and handles ([Spatial queries](#spatial))."
                ],
                [
                  "`storage-sample`",
                  "`/playtime` in F8, `playtime-top` in the server console.",
                  "[Persistent storage](#server-storage), keyed on accounts."
                ],
                [
                  "`teleport-sample`",
                  "`/pos`, `/tp x y [z]`, `/tpm`, `/goto <playerId>`.",
                  "Moving the local player, waiting for collisions, a server lookup through a remote call."
                ],
                [
                  "`texture-sample`",
                  "`/texture file`, `/texture pixels`, `/texture info`, `/texture off`.",
                  "An image file of the resource and pixels computed by the script, shown in place of a texture of the map ([Textures](#textures))."
                ],
                [
                  "`vehicle-spawner`",
                  "`/car [model]`, `/dv`.",
                  "Server-created vehicles owned by a player; the [tutorial](#tutorial-car) builds a smaller one."
                ],
                [
                  "`weather-sample`",
                  "`weather`, `weather RAIN 10`, `weather cycle` in the server console; `/sky SNOW`, `/sky off` in F8.",
                  "Reading and forcing the synchronized [weather](#weather), a local sky for one player."
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Lua versions",
              "level": 2,
              "id": "examples-lua"
            },
            {
              "type": "text",
              "md": "The same samples in Lua. Their commands, events and permissions end in `-lua`, so they run next to the JavaScript ones. `hello-world-lua` is written in Lua on both sides; the three others have their server half in Lua and keep a JavaScript client."
            },
            {
              "type": "table",
              "headers": [
                "Resource",
                "Try it",
                "Lua version of"
              ],
              "rows": [
                [
                  "`hello-world-lua`",
                  "`/hello-lua`; `hello-lua some words` in the server console.",
                  "`hello-world`"
                ],
                [
                  "`events-sample-lua`",
                  "`/rpc-lua`, `/blob-lua`, `/bigdata-lua`.",
                  "`events-sample`"
                ],
                [
                  "`storage-sample-lua`",
                  "`/playtime-lua`, `playtime-top-lua` in the server console.",
                  "`storage-sample`"
                ],
                [
                  "`perms-sample-lua`",
                  "`/whoami-lua`, `/promote-lua <playerId>`, `/demote-lua <playerId>`.",
                  "`perms-sample`"
                ]
              ]
            },
            {
              "type": "heading",
              "text": "Tools",
              "level": 2,
              "id": "examples-tools"
            },
            {
              "type": "text",
              "md": "Two resources for testing maps. Leave them out of a public server."
            },
            {
              "type": "table",
              "headers": [
                "Resource",
                "Try it",
                "What for"
              ],
              "rows": [
                [
                  "`emptymap`",
                  "`/unloadmap [group...]`, `/reloadmap`, `/mapstate`, `/maprelease`.",
                  "Unloads the base map while playing ([Hot resources, stream sets and archives](#client-resources))."
                ],
                [
                  "`streamset-sample`",
                  "`/loadset <resource> <set>`, `/unloadset`, `/setstate`.",
                  "Loads and unloads the stream sets of any resource."
                ]
              ]
            }
          ]
        }
      ]
    }
  ]
}
