@plupin/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,65 @@
1
+ # Plupin game SDK — docs
2
+
3
+ Everything a creator needs to put an existing game into a Plupin room. No engine assumptions: the
4
+ same three calls work for a Three.js world, a canvas 2D game, Phaser, or plain DOM.
5
+
6
+ | Doc | Read it when |
7
+ |---|---|
8
+ | [recipes.md](recipes.md) | you want per-task recipes (≤ 40 lines) for multiplayer, the payment boundary, leaderboard, deploy |
9
+ | [prompt.md](prompt.md) | you want the owner template prompt and Definition of Done for building a game |
10
+ | [quickstart.md](quickstart.md) | you want your game multiplayer today |
11
+ | [api.md](api.md) | you need the exact surface: every option, method, event |
12
+ | [netcode.md](netcode.md) | you must choose between host-relayed world and server-authoritative play |
13
+ | [leaderboards.md](leaderboards.md) | your game should keep a ranking, and you want the top list plus each player's own place |
14
+ | [integration.md](integration.md) | you have a game on your laptop and want it online |
15
+ | [cli.md](cli.md) | you want `plupin dev` / `plupin deploy` (**planned**) |
16
+ | [checks.md](checks.md) | `plupin up` refused your build, or you want to know what it measures: MB, page load, time-to-first-input |
17
+ | [mcp.md](mcp.md) | an agent should drive the loop (**planned**) |
18
+
19
+ ## The 40-line adapter
20
+
21
+ `packages/game-sdk/examples/net.ts` is the whole client integration in one file: room, peers, join,
22
+ publish, sample, leave — with the authority choice and the clock rule written down where you need
23
+ them. Its test (`packages/game-sdk/tests/net.test.ts`) boots a real `plupin dev` server for a game that
24
+ has nothing but a bundle and a `plupin.json`, connects two clients, and asserts that the observer's
25
+ scene hooks receive an interpolated pose and a despawn.
26
+
27
+ One trap that file documents: `frame.ts` is the **room's** clock. Comparing it with your browser's
28
+ `performance.now()` makes remote peers never time out. Push with arrival time, or map the room clock
29
+ onto yours once you maintain a measured offset.
30
+
31
+ ## The whole API
32
+
33
+ ```ts
34
+ import { Peers, Room } from "@plupin/game-sdk"
35
+
36
+ const room = new Room({ gameId: "my-game", name: "guest", authority: "host" })
37
+ await room.connect()
38
+
39
+ room.on("relay", ({ frame }) => peers.push(frame.from, performance.now(), frame.data))
40
+ room.broadcast("pose", { x, y, z })
41
+
42
+ const peers = new Peers({
43
+ blend: (a, b, t) => ({ ...a, x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }),
44
+ create: (seat) => scene.add(seat),
45
+ update: (seat, at) => scene.move(seat, at),
46
+ remove: (seat) => scene.remove(seat),
47
+ })
48
+ ```
49
+
50
+ Three concepts, that is the entire SDK: **Room** (the connection), **Peers** (the other players),
51
+ **Interpolator** (smoothing, used by Peers, exposed for custom cases).
52
+
53
+ ## Status
54
+
55
+ | Piece | State |
56
+ |---|---|
57
+ | `Room` client | shipped |
58
+ | `Peers` / `Interpolator` | shipped |
59
+ | Server relay room (`authority: "host"`) | shipped and routed: `plupin.json` `authority: "host"` admits a room with kind `l`, no document needed |
60
+ | Referee (`room.claim`) | in progress |
61
+ | Leaderboards (`plupin.json` `leaderboards[]`, `GET /api/games/:gameId/leaderboards/:boardId`) | implemented, not deployed yet: declared in the manifest, written by the room, read with the caller's own rank. A `host`-authority game has no server result, so its boards stay empty |
62
+ | `plupin dev`, `plupin deploy`, `plupin mcp` | planned — contracts written, not implemented |
63
+
64
+ Docs marked **planned** describe a contract that exists so the implementation can be checked against
65
+ it. They never describe something you can run today.
@@ -0,0 +1,325 @@
1
+ # API
2
+
3
+ The complete public surface. If something is not on this page it is not stable.
4
+
5
+ ## `new Room(options)`
6
+
7
+ | option | type | default | meaning |
8
+ |---|---|---|---|
9
+ | `gameId` | `string` | — | the game id from `plupin.json` |
10
+ | `name` | `string` | — | display name for the seat |
11
+ | `authority` | `"server" \| "host"` | `"server"` | who produces world state; `"host"` enables `broadcast()` |
12
+ | `url` | `string` | same origin | API origin. Omit when served from `<game>.plupin.com` |
13
+ | `storage` | `CapabilityStore` | `sessionStorage` | where the seat capability is remembered |
14
+ | `fetch` | `FetchLike` | global `fetch` | injection point for tests |
15
+ | `WebSocket` | `SocketCtor` | global `WebSocket` | injection point for tests |
16
+ | `maxQueue` | `number` | `32` | intents buffered while one is in flight |
17
+ | `maxReconnects` | `number` | `6` | reconnect attempts before the room gives up |
18
+
19
+ ### Methods
20
+
21
+ | call | returns | notes |
22
+ |---|---|---|
23
+ | `await connect()` | `Promise<void>` | admits, opens the socket, resolves on the first snapshot |
24
+ | `send(intent)` | `boolean` | queued; `false` when not connected, finished, or the queue is full |
25
+ | `broadcast(kind, data)` | `boolean` | throws unless `authority: "host"` |
26
+ | `claim(claim)` | `boolean` | tier P: `{ kind: "reach", target }` or `{ kind: "ray", target, dir, from? }`; the room answers with `damage` / `down` / `error` |
27
+ | `on(kind, handler)` | `() => void` | unsubscribe function |
28
+ | `close()` | `void` | stops reconnecting and closes the socket |
29
+
30
+ ### Getters
31
+
32
+ | getter | type | meaning |
33
+ |---|---|---|
34
+ | `state` | `RoomStatus` | `idle \| connecting \| joined \| reconnecting \| finished \| closed` |
35
+ | `view` | `TView \| null` | last authoritative state |
36
+ | `token` | `string \| null` | state token; intents carry it |
37
+ | `finished` | `boolean` | the room ended |
38
+ | `seatId` | `string \| null` | your seat |
39
+ | `leader` | `string | null` | seat the room elected to produce world state |
40
+ | `isLeader` | `boolean` | `leader === seatId` (Perhatian: `connect()` resolve sebelum pemilihan host; jangan baca `isLeader` tepat setelah `await connect()`, dengarkan event `host`) |
41
+
42
+ ### Events
43
+
44
+ | event | payload |
45
+ |---|---|
46
+ | `snapshot` | `{ snapshot: { token, seq, view, you, characters, deadline, finished } }` |
47
+ | `relay` | `{ frame: { from, kind, data, ts } }` |
48
+ | `host` | `{ seat }` |
49
+ | `seat` | `{ seatId }` |
50
+ | `status` | `{ status }` |
51
+ | `damage` | `{ target, amount, by, hp, at }` — the room's answer to your claim |
52
+ | `down` | `{ seat }` — once per seat, when its hp reaches zero |
53
+ | `error` | `{ code }` — `invalid_capability`, `room_unavailable`, `room_mismatch`, `reconnect_exhausted`, `frame_too_large`, or a refused claim: `stale_claim`, `rate_limited`, `cooldown`, `out_of_range`, `missed`, `blocked`, `invalid_origin`, `unknown_target`, `target_down`, `down`, `invalid_claim`, `no_pose` |
54
+
55
+ ## `new Peers(options)`
56
+
57
+ | option | type | default | meaning |
58
+ |---|---|---|---|
59
+ | `blend` | `(a, b, t) => T` | — | your interpolation |
60
+ | `create` | `(seat) => void` | — | spawn a remote entity |
61
+ | `update` | `(seat, value, latest) => void` | — | per rendered frame |
62
+ | `remove` | `(seat) => void` | — | leave or timeout |
63
+ | `delayMs` | `number` | `120` | render behind the newest frame |
64
+ | `timeoutMs` | `number` | `3000` | silence before a peer is dropped |
65
+ | `maxPeers` | `number` | `64` | hard cap |
66
+
67
+ Methods: `push(seat, at, value)`, `sample(now)`, `latest(seat)`, `seats()`, `drop(seat)`, `clear()`.
68
+
69
+ ## `new Interpolator(blend, delayMs?, limit?)`
70
+
71
+ Methods: `push(at, value)`, `sample(now)`, `latest()`, `clear()`. Used by `Peers`; use it directly
72
+ only when you need your own buffer policy (for example, a camera target that must not lag).
73
+
74
+ ## `new Leaderboard(options)`
75
+
76
+ ## In-app purchases
77
+
78
+ A game asks; the player confirms on the platform's own page; the platform moves the Sigma. A static game with no server just reads what the player holds; a game with a server can take a signed receipt instead. A game never holds spending authority ([ADR-0018](../architecture/adr/0018-game-address-and-identity.md)).
79
+ The creator keeps 95% and the platform 5% (`GAME_CREATOR_SHARE_BPS`). The paid-Sigma part of that share becomes Creator Earnings, cashable at Rp80 per Sigma after a 30-day hold ([payouts](../product/payouts.md)). A creator cannot buy from their own game (`SELF_PURCHASE`).
80
+
81
+ ### 1. Declare what you sell
82
+
83
+ In `plupin.json`. A deploy writes this to the platform, and it is the only source of a price.
84
+
85
+ ```json
86
+ {
87
+ "products": [
88
+ { "sku": "gems-100", "title": "100 gems", "price": 50, "kind": "consumable" },
89
+ { "sku": "gold-skin", "title": "Gold skin", "price": 200, "kind": "permanent" }
90
+ ]
91
+ }
92
+ ```
93
+
94
+ | field | type | meaning |
95
+ |---|---|---|
96
+ | `sku` | `string` | 1–64 letters, digits, `.`, `_`, `-` |
97
+ | `title` | `string` | 1–60 chars, shown on the confirmation page |
98
+ | `price` | `number` | Sigma, 2–100000. Fixed here: no call can name a price |
99
+ | `kind` | `"consumable" \| "permanent"` | default `consumable`. Permanent is owned once. Fixed once the SKU exists |
100
+
101
+ That is all a static game needs. Add `receiptUrl` only if you run a server (step 4).
102
+
103
+ ### 2. Ask, from a click
104
+
105
+ ```ts
106
+ import { requestPurchase } from "@plupin/game-sdk"
107
+
108
+ button.onclick = async () => {
109
+ const result = await requestPurchase("gems-100", { tag: myPlayerId })
110
+ if (result.status === "completed") refreshItems() // a hint: read what the player really holds
111
+ }
112
+ ```
113
+
114
+ | option | meaning |
115
+ |---|---|
116
+ | `tag` | receipt servers only: how your server names this player, echoed in the receipt. Optional, up to 128 of `A-Za-z0-9:._-`. The player's browser carries it, so it can only choose who gets what that player paid for |
117
+ | `gameId` | defaults to the first label of the current host |
118
+
119
+ Returns `{ status: "completed", purchaseId, sku }`, `{ status: "canceled" }` or `{ status: "failed", code }`, with `code` such as `popup_blocked`. Call it from a user gesture, or the browser blocks the window. **Grant nothing on this result**: a page's own scripts can fake it.
120
+
121
+ ### 3. Read and use what the player holds
122
+
123
+ With no `receiptUrl`, the platform holds the items, and a sale delivers them in the same transaction. Permanent items and consumable counts live in Plupin's database, for this player and this game.
124
+
125
+ ```ts
126
+ import { connectPlayer, consume, getEntitlements } from "@plupin/game-sdk"
127
+
128
+ const held = await getEntitlements()
129
+ if (held.status === "signin_required") showConnectButton() // onclick: await connectPlayer()
130
+ if (held.status === "ok") render(held.items) // [{ sku, kind, quantity }]
131
+
132
+ const used = await consume("gems-100", { key: useId }) // { status: "ok", remaining, replayed }
133
+ ```
134
+
135
+ | call | notes |
136
+ |---|---|
137
+ | `getEntitlements()` | `{ status: "ok", items }`, `{ status: "signin_required" }` or `{ status: "failed", code }` |
138
+ | `consume(sku, { key })` | takes one. The same `key` never takes twice, so send it again when you retry. `failed` with `NOTHING_TO_CONSUME` or `NOT_CONSUMABLE` |
139
+ | `connectPlayer()` | one click on the platform's page, from a user gesture. A purchase already connects the player |
140
+
141
+ The page holds a token for one player in one game, kept in `localStorage` for up to 7 days. It can read and consume those items and nothing else: no Sigma, no other game.
142
+
143
+ **Tradeoff:** platform-held ownership cannot be forged, but your rules run in the browser, so a modified client can apply an effect without calling `consume`.
144
+ A receipt server is the stronger option for a competitive game, because your own server decides what each item does.
145
+
146
+ ### 4. Or grant on a receipt
147
+
148
+ Declare your server, and issue the key it uses. The key is shown once and replaces any earlier one. A `receiptUrl` with no key is not on sale, since nothing could verify a receipt.
149
+
150
+ ```json
151
+ { "receiptUrl": "https://api.example.com/plupin/receipts" }
152
+ ```
153
+
154
+ ```bash
155
+ plupin purchases key
156
+ ```
157
+
158
+ The game's own server is now the source of truth, so `getEntitlements` and `consume` have nothing for these sales. The platform posts each sale to `receiptUrl`, signed with your key, and sends it again until you acknowledge it: right after the sale, then at growing intervals up to six hours apart. Like Roblox's `ProcessReceipt`, it can arrive more than once, so grant once per `id`.
159
+
160
+ ```ts
161
+ import { receiptAck, verifyReceipt } from "@plupin/game-sdk"
162
+
163
+ export async function POST(request: Request) {
164
+ const receipt = await verifyReceipt({
165
+ body: await request.text(), // the raw body, before any parsing
166
+ signature: request.headers.get("plupin-signature"),
167
+ serverKey: process.env.PLUPIN_SERVER_KEY,
168
+ })
169
+ if (!receipt) return new Response("bad signature", { status: 401 })
170
+ await grantOnce(receipt.id, receipt.tag, receipt.sku) // idempotent on receipt.id
171
+ return Response.json(receiptAck(receipt))
172
+ }
173
+ ```
174
+
175
+ `verifyReceipt` returns the receipt, or `null` for a bad signature or one over five minutes old (`toleranceMs`). Only status 200 with `receiptAck(receipt)` as the body acknowledges; anything else means "try again later", and redirects are not followed.
176
+
177
+ | receipt field | meaning |
178
+ |---|---|
179
+ | `id` | the purchase id: your idempotency key |
180
+ | `gameId`, `sku`, `kind`, `price` | what was sold |
181
+ | `playerId` | this player in this game: stable, and useless on any other game. Never an account id |
182
+ | `tag` | what you passed to `requestPurchase`, or `null` |
183
+ | `createdAt` | ISO time of the sale |
184
+
185
+ **A purchase nobody acknowledges within 72 hours refunds itself**, and so does one whose game is removed. The player gets the full price, and the creator's share, which is held and unspendable until the acknowledgement, is reversed. An acknowledged purchase is final.
186
+
187
+ ### Game-server routes
188
+
189
+ For your server only, with `Authorization: Bearer <server key>`. Each one sees this game's purchases and nothing else, and none can take Sigma from a player.
190
+
191
+ | route | answer |
192
+ |---|---|
193
+ | `GET /api/games/<game>/purchases/<id>` | `{ purchase }`, the authoritative record, including `status`: `paid`, `delivered` or `refunded` |
194
+ | `POST /api/games/<game>/purchases/<id>/ack` | acknowledge outside a receipt. Safe to repeat. `409 PURCHASE_REFUNDED` if it was refunded |
195
+ | `POST /api/games/<game>/purchases/<id>/refund` | you cannot grant it: refund now. Safe to repeat. `409 PURCHASE_DELIVERED` once acknowledged |
196
+ | `GET /api/games/<game>/entitlements?player=<playerId>&cursor=&limit=` | what this player holds, newest first, for restoring permanent items. `{ items, cursor }` |
197
+
198
+ ### Test mode
199
+
200
+ `plupin dev` runs the same flow with no money and no database: `requestPurchase` opens a test confirmation page on the dev origin, and the wallet is the test wallet. With no `receiptUrl`, `getEntitlements` and `consume` work as in production. To test a receipt server:
201
+
202
+ ```bash
203
+ plupin dev --receipt-url http://127.0.0.1:9000/receipts
204
+ ```
205
+
206
+ Receipts go to that URL, signed with the fixed key `plupin_gsk_dev`, retried every 5 seconds; `verifyReceipt` and the game-server routes work unchanged with that key. `POST /_dev/purchases/expire` stands in for the window running out and refunds whatever is unacknowledged. On the dev origin a game's scripts share the page's test wallet, so test mode proves your flow, not the origin boundary.
207
+
208
+ ## `plupin.json`
209
+
210
+ The ranking your `plupin.json` declares, read from the game. Read-only on purpose: a score is produced
211
+ by the room that finished the match, so there is no method here that accepts a number from the client
212
+ ([leaderboards.md](./leaderboards.md)).
213
+
214
+ ```ts
215
+ import { Leaderboard } from "@plupin/game-sdk"
216
+
217
+ const board = new Leaderboard({ gameId: "dino", board: "score" })
218
+ const page = await board.top(10)
219
+ for (const entry of page.entries) hud.rank(entry.rank, entry.name, entry.score)
220
+ if (page.me) hud.you(page.me.rank)
221
+ ```
222
+
223
+ | option | type | default | meaning |
224
+ |---|---|---|---|
225
+ | `gameId` | `string` | — | the id from `plupin.json` |
226
+ | `board` | `string` | — | a board id declared in `plupin.json`'s `leaderboards` |
227
+ | `url` | `string` | same origin | API origin; omit on `<game>.plupin.com`. `plupin dev` does not serve this route: its test board is `/_dev/leaderboard/<id>` |
228
+ | `fetch` | `FetchLike` | global `fetch` | injection point for tests |
229
+
230
+ `top(n = 10, { window?, around? })` returns `{ gameId, revision, board, window, total, entries, me,
231
+ around }`. `entries` is the top `n` (1–100); `me` is your own row even when it is outside that slice;
232
+ `around: 3` adds three neighbours above and below. `window` is a key the board's own calendar
233
+ produces (`2026-10-31` for `daily`, `2026-W44` for `weekly`); omit it for the current window.
234
+
235
+ ## `new PlatformClient(options)`
236
+
237
+ The one place the SDK calls `fetch`. `Leaderboard` is built on it; reach for it directly only to read
238
+ a platform `/api/*` route the SDK has no class for yet, so the path, the status mapping and the error
239
+ shape are not yours to invent.
240
+
241
+ ```ts
242
+ import { PlatformClient } from "@plupin/game-sdk"
243
+
244
+ const platform = new PlatformClient({ gameId: "dino" })
245
+ const board = await platform.get<{ total: number }>("/api/games/dino/leaderboards/score", { limit: 10 })
246
+ ```
247
+
248
+ | option | type | default | meaning |
249
+ |---|---|---|---|
250
+ | `gameId` | `string` | — | the id from `plupin.json`, read back as `platform.gameId` |
251
+ | `url` | `string` | same origin | API origin, read back as `platform.origin`; required where there is no `location` |
252
+ | `fetch` | `FetchLike` | global `fetch` | injection point for tests |
253
+
254
+ `get<T>(path, query?)` is the only method. `path` must start with `/api/`, `query` values that are
255
+ `undefined` are left out, and it answers the parsed JSON typed as `T` without validating it, so check
256
+ the shape as `Leaderboard` does. Credentials are omitted: a game page holds no session cookie. Every
257
+ failure rejects with an `AppError`.
258
+
259
+ ## Errors
260
+
261
+ Every failure of `Leaderboard` and `PlatformClient` is one object, `AppError` from this package:
262
+
263
+ ```ts
264
+ import { AppError } from "@plupin/game-sdk"
265
+
266
+ try {
267
+ await board.top(10)
268
+ } catch (error) {
269
+ if (error instanceof AppError) {
270
+ hud.say(error.message) // what happened
271
+ if (error.retryable) setTimeout(retry, (error.retryAfterSeconds ?? 5) * 1000)
272
+ console.warn(error.code, error.fix) // what to change
273
+ }
274
+ }
275
+ ```
276
+
277
+ `code` is typed and exhaustive (`ErrorCode`, with every value in `ERROR_CODES`), `fix` is one sentence
278
+ about what to change, `retryable` is true only for `TOO_MANY_REQUESTS`, `SERVER_UNAVAILABLE` and
279
+ `NETWORK_UNREACHABLE`, `retryAfterSeconds` is the wait the platform named when it named one, and
280
+ `JSON.stringify(error)` carries no stack trace. The full table: [errors.md](./errors.md).
281
+
282
+ ## `plupin.json`
283
+
284
+ Validated by `@plupin/game-manifest`; run `parseManifest(json)` to get the same errors the platform
285
+ would, with defaults filled in.
286
+
287
+ | field | type | default | meaning |
288
+ |---|---|---|---|
289
+ | `id` | `string` | — | hostname label: lowercase letters, digits, dashes, 3–63 chars |
290
+ | `name` | `string` | — | display name, 1–60 chars |
291
+ | `entry` | `string` | `"index.html"` | file served for `/` and extension-less paths; must stay inside the bundle |
292
+ | `authority` | `"server" \| "host"` | `"server"` | who produces world state; `host` routes the room to RelayRoom |
293
+ | `maxPlayers` | `number` | `8` | 1–64 |
294
+ | `referee` | `object` | none | optional PvP validation; see below |
295
+ | `products` | `array` | `[]` | what the game sells; see [In-app purchases](#in-app-purchases) |
296
+ | `receiptUrl` | `string` | none | optional: your server, for signed receipts; see [In-app purchases](#in-app-purchases) |
297
+
298
+ `referee` fields: `defaultHp` (100), `weapons` (map of `{ damage, range, cooldownMs }`), `body`
299
+ (`{ radius: 0.4, height: 1.8 }`), and an optional `losGrid` (`{ cell, width, height, bits }`, base64
300
+ bitmap, row-major, 1 = wall) for line-of-sight checks. `cell` is metres per bitmap cell, so the map
301
+ covers `width × height` cells starting at the world origin, and it is capped at 262144 cells (a
302
+ 512×512 map is 1 km at 2 m cells) because the room keeps the bitmap in its own record. A weapon is
303
+ named by `claim.weapon` and falls back to the claim kind (`reach`, `ray`); a manifest with no
304
+ referee block still referees range and rate with the defaults above, and one the room cannot read is
305
+ refused at room start with `invalid_referee`.
306
+
307
+ ## Wire protocol
308
+
309
+ Both client and server speak JSON over one WebSocket. You never write these by hand — `Room` does —
310
+ but they are the contract if you write a client in another language.
311
+
312
+ Client → server: `join { name, capability? }`, `intent { token, seq, intent }`,
313
+ `relay { kind, data }` (host authority only), `claim { claim }` (host authority only: the room
314
+ answers it instead of forwarding it).
315
+
316
+ Server → client: `seat { seatId, capability }`, `snapshot { token, seq, view, you, characters,
317
+ deadline, finished }`, `relay { from, kind, data, ts }`, `host { seat }`,
318
+ `damage { target, amount, by, hp, at }`, `down { seat }`, `error { code }`.
319
+
320
+ Two rules the client must follow, both already implemented:
321
+
322
+ 1. one intent in flight — the next goes out only after a snapshot with `seq >= inFlight.seq`;
323
+ 2. replay an uncommitted intent only when the state token is unchanged.
324
+
325
+ Full protocol, cost model and authority tiers: [../architecture/game-sdk.md](../architecture/game-sdk.md).
@@ -0,0 +1,48 @@
1
+ # Characters
2
+
3
+ > Authoritative for: the character API a game uses.
4
+
5
+ `@plupin/character` gives a game one character in 2D or 3D. Every rig answers to the same six names (`head`, `torso`, `armL`, `armR`, `legL`, `legR`), so a pose or clip written once drives every body.
6
+
7
+ | Rig | Body |
8
+ | --- | --- |
9
+ | `plup` | Plup: a round body on stubby limbs |
10
+ | `r6` | Roblox R6 proportions, six parts |
11
+ | `r15` | Roblox R15 proportions, fifteen parts with elbows and knees |
12
+
13
+ ## 3D, with three.js
14
+
15
+ ```ts
16
+ import { createCharacter } from "@plupin/character/three"
17
+
18
+ const player = createCharacter("r15", { bodyColor: "#3d7bff", shirt, pants })
19
+ scene.add(player.object)
20
+
21
+ player.play("run") // idle, walk, run, jump, wave, dance
22
+ player.pose({ armR: { x: -1.2 } }) // hold a joint on top of the clip
23
+ player.bone("armR")?.add(sword) // attach anything to a joint
24
+
25
+ // every frame
26
+ player.update(deltaSeconds)
27
+ ```
28
+
29
+ ## 2D, with canvas
30
+
31
+ ```ts
32
+ import { drawCharacter2D } from "@plupin/character/canvas"
33
+
34
+ drawCharacter2D(context, {
35
+ rig: "r6",
36
+ look: { bodyColor: "#3d7bff", shirt, pants },
37
+ x: 200,
38
+ y: 300,
39
+ scale: 24,
40
+ view: "side",
41
+ clip: "walk",
42
+ seconds: time,
43
+ })
44
+ ```
45
+
46
+ ## Roblox clothing
47
+
48
+ `shirt` and `pants` take a Roblox classic template, a 585×559 PNG, unchanged. `validateClassicTemplate(width, height)` rejects any other size. T-shirts (512×512) and 3D layered clothing are not supported yet.
@@ -0,0 +1,102 @@
1
+ # What `plupin up` checks
2
+
3
+ `plupin up` measures a build the way a phone plays it before publishing, and refuses when the build
4
+ crosses the ceiling the creator wrote in `plupin.json` → `budget`. There is no separate command: a check
5
+ an agent has to remember to run is a check that does not run. `--skip-checks` publishes unmeasured, and
6
+ `--dry-run` measures without publishing.
7
+
8
+ ```
9
+ $ plupin up ./dist --dry-run
10
+ checks my-game (5 responses, 8420 ms)
11
+ device iPhone 13, 390x844 @3x, touch
12
+ network fast3g: 150 ms RTT, 1600/750 kbps
13
+ source local host, no production server, no credentials
14
+ wire 0.193 MB before input (0.193 MB total, 5 responses, heaviest /three.core.min.js 0.103 MB)
15
+ load 1204 ms
16
+ ttfi 2.22 s — input listener at 2.219 s, tap accepted at 3.807 s
17
+ listener 2.219 s, canvas 0.326 s, tap 3.807 s
18
+ errors 0 (console 0, unhandled 0, webgl lost 0)
19
+ budget mb 6, ttfi 6 s, errors 0
20
+ pass every budget met
21
+ ```
22
+
23
+ ## What it runs
24
+
25
+ | | |
26
+ |---|---|
27
+ | game | the folder you point at, served by the same local host `plupin dev` uses (`127.0.0.1`, random port) |
28
+ | device | Chromium headless, viewport `390x844`, DPR 3, touch, iPhone Safari UA |
29
+ | network | fast 3G through CDP: 150 ms RTT, 1600 kbps down, 750 kbps up |
30
+ | needs | nothing remote for this step: no API, no token, no production server. Playwright's Chromium must be installed (`bunx playwright install chromium`) |
31
+
32
+ ## The numbers
33
+
34
+ **wire** — bytes the page actually transferred, read from Chromium's own network stack
35
+ (`encodedDataLength`), not from file sizes on disk. Two things make it honest:
36
+
37
+ - the local host gzips text responses the way Cloudflare does in production, so a 365 KB script is
38
+ counted as the 87 KB a phone downloads;
39
+ - bytes are counted as they arrive, so a texture still downloading when the run ends is charged for
40
+ what it already cost, and `incomplete` says how many responses were cut off.
41
+
42
+ `initialMb` is the part that landed before the game accepted input (or before the `load` event,
43
+ whichever came later): what a player waits through. `mb` is everything the run transferred and is
44
+ what the budget is measured against. The five heaviest assets are listed with their own sizes.
45
+
46
+ **ttfi** — seconds until the page can accept the first input, read off the page's own clock:
47
+
48
+ 1. the first `pointerdown` / `touchstart` / `mousedown` / `keydown` listener the game registers
49
+ (Playwright's own hit-target interceptors and the probe itself are excluded by stack), and
50
+ 2. a real touch tap sent through the touch screen, which must reach the page after that listener.
51
+
52
+ A page that never registers a listener fails with `ttfi: no input`, because a canvas that draws
53
+ nothing you can press is not a game. One that listens but never receives the tap fails with `ttfi: no
54
+ tap accepted`.
55
+
56
+ **load** — the page reaches its `load` event inside 45 s on that throttled link.
57
+
58
+ **errors** — console errors, uncaught exceptions, unhandled rejections, and WebGL context losses
59
+ (the last one is invisible in the console: the canvas keeps its size and stops drawing, so it is
60
+ counted where the context is handed out).
61
+
62
+ ## The budget
63
+
64
+ `plupin.json`:
65
+
66
+ ```json
67
+ { "id": "my-game", "name": "My Game", "budget": { "mb": 4, "ttfi": 5 } }
68
+ ```
69
+
70
+ | key | default | what it means |
71
+ |---|---|---|
72
+ | `mb` | `6` | megabytes transferred during the run |
73
+ | `ttfi` | `6` | seconds until the first input is accepted |
74
+ | `errors` | `0` | tolerated console errors + unhandled rejections + lost WebGL contexts |
75
+
76
+ A partial block fills the rest from the defaults. No block means the defaults, which are written
77
+ for a phone on fast 3G at `390x844`, not for a laptop on loopback. Every key is validated by
78
+ `@plupin/game-manifest`, so a typo is a manifest error instead of a budget that silently does not
79
+ apply.
80
+
81
+ ## Exit codes and artifacts
82
+
83
+ - `5` — a check failed and nothing was published. The summary names every metric
84
+ (`FAIL mb: 7.42 MB > 6 MB`).
85
+ - `1` — the folder is not a valid build, or Playwright's browser is missing. Install it with
86
+ `bunx playwright install chromium`.
87
+
88
+ Two files land in `.plupin/` beside the build (`./.plus1/` for `./dist`), never inside it, because
89
+ everything inside the folder is the bundle: `checks.json` holds the measured result and `checks.png` is
90
+ a screenshot of the phone viewport at the end of the run.
91
+
92
+ ## What it does not prove
93
+
94
+ - **A document that is not the build is never measured.** Before the first metric, the checks hash what
95
+ the local host answers and compare it with `<dir>/<entry>`; a mismatch is exit 1. A catch-all `200`,
96
+ an SPA shell or a stale revision would otherwise be reported as a game.
97
+ - **Software rendering.** Headless Chromium rasterises with SwiftShader, so `ttfi` includes a
98
+ software-rendering cost a real phone GPU does not pay. Treat it as an upper bound; the network
99
+ half is faithful because it goes through CDP throttling.
100
+ - **Gameplay.** No match is played. A build that loads and takes a tap can still be broken after that.
101
+ - **Real devices.** This is a phone-shaped Chromium on a Mac, not a mid-range Android on a train.
102
+ It catches the 8 MB build and the six-second load, not a 200 ms jank.