> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nodeloc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK 参考

> @nodeloc/game-sdk 的全部 nl.* 方法、参数、返回值、错误和网页版行为

## 引入

```html theme={null}
<script src="nl-game-sdk.js"></script>  <!-- 全局 nl -->
```

```javascript theme={null}
import nl from "@nodeloc/game-sdk";       // ES 模块
const nl = require("@nodeloc/game-sdk");  // CommonJS
```

SDK 不需要构建。打包时把 `nl-game-sdk.js` 放进游戏包。类型定义见包里的 `index.d.ts`。

## 约定

* 异步方法返回 Promise，默认 5 秒超时。需要用户操作的方法不设超时：`energy.requestPayment`、`energy.deposit`、`energy.withdraw`、`energy.claimDaily`、`energy.confirmStake`、`share.invite`、`auth.login`。
* 失败时以 `NLError` 拒绝，`code` 为下表之一：

| code | 含义 | 游戏应该怎么做 |
| - | - | - |
| `NOT_SUPPORTED` | 当前宿主没有这个能力 | 隐藏对应功能 |
| `SCOPE_DENIED` | 游戏没有获批这项权限 | 隐藏对应功能 |
| `USER_CANCELLED` | 用户在面板或弹窗中取消 | 不是错误，静默返回 |
| `AUTH_REQUIRED` | 用户没登录论坛或登录已过期 | 显示「请先登录」和按钮，按钮里调 `nl.auth.login()` |
| `INVALID_PARAMS` | 参数不对 | 修代码 |
| `RATE_LIMITED` | 调用太频繁 | 稍后重试 |
| `NETWORK` | 网络或服务端错误 | 提示重试 |
| `INTERNAL` | 宿主内部错误 | 提示重试 |

* `nl.system.getInfo().capabilities` 列出当前宿主真正可用的方法，可用来做降级判断。

## 启动

| 方法 | 说明 |
| - | - |
| `nl.setLoadingProgress(p)` | 加载进度，0–1。宿主加载页显示进度 |
| `nl.ready(): Promise<void>` | 关闭宿主加载页。资源够开始玩时就调用。15 秒没调用，宿主显示「重试 / 退出」 |
| `nl.exit(): Promise<void>` | 退出游戏 |

## 系统

| 方法 | 返回 |
| - | - |
| `nl.system.getInfo()` | `{platform, osVersion, clientVersion, sdkProtocol, locale, safeArea, pixelRatio, capabilities, launch?, gameService?}`。`platform` 为 `ios`、`android` 或 `web`；`gameService` 是实时游戏服务的 WebSocket 地址 |
| `nl.system.getLaunchOptions()` | 同步返回 `{room?}`：从邀请链接进入时的房间号 |

## 界面

| 方法 | 说明 |
| - | - |
| `nl.ui.getCapsuleRect(): Promise<{x, y, width, height}>` | 右上角「退出」胶囊的位置。标题栏和按钮要避开它 |
| `nl.ui.toast(text)` | 轻提示 |
| `nl.ui.requestFullscreen(): Promise<void>` | 网页版：进入全屏，手机上按清单方向锁定屏幕 |

## 生命周期

| 方法 | 说明 |
| - | - |
| `nl.lifecycle.on(event, cb)` | `event` 为 `pause`、`resume`、`back`、`memoryWarning`。返回取消订阅的函数 |
| `nl.lifecycle.setExitGuard(on, message?)` | 打开后，用户退出时先确认。对局中建议打开 |

切到后台时（`pause`）应暂停计时、关掉背景音乐。

## 音频

| 方法 | 说明 |
| - | - |
| `nl.audio.preload(keys): Promise<void>` | 预加载包内音频路径 |
| `nl.audio.play(key, {volume?, loop?, rate?}): number` | 播放，返回 handle。不等待回复 |
| `nl.audio.stop(handle)` | 停止 |
| `nl.audio.bgm.play(key)` / `pause()` / `resume()` / `stop()` | 背景音乐 |
| `nl.audio.setMasterVolume(v)` / `setMuted(muted)` | 总音量、静音 |

App 中使用原生音频，静音键和来电打断由宿主处理。网页版使用 Web Audio，首次点按后解锁。

## 震动

| 方法 | 说明 |
| - | - |
| `nl.haptics.impact(style?)` | `light`、`medium`、`heavy`、`rigid`、`soft` |
| `nl.haptics.notify(type?)` | `success`、`warning`、`error` |
| `nl.haptics.selection()` | 选择反馈 |

每 50 毫秒最多震动一次，多余的调用会被丢弃。网页版使用 `navigator.vibrate`，iOS Safari 不支持时静默跳过。

## 身份

| 方法 | 返回 | 说明 |
| - | - | - |
| `nl.auth.getUser()` | `{id, username, name, avatar, tier?}` | `id` 是按游戏派生的匿名编号，不是论坛用户编号 |
| `nl.auth.getToken()` | `{token, expiresAt}` | 连游戏服务用的 game token，`expiresAt` 是 Unix 毫秒，过期前 60 秒自动换新 |
| `nl.auth.login()` | `Promise<void>` | 让用户登录论坛。必须在点击事件里调用 |

没登录时前两个方法返回 `AUTH_REQUIRED`。App 中宿主会提示登录，登录后重新加载游戏。网页版没有令牌时，SDK 整页跳转到论坛授权页，用户首次进入需要勾选年满 18 周岁并同意授权。

## 游戏能量

| 方法 | 返回 | 权限 |
| - | - | - |
| `nl.energy.getWallet()` | 钱包，见下 | 任一游戏能量权限 |
| `nl.energy.getHistory({cursor?, limit?, kinds?, allGames?})` | `{entries, nextCursor}` | 任一游戏能量权限 |
| `nl.energy.claimDaily()` | `{granted, balance}` | 任一游戏能量权限 |
| `nl.energy.deposit()` | `{deposited, balance}` | `game.energy.stake` 或 `game.energy.pay` |
| `nl.energy.withdraw()` | `{withdrawn, balance, withdrawable}` | 任一游戏能量权限 |
| `nl.energy.confirmStake({base, cap, table?, title?})` | `{confirmed: true, remembered}` | `game.energy.stake` |
| `nl.energy.requestPayment(orderToken)` | `{status: "paid", orderId}` | `game.energy.stake` 或 `game.energy.pay` |

游戏能量权限指 `game.energy.read`、`game.energy.stake`、`game.energy.pay`，后两项都包含读取。`claimDaily`、`deposit`、`withdraw` 打开宿主面板，数量由用户在面板中选择。

钱包：

```typescript theme={null}
{
  balance: number;
  withdrawable: number;          // 可兑回社区能量的部分
  dailyFreeClaimable: boolean;
  limits: {
    stakeToday, stakeCap, netLossToday, netLossCap,
    depositToday, depositCap, withdrawToday, withdrawCap,
    withdrawMin, withdrawEnabled, withdrawLockDays
  };
  remaining: { stake, netLoss, deposit, withdraw };  // 今天还剩的额度
}
```

明细的每一条：`{id, createdAt, kind, label, amount, balanceAfter, withdrawableDelta, withdrawableAfter, game, roomId?, orderId?}`。`label` 已按用户语言翻译；`amount` 为正数时是进账；`game` 为 `null` 表示钱包本身的流水（兑入、兑回、领取）。`nextCursor` 为 `null` 时没有更多。默认只列本游戏和钱包本身的流水，`allGames` 只在 App 中可用。

`kind` 可为 `deposit`、`withdraw`、`daily_grant`、`relief_grant`、`stake_hold`、`stake_release`、`win`、`loss`、`bot_win`、`bot_loss`、`rake_burn`、`cap_burn`、`ticket`、`prize`、`bonus`、`item`、`refund`。

规则和额度见[游戏能量与支付](https://docs.nodeloc.com/minigames/energy.md)。

## 分享

| 方法 | 说明 |
| - | - |
| `nl.share.invite({title, text?, roomCode?, image?})` | 返回 `{shared}`。邀请链接为 `https://www.nodeloc.com/games/{slug}?room=…` |
| `nl.share.onInvite(cb)` | 游戏运行中用户又点了同一个游戏的邀请时触发，`cb({room})`。返回取消订阅的函数 |

## 调试与配置

| 方法 | 说明 |
| - | - |
| `nl.debug.log(...args)` | App 调试面板中可见 |
| `nl.configure({slug?, site?, gameService?, orientation?, capsule?, loading?})` | 只在网页版或本地调试时需要。`capsule: false` 不画退出按钮，`loading: false` 不画加载层 |

启动耗时、崩溃、帧率、连接质量由宿主自动上报，游戏不需要处理。

## 网页版的行为

| 能力 | 网页版做法 |
| - | - |
| 身份 | 论坛授权（PKCE）。令牌和刷新令牌存在 `sessionStorage`，刷新令牌 7 天有效 |
| 余额、明细 | 用 game token 读论坛的只读接口（请求头 `X-Game-Token`）。只能看本游戏的明细，`allGames` 返回 `SCOPE_DENIED` |
| 领取、兑入、兑回、支付 | 打开论坛弹窗，用户在论坛页面上确认。必须在点击事件里同步调用，弹窗被拦截或关闭时返回 `USER_CANCELLED` |
| 下注确认 | SDK 在页面上画确认框。这只是提醒，实际扣款由服务端规则和支付确认保证 |
| 分享 | `navigator.share`，不支持时复制链接并提示 |
| 生命周期 | `visibilitychange` 对应 pause / resume；`setExitGuard` 使用 `beforeunload` |
| 胶囊、加载页、方向 | SDK 画退出按钮和加载层；手机上方向不对时显示「请把手机横过来」 |
| 版本 | 打开的是旧 build 时，SDK 自动跳到当前版本 |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.