@hagicode/steamworks.js 0.0.0-stage → 0.1.6-dev.17

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) 2022 Gabriel Francisco Dos Santos
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,481 @@
1
- # Temporary Holding Version
1
+ [![Build Status](https://github.com/HagiCode-org/steamworks.js/actions/workflows/publish.yml/badge.svg)](https://github.com/HagiCode-org/steamworks.js/actions/workflows/publish.yml)
2
+ [![npm](https://img.shields.io/npm/v/@hagicode/steamworks.js.svg)](https://npmjs.com/package/@hagicode/steamworks.js)
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
2
4
 
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.
5
+ # Steamworks.js
6
+
7
+ A modern implementation of the Steamworks SDK for HTML/JS and NodeJS based applications.
8
+
9
+ ## Why
10
+
11
+ I used [greenworks](https://github.com/greenheartgames/greenworks) for a long time and it's great, but I gave up for the following reasons.
12
+
13
+ * It's not being maintained anymore.
14
+ * It's not up to date.
15
+ * It's not context-aware.
16
+ * You have to build the binaries by yourself.
17
+ * Don't have typescript definitions.
18
+ * The API it's not trustful.
19
+ * The API implement callbacks instead of return flags or promises.
20
+ * I hate C++.
21
+
22
+ ## API
23
+
24
+ ```js
25
+ const steamworks = require('steamworks.js')
26
+
27
+ // You can pass an appId, or don't pass anything and use a steam_appid.txt file
28
+ const client = steamworks.init(480)
29
+
30
+ // Print Steam username
31
+ console.log(client.localplayer.getName())
32
+
33
+ // Tries to activate an achievement
34
+ if (client.achievement.activate('ACHIEVEMENT')) {
35
+ // ...
36
+ }
37
+ ```
38
+
39
+ You can refer to the [declarations file](https://github.com/HagiCode-org/steamworks.js/blob/main/client.d.ts) to check the API support and get more detailed documentation of each function.
40
+
41
+ ## Installation
42
+
43
+ To use steamworks.js you don't have to build anything, just install it from npm:
44
+
45
+ ```sh
46
+ npm i @hagicode/steamworks.js
47
+ ```
48
+
49
+ Guides and agent skills are on the documentation site at https://steamworks.hagicode.com/.
50
+
51
+ ### Migration from `steamworks.js`
52
+
53
+ If you were using the unscoped `steamworks.js` package, update your `package.json`:
54
+
55
+ ```json
56
+ {
57
+ "dependencies": {
58
+ "@hagicode/steamworks.js": "latest"
59
+ }
60
+ }
61
+ ```
62
+
63
+ Then run `pnpm install`. Your `require('steamworks.js')` statements will continue to work without changes.
64
+
65
+ ### Electron
66
+
67
+ Steamworks.js is a native module and cannot be used by default in the renderer process. To enable the usage of native modules on the renderer process, the following configurations should be made on `main.js`:
68
+
69
+ ```js
70
+ const mainWindow = new BrowserWindow({
71
+ // ...
72
+ webPreferences: {
73
+ // ...
74
+ contextIsolation: false,
75
+ nodeIntegration: true
76
+ }
77
+ })
78
+ ```
79
+
80
+ To make the steam overlay working, call the `electronEnableSteamOverlay` on the end of your `main.js` file:
81
+
82
+ ```js
83
+ require('steamworks.js').electronEnableSteamOverlay()
84
+ ```
85
+
86
+ For the production build, copy the relevant distro files from `sdk/redistributable_bin/{YOUR_DISTRO}` into the root of your build. If you are using electron-forge, look for [#75](https://github.com/HagiCode-org/steamworks.js/issues/75).
87
+
88
+
89
+ ## How to build
90
+
91
+ > You **only** need to build if you are going to change something on steamworks.js code, if you are looking to just consume the library or use it in your game, refer to the [installation section](#installation).
92
+
93
+ Make sure you have the latest [node.js](https://nodejs.org/en/), [Rust](https://www.rust-lang.org/tools/install) and [Clang](https://rust-lang.github.io/rust-bindgen/requirements.html). We also need [Steam](https://store.steampowered.com/about/) installed and running.
94
+
95
+ ### Cloning the repository
96
+
97
+ This project uses git submodules for the steamworks-rs dependency. When cloning the repository, use:
98
+
99
+ ```sh
100
+ git clone --recurse-submodules https://github.com/HagiCode-org/steamworks.js.git
101
+ ```
102
+
103
+ If you have already cloned the repository without submodules, initialize them with:
104
+
105
+ ```sh
106
+ git submodule update --init --recursive
107
+ ```
108
+
109
+ ### Building
110
+
111
+ Install dependencies with `pnpm install` and then run `pnpm run build:debug` to build the library.
112
+
113
+ There is no way to build for all targets easily. The good news is that you don't need to. You can develop and test on your current target, and open a PR. When the code is merged to main, a github action will build for all targets and publish a new version.
114
+
115
+ ### Testing Electron
116
+
117
+ Go to the [test/electron](./test/electron) directory. There, you can run `pnpm install` and then `pnpm start` to run the Electron app.
118
+
119
+ Click "activate overlay" to test the overlay.
120
+
121
+ ## Contributing
122
+
123
+ Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines on commit conventions and the pull request process.
124
+
125
+ ## Workshop Screenshots (Additional Previews)
126
+
127
+ Besides the main preview, a Workshop item can show extra screenshots. Read them with `includeAdditionalPreviews`, and add more with `additionalPreviewPaths` (an update that carries only the new images):
128
+
129
+ ```js
130
+ const steamworks = require('steamworks.js')
131
+ const client = steamworks.init(appId)
132
+
133
+ // list: each entry has urlOrVideoId, originalFilename and previewType (ItemPreviewType)
134
+ const item = await client.workshop.getItem(itemId, { includeAdditionalPreviews: true })
135
+ console.log(item.additionalPreviews)
136
+
137
+ // add: appended to the item's screenshots; no content and no title change are sent
138
+ await client.workshop.updateItem(itemId, { additionalPreviewPaths: ['/abs/path/shot-2.png'] }, appId)
139
+
140
+ // remove: pass the 0-based indexes from `additionalPreviews`; the main preview is not affected
141
+ await client.workshop.updateItem(itemId, { removeAdditionalPreviewIndexes: [0, 2] }, appId)
142
+ ```
143
+
144
+ - Removals run before additions in the same update, from the highest index down. Indexes always refer to the list as it was before this update, so read the list again before removing.
145
+ - Screenshots cannot be reordered through this API. The main preview is replaced with `previewPath`, not removed.
146
+ - Steam lists screenshots by file name. Send only the files that are not listed yet, otherwise they are added again.
147
+ - Adding screenshots needs a Steam client that is running and logged in, and an account that owns the app.
148
+
149
+ ## Workshop Preview and Content Updates
150
+
151
+ `updateItem` accepts every field as optional, so a call that carries only `previewPath` or only `contentPath` already updates just that part. Two explicit helpers make that intent obvious and check the path before talking to Steam:
152
+
153
+ ```js
154
+ const steamworks = require('steamworks.js')
155
+ const client = steamworks.init(appId)
156
+
157
+ // replace only the main preview image; the mod files are not uploaded
158
+ await client.workshop.updateItemPreview(itemId, '/abs/path/preview.png', appId, 'New preview')
159
+
160
+ // upload only the mod folder; the preview image is not touched
161
+ await client.workshop.updateItemContent(itemId, '/abs/path/mod-folder', appId, 'Fix crash on load')
162
+ ```
163
+
164
+ - Signature for both: `(itemId, path, appId?, changeNote?)`. `appId` defaults to the app the client was initialized with, and `changeNote` is optional.
165
+ - `updateItemPreview` rejects when the path is missing or is not a file. `updateItemContent` rejects when the path is missing or is not a folder. Both check before any Steam call.
166
+ - Title, description, tags and visibility are not sent, so they stay as they are. To change them together with a file, keep using `updateItem`.
167
+ - Neither helper reports upload progress. For a large content upload use `updateItemWithCallback`.
168
+
169
+ ## Workshop Item Dependencies
170
+
171
+ A Workshop item can require another item, so Steam installs the required item along with it. `addDependency` and `removeDependency` take the parent and the child as `bigint` ids and resolve with the Steam result code. `1` means OK. Any other code is a Steam failure reason, and it arrives as a resolved number, not a rejection.
172
+
173
+ ```js
174
+ const steamworks = require('steamworks.js')
175
+ const client = steamworks.init(appId)
176
+
177
+ const modId = 123456789n // your mod: an item owned by the logged-in account
178
+ const requiredId = 3836453389n // the required child item (Outing Picker)
179
+
180
+ // mark the child as required by the mod
181
+ const added = await client.workshop.addDependency(modId, requiredId)
182
+ if (added !== 1) {
183
+ console.error(`Steam refused the dependency, result code ${added}`)
184
+ }
185
+
186
+ // remove it again; the result code is returned the same way
187
+ const removed = await client.workshop.removeDependency(modId, requiredId)
188
+ ```
189
+
190
+ - Both calls need a running, logged-in Steam client, and the parent must be an item the logged-in account owns.
191
+ - An id that is negative or does not fit in 64 bits rejects before any Steam call. A failed call with no completion also rejects, and the error says the outcome is unknown, so check the item before retrying.
192
+
193
+ ## Workshop Multilingual Support
194
+
195
+ Steamworks.js supports localized content for Steam Workshop items. You can update the title and description for different languages using the `language` parameter.
196
+
197
+ ### Basic Usage
198
+
199
+ ```js
200
+ // Update English content (backward compatible - no language specified)
201
+ await workshop.updateItem(itemId, {
202
+ title: "My Mod",
203
+ description: "English description"
204
+ });
205
+
206
+ // Update English content (explicitly)
207
+ await workshop.updateItem(itemId, {
208
+ title: "My Mod",
209
+ description: "English description",
210
+ language: "english"
211
+ });
212
+
213
+ // Update Chinese content
214
+ await workshop.updateItem(itemId, {
215
+ title: "我的模组",
216
+ description: "中文描述",
217
+ language: "schinese"
218
+ });
219
+ ```
220
+
221
+ ### Multiple Languages
222
+
223
+ Since Steam API only supports updating one language at a time, you need to make multiple `updateItem()` calls for each language:
224
+
225
+ ```js
226
+ // Sequential updates
227
+ await workshop.updateItem(itemId, {
228
+ title: "My Mod",
229
+ description: "English description",
230
+ language: "english"
231
+ });
232
+
233
+ await workshop.updateItem(itemId, {
234
+ title: "Mon Mod",
235
+ description: "Description française",
236
+ language: "french"
237
+ });
238
+
239
+ await workshop.updateItem(itemId, {
240
+ title: "Mi Mod",
241
+ description: "Descripción en español",
242
+ language: "spanish"
243
+ });
244
+ ```
245
+
246
+ Or use `Promise.all()` for parallel updates:
247
+
248
+ ```js
249
+ await Promise.all([
250
+ workshop.updateItem(itemId, {
251
+ title: "Mein Mod",
252
+ description: "Deutsche Beschreibung",
253
+ language: "german"
254
+ }),
255
+ workshop.updateItem(itemId, {
256
+ title: "私のMod",
257
+ description: "日本語の説明",
258
+ language: "japanese"
259
+ }),
260
+ workshop.updateItem(itemId, {
261
+ title: "내 모드",
262
+ description: "한국어 설명",
263
+ language: "korean"
264
+ })
265
+ ]);
266
+ ```
267
+
268
+ ### Supported Language Codes
269
+
270
+ Steam supports the following language codes:
271
+
272
+ | Code | Language | Code | Language |
273
+ |------|----------|------|----------|
274
+ | `english` | English | `schinese` | Simplified Chinese |
275
+ | `tchinese` | Traditional Chinese | `german` | German |
276
+ | `french` | French | `italian` | Italian |
277
+ | `korean` | Korean | `spanish` | Spanish |
278
+ | `russian` | Russian | `thai` | Thai |
279
+ | `japanese` | Japanese | `portuguese` | Portuguese |
280
+ | `polish` | Polish | `danish` | Danish |
281
+ | `dutch` | Dutch | `finnish` | Finnish |
282
+ | `norwegian` | Norwegian | `swedish` | Swedish |
283
+ | `hungarian` | Hungarian | `czech` | Czech |
284
+ | `romanian` | Romanian | `turkish` | Turkish |
285
+ | `brazilian` | Brazilian Portuguese | `bulgarian` | Bulgarian |
286
+ | `greek` | Greek | `arabic` | Arabic |
287
+ | `ukrainian` | Ukrainian | `vietnamese` | Vietnamese |
288
+
289
+ **Note**: If `language` is omitted, it defaults to `"english"`.
290
+
291
+ ## Friends
292
+
293
+ The `friends` namespace reads the local user's friend list, friend state and avatars, and sends game invites. SteamIDs are `bigint` values.
294
+
295
+ ```js
296
+ const steamworks = require('steamworks.js')
297
+ const client = steamworks.init(appId)
298
+
299
+ // 0x4 = immediate friends (FriendFlags.IMMEDIATE)
300
+ for (const friend of client.friends.getFriends(0x4)) {
301
+ const state = client.friends.getFriendState(friend.steamId64)
302
+ const avatar = client.friends.getMediumAvatar(friend.steamId64) // Buffer of RGBA pixels, or null
303
+ console.log(friend.nickName ?? friend.name, state, avatar?.length ?? 0)
304
+ }
305
+
306
+ // Invite a friend to the current game with a connect string
307
+ client.friends.inviteUserToGame(friendSteamId, 'lobby=abc')
308
+
309
+ // Remove the Rich Presence keys set with localplayer.setRichPresence
310
+ client.friends.clearRichPresence()
311
+ ```
312
+
313
+ - `getFriendState` returns a `FriendState` value; `getFriendGamePlayed` returns the AppID of the game a friend is playing, or `null`.
314
+ - Avatars are `null` until Steam has loaded them. Call `client.friends.requestUserInformation(steamId64, true)` to ask for a user's information, and wait for the `PersonaStateChange` callback before reading it again.
315
+ - Name and state updates arrive through `runCallbacks()`, which `init()` already calls on a timer.
316
+
317
+ ## Stats, Achievements and Leaderboards
318
+
319
+ `stats` gains float stats, the achievement count and a request for another user's stats. `achievement` gains global unlock percentages. The `leaderboard` namespace finds and creates leaderboards, uploads scores and downloads entries.
320
+
321
+ ```js
322
+ const steamworks = require('steamworks.js')
323
+ const client = steamworks.init(appId)
324
+
325
+ client.stats.setFloat('distance', 12.5)
326
+ console.log(client.stats.getFloat('distance')) // 12.5, or null when the stat is not defined
327
+ console.log(client.stats.getNumAchievements())
328
+
329
+ // Global unlock percentages: call the request first, then read each achievement
330
+ await client.achievement.requestGlobalPercentages()
331
+ console.log(client.achievement.getAchievedPercent('FIRST_RUN')) // 0 to 100, or null
332
+
333
+ // Leaderboards: 0 = Ascending, 0 = Numeric; upload with 0 = KeepBest, download with 0 = Global
334
+ const board = await client.leaderboard.findOrCreate('Fastest', 0, 0)
335
+ if (board) {
336
+ const result = await board.uploadScore(0, 1234, []) // null when Steam did not accept the upload
337
+ const top = await board.downloadEntries(0, 0, 10, 0) // ranks 0 to 9
338
+ console.log(board.getName(), board.getEntryCount(), result, top)
339
+ }
340
+ ```
341
+
342
+ - `requestUserStats(steamId64)` only starts the request. Its result arrives through the `UserStatsReceived` callback (see `callback.register`).
343
+ - The Promise-returning functions (`requestGlobalPercentages`, `find`, `findOrCreate`, `uploadScore`, `downloadEntries`) resolve when Steam answers. Steam delivers those answers inside `runCallbacks()`. `init()` runs it about 30 times a second, so you do not need to call it yourself while the client is initialized.
344
+ - A Promise rejects with a readable message when Steam reports a failure. When the answer is lost, the message says the outcome is unknown, so check the data before retrying an upload.
345
+
346
+ ## Networking: `networking` and the New Namespaces
347
+
348
+ Two families of networking APIs coexist. The `networking` namespace is the original P2P packet API (`sendP2PPacket`, `readP2PPacket`, `acceptP2PSession`), and it is unchanged. The new `networkingSockets`, `networkingMessages` and `networkingUtils` namespaces wrap Steam's Networking Sockets, Networking Messages and Networking Utils interfaces.
349
+
350
+ - `networking` sends unreliable or reliable packets to a SteamID and reads them back in arrival order. There is no connection object, so you cannot close one peer or tell when it dropped.
351
+ - `networkingSockets` creates listen sockets and connections (by IP address or by SteamID), sends and receives messages with send flags, and groups connections into poll groups. Connections are objects with `close`, and state queries show whether each one is open.
352
+ - `networkingMessages` is connectionless, like UDP: send to a SteamID on a channel, receive by channel, and handle session requests and failures. Steam creates the underlying session implicitly.
353
+ - `networkingUtils` starts relay network access and reports its availability.
354
+
355
+ ```js
356
+ const steamworks = require('steamworks.js')
357
+ const client = steamworks.init(appId)
358
+
359
+ // Relay access and authentication: start them early if you expect relayed or authenticated connections
360
+ client.networkingUtils.initRelayNetworkAccess()
361
+ console.log(client.networkingUtils.getRelayNetworkStatus()) // NetworkingAvailability value
362
+ client.networkingSockets.initAuthentication()
363
+
364
+ // Host: poll the listen socket without waiting, accept connecting peers and take the connection when it is connected
365
+ const listen = client.networkingSockets.createListenSocketIp('0.0.0.0:27015')
366
+ const event = listen.tryReceiveEvent() // null when nothing is pending
367
+ if (event && event.kind === 0 /* Connecting */) {
368
+ event.accept()
369
+ }
370
+ if (event && event.kind === 1 /* Connected */) {
371
+ const connection = event.takeConnection()
372
+ connection.send(Buffer.from('hello'), 8) // 8 = reliable
373
+ console.log(connection.receive(16))
374
+ }
375
+
376
+ // Client: connect by IP address, then close with a reason
377
+ const connection = client.networkingSockets.connectByIpAddress('203.0.113.5:27015')
378
+ connection.setUserData(1n)
379
+ connection.close(1000, 'done', true)
380
+
381
+ // Messages: accept requests from Steam users and read channel 3
382
+ client.networkingMessages.onSessionRequest((request) => request.accept())
383
+ client.networkingMessages.sendMessageToUser(friendSteamId, 8, Buffer.from('hi'), 3)
384
+ console.log(client.networkingMessages.receiveMessagesOnChannel(3, 10))
385
+ ```
386
+
387
+ - Send flags are a bitmask of Steam's `k_nSteamNetworkingSend_*` values: `0` unreliable, `8` reliable, `1` no Nagle delay. Invalid addresses and closed handles fail with a readable error.
388
+ - Listen socket events and session requests are only produced while `runCallbacks()` runs. `init()` already calls it about 30 times a second.
389
+ - A connection or request you never close or answer is closed or rejected when its JavaScript object is garbage collected. Close connections explicitly.
390
+ - Connections and messages need a Steam network path, so they cannot be exercised offline. The offline smoke test only checks that these functions are exported.
391
+
392
+ ## Server Browser, Timeline, Screenshots and Remote Play
393
+
394
+ `matchmakingServers` lists game servers and queries single servers. `timeline` marks game state and events for Steam's timeline. `screenshots` hooks the screenshot hotkey and adds images to the Steam library. `remotePlay` lists Remote Play Together sessions and sends invites.
395
+
396
+ ```js
397
+ const steamworks = require('steamworks.js')
398
+ const client = steamworks.init(appId)
399
+
400
+ // Server list: request, read, then release it
401
+ const list = client.matchmakingServers.lanServerList(appId)
402
+ try {
403
+ for (let i = 0; i < list.getServerCount(); i++) {
404
+ const server = list.getServerDetails(i) // ip, port, name, map, players, maxPlayers, ping
405
+ console.log(server.name, server.players, server.maxPlayers, server.ping)
406
+ }
407
+ } finally {
408
+ list.release()
409
+ }
410
+
411
+ // Single server: these are Promises and reject when the server does not answer
412
+ const ping = await client.matchmakingServers.pingServer('192.168.1.10', 27015)
413
+ const players = await client.matchmakingServers.playerDetails('192.168.1.10', 27015)
414
+ const rules = await client.matchmakingServers.serverRules('192.168.1.10', 27015)
415
+
416
+ // Timeline: 0 = Playing (the game mode values are Playing, Staging, Menus, LoadingScreen)
417
+ client.timeline.setGameMode(0)
418
+ client.timeline.addEvent('icon', 'Boss defeated', '', 0, -5, 5, 1) // clip priority 1 = Standard
419
+
420
+ // Screenshots: with the hook on, the hotkey raises ScreenshotRequested instead of Steam taking the picture
421
+ client.screenshots.hookScreenshots(true)
422
+ client.screenshots.triggerScreenshot()
423
+
424
+ // Remote Play Together
425
+ for (const session of client.remotePlay.sessions()) {
426
+ console.log(session.sessionId, session.steamId64, client.remotePlay.sessionDetails(session.sessionId))
427
+ }
428
+ client.remotePlay.invite(friendSteamId)
429
+ ```
430
+
431
+ - Steam fills a server list over time, through callbacks that `init()` pumps automatically. Read the count after a short wait, not right after the request. The single-server functions are Promises that resolve the same way.
432
+ - Release every server list request when you finish with it. Methods called after `release()` throw a readable error.
433
+ - Invalid IPv4 addresses, negative durations and strings with NUL characters are rejected with a readable error before any Steam call.
434
+ - `timeline` calls are silent when the Steam timeline interface is unavailable.
435
+
436
+ ## Supplemental Functions
437
+
438
+ These functions extend existing namespaces. Nothing that existed before has changed.
439
+
440
+ ```js
441
+ const client = steamworks.init(appId)
442
+
443
+ // apps: the launch command line, and a query parameter from a Steam link such as steam://run/480//mode=demo
444
+ client.apps.launchCommandLine()
445
+ client.apps.launchQueryParam('mode') // '' when the parameter is absent
446
+
447
+ // utils: overlay and UI state
448
+ client.utils.isOverlayEnabled()
449
+ client.utils.isSteamInBigPictureMode()
450
+ client.utils.getUiLanguage() // for example 'english'
451
+
452
+ // input: digital and analog action data, and the origins bound to an action
453
+ const pressed = client.input.getDigitalActionData(controllerHandle, actionHandle).state
454
+ const stick = client.input.getAnalogActionData(controllerHandle, analogHandle) // { x, y, active }
455
+ const origins = client.input.getDigitalActionOrigins(controllerHandle, actionSetHandle, actionHandle)
456
+ const label = client.input.getStringForActionOrigin(origins[0] ?? 0)
457
+
458
+ // networking: P2P packets on a channel, and closing a session
459
+ client.networking.sendP2PPacketOnChannel(friendSteamId, SendType.Reliable, Buffer.from('hi'), 2)
460
+ client.networking.isP2PPacketAvailableOnChannel(2)
461
+ client.networking.closeP2PSession(friendSteamId)
462
+
463
+ // cloud: share a file (a Promise), stop syncing it, and choose the platforms it syncs to
464
+ const shareHandle = await client.cloud.shareFile('save.json')
465
+ client.cloud.forgetFile('save.json')
466
+ client.cloud.setSyncPlatforms('save.json', 0 /* SyncPlatform.None */)
467
+ ```
468
+
469
+ - `getStringForActionOrigin` and `getGlyphForActionOrigin` return an empty string for an origin number that Steam does not define.
470
+ - `getSyncPlatforms` rejects when a file syncs to a combination of platforms, because a single `SyncPlatform` value cannot describe it.
471
+ - `shareFile` resolves once Steam answers, which happens through `runCallbacks()`. `init()` runs it for you.
472
+
473
+ ## Release Process
474
+
475
+ This project uses automated release management:
476
+
477
+ - **Dev builds**: Every push to the `main` branch publishes a build to the npm `dev` dist-tag for testing
478
+ - **Release drafts**: Every push to `main` updates one draft GitHub release for the next `vX.Y.Z`, drafted by [hagi-release-drafter](https://github.com/HagiCode-org/hagi-release-drafter). It is never published automatically
479
+ - **Official releases**: Publish the draft in the GitHub UI. That creates the `vX.Y.Z` tag, and the tag publishes the npm `latest` version
480
+
481
+ Release notes are automatically generated from Conventional Commit messages. See [CONTRIBUTING.md](./CONTRIBUTING.md) for the commit message format.
package/callbacks.d.ts ADDED
@@ -0,0 +1,170 @@
1
+ import client = require('./client')
2
+
3
+ export const enum ChatMemberStateChange {
4
+ /** This user has joined or is joining the lobby. */
5
+ Entered,
6
+ /** This user has left or is leaving the lobby. */
7
+ Left,
8
+ /** User disconnected without leaving the lobby first. */
9
+ Disconnected,
10
+ /** The user has been kicked. */
11
+ Kicked,
12
+ /** The user has been kicked and banned. */
13
+ Banned,
14
+ }
15
+
16
+ /**
17
+ * Serde form of steamworks-rs `SteamError`: a unit variant name such as `"NoConnection"`,
18
+ * or `{ UnknownResult: code }` for a Steam result code that has no name.
19
+ */
20
+ export type SteamErrorName = string | { UnknownResult: number }
21
+
22
+ /** Serde form of `Result<(), SteamError>`: `{ Ok: null }` on success, `{ Err: ... }` on failure. */
23
+ export type SteamResult = { Ok: null } | { Err: SteamErrorName }
24
+
25
+ /** Serde form of steamworks-rs `ChatEntryType` (a unit variant name). */
26
+ export type ChatEntryTypeName =
27
+ | 'Invalid'
28
+ | 'ChatMsg'
29
+ | 'Typing'
30
+ | 'InviteGame'
31
+ | 'Emote'
32
+ | 'LeftConversation'
33
+ | 'Entered'
34
+ | 'WasKicked'
35
+ | 'WasBanned'
36
+ | 'Disconnected'
37
+ | 'HistoricalChat'
38
+ | 'LinkBlocked'
39
+
40
+ /** Serde form of steamworks-rs `ChatRoomEnterResponse` (a unit variant name). */
41
+ export type ChatRoomEnterResponseName =
42
+ | 'Success'
43
+ | 'DoesntExist'
44
+ | 'NotAllowed'
45
+ | 'Full'
46
+ | 'Error'
47
+ | 'Banned'
48
+ | 'Limited'
49
+ | 'ClanDisabled'
50
+ | 'CommunityBan'
51
+ | 'MemberBlockedYou'
52
+ | 'YouBlockedMember'
53
+ | 'RatelimitExceeded'
54
+
55
+ /** Serde form of steamworks-rs `AuthSessionValidateError` (a unit variant name). */
56
+ export type AuthSessionValidateErrorName =
57
+ | 'UserNotConnectedToSteam'
58
+ | 'NoLicenseOrExpired'
59
+ | 'VACBanned'
60
+ | 'LoggedInElseWhere'
61
+ | 'VACCheckTimedOut'
62
+ | 'AuthTicketCancelled'
63
+ | 'AuthTicketInvalidAlreadyUsed'
64
+ | 'AuthTicketInvalid'
65
+ | 'PublisherIssuedBan'
66
+
67
+ /**
68
+ * Measured with napi-rs 2.16 (`serde-json` and `napi6` features): a JSON integer within
69
+ * +/-(2^53 - 1) reaches JavaScript as a `number`, and a larger one as a `bigint`.
70
+ * SteamIDs, lobby IDs and friend IDs are always beyond 2^53, so they are `bigint`.
71
+ * `GameId` and `PublishedFileId` are `u64` values that may be small, so they are `number | bigint`.
72
+ */
73
+ export interface CallbackReturns {
74
+ [client.callback.SteamCallback.PersonaStateChange]: {
75
+ steam_id: bigint
76
+ flags: { bits: number }
77
+ }
78
+ [client.callback.SteamCallback.SteamServersConnected]: {}
79
+ [client.callback.SteamCallback.SteamServersDisconnected]: {
80
+ reason: number
81
+ }
82
+ [client.callback.SteamCallback.SteamServerConnectFailure]: {
83
+ reason: number
84
+ still_retrying: boolean
85
+ }
86
+ [client.callback.SteamCallback.LobbyDataUpdate]: {
87
+ lobby: bigint
88
+ member: bigint
89
+ success: boolean
90
+ }
91
+ [client.callback.SteamCallback.LobbyChatUpdate]: {
92
+ lobby: bigint
93
+ user_changed: bigint
94
+ making_change: bigint
95
+ member_state_change: ChatMemberStateChange
96
+ }
97
+ [client.callback.SteamCallback.P2PSessionRequest]: {
98
+ remote: bigint
99
+ }
100
+ [client.callback.SteamCallback.P2PSessionConnectFail]: {
101
+ remote: bigint
102
+ error: number
103
+ }
104
+ [client.callback.SteamCallback.GameLobbyJoinRequested]: {
105
+ lobby_steam_id: bigint
106
+ friend_steam_id: bigint
107
+ }
108
+ [client.callback.SteamCallback.MicroTxnAuthorizationResponse]: {
109
+ app_id: number
110
+ order_id: number | bigint
111
+ authorized: boolean
112
+ }
113
+ [client.callback.SteamCallback.DownloadItemResult]: {
114
+ app_id: number
115
+ published_file_id: number | bigint
116
+ /** `null` when the item downloaded without error. */
117
+ error: SteamErrorName | null
118
+ }
119
+ [client.callback.SteamCallback.UserStatsReceived]: {
120
+ steam_id: bigint
121
+ game_id: number | bigint
122
+ result: SteamResult
123
+ }
124
+ [client.callback.SteamCallback.UserStatsStored]: {
125
+ game_id: number | bigint
126
+ result: SteamResult
127
+ }
128
+ [client.callback.SteamCallback.UserAchievementStored]: {
129
+ game_id: number | bigint
130
+ achievement_name: string
131
+ current_progress: number
132
+ max_progress: number
133
+ }
134
+ [client.callback.SteamCallback.GameOverlayActivated]: {
135
+ active: boolean
136
+ }
137
+ [client.callback.SteamCallback.GameRichPresenceJoinRequested]: {
138
+ friend_steam_id: bigint
139
+ connect: string
140
+ }
141
+ [client.callback.SteamCallback.LobbyEnter]: {
142
+ lobby: bigint
143
+ chat_permissions: number
144
+ blocked: boolean
145
+ chat_room_enter_response: ChatRoomEnterResponseName
146
+ }
147
+ [client.callback.SteamCallback.LobbyChatMsg]: {
148
+ lobby: bigint
149
+ user: bigint
150
+ chat_entry_type: ChatEntryTypeName
151
+ chat_id: number
152
+ }
153
+ /** Unit struct: serialises to `null`. */
154
+ [client.callback.SteamCallback.ScreenshotRequested]: null
155
+ [client.callback.SteamCallback.ScreenshotReady]: {
156
+ /** `{ Ok: handle }` with the library handle, or `{ Err: ... }` when the screenshot could not be saved. */
157
+ local_handle: { Ok: number } | { Err: 'Fail' | 'IoFailure' }
158
+ }
159
+ /** Unit struct: serialises to `null`. */
160
+ [client.callback.SteamCallback.NewUrlLaunchParameters]: null
161
+ [client.callback.SteamCallback.AuthSessionTicketResponse]: {
162
+ ticket: number
163
+ result: SteamResult
164
+ }
165
+ [client.callback.SteamCallback.ValidateAuthTicketResponse]: {
166
+ steam_id: bigint
167
+ response: { Ok: null } | { Err: AuthSessionValidateErrorName }
168
+ owner_steam_id: bigint
169
+ }
170
+ }