@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,55 @@
1
+ # Playbook Agent Game SDK — Prompt Template & Definisi Selesai
2
+
3
+ Dokumen ini adalah panduan operasional satu pintu bagi owner dan coding agent untuk membangun game interaktif di platform Plupin dari nol hingga live.
4
+
5
+ ---
6
+
7
+ ## 1. Kalimat Template Owner
8
+
9
+ Owner cukup menyalin dan menempelkan satu kalimat ini ke agent (ganti `[NAMA_GAME]` dan deskripsi konsep game):
10
+
11
+ ```text
12
+ Gw mau buat game [NAMA_GAME], gunakan SDK Plupin untuk multiplayer, leaderboard, dan deploy.
13
+ ```
14
+
15
+ Contoh spesifik:
16
+ ```text
17
+ Gw mau buat game arena pertarungan tank 2D top-down bernama 'tank-brawl', gunakan SDK Plupin untuk multiplayer, leaderboard, dan deploy.
18
+ ```
19
+
20
+ ---
21
+
22
+ ## 2. Daftar Wajib Baca Sebelum Menulis Kode
23
+
24
+ Sebelum agent menyentuh kode atau menghasilkan berkas proyek apa pun, agent **wajib** membaca dokumen referensi berikut secara berurutan:
25
+
26
+ 1. **`docs/game-sdk/recipes.md`** — Resep siap pakai per-task (Mulai, Multiplayer, batas Payment, Leaderboard, Deploy, Error Handling). Setiap resep mandiri dan ≤ 40 baris kode.
27
+ 2. **`docs/game-sdk/api.md`** — Spesifikasi lengkap permukaan SDK (`Room`, `Peers`, `Interpolator`, `Leaderboard`, options, method, events).
28
+ 3. **`docs/game-sdk/errors.md`** — Kontrak kode error terketik (`code`) dan aksi perbaikan spesifik.
29
+ 4. **`docs/game-sdk/cli.md`** — Perilaku CLI pengembang (`plupin dev`, `plupin up`, `plupin status`).
30
+ 5. **`AGENTS.md` & `docs/PRD.md`** — Prinsip platform: netral engine (Three.js, Phaser, Canvas 2D, atau DOM adalah pilihan setara), nol runtime dependency di client SDK, dan arsitektur server-refereed.
31
+
32
+ ---
33
+
34
+ ## 3. Definisi Selesai (Definition of Done)
35
+
36
+ Suatu tugas pembuatan game oleh agent dinyatakan **SELESAI** jika dan hanya jika ketiga kriteria berikut terpenuhi dan dibuktikan dengan log eksekusi nyata:
37
+
38
+ 1. **2 Peer Satu Room:**
39
+ - Dua client/tab peramban berhasil bergabung ke dalam satu room yang sama (`state === "joined"`).
40
+ - Kedua seat dapat saling bertukar intent atau relay pose terinterpolasi melalui `Peers`.
41
+ - Event spawn dan despawn berjalan bersih tanpa kebocoran state.
42
+
43
+ 2. **Tidak Membelanjakan Sigma:**
44
+ - Kode game tidak memanggil debit apa pun; SDK tidak mengekspor `wallet` dan ADR-0018 melarang game membelanjakan Sigma pemain.
45
+ - Jika game menjual sesuatu, alurnya dicoba di mode uji `plupin dev`: `POST /_dev/wallet/spend` dua kali dengan `idempotencyKey` yang sama menghasilkan satu debit di `/_dev/ledger`.
46
+ - Pembuktian rute uji ini tidak dianggap sebagai pembayaran produksi.
47
+
48
+ 3. **Host Melayani Game:**
49
+ - Perintah publikasi berhasil dijalankan, tanpa `--skip-checks`:
50
+ ```bash
51
+ plupin up ./dist
52
+ ```
53
+ - Perintah ini mengukur build lebih dulu dan menolak yang melewati `budget` di `plupin.json` (bawaan 6 MB, 6 detik sampai tap pertama diterima, 0 error, halaman termuat), jadi tidak ada langkah pengecekan terpisah.
54
+ - Alamat game dicetak oleh perintah tersebut.
55
+ - Probe host mengembalikan status **HTTP 200** dengan berkas entry yang baru diunggah, yang memverifikasi bahwa bundle live dan dapat dimainkan publik.
@@ -0,0 +1,119 @@
1
+ # Quickstart
2
+
3
+ From a game that runs on one machine to a game two people can play. Three steps, one file.
4
+
5
+ ## 1. Describe the game
6
+
7
+ `plupin.json` at the root of your build folder:
8
+
9
+ ```json
10
+ {
11
+ "id": "dude-theft",
12
+ "name": "Dude Theft",
13
+ "engine": "2d",
14
+ "entry": "index.html",
15
+ "authority": "host",
16
+ "maxPlayers": 8
17
+ }
18
+ ```
19
+
20
+ `engine` is the badge the catalogue shows (`2d` or `3d`). It defaults to `3d`, so a 2D game has to
21
+ say so; `plupin create` and `plupin up` record it instead of guessing from a flag.
22
+
23
+ `authority` is the only choice you must make:
24
+
25
+ - `"host"` — your game keeps its own physics; one player's client simulates the world and Plupin
26
+ forwards it. Use this if the game already has gravity, vehicles, ragdolls.
27
+ - `"server"` — Plupin runs the rules and sends you the state. Use this for turn-based or ranked play
28
+ where nobody may cheat.
29
+
30
+ Unsure? Start with `"host"`. You can move a single game to `"server"` later without changing the
31
+ client code.
32
+
33
+ ## 2. Connect
34
+
35
+ ```ts
36
+ import { Room } from "@plupin/game-sdk"
37
+
38
+ const room = new Room({ gameId: "dude-theft", name: "guest", authority: "host" })
39
+ await room.connect() // resolves on the first state from the room
40
+ ```
41
+
42
+ The id is compiled into your bundle, not read from `plupin.json` at runtime. If you copy a project
43
+ folder and change `id`, rebuild before deploying: the SDK compares the address it is served from
44
+ (`<id>.plupin.com`) with the `gameId` it was built for, and refuses with one sentence naming both
45
+ instead of a bare `admission failed: 404`.
46
+
47
+ Then publish your own state a few times per second — 10 to 15 Hz is plenty:
48
+
49
+ ```ts
50
+ setInterval(() => {
51
+ room.broadcast("pose", {
52
+ p: [player.pos.x, player.y, player.pos.z],
53
+ ry: character.group.rotation.y,
54
+ })
55
+ }, 66)
56
+ ```
57
+
58
+ ## 3. Draw the others
59
+
60
+ ```ts
61
+ import { Peers } from "@plupin/game-sdk"
62
+
63
+ const peers = new Peers<{ p: [number, number, number]; ry: number }>({
64
+ blend: (a, b, t) => ({
65
+ p: [
66
+ a.p[0] + (b.p[0] - a.p[0]) * t,
67
+ a.p[1] + (b.p[1] - a.p[1]) * t,
68
+ a.p[2] + (b.p[2] - a.p[2]) * t,
69
+ ],
70
+ ry: a.ry + ((((b.ry - a.ry) % (Math.PI * 2)) + Math.PI * 3) % (Math.PI * 2) - Math.PI) * t,
71
+ }),
72
+ create: (seat) => world.spawnRemote(seat),
73
+ update: (seat, at) => world.moveRemote(seat, at),
74
+ remove: (seat) => world.despawnRemote(seat),
75
+ })
76
+
77
+ room.on("relay", ({ frame }) => {
78
+ if (frame.kind === "pose") peers.push(frame.from, performance.now(), frame.data)
79
+ })
80
+
81
+ const frame = () => { peers.sample(performance.now()); requestAnimationFrame(frame) }
82
+ frame()
83
+ ```
84
+
85
+ **2D is the same code.** Swap the tuple for `{ x, y }`, blend two numbers, and point `create` /
86
+ `update` / `remove` at your sprites.
87
+
88
+ ## Local play
89
+
90
+ ```bash
91
+ bunx plupin dev ./dist --port 8787
92
+ # game http://127.0.0.1:8787
93
+ # rooms http://127.0.0.1:8787/api/play/dude-theft/rooms
94
+ ```
95
+
96
+ One origin serves the build and hosts the room, exactly like `<game>.plupin.com`. The room is the
97
+ production `RelayRoom` class, so a frame you see locally is a frame the platform accepts. Open the
98
+ game twice and both tabs are in the same room; no `url` override needed because the game and the
99
+ API share an origin.
100
+
101
+ `plupin deploy` is not implemented yet: a build folder cannot be published from the CLI today.
102
+
103
+ ## Live (planned)
104
+
105
+ ```bash
106
+ npx plupin deploy ./dist
107
+ # → https://dude-theft.plupin.com
108
+ ```
109
+
110
+ No build runs on the platform: you upload the folder your own toolchain produced.
111
+
112
+ ## Checklist before you ship
113
+
114
+ - [ ] `plupin.json` exists in the build output, not only in the source tree.
115
+ - [ ] The game runs from a subpath (`/index.html` served by any static server), not only from `/`.
116
+ - [ ] Assets are relative paths — absolute `/fonts/x.woff` breaks on a game subdomain.
117
+ - [ ] No `localStorage` for anything that must follow the player between devices; that is what the
118
+ Plupin profile is for.
119
+ - [ ] Pointer lock, audio and WebGL are started from a user gesture (mobile browsers require it).
@@ -0,0 +1,205 @@
1
+ # Playbook Game SDK — Resep per-Task
2
+
3
+ Resep siap pakai untuk mengintegrasikan game apa pun ke platform Plupin menggunakan `@plupin/game-sdk`.
4
+
5
+ SDK ini memiliki **nol runtime dependency** dan netral engine: kode yang sama bekerja identik untuk Three.js, Phaser, HTML5 2D Canvas, WebGL murni, maupun DOM.
6
+
7
+ Setiap resep di bawah ini berisi kode lengkap (≤ 40 baris), import mandiri, dan satu perintah verifikasi langsung. Resep hanya memakai ekspor SDK yang benar-benar ada: `Room`, `Peers`, `Interpolator`, `Leaderboard`, `PlatformClient`, `AppError`, `ERROR_CODES`; `packages/game-sdk/tests/recipes.test.ts` menjaganya, dan mengompilasi setiap resep dengan TypeScript strict.
8
+
9
+ ---
10
+
11
+ ## Resep 1: Mulai (Game Kosong → SDK Init → Satu Room Hidup)
12
+
13
+ Inisialisasi room multiplayer untuk game baru.
14
+
15
+ ```ts
16
+ import { Room } from "@plupin/game-sdk"
17
+
18
+ const room = new Room({
19
+ gameId: "arena-dash",
20
+ name: "player-alpha",
21
+ authority: "host", // "host" untuk simulasi lokal client relay, "server" untuk platform authoritative
22
+ })
23
+
24
+ try {
25
+ await room.connect()
26
+ console.log(`Room aktif. Seat: ${room.seatId}, status: ${room.state}`)
27
+ } catch (error) {
28
+ console.error("Gagal inisialisasi room:", error)
29
+ }
30
+ ```
31
+
32
+ **Perintah verifikasi:**
33
+ ```bash
34
+ plupin dev ./dist --port 8787
35
+ ```
36
+ Buka `http://127.0.0.1:8787`, amati log konsol mencetak `Room aktif. Seat: ...`.
37
+
38
+ ---
39
+
40
+ ## Resep 2: Multiplayer (Admission, Snapshot/Intent, Peers, Authority, Reconnect)
41
+
42
+ Sinkronisasi multiplayer: admission otomatis via `connect()`, snapshot & intent untuk state, `Peers` untuk interpolasi remote player, seleksi authority leader, dan reconnect saat jaringan putus.
43
+
44
+ > **Penting (host election):** `connect()` resolve sebelum pemilihan host; jangan baca `isLeader` tepat setelah `await`. Tunggu event `room.on("host", ...)` untuk mendeteksi apakah seat ini terpilih memegang authority simulasi.
45
+
46
+ ```ts
47
+ import { Peers, Room } from "@plupin/game-sdk"
48
+
49
+ const peers = new Peers<{ x: number; y: number }>({
50
+ blend: (a, b, t) => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }),
51
+ create: (seat) => console.log(`[Spawn] Remote peer masuk: ${seat}`),
52
+ update: (seat, pos) => console.log(`[Move] Peer ${seat}:`, pos),
53
+ remove: (seat) => console.log(`[Despawn] Peer keluar: ${seat}`),
54
+ delayMs: 120,
55
+ })
56
+
57
+ const room = new Room<{ score: number }, { type: "move"; x: number; y: number }>({
58
+ gameId: "arena-dash",
59
+ name: "player-alpha",
60
+ authority: "host",
61
+ })
62
+
63
+ room.on("status", ({ status }) => console.log("Status room:", status))
64
+ room.on("host", ({ seat }) => {
65
+ // `seat` adalah hasil pemilihan. Bandingkan dengan seat milikmu — jangan baca
66
+ // `isLeader` di luar handler ini, karena `connect()` resolve sebelum pemilihan selesai.
67
+ if (seat === room.seatId) console.log("Seat ini memegang authority simulasi:", seat)
68
+ })
69
+ room.on("relay", ({ frame }) => {
70
+ // `data` milik pengirim, jadi SDK mengetiknya `unknown`: game yang menyatakan bentuknya.
71
+ if (frame.kind === "pose") peers.push(frame.from, performance.now(), frame.data as { x: number; y: number })
72
+ })
73
+ room.on("snapshot", ({ snapshot }) => console.log("Authoritative state update:", snapshot.view))
74
+
75
+ try {
76
+ await room.connect()
77
+ // PENTING: connect() resolve sebelum pemilihan host; jangan baca isLeader di sini.
78
+ room.send({ type: "move", x: 12, y: 34 })
79
+ room.broadcast("pose", { x: 12, y: 34 })
80
+ const frame = () => {
81
+ peers.sample(performance.now())
82
+ requestAnimationFrame(frame)
83
+ }
84
+ requestAnimationFrame(frame)
85
+ } catch (error) {
86
+ console.error("Multiplayer error:", error)
87
+ }
88
+ ```
89
+
90
+ **Perintah verifikasi:**
91
+ ```bash
92
+ plupin dev ./dist --port 8787
93
+ ```
94
+ Buka 2 tab browser; amati log kedua tab mencetak event `[Spawn]` dan frame pertukaran pose.
95
+
96
+ ---
97
+
98
+ ## Resep 3: Payment (Game Tidak Membelanjakan Sigma)
99
+
100
+ SDK **tidak punya** `wallet`, dan memang tidak akan punya `wallet.spend`: ADR-0018 melarang game membelanjakan Sigma pemain. Debit dan pembelian terjadi di platform dengan sesi root pemain, bukan di halaman game. Token game yang di-scope (`docs/architecture/identity.md` §2) baru spesifikasi, jadi SDK belum punya permukaan `auth` atau `wallet`.
101
+
102
+ Yang ada hari ini hanya mode uji lokal: `plupin dev` menjalankan dompet palsu di `/_dev/*` tanpa payment gateway, supaya idempotensi alur belanja bisa dicoba. Rute ini hanya ada di proses `plupin dev`, tidak ada di game yang sudah dideploy, jadi jangan dipanggil dari kode game yang dirilis.
103
+
104
+ **Perintah verifikasi:**
105
+ ```bash
106
+ TOKEN=$(curl -s -X POST http://127.0.0.1:8787/_dev/auth/sign-in -d '{"name":"alpha"}' | jq -r .token)
107
+ curl -s -X POST http://127.0.0.1:8787/_dev/wallet/spend -H "Authorization: Bearer $TOKEN" \
108
+ -d '{"sku":"skin-legendary","amount":25,"idempotencyKey":"buy-1"}'
109
+ curl -s http://127.0.0.1:8787/_dev/ledger -H "Authorization: Bearer $TOKEN"
110
+ ```
111
+ Kirim ulang `idempotencyKey` yang sama: ledger tetap mencatat satu debit.
112
+
113
+ ---
114
+
115
+ ## Resep 4: Leaderboard (Top Ranking & Server-Refereed Score)
116
+
117
+ Membaca top ranking dan posisi pemain sendiri. `Leaderboard` hanya membaca: skor dihasilkan oleh room yang menyelesaikan match, jadi tidak ada `submit()` dan tidak ada rute yang menerima angka dari client. Board harus dideklarasikan di `leaderboards` pada `plupin.json`.
118
+
119
+ ```ts
120
+ import { AppError, Leaderboard } from "@plupin/game-sdk"
121
+
122
+ const board = new Leaderboard({ gameId: "arena-dash", board: "high-score" })
123
+
124
+ try {
125
+ const page = await board.top(10, { around: 3 })
126
+ for (const entry of page.entries) {
127
+ console.log(`#${entry.rank} ${entry.name}: ${entry.score}`)
128
+ }
129
+ if (page.me) console.log(`Posisi pemain: rank #${page.me.rank}`)
130
+ } catch (error) {
131
+ if (error instanceof AppError) console.error(`Gagal memuat ranking [${error.code}]: ${error.fix}`)
132
+ }
133
+ ```
134
+
135
+ **Perintah verifikasi:** `Leaderboard` memanggil route platform, jadi uji pada game yang sudah dideploy dengan alamat yang dicetak `plupin up`:
136
+ ```bash
137
+ curl -s https://<alamat-game>/api/games/arena-dash/leaderboards/high-score
138
+ ```
139
+ Respons berupa JSON berisi `board`, `entries`, dan `me`. Di `plupin dev`, board uji ada di `/_dev/leaderboard/<id>`, bukan di route ini.
140
+
141
+ ---
142
+
143
+ ## Resep 5: Deploy (plupin.json minimal, plupin up)
144
+
145
+ Konfigurasi berkas `plupin.json` minimal di direktori build (`dist/plupin.json`), lalu publikasikan. Tidak ada perintah pengecekan terpisah: `plupin up` mengukur build lebih dulu dan menolak mempublikasikan build yang gagal.
146
+
147
+ **Berkas `plupin.json` minimal:**
148
+ ```json
149
+ {
150
+ "id": "arena-dash",
151
+ "name": "Arena Dash",
152
+ "entry": "index.html",
153
+ "authority": "host",
154
+ "maxPlayers": 8
155
+ }
156
+ ```
157
+
158
+ **Perintah Publish Satu Langkah:**
159
+ ```bash
160
+ plupin up ./dist
161
+ ```
162
+ Perintah ini memvalidasi folder & manifest, mengukur build secara lokal, mendaftarkan game di registry jika baru, mengunggah aset, dan melakukan polling ke alamat game sampai host menyajikan berkas entry yang baru diunggah (timeout 15s). Alamatnya dicetak oleh perintah ini.
163
+
164
+ **Ukur tanpa publikasi:** `plupin up ./dist --dry-run` (tanpa login).
165
+
166
+ > **Peringatan tegas:** Opsi `--skip-checks` mematikan gerbang pengukuran kualitas build (`mb`, `load`, `ttfi`, `errors`). Dilarang keras menggunakan `--skip-checks` pada publikasi produksi atau penyelesaian tugas karena menonaktifkan validasi gerbang platform.
167
+
168
+ ### Arti Tiap Angka
169
+
170
+ Build yang gagal berarti exit 5, metriknya disebut, dan belum ada request ke platform. Batasnya bisa diubah di `plupin.json` → `budget`. Rincian: [checks.md](checks.md).
171
+
172
+ | Metrik | Arti & Pengukuran | Nilai Default Budget | Solusi Jika Gagal |
173
+ |---|---|---|---|
174
+ | **`mb`** | Total ukuran transfer data selama pengujian, diukur via stack jaringan Chromium (Fast 3G: 1.6 Mbps download, 150 ms latency). Menampilkan aset terberat. | `mb ≤ 6` | Kompres tekstur/audio, muat aset besar belakangan. |
175
+ | **`load`** | Halaman mencapai event `load` dalam 45 detik. | wajib | Periksa aset yang menggantung saat halaman dimuat. |
176
+ | **`ttfi`** | *Time to First Input* (detik). Waktu sampai halaman memasang event listener (pointer/touch/key) dan sebuah tap benar-benar sampai. | `ttfi ≤ 6` | Hindari JS yang memblokir sebelum listener terpasang, dan overlay yang menutupi game. |
177
+ | **`errors`** | Console error, uncaught exception, unhandled rejection, dan WebGL context loss. | `errors: 0` | Periksa log konsol, shader, dan pemuatan aset. |
178
+
179
+ ---
180
+
181
+ ## Resep 6: Error → Aksi
182
+
183
+ Kegagalan dari method SDK yang memanggil platform adalah satu `AppError` dengan `code`, `message`, `fix`, `retryable`, dan `retryAfterSeconds` kalau platform menyebut waktu tunggu. Daftar kode dan kalimat perbaikannya ada di satu tempat: [errors.md](errors.md).
184
+
185
+ ```ts
186
+ import { AppError, Leaderboard } from "@plupin/game-sdk"
187
+
188
+ const board = new Leaderboard({ gameId: "arena-dash", board: "high-score" })
189
+
190
+ try {
191
+ await board.top(10)
192
+ } catch (error) {
193
+ if (!(error instanceof AppError)) throw error
194
+ console.warn(error.code, error.fix)
195
+ if (error.retryable) setTimeout(() => board.top(10), (error.retryAfterSeconds ?? 5) * 1000)
196
+ else console.error(error.message)
197
+ }
198
+ ```
199
+
200
+ Penolakan di dalam room (`stale_claim`, `out_of_range`, `reconnect_exhausted`, dan seterusnya) bukan kode di atas: ia datang lewat `room.on("error", ({ code }) => ...)`, daftarnya ada di [api.md](api.md).
201
+
202
+ **Perintah verifikasi:**
203
+ ```bash
204
+ plupin docs sdk | grep BOARD_NOT_FOUND
205
+ ```