peerodactyl 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gian
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,201 @@
1
- # Temporary Holding Version
1
+ # 🦅 peerodactyl
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ P2P rooms where **one player acts as the server**. The host is authoritative:
4
+ guests send *intents*, the host decides and broadcasts *events*. Peerodactyl
5
+ knows nothing about your game, it only moves messages between host and guests.
6
+
7
+ > Status: v0.1.0, early but tested (54 tests, e2e in Chrome, real phone over mobile data). Live demo: https://gianluks90.github.io/peerodactyl/
8
+
9
+ ```
10
+ npm install peerodactyl
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ Create **one** client, then host or join. Host and guest share the same API, so your code
16
+ does not care which role it plays. The library knows nothing about your game: you define the
17
+ types of intents (guest → host), events (host → everyone) and the snapshot (full state).
18
+
19
+ ```ts
20
+ import { PeerodactylClient, trysteroTransport } from 'peerodactyl'
21
+ import { joinRoom } from 'trystero' // any Trystero strategy works (Nostr here)
22
+
23
+ type Intent = { move: [number, number] }
24
+ type Event = { moved: { by: string; to: [number, number] } }
25
+ type State = { tokens: Record<string, [number, number]> }
26
+
27
+ const pd = new PeerodactylClient<Intent, Event, State>({
28
+ transport: trysteroTransport(joinRoom, { appId: 'my-unique-app-id' }, { turnUrl: 'https://…' })
29
+ })
30
+
31
+ // Host only: the single place where YOUR rules live (guests' intents and the host's own).
32
+ pd.setSnapshot(() => state)
33
+ pd.on('intent', (intent, from) => {
34
+ if (!allowed(intent, from)) return
35
+ pd.broadcast({ moved: { by: from, to: intent.move } })
36
+ })
37
+
38
+ // Everyone, host included: apply events with the same code.
39
+ pd.on('event', (e) => apply(e))
40
+ pd.on('snapshot', (s) => (state = s)) // guests: full state on join and after reconnections
41
+ pd.on('ended', (reason) => showLobby(reason)) // 'closed' | 'kicked' | 'lost'
42
+
43
+ const code = await pd.hostRoom() // "K7QM": share it
44
+ await pd.joinRoom('K7QM') // ...or join one
45
+ pd.sendIntent({ move: [3, 4] }) // same call for host and guest
46
+ pd.leave()
47
+ ```
48
+
49
+ Render from `pd.state` (status, role, code, players with online/away, latency, snapshot...)
50
+ and `pd.subscribe(listener)`: it maps straight onto signals, `useSyncExternalStore`, stores.
51
+
52
+ After a page reload, `await pd.rejoin()` gets the guest its seat back (the client remembers the room in `sessionStorage`).
53
+
54
+ ### Angular
55
+
56
+ ```ts
57
+ // app.config.ts
58
+ import { providePeerodactyl } from 'peerodactyl/angular'
59
+ export const appConfig = {
60
+ providers: [providePeerodactyl({ transport: trysteroTransport(joinRoom, { appId: 'my-app' }, { turnUrl }) })]
61
+ }
62
+
63
+ // any component or service
64
+ import { injectPeerodactyl } from 'peerodactyl/angular'
65
+ pd = injectPeerodactyl<Intent, Event, State>()
66
+ // template: @if (pd.status() === 'reconnecting') { 📡 } @for (p of pd.players(); track p.id) { ... }
67
+ // code: await pd.client.hostRoom()
68
+ ```
69
+
70
+ `@angular/core` (>= 17) is an optional peer dependency, only needed for `peerodactyl/angular`.
71
+
72
+ ### Lower level
73
+
74
+ `host()` / `join()` return `HostRoom` / `GuestRoom` directly, if you want the raw pieces:
75
+
76
+ ```ts
77
+ const room = await host<Intent, Event, State>({ transport })
78
+ room.on('intent', (intent, from) => room.broadcast(/* … */))
79
+ const guest = await join<Intent, Event, State>({ transport, code: room.code })
80
+ guest.on('event', apply)
81
+ guest.sendIntent({ move: [3, 4] })
82
+ ```
83
+
84
+ ## Pieces
85
+
86
+ | Piece | What it does |
87
+ | --- | --- |
88
+ | `PeerodactylClient` | **The entry point.** One object for host and guest: state + subscribe, events, intents, rejoin after reload |
89
+ | `peerodactyl/angular` | `providePeerodactyl()` / `injectPeerodactyl()`: the client's state as signals |
90
+ | `host()` / `HostRoom` | Opens a room, validates joins, receives intents, broadcasts events and snapshots |
91
+ | `join()` / `GuestRoom` | Finds the host by room code, gets the snapshot, sends intents |
92
+ | `Transport` | Tiny interface (`send`, `onMessage`, `onPeerJoin`, `onPeerLeave`, `leave`). Factories may be async |
93
+ | `trysteroTransport(joinRoom, config)` | Real P2P over Trystero (WebRTC + public signaling). You pass the `joinRoom` of the strategy you like, so peerodactyl has **no dependency** on Trystero |
94
+ | `broadcastChannelTransport()` | Tabs of the same browser talk to each other, no network. For dev, demos and tests |
95
+ | `createMemoryNetwork()` | In-process transport for unit tests: several "players", no browser |
96
+ | `debug: true` | Logs connection events with a dinosaur scream (`screams` is customisable) |
97
+
98
+ Not included on purpose: game rules, dice, maps, line of sight. Those live in your app.
99
+
100
+ ## Heartbeat and reconnection
101
+
102
+ Phones lock, tabs reload, Wi-Fi drops. Peerodactyl handles it so your app doesn't have to.
103
+
104
+ - Every guest has a **stable id** (`guest.selfId`), the same across reconnections, so the host
105
+ can key game state on it (a token, a character) without losing it.
106
+ - Guests ping the host; the host answers. Silence for `timeoutMs` (default 3 × `heartbeatMs`, 5 s)
107
+ marks a guest **away**: `guestAway`. Its seat is kept for `graceMs` (default 60 s); after that
108
+ `guestLeave(id, 'timeout')`. An explicit `leave()` frees the seat at once (`'bye'`), `kick()` gives `'kicked'`.
109
+ - When the guest comes back, `guestBack` fires and it gets a fresh snapshot (events missed while away are dropped, the snapshot replaces them).
110
+ - The guest side reconnects by itself (`reconnect: true`, `reconnectTimeoutMs`, default 30 s):
111
+ `reconnecting` → `reconnected(resumed)`. Give up → `hostLeft('lost')`. Host closed → `hostLeft('closed')`, no retries.
112
+ - **Surviving a page reload**: save `guest.selfId` (e.g. in `sessionStorage`) and pass it as `join({ sessionId })`.
113
+ The host gives the same seat back (`guest.resumed === true`).
114
+
115
+ ```ts
116
+ host.on('guestAway', (id) => markOffline(id))
117
+ host.on('guestBack', (id) => markOnline(id))
118
+ host.on('guestLeave', (id, reason) => removeToken(id)) // 'bye' | 'timeout' | 'kicked'
119
+
120
+ const guest = await join({ transport, code, sessionId: saved?.sid })
121
+ guest.on('reconnecting', () => showBanner('📡 Reconnecting…'))
122
+ guest.on('reconnected', (resumed) => hideBanner())
123
+ guest.on('hostLeft', (reason) => goToLobby(reason)) // 'closed' | 'kicked' | 'lost'
124
+ sessionStorage.setItem('sid', guest.selfId)
125
+ ```
126
+
127
+ Simulating failures in tests: `createMemoryNetwork()` offers `partition(peerId)` (silent drop), `heal(peerId)` and `kill(peerId)` (abrupt disconnect).
128
+
129
+ ## TURN fallback (strict networks)
130
+
131
+ WebRTC tries a direct path first (STUN). On some networks (mobile carriers with CGNAT,
132
+ corporate firewalls) that fails and the peers need a **TURN relay** that forwards their traffic.
133
+ The signaling relays (Nostr) never carry game data, so TURN is a separate thing.
134
+
135
+ Trystero passes `turnConfig` / `rtcConfig` straight to WebRTC, and peerodactyl passes your config through:
136
+
137
+ ```ts
138
+ const transport = trysteroTransport(joinRoom, {
139
+ appId: 'adventurer-studio',
140
+ turnConfig: [
141
+ { urls: 'turn:YOUR-TURN-HOST:443?transport=tcp', username: '...', credential: '...' }
142
+ ]
143
+ })
144
+ ```
145
+
146
+ - **Recommended:** don't hardcode anything. Point `turnUrl` at a tiny endpoint (a Cloudflare Worker) that returns fresh credentials as `[{ urls, username, credential }]`:
147
+ `trysteroTransport(joinRoom, { appId }, { turnUrl: 'https://your-worker.workers.dev' })`.
148
+ Credentials are fetched when the room opens (cached 30 min); if the endpoint is down, peerodactyl carries on without TURN.
149
+ - Use the **same** TURN config on host and guests. Port 443 over TCP/TLS passes the strictest firewalls.
150
+ - Free-ish options (check current limits): Cloudflare Realtime TURN (1,000 GB/month free tier), Metered Open Relay (20 GB/month free), or your own `coturn`.
151
+ - Short-lived credentials are better than static ones: a tiny serverless function (Firebase Functions, Cloudflare Worker) can mint them and return the `turnConfig` before you call `host()`/`join()`. Never commit TURN secrets to a public repo.
152
+ - Only relayed traffic uses TURN bandwidth (a minority of connections); a game of small messages barely registers.
153
+
154
+ **Testing it**: in the demo open "🛰️ TURN", paste your servers as JSON and tick "Forza il relay"
155
+ (`rtcConfig: { iceTransportPolicy: 'relay' }`). If two devices still connect, the TURN works.
156
+ On a phone, switch Wi-Fi off and use mobile data to exercise the real worst case.
157
+
158
+ ## Demo
159
+
160
+ ```
161
+ npm install
162
+ npm run demo
163
+ ```
164
+
165
+ Pick **"Due schede, senza rete"**, create a room in one tab, join with the code in another.
166
+ Pick **"P2P vero"** to go through Trystero (needs Internet; try it from two devices).
167
+ The host refuses moves longer than 3 cells: guests cannot cheat, that is the point.
168
+
169
+ ## Live demo (GitHub Pages)
170
+
171
+ Pushing to `main` runs `.github/workflows/pages.yml`: typecheck, tests, build the
172
+ demo and publish it. One-time setup in the repo: **Settings → Pages → Source: GitHub Actions**.
173
+ The demo uses relative paths, so it works under any `https://<user>.github.io/<repo>/`.
174
+ HTTPS is required for the real-Internet mode (Trystero uses browser crypto that only
175
+ exists on secure pages), so test it from there on your phone, not from `http://<LAN-ip>`.
176
+
177
+ ## Scripts
178
+
179
+ ```
180
+ npm test # vitest (memory, BroadcastChannel, fake Trystero, heartbeat, client, Angular)
181
+ npm run typecheck
182
+ npm run build # tsup -> dist/
183
+ npm run demo # vite dev server for demo/
184
+ npm run demo:build # static build into demo-dist/
185
+ ```
186
+
187
+ ## Roadmap
188
+
189
+ 1. ✅ Core, in-memory transport, tests
190
+ 2. ✅ Trystero adapter, BroadcastChannel transport, demo page
191
+ 3. ✅ Heartbeat / reconnection / resume after reload
192
+ 4. ✅ TURN fallback (`turnUrl`), tested on a phone over mobile data with relay forced
193
+ 5. ⬜ First integration (Adventurer Studio maps), then CyberCadungeon
194
+ 6. ✅ Client service + Angular signals (`peerodactyl/angular`)
195
+ 7. ✅ Published to npm
196
+
197
+ ## Known limits
198
+
199
+ - The real-Internet path (Trystero over public relays) is covered by tests against a fake with the same API shape, not yet against live relays. Try the demo from two devices.
200
+ - Without a TURN server, peers behind strict NATs (some mobile or corporate networks) may fail to connect.
201
+ - If the host disappears, the room ends. Resuming from a saved checkpoint is up to the app.
@@ -0,0 +1,42 @@
1
+ import { InjectionToken, Signal, Provider } from '@angular/core';
2
+ import { P as PeerodactylClient, C as ClientState, a as ClientStatus, b as PlayerInfo, c as PeerodactylClientOptions } from './client-DRstnAkE.js';
3
+
4
+ /** The client plus its state as Angular signals. */
5
+ interface PeerodactylSignals<I = unknown, E = unknown, S = unknown> {
6
+ /** Use it to host, join, send intents, listen to `intent` / `event`... */
7
+ readonly client: PeerodactylClient<I, E, S>;
8
+ readonly state: Signal<ClientState<S>>;
9
+ readonly status: Signal<ClientStatus>;
10
+ readonly role: Signal<'host' | 'guest' | null>;
11
+ readonly isHost: Signal<boolean>;
12
+ readonly code: Signal<string | null>;
13
+ readonly selfId: Signal<string | null>;
14
+ readonly players: Signal<readonly PlayerInfo[]>;
15
+ readonly latency: Signal<number | null>;
16
+ readonly snapshot: Signal<S | null>;
17
+ readonly endedReason: Signal<ClientState<S>['endedReason']>;
18
+ }
19
+ /** Where the shared instance lives. Prefer `providePeerodactyl()` + `injectPeerodactyl()`. */
20
+ declare const PEERODACTYL: InjectionToken<PeerodactylSignals<any, any, any>>;
21
+ /**
22
+ * Register peerodactyl once (app config or a route's providers):
23
+ *
24
+ * ```ts
25
+ * bootstrapApplication(App, {
26
+ * providers: [providePeerodactyl({ transport: trysteroTransport(joinRoom, { appId: 'my-app' }, { turnUrl }) })]
27
+ * })
28
+ * ```
29
+ */
30
+ declare function providePeerodactyl(options: PeerodactylClientOptions): Provider[];
31
+ /**
32
+ * Get the shared instance in any component or service:
33
+ *
34
+ * ```ts
35
+ * pd = injectPeerodactyl<Intent, Event, State>()
36
+ * // template: @if (pd.status() === 'reconnecting') { ... } {{ pd.players().length }}
37
+ * // code: await pd.client.hostRoom()
38
+ * ```
39
+ */
40
+ declare function injectPeerodactyl<I = unknown, E = unknown, S = unknown>(): PeerodactylSignals<I, E, S>;
41
+
42
+ export { ClientState, ClientStatus, PEERODACTYL, PeerodactylClient, PeerodactylClientOptions, type PeerodactylSignals, PlayerInfo, injectPeerodactyl, providePeerodactyl };
@@ -0,0 +1,48 @@
1
+ import {
2
+ PeerodactylClient
3
+ } from "./chunk-ULFDGPNT.js";
4
+
5
+ // src/angular/index.ts
6
+ import {
7
+ DestroyRef,
8
+ InjectionToken,
9
+ computed,
10
+ inject,
11
+ signal
12
+ } from "@angular/core";
13
+ var PEERODACTYL = new InjectionToken("PEERODACTYL");
14
+ function createSignals(options) {
15
+ const client = new PeerodactylClient(options);
16
+ const state = signal(client.state);
17
+ const off = client.subscribe((s) => state.set(s));
18
+ inject(DestroyRef, { optional: true })?.onDestroy(() => {
19
+ off();
20
+ client.leave();
21
+ });
22
+ return {
23
+ client,
24
+ state: state.asReadonly(),
25
+ status: computed(() => state().status),
26
+ role: computed(() => state().role),
27
+ isHost: computed(() => state().role === "host"),
28
+ code: computed(() => state().code),
29
+ selfId: computed(() => state().selfId),
30
+ players: computed(() => state().players),
31
+ latency: computed(() => state().latency),
32
+ snapshot: computed(() => state().snapshot),
33
+ endedReason: computed(() => state().endedReason)
34
+ };
35
+ }
36
+ function providePeerodactyl(options) {
37
+ return [{ provide: PEERODACTYL, useFactory: () => createSignals(options) }];
38
+ }
39
+ function injectPeerodactyl() {
40
+ return inject(PEERODACTYL);
41
+ }
42
+ export {
43
+ PEERODACTYL,
44
+ PeerodactylClient,
45
+ injectPeerodactyl,
46
+ providePeerodactyl
47
+ };
48
+ //# sourceMappingURL=angular.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/angular/index.ts"],"sourcesContent":["import {\n DestroyRef,\n InjectionToken,\n computed,\n inject,\n signal,\n type Provider,\n type Signal\n} from '@angular/core'\nimport {\n PeerodactylClient,\n type ClientState,\n type ClientStatus,\n type PeerodactylClientOptions,\n type PlayerInfo\n} from '../client'\n\nexport type { ClientState, ClientStatus, PeerodactylClientOptions, PlayerInfo }\nexport { PeerodactylClient }\n\n/** The client plus its state as Angular signals. */\nexport interface PeerodactylSignals<I = unknown, E = unknown, S = unknown> {\n /** Use it to host, join, send intents, listen to `intent` / `event`... */\n readonly client: PeerodactylClient<I, E, S>\n readonly state: Signal<ClientState<S>>\n readonly status: Signal<ClientStatus>\n readonly role: Signal<'host' | 'guest' | null>\n readonly isHost: Signal<boolean>\n readonly code: Signal<string | null>\n readonly selfId: Signal<string | null>\n readonly players: Signal<readonly PlayerInfo[]>\n readonly latency: Signal<number | null>\n readonly snapshot: Signal<S | null>\n readonly endedReason: Signal<ClientState<S>['endedReason']>\n}\n\n/** Where the shared instance lives. Prefer `providePeerodactyl()` + `injectPeerodactyl()`. */\nexport const PEERODACTYL = new InjectionToken<PeerodactylSignals<any, any, any>>('PEERODACTYL')\n\nfunction createSignals<I, E, S>(options: PeerodactylClientOptions): PeerodactylSignals<I, E, S> {\n const client = new PeerodactylClient<I, E, S>(options)\n const state = signal<ClientState<S>>(client.state)\n const off = client.subscribe((s) => state.set(s))\n inject(DestroyRef, { optional: true })?.onDestroy(() => {\n off()\n client.leave()\n })\n return {\n client,\n state: state.asReadonly(),\n status: computed(() => state().status),\n role: computed(() => state().role),\n isHost: computed(() => state().role === 'host'),\n code: computed(() => state().code),\n selfId: computed(() => state().selfId),\n players: computed(() => state().players),\n latency: computed(() => state().latency),\n snapshot: computed(() => state().snapshot),\n endedReason: computed(() => state().endedReason)\n }\n}\n\n/**\n * Register peerodactyl once (app config or a route's providers):\n *\n * ```ts\n * bootstrapApplication(App, {\n * providers: [providePeerodactyl({ transport: trysteroTransport(joinRoom, { appId: 'my-app' }, { turnUrl }) })]\n * })\n * ```\n */\nexport function providePeerodactyl(options: PeerodactylClientOptions): Provider[] {\n return [{ provide: PEERODACTYL, useFactory: () => createSignals(options) }]\n}\n\n/**\n * Get the shared instance in any component or service:\n *\n * ```ts\n * pd = injectPeerodactyl<Intent, Event, State>()\n * // template: @if (pd.status() === 'reconnecting') { ... } {{ pd.players().length }}\n * // code: await pd.client.hostRoom()\n * ```\n */\nexport function injectPeerodactyl<I = unknown, E = unknown, S = unknown>(): PeerodactylSignals<\n I,\n E,\n S\n> {\n return inject(PEERODACTYL) as PeerodactylSignals<I, E, S>\n}\n"],"mappings":";;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AA6BA,IAAM,cAAc,IAAI,eAAkD,aAAa;AAE9F,SAAS,cAAuB,SAAgE;AAC9F,QAAM,SAAS,IAAI,kBAA2B,OAAO;AACrD,QAAM,QAAQ,OAAuB,OAAO,KAAK;AACjD,QAAM,MAAM,OAAO,UAAU,CAAC,MAAM,MAAM,IAAI,CAAC,CAAC;AAChD,SAAO,YAAY,EAAE,UAAU,KAAK,CAAC,GAAG,UAAU,MAAM;AACtD,QAAI;AACJ,WAAO,MAAM;AAAA,EACf,CAAC;AACD,SAAO;AAAA,IACL;AAAA,IACA,OAAO,MAAM,WAAW;AAAA,IACxB,QAAQ,SAAS,MAAM,MAAM,EAAE,MAAM;AAAA,IACrC,MAAM,SAAS,MAAM,MAAM,EAAE,IAAI;AAAA,IACjC,QAAQ,SAAS,MAAM,MAAM,EAAE,SAAS,MAAM;AAAA,IAC9C,MAAM,SAAS,MAAM,MAAM,EAAE,IAAI;AAAA,IACjC,QAAQ,SAAS,MAAM,MAAM,EAAE,MAAM;AAAA,IACrC,SAAS,SAAS,MAAM,MAAM,EAAE,OAAO;AAAA,IACvC,SAAS,SAAS,MAAM,MAAM,EAAE,OAAO;AAAA,IACvC,UAAU,SAAS,MAAM,MAAM,EAAE,QAAQ;AAAA,IACzC,aAAa,SAAS,MAAM,MAAM,EAAE,WAAW;AAAA,EACjD;AACF;AAWO,SAAS,mBAAmB,SAA+C;AAChF,SAAO,CAAC,EAAE,SAAS,aAAa,YAAY,MAAM,cAAc,OAAO,EAAE,CAAC;AAC5E;AAWO,SAAS,oBAId;AACA,SAAO,OAAO,WAAW;AAC3B;","names":[]}