Skip to content

About

A steamworks implementation for nw.js/electron games

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

289 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status npm License: MIT

Steamworks.js (HagiCode fork)

Node.js and Electron bindings for the Steamworks SDK, maintained as a personal fork of ceifa/steamworks.js.

Introduction, guides and agent skills: https://steamworks.hagicode.com/

About this fork

This project is a fork of the upstream steamworks.js (Node/Electron bindings) and, through the vendor/steamworks-rs submodule, of steamworks-rs (the Rust bindings it is built on). The Rust side lives in HagiCode-org/steamworks-rs.

It exists for my own development work, not as a general replacement for upstream. It is shaped around two needs:

  • Working well with coding agents. The repository carries agent guidance (AGENTS.md), task-oriented skills for Steam Workshop work (steamworks-js/ and the steamworks-workshop-* folders), and a documentation site built from this README and those skills.
  • Covering the Steamworks features my projects use. Steam Workshop (UGC) is the most complete area: creating items of any file type, publishing and updating them (additional previews and videos, preview-only and content-only updates, metadata, key-value tags, content descriptors, known game versions, per-language titles and descriptions), item and app dependencies, and the logged-in user's votes, favorites and playtime tracking. Beyond Workshop it covers friends, stats and leaderboards, networking sockets/messages/utils, the server browser, timeline, screenshots and Remote Play.

What that means in practice:

  • The npm package is @hagicode/steamworks.js, not the unscoped steamworks.js, and it is released on its own schedule.
  • Changes follow what I need, so there is no promise of staying in step with upstream. If you want the general-purpose library, use upstream.
  • Upstream's history is kept. All credit for the original design and implementation goes to the upstream authors, and the MIT license with the original copyright notice (Gabriel Francisco Dos Santos) is kept in LICENSE. The Steamworks SDK files bundled through vendor/steamworks-rs are not covered by that license and remain under Valve's terms.

Bug reports and pull requests are still welcome. See CONTRIBUTING.md.

API

const steamworks = require('steamworks.js')

// You can pass an appId, or don't pass anything and use a steam_appid.txt file
const client = steamworks.init(480)

// Print Steam username
console.log(client.localplayer.getName())

// Tries to activate an achievement
if (client.achievement.activate('ACHIEVEMENT')) {
    // ...
}

You can refer to the declarations file to check the API support and get more detailed documentation of each function.

What is covered

Every namespace below is on the client returned by init(). Every function, with its parameters, return value and failure cases, is in the API reference, which is rendered from the JSDoc in client.d.ts. Most calls need a running, logged-in Steam client. Anything marked unverified has not been run against a live client yet.

Area Namespaces Where to read more
Steam Workshop (UGC) workshop The Workshop sections below, and the agent skills for publishing, updating, querying and client state
Friends and identity friends, localplayer, auth Friends; the API reference for the rest
Stats, achievements, leaderboards stats, achievement, leaderboard Stats, Achievements and Leaderboards
Networking networking, networkingSockets, networkingMessages, networkingUtils Networking
Servers, lobbies, Remote Play matchmaking, matchmakingServers, remotePlay Server Browser, Timeline, Screenshots and Remote Play; lobbies are in the API reference
Timeline and screenshots timeline, screenshots Same section
App, overlay, input, cloud, utilities apps, overlay, input, cloud, utils, callback Supplemental Functions; the API reference for the rest

What the Workshop namespace can do today:

  • Read: getItem, getItems, getAllItems, getUserItems, with additional previews, supported game versions and dependency links on request.
  • Create and update: createItem (any WorkshopFileType), updateItem and its preview-only and content-only helpers, with title and description per language, tags, visibility, metadata, key-value tags, content descriptors, screenshots, YouTube videos and game-version ranges.
  • Dependencies: required items (addDependency, removeDependency) and required apps (addAppDependency, removeAppDependency, getAppDependencies).
  • The logged-in user: subscribe, download and install info, votes, favorites and playtime tracking.

Not in scope: remote_storage publish and screenshots tagging

These two parts of the SDK are deliberately not wrapped. This section records the decision and its reasons, so the question is not reopened without new facts. The public API did not change for it: client.d.ts has no remote_storage publish function and no screenshots tagging function.

Feature Decision Checked in the code or SDK headers Reason Unverified
remote_storage publish (PublishWorkshopFile) Exclude The SDK header declares PublishWorkshopFile with the other remote storage calls. Nothing in this repository wraps or calls it. The UGC calls this binding already wraps (createItem, updateItem, the dependency and preview calls) cover publishing. A second publish route would need its own tests and skill. Whether Steam still accepts this route for current accounts.
Screenshots tagging (TagPublishedFile) Defer The header declares TagPublishedFile on ISteamScreenshots. The screenshots namespace only hooks the screenshot hotkey. The call needs a screenshot handle from the hooked hotkey flow. Without a use case in this repository, a wrapper would ship untested. Reopen it when a consumer needs it. Whether a tag call succeeds and shows on the item page. It needs a running client.

Recommendation: keep both out of the public API. When screenshots tagging is needed, start with a live check on a private test item.

Installation

To use steamworks.js you don't have to build anything, just install it from npm:

npm i @hagicode/steamworks.js

Guides and agent skills are on the documentation site at https://steamworks.hagicode.com/. To try the latest build from main, install the dev dist-tag: npm i @hagicode/steamworks.js@dev.

Migration from upstream steamworks.js

If you were using the unscoped upstream steamworks.js package and want this fork instead, update your package.json:

{
  "dependencies": {
    "@hagicode/steamworks.js": "latest"
  }
}

Then run pnpm install. Your require('steamworks.js') statements will continue to work without changes.

Electron

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:

const mainWindow = new BrowserWindow({
    // ...
    webPreferences: {
        // ...
        contextIsolation: false,
        nodeIntegration: true
    }
})

To make the steam overlay working, call the electronEnableSteamOverlay on the end of your main.js file:

require('steamworks.js').electronEnableSteamOverlay()

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.

How to build

You only need to build if you are going to change something on this fork's code. If you just want to use the library in your game, see the installation section.

Make sure you have the latest node.js, Rust and Clang. We also need Steam installed and running.

Cloning the repository

This project uses git submodules for the steamworks-rs dependency. When cloning the repository, use:

git clone --recurse-submodules https://github.com/HagiCode-org/steamworks.js.git

If you have already cloned the repository without submodules, initialize them with:

git submodule update --init --recursive

Building

Install dependencies with pnpm install and then run pnpm run build:debug to build the library.

There is no easy way to build for all targets locally, and you do not need to. Develop and test on your current target. When the code is merged to main, a GitHub Action builds every target and publishes a dev build.

Testing Electron

Go to the test/electron directory. There, you can run pnpm install and then pnpm start to run the Electron app.

Click "activate overlay" to test the overlay.

Contributing

Please see CONTRIBUTING.md for guidelines on commit conventions and the pull request process.

Workshop Screenshots (Additional Previews)

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):

const steamworks = require('steamworks.js')
const client = steamworks.init(appId)

// list: each entry has urlOrVideoId, originalFilename and previewType (ItemPreviewType)
const item = await client.workshop.getItem(itemId, { includeAdditionalPreviews: true })
console.log(item.additionalPreviews)

// add: appended to the item's screenshots; no content and no title change are sent
await client.workshop.updateItem(itemId, { additionalPreviewPaths: ['/abs/path/shot-2.png'] }, appId)

// remove: pass the 0-based indexes from `additionalPreviews`; the main preview is not affected
await client.workshop.updateItem(itemId, { removeAdditionalPreviewIndexes: [0, 2] }, appId)
  • 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.
  • Screenshots cannot be reordered through this API. The main preview is replaced with previewPath, not removed.
  • Steam lists screenshots by file name. Send only the files that are not listed yet, otherwise they are added again.
  • Adding screenshots needs a Steam client that is running and logged in, and an account that owns the app.

Workshop Preview and Content Updates

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:

const steamworks = require('steamworks.js')
const client = steamworks.init(appId)

// replace only the main preview image; the mod files are not uploaded
await client.workshop.updateItemPreview(itemId, '/abs/path/preview.png', appId, 'New preview')

// upload only the mod folder; the preview image is not touched
await client.workshop.updateItemContent(itemId, '/abs/path/mod-folder', appId, 'Fix crash on load')
  • Signature for both: (itemId, path, appId?, changeNote?). appId defaults to the app the client was initialized with, and changeNote is optional.
  • 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.
  • Title, description, tags and visibility are not sent, so they stay as they are. To change them together with a file, keep using updateItem.
  • Neither helper reports upload progress. For a large content upload use updateItemWithCallback.

Creating items and the new update fields

createItem(appId?, fileType?) creates an empty item. Without fileType it is a Community item, as before. The WorkshopFileType values are Community, Art, Screenshot, Video, Collection, WebGuide and IntegratedGuide.

updateItem accepts these optional fields. A field left out keeps the item's current value:

  • additionalPreviewVideos: YouTube video IDs, 11 characters each, not URLs. A malformed ID rejects with the entry named, before anything is sent. Whether Steam shows a video added this way is unverified until a live run.
  • metadata: a developer metadata string.
  • keyValueTags: { clear?, remove?, add? }, applied in the order clear, remove, add. add takes { key, value } pairs and remove takes keys.
  • contentDescriptors: { remove?, add? } of WorkshopContentDescriptor values, removals first. Only the five SDK values exist, so any other number is refused.
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
const { WorkshopFileType, WorkshopContentDescriptor } = client.workshop

const created = await client.workshop.createItem(appId, 1)  // 1 = WorkshopFileType.Art
await client.workshop.updateItem(created.itemId, {
  metadata: 'v2',
  keyValueTags: { clear: true, add: [{ key: 'mode', value: 'hard' }] },
  contentDescriptors: { add: [5] },                         // 5 = WorkshopContentDescriptor.AnyMatureContent
  additionalPreviewVideos: ['dQw4w9WgXcQ'],
}, appId)
  • Each of these calls changes the item on Steam. Confirm the item and the change first.
  • The typings expose no read for an item's metadata, key-value tags or content descriptors, so after a write only the Steam result code can be checked.
  • workshop.py upload sends --file-type and the YouTube videos listed in workshop.json. It does not send metadata, key-value tags or content descriptors; those are steamworks.js calls only.

Workshop Item Dependencies

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.

const steamworks = require('steamworks.js')
const client = steamworks.init(appId)

const modId = 123456789n        // your mod: an item owned by the logged-in account
const requiredId = 3836453389n  // the required child item (Outing Picker)

// mark the child as required by the mod
const added = await client.workshop.addDependency(modId, requiredId)
if (added !== 1) {
  console.error(`Steam refused the dependency, result code ${added}`)
}

// remove it again; the result code is returned the same way
const removed = await client.workshop.removeDependency(modId, requiredId)
  • Both calls need a running, logged-in Steam client, and the parent must be an item the logged-in account owns.
  • 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.

App dependencies

An item can also require an app, such as a DLC. addAppDependency(itemId, appId) and removeAppDependency(itemId, appId) resolve with the Steam result code, the same way as the item calls above.

getAppDependencies(itemId) resolves with { result, appIds, totalAppDependencies }. Steam sends the list in pages of up to 32, and the binding collects them until the reported total is reached. If appIds is shorter than totalAppDependencies, the list is incomplete. The paging follows the SDK header, and it is unverified against a live Steam client.

Workshop User Actions

These calls act for the logged-in user on Steam, so they change that user's state and not only the item. Each one resolves when Steam confirms it. getUserItemVote is the only one that reads.

const steamworks = require('steamworks.js')
const client = steamworks.init(appId)

await client.workshop.setUserItemVote(itemId, true)        // vote up; false votes down
const vote = await client.workshop.getUserItemVote(itemId) // { votedUp, votedDown, skipped }

await client.workshop.addItemToFavorites(itemId)           // appId defaults to the client's app
await client.workshop.removeItemFromFavorites(itemId)

await client.workshop.startPlaytimeTracking([itemId])      // the list must not be empty
await client.workshop.stopPlaytimeTracking([itemId])
  • Item ID 0, a negative id and an empty playtime list are refused before any Steam call.
  • Start and stop playtime tracking in pairs. The SDK header describes these calls as tracking the user's playtime for the listed items; that behavior is unverified against a live client.
  • These calls need a running, logged-in Steam client.

Workshop Known Game Versions

An item can declare the game versions (Steam branches such as open_beta or public) it is valid for. Every item returned by a query carries those ranges in supportedGameVersions, and updateItem changes them with requiredGameVersionMin and requiredGameVersionMax:

const steamworks = require('steamworks.js')
const client = steamworks.init(appId)

// read: one entry per range; an open end is left out (undefined)
const item = await client.workshop.getItem(itemId)
console.log(item.supportedGameVersions) // e.g. [{ minBranch: 'open_beta', maxBranch: 'open_beta' }, { minBranch: 'public' }]

// change: valid for open_beta and every branch published after it; the content is sent in the same update
await client.workshop.updateItem(itemId, {
  contentPath: '/abs/path/mod-folder',
  requiredGameVersionMin: 'open_beta',
  requiredGameVersionMax: '',
}, appId)
  • supportedGameVersions comes with items from getItem, getItems, getAllItems and getUserItems. It is an empty list when Steam returns no range for the item.
  • Both change fields are optional. Setting one changes that end, and the other end is left open. Leaving both out keeps the range as it is.
  • Pass both as "" to make the item valid for every game version again.
  • Steam applies the range only when the same update changes the item's content, so send contentPath with it. Otherwise Steam does not apply the range.
  • Changing the range needs a running, logged-in Steam client and an item the logged-in account owns.

Workshop Multilingual Support

Steamworks.js supports localized content for Steam Workshop items. You can update the title and description for different languages using the language parameter.

Basic Usage

// Update English content (backward compatible - no language specified)
await workshop.updateItem(itemId, {
  title: "My Mod",
  description: "English description"
});

// Update English content (explicitly)
await workshop.updateItem(itemId, {
  title: "My Mod",
  description: "English description",
  language: "english"
});

// Update Chinese content
await workshop.updateItem(itemId, {
  title: "我的模组",
  description: "中文描述",
  language: "schinese"
});

Multiple Languages

Since Steam API only supports updating one language at a time, you need to make multiple updateItem() calls for each language:

// Sequential updates
await workshop.updateItem(itemId, {
  title: "My Mod",
  description: "English description",
  language: "english"
});

await workshop.updateItem(itemId, {
  title: "Mon Mod",
  description: "Description française",
  language: "french"
});

await workshop.updateItem(itemId, {
  title: "Mi Mod",
  description: "Descripción en español",
  language: "spanish"
});

Or use Promise.all() for parallel updates:

await Promise.all([
  workshop.updateItem(itemId, {
    title: "Mein Mod",
    description: "Deutsche Beschreibung",
    language: "german"
  }),
  workshop.updateItem(itemId, {
    title: "私のMod",
    description: "日本語の説明",
    language: "japanese"
  }),
  workshop.updateItem(itemId, {
    title: "내 모드",
    description: "한국어 설명",
    language: "korean"
  })
]);

Supported Language Codes

Steam supports the following language codes:

Code Language Code Language
english English schinese Simplified Chinese
tchinese Traditional Chinese german German
french French italian Italian
korean Korean spanish Spanish
russian Russian thai Thai
japanese Japanese portuguese Portuguese
polish Polish danish Danish
dutch Dutch finnish Finnish
norwegian Norwegian swedish Swedish
hungarian Hungarian czech Czech
romanian Romanian turkish Turkish
brazilian Brazilian Portuguese bulgarian Bulgarian
greek Greek arabic Arabic
ukrainian Ukrainian vietnamese Vietnamese

Note: If language is omitted, it defaults to "english".

Friends

The friends namespace reads the local user's friend list, friend state and avatars, and sends game invites. SteamIDs are bigint values.

const steamworks = require('steamworks.js')
const client = steamworks.init(appId)

// 0x4 = immediate friends (FriendFlags.IMMEDIATE)
for (const friend of client.friends.getFriends(0x4)) {
  const state = client.friends.getFriendState(friend.steamId64)
  const avatar = client.friends.getMediumAvatar(friend.steamId64) // Buffer of RGBA pixels, or null
  console.log(friend.nickName ?? friend.name, state, avatar?.length ?? 0)
}

// Invite a friend to the current game with a connect string
client.friends.inviteUserToGame(friendSteamId, 'lobby=abc')

// Remove the Rich Presence keys set with localplayer.setRichPresence
client.friends.clearRichPresence()
  • getFriendState returns a FriendState value; getFriendGamePlayed returns the AppID of the game a friend is playing, or null.
  • 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.
  • Name and state updates arrive through runCallbacks(), which init() already calls on a timer.

Stats, Achievements and Leaderboards

stats gains float stats, the achievement count and a request for another user's stats. achievement gains global unlock percentages and the data an achievement page needs: display name, description, hidden flag, unlock time, progress limits and icon. The leaderboard namespace finds and creates leaderboards, uploads scores and downloads entries.

const steamworks = require('steamworks.js')
const client = steamworks.init(appId)

client.stats.setFloat('distance', 12.5)
console.log(client.stats.getFloat('distance')) // 12.5, or null when the stat is not defined
console.log(client.stats.getNumAchievements())

// Global unlock percentages: call the request first, then read each achievement
await client.achievement.requestGlobalPercentages()
console.log(client.achievement.getAchievedPercent('FIRST_RUN')) // 0 to 100, or null

// Leaderboards: 0 = Ascending, 0 = Numeric; upload with 0 = KeepBest, download with 0 = Global
const board = await client.leaderboard.findOrCreate('Fastest', 0, 0)
if (board) {
  const result = await board.uploadScore(0, 1234, [])   // null when Steam did not accept the upload
  const top = await board.downloadEntries(0, 0, 10, 0)  // ranks 0 to 9
  console.log(board.getName(), board.getEntryCount(), result, top)
}
  • requestUserStats(steamId64) only starts the request. Its result arrives through the UserStatsReceived callback (see callback.register).
  • 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.
  • 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.

Achievement display data

achievement.getAll() and achievement.getInfo(name) return what a client needs to list achievements. Call requestGlobalPercentages() first to fill globalPercent.

await client.achievement.requestGlobalPercentages()

for (const item of client.achievement.getAll()) {
  // item: { name, displayName?, description?, hidden?, unlocked, unlockTime?, globalPercent?, progressLimits? }
  const when = item.unlockTime === undefined ? null : new Date(item.unlockTime * 1000)
  console.log(item.displayName ?? item.name, item.unlocked, when, item.globalPercent)
}

// Icon as raw RGBA pixels; loadIcon waits for Steam to fetch it, getIcon does not
const icon = await client.achievement.loadIcon('FIRST_RUN', 3000) // { width, height, rgba: Buffer } or null
  • unlockTime is in seconds since 1970-01-01 UTC. It is left out for a locked achievement and for unlocks that Steam has no time for (Steam reports 0 for unlocks before December 2009).
  • displayName, description and hidden come from Steam's localized achievement data. They are left out when Steam has no data, for example before the user's stats have arrived.
  • getInfo returns null when Steam cannot read the achievement (unknown name, stats not received). That is a failed lookup, not a locked achievement. getAll skips such entries, so compare its length with stats.getNumAchievements().
  • names() returns an empty array when the app defines no achievements instead of throwing.
  • progressLimits (also getProgressLimits(name)) gives the min and max of the stat that Steam links to the achievement, or is left out when there is none. Steam's achievement API does not return the current value: read the linked stat with stats.getInt or stats.getFloat.
  • indicateProgress(name, current, max) shows the Steam overlay progress notice. It never unlocks the achievement.
  • getIcon and loadIcon return null while Steam has not fetched the icon and when the achievement has no icon. Steam picks the locked or unlocked artwork from the user's state. Convert the RGBA pixels to PNG on your side if you need a file.
  • Not verified against a live Steam client in this checkout: only the export list and the TypeScript declarations are tested offline.

Global stats, achievement ranking, utils and apps

stats gains other users' stats, global stats with daily history, average-rate stats and the current player count. achievement.getMostAchievedAchievements() returns the global ranking. leaderboard gains attachUgc and downloadEntriesForUsers. utils gains the Steam universe, IPv6 state, file signature check and text filter. apps gains DLC listing and install control, file details, timed trial, beta branches and proof-of-purchase keys.

const steamworks = require('steamworks.js')
const client = steamworks.init(appId)

// Global stats: request first, then read. int64 values are BigInts; history is newest day first
await client.stats.requestGlobalStats(7)
console.log(client.stats.getGlobalInt('total_kills'), client.stats.getGlobalIntHistory('total_kills', 7))

// Achievement ranking, most achieved first; needs requestGlobalPercentages() first
await client.achievement.requestGlobalPercentages()
console.log(client.achievement.getMostAchievedAchievements()) // [{ name, percent, achieved }]

// DLC and beta branches. installDlc and setActiveBeta change the local installation
const dlcs = client.apps.getDlcs()     // [{ appId, available, name }]
const betas = client.apps.getBetas()   // [{ name, description, buildId, flags, isDefault, isSelected, ... }]

// Text filter: initFilterText() first; 2 = Chat
client.utils.initFilterText()
const filtered = client.utils.filterText(2, 76561198000000000n, 'some chat text') // { text, filteredCount } or null
  • getUserInt and getUserFloat need requestUserStats(steamId64) to have completed for that user. They return null when the stat is missing or the user's stats are not loaded.
  • Promises from requestGlobalStats, getNumberOfCurrentPlayers, attachUgc, downloadEntriesForUsers, checkFileSignature and getFileDetails resolve when Steam answers. That happens inside runCallbacks(), which init() runs about 30 times a second. A Promise rejects with a readable message when Steam reports an error.
  • requestGlobalStats(days) accepts at most 60 days, and the global history getters return null above that. The global getters return null until the request completes.
  • updateAvgRateStat changes the local stats. Nothing reaches Steam until stats.store(). Steam keeps the count as a 32-bit float.
  • downloadEntriesForUsers takes at most 100 SteamIDs; more are rejected before Steam is called. attachUgc changes the user's leaderboard data on Steam.
  • installDlc, uninstallDlc, markContentCorrupt and setActiveBeta change the local installation. setDlcContext only tells Steam which DLC is being played.
  • requestProofOfPurchaseKey and requestAllProofOfPurchaseKeys answer through the AppProofOfPurchaseKeyResponse callback (callback.register). The final callback of the full request has appId 0. The keys are secrets: do not log them.
  • Units: getEarliestPurchaseUnixTime is seconds since 1970-01-01 UTC. getDlcDownloadProgress and getFileDetails report bytes as BigInts. getFileDetails().sha1 is 40 lowercase hex characters. getSecondsSinceAppActive and getSecondsSinceComputerActive are seconds. getCurrentBatteryPower is a percentage, and 255 means AC power.
  • Sync calls return null or false on failure and do not throw. The SDK header does not say what getEarliestPurchaseUnixTime returns without a purchase, and does not define the available flag of a DLC or the flags of getFileDetails.
  • Not verified against a live Steam client: all of the above. Only the export list and the TypeScript types are tested offline.

Inventory

client.inventory reads and changes the user's Steam Inventory: item instances, item definitions, promotions, prices and purchases. Most calls resolve once Steam has answered.

const { items, timestamp, expired } = await client.inventory.getAllItems()
for (const item of items) {
  // item: { itemId: bigint, definition: number, quantity: number, flags: number }
  console.log(item.itemId, item.definition, item.quantity)
}

// Changes the real inventory: ask the user before you call this
const { items: changed } = await client.inventory.consumeItem(items[0].itemId, 1)

// Items another player sent: null when Steam rejects the buffer or it belongs to someone else
const verified = client.inventory.deserializeResult(received, senderSteamId)

// Property changes are one batch: set what you need, then submit once
const update = client.inventory.startUpdateProperties()
update?.setInt64(items[0].itemId, 'level', 3n)
await update?.submit()
  • Each Promise resolves when Steam's SteamInventoryResultReady_t callback arrives. Steam delivers that callback inside runCallbacks(), which init() runs on a timer. Every async function takes an optional timeoutMs (default 30000).
  • A Promise rejects with a readable message when Steam reports an error. When no answer arrives within timeoutMs, the message says the outcome is unknown: the change may still have happened, so check the inventory before you retry.
  • Functions that grant, create, consume, exchange, trade, buy or submit property changes change the user's real inventory. Ask the user to confirm before you call them.
  • Item instance ids, Steam ids and prices are bigint, because they can exceed 2^53. definition, quantity and flags are number. Prices are in the smallest unit of the currency that requestPrices() reports.
  • expired: true means Steam may have changed the result since it was made, for example because an item was traded or consumed. The items are still returned.
  • serializeItems(itemIds) returns a Buffer. Steam marks a serialized result expired after one hour. deserializeResult(data, steamId) is synchronous and returns null on failure, so pass the Steam id of the player who sent the buffer.
  • loadItemDefinitions() only starts the load. This binding does not expose Steam's definition-update callback, so it cannot tell you when the definitions are complete. getItemDefinitions() can return an incomplete list until then.
  • startPurchase() resolves when Steam opens the transaction. The user completes the purchase in the Steam overlay, and the final result arrives later through Steam's result-ready callback, not through this Promise.
  • tradeItems() and sendItemDropHeartbeat() are deprecated by Steam. The SDK documents trading as not supported, so tradeItems() is expected to reject.
  • Not verified against a live Steam client: no call was made against a Steam account in this checkout. Only the export list, the TypeScript declarations and the pure conversion code are tested offline.

User, user-file and UGC calls (localplayer, auth, cloud)

  • localplayer adds the ISteamUser calls that were missing: getHSteamUser(), trackAppUsageEvent(), getUserDataFolder(), the voice calls (startVoiceRecording(), stopVoiceRecording(), getAvailableVoice(), getVoice(), decompressVoice(), getVoiceOptimalSampleRate()), isBehindNat(), advertiseGame(), getGameBadgeLevel(), the phone and two-factor checks, getMarketEligibility(), getDurationControl() and setDurationControlOnlineState().
  • auth adds requestEncryptedAppTicket(), getEncryptedAppTicket() and requestStoreAuthUrl(). The encrypted ticket is requested first, then read; getEncryptedAppTicket() does not call Steam.
  • cloud adds the user-file calls getQuota(), writeFileAsync(), openWriteStream() (a FileWriteStream with writeChunk(), close() and cancel()), beginFileWriteBatch(), endFileWriteBatch() and getLocalFileChanges().
  • cloud also adds the UGC calls downloadUgc(), downloadUgcToLocation(), getUgcDownloadProgress(), getUgcDetails(), readUgc(), getCachedUgcCount() and getCachedUgcHandle().
  • Steam ids and UGC handles are bigint. A negative id or one of 2^64 or more is rejected before anything is sent. Results that Steam can leave empty come back as null.
  • Async functions resolve through runCallbacks(), which init() already calls. There is no timeout: if Steam never answers, the Promise stays pending. For writeFileAsync() and the downloadUgc*() calls, the outcome is then unknown.
  • writeFileAsync() and FileWriteStream.close() change the user's cloud files, and downloadUgc*() starts network transfers. Ask the user to confirm before you call them.
  • A FileWriteStream that is garbage-collected without close() or cancel() is closed by the wrapper, which commits the chunks written so far. When that happens depends on the garbage collector, so call close() or cancel() yourself.
  • The legacy Workshop publishing calls of ISteamRemoteStorage are not exposed; ISteamUGC replaces them (see the workshop namespace).
  • Not verified against a live Steam client: no call was made against a Steam account in this checkout. Only the export list, the TypeScript declarations and the argument checks that run before any Steam call are tested offline.

ISteamFriends: groups, clans, clan chat, follows and profile items

The friends namespace also covers the rest of ISteamFriends: friends groups, clans and clan officers, clan and friend chat, follower counts, equipped profile items, rich presence reads and clan activity counts. This example shows one call of each kind.

const steamworks = require('steamworks.js')
const client = steamworks.init(appId)

// A cache read: no Steam request. Each group lists its members as SteamID64 bigints.
for (const group of client.friends.getFriendGroups()) {
  console.log(group.name, group.members.length)
}

async function readClanChat(clanChatId) {
  // 1 = ChatRoomEnterResponse.Success; other values are Steam's failure reasons
  if ((await client.friends.joinClanChatRoom(clanChatId)) !== 1) return null
  return client.friends.getClanChatMessage(clanChatId, 0) // ChatMessage or null
}

async function readFollowing() {
  // One page of the following list, up to 50 SteamIDs per page
  const page = await client.friends.enumerateFollowingList(0)
  console.log(page.steamIds.length, page.totalCount)
}
  • Units: SteamIDs and clan chat ids are bigint. Indexes, counts and totalCount are number. enumerateFollowingList(startIndex) returns at most 50 SteamIDs per page, the SDK's k_cEnumerateFollowersMax limit.
  • Cache reads (getFriendGroups(), getClans(), getFriendRichPresence(), getProfileItemPropertyString()) answer from data that Steam already holds. Without that data they return null, 0 or an empty list. Request it first: requestFriendRichPresence() (the FriendRichPresenceUpdate callback follows), and the Promises of requestEquippedProfileItems(), downloadClanActivityCounts(), requestClanOfficerList() and getClanInfo().
  • The Promise calls (joinClanChatRoom(), getFollowerCount(), isFollowing(), enumerateFollowingList(), requestEquippedProfileItems(), getClanInfo(), downloadClanActivityCounts(), requestClanOfficerList()) resolve through runCallbacks(), which init() already calls. They reject with Steam's error text when Steam reports a failure. There is no timeout: a call that Steam never answers stays pending.
  • joinClanChatRoom() resolves with a ChatRoomEnterResponse. Only 1 (Success) means the room was joined. Values 2 to 12 are the SDK's failure reasons.
  • Chat messages arrive as callbacks. Register GameConnectedFriendChatMsg, GameConnectedClanChatMsg, GameConnectedChatJoin and GameConnectedChatLeave with callback.register(), and call setListenForFriendsMessages(true) before you expect friend messages. The callbacks fire only from runCallbacks().
  • getClanChatMessage(clanChatId, index) and getFriendMessage(steamId, index) return a ChatMessage or null. sendClanChatMessage() and replyToFriendMessage() return a boolean, which is true only when Steam accepts the message. Not verified: the order of the message index and what Steam returns for an index past the end.
  • Not verified against a live Steam client: no call was made against a Steam account in this checkout. Also unverified: a clan's name before its download, a friend's Steam level before Steam loads it, the value of an empty rich presence key, and what registerProtocolInOverlayBrowser() does in the overlay. The export list, the TypeScript declarations, the enum values and the callback numbers are tested offline.

Steam HTTP (http)

Sends HTTP requests through the Steam client. It needs init() and a running, logged-in Steam client.

const client = steamworks.init(480)
const response = await client.http.request({
    method: 'GET',
    url: 'https://example.com/api/items',
    query: { page: '1' },
    headers: { Accept: 'application/json' },
    responseHeaders: ['ETag'],
    timeoutMs: 10000,
})
console.log(response.status, response.headers.ETag, response.body.toString('utf8'))
  • request() resolves for every answer the server gives, including 404 and 500, so check status yourself. It rejects when the request cannot be created or sent, when Steam refuses a header or option, when Steam cannot complete the request, when no answer comes, or when the request times out.
  • Units: timeoutMs is a total time limit in milliseconds. Unlike the inactivity timeout, it does not reset when data arrives. Steam's default is no total limit.
  • Methods: GET, HEAD, POST, PUT, DELETE, OPTIONS and PATCH, in any letter case. query is added to the URL for GET and sent as form data for other methods. form is sent as form data. body (a Buffer) needs a method that accepts a body, cannot be combined with form or query, and uses contentType (default application/octet-stream).
  • responseHeaders names the response headers to return. Steam cannot list all of them, so name each one you need. The response has no status text, because the SDK does not provide one.
  • Cookies: client.http.createCookieContainer(allowResponsesToModify) makes a container that lasts for this process only. Pass it as cookieContainer and add cookies with setCookie(host, url, cookie).
  • The promise resolves through runCallbacks(), which init() already calls.
  • Not verified against a live Steam client: how HTTPS certificates are checked against a browser's rules, and what requireVerifiedCertificate: false does.

Networking utilities (networkingUtils)

Ping locations, data centers (POPs), fake IP addresses and config values. These functions need init(). Reads that Steam cannot answer yet return null.

const client = steamworks.init(480)
client.networkingUtils.initRelayNetworkAccess()
// Ping data takes a few seconds to appear after relay access starts.
const here = client.networkingUtils.getLocalPingLocation()
const pops = client.networkingUtils.getPops() // id, code (for example 'iad') and ping for each data center
const ms = here ? client.networkingUtils.estimatePingFromLocalHost(here.location) : null
  • getLocalPingLocation() returns { location, ageSeconds }, or null when Steam has no ping data yet. Pass location only to the functions in this namespace, and do not parse it yourself.
  • Units: pings are milliseconds, ages are seconds, and getLocalTimestamp() returns microseconds as a bigint. That timestamp is comparable only within one run of the process.
  • estimatePingFromLocalHost() and estimatePingBetweenLocations() return null when Steam cannot estimate, and throw when a location text is not understood.
  • checkPingDataUpToDate(maxAgeSeconds) returns false when the data is older than that, and Steam then starts a new measurement. Call it only when you need fresh data now, because Steam refreshes the data on its own.
  • getRealIdentityForFakeIp() throws with Steam's reason when the address is not a fake IP (InvalidParameter) or the mapping is unknown (NoMatch). Steam keeps the mapping for active connections and for a short time after they close.
  • Config values: the setGlobalConfigValue* and setConnectionConfigValue* functions return true when Steam accepts the value and false when it refuses it. Connection functions take the raw connection handle as a number. The Connection object does not expose that handle yet. getConfigValue(valueId, connection?) returns a number for int32 and float values, a bigint for int64 values, a string for string values, or null. Use getConfigValueInfo() for a value's name, type and scope, and iterateGenericEditableConfigValues() to list the value numbers.
  • Not in this binding: SetDebugOutputFunction, the SetGlobalCallback_* functions, SetGlobalConfigValuePtr, and SetConfigValue/SetConfigValueStruct. They need C function pointers or void* arguments.
  • Not verified against a live Steam client: the byte order of IPv4 numbers in isFakeIpv4() and getIpv4FakeIpType(), when ping data first appears, and whether every data center reports a code.

Timeline additions (timeline)

Event handles and game phases on the Steam timeline. These functions need init(). If the Steam client does not provide the timeline, the functions that change it do nothing.

const client = steamworks.init(480)
const { TimelineEventClipPriority } = client.timeline
const event = client.timeline.startRangeTimelineEvent('Boss fight', 'Round 1', 'steam_victory', 0, 0, TimelineEventClipPriority.Featured)
if (event !== null) client.timeline.endRangeTimelineEvent(event, 0)
client.timeline.setGamePhaseId('chapter-1')
const answer = await client.timeline.doesGamePhaseRecordingExist('chapter-1')
  • Event handles are bigint values, and null means the timeline is unavailable. A handle is valid only in this run of the game. Passing a value that is not a handle from this API throws.
  • Units: offsets and durations are seconds, measured from now. Negative offsets are in the past. recordingMs and longestClipMs are milliseconds.
  • A range event must be ended with endRangeTimelineEvent(). Steam discards range events that are still open when the game exits.
  • doesEventRecordingExist() and doesGamePhaseRecordingExist() return promises. They resolve during runCallbacks() and reject when the timeline is unavailable or Steam cannot answer.
  • A phase ID is at most 63 bytes and must not contain a NUL character. Calls with a longer ID throw.
  • clipPriority is None, Standard or Featured.
  • Not verified against a live Steam client: what the overlay shows for openOverlayToGamePhase() and openOverlayToTimelineEvent(), and how the timeline behaves on Steam clients that do not support it.

Networking: networking and the New Namespaces

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.

  • 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.
  • 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.
  • 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.
  • networkingUtils starts relay network access and reports its availability.
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)

// Relay access and authentication: start them early if you expect relayed or authenticated connections
client.networkingUtils.initRelayNetworkAccess()
console.log(client.networkingUtils.getRelayNetworkStatus()) // NetworkingAvailability value
client.networkingSockets.initAuthentication()

// Host: poll the listen socket without waiting, accept connecting peers and take the connection when it is connected
const listen = client.networkingSockets.createListenSocketIp('0.0.0.0:27015')
const event = listen.tryReceiveEvent() // null when nothing is pending
if (event && event.kind === 0 /* Connecting */) {
  event.accept()
}
if (event && event.kind === 1 /* Connected */) {
  const connection = event.takeConnection()
  connection.send(Buffer.from('hello'), 8) // 8 = reliable
  console.log(connection.receive(16))
}

// Client: connect by IP address, then close with a reason
const connection = client.networkingSockets.connectByIpAddress('203.0.113.5:27015')
connection.setUserData(1n)
connection.close(1000, 'done', true)

// Messages: accept requests from Steam users and read channel 3
client.networkingMessages.onSessionRequest((request) => request.accept())
client.networkingMessages.sendMessageToUser(friendSteamId, 8, Buffer.from('hi'), 3)
console.log(client.networkingMessages.receiveMessagesOnChannel(3, 10))
  • 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.
  • Listen socket events and session requests are only produced while runCallbacks() runs. init() already calls it about 30 times a second.
  • A connection or request you never close or answer is closed or rejected when its JavaScript object is garbage collected. Close connections explicitly.
  • 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.

Server Browser, Timeline, Screenshots and Remote Play

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.

const steamworks = require('steamworks.js')
const client = steamworks.init(appId)

// Server list: request, read, then release it
const list = client.matchmakingServers.lanServerList(appId)
try {
  for (let i = 0; i < list.getServerCount(); i++) {
    const server = list.getServerDetails(i) // ip, port, name, map, players, maxPlayers, ping
    console.log(server.name, server.players, server.maxPlayers, server.ping)
  }
} finally {
  list.release()
}

// Single server: these are Promises and reject when the server does not answer
const ping = await client.matchmakingServers.pingServer('192.168.1.10', 27015)
const players = await client.matchmakingServers.playerDetails('192.168.1.10', 27015)
const rules = await client.matchmakingServers.serverRules('192.168.1.10', 27015)

// Timeline: 0 = Playing (the game mode values are Playing, Staging, Menus, LoadingScreen)
client.timeline.setGameMode(0)
client.timeline.addEvent('icon', 'Boss defeated', '', 0, -5, 5, 1) // clip priority 1 = Standard

// Screenshots: with the hook on, the hotkey raises ScreenshotRequested instead of Steam taking the picture
client.screenshots.hookScreenshots(true)
client.screenshots.triggerScreenshot()

// Remote Play Together
for (const session of client.remotePlay.sessions()) {
  console.log(session.sessionId, session.steamId64, client.remotePlay.sessionDetails(session.sessionId))
}
client.remotePlay.invite(friendSteamId)
  • 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.
  • Release every server list request when you finish with it. Methods called after release() throw a readable error.
  • Invalid IPv4 addresses, negative durations and strings with NUL characters are rejected with a readable error before any Steam call.
  • timeline calls are silent when the Steam timeline interface is unavailable.

Supplemental Functions

These functions extend existing namespaces. Nothing that existed before has changed.

const client = steamworks.init(appId)

// apps: the launch command line, and a query parameter from a Steam link such as steam://run/480//mode=demo
client.apps.launchCommandLine()
client.apps.launchQueryParam('mode') // '' when the parameter is absent

// utils: overlay and UI state
client.utils.isOverlayEnabled()
client.utils.isSteamInBigPictureMode()
client.utils.getUiLanguage() // for example 'english'

// input: digital and analog action data, and the origins bound to an action
const pressed = client.input.getDigitalActionData(controllerHandle, actionHandle).state
const stick = client.input.getAnalogActionData(controllerHandle, analogHandle) // { x, y, active }
const origins = client.input.getDigitalActionOrigins(controllerHandle, actionSetHandle, actionHandle)
const label = client.input.getStringForActionOrigin(origins[0] ?? 0)

// networking: P2P packets on a channel, and closing a session
client.networking.sendP2PPacketOnChannel(friendSteamId, SendType.Reliable, Buffer.from('hi'), 2)
client.networking.isP2PPacketAvailableOnChannel(2)
client.networking.closeP2PSession(friendSteamId)

// cloud: share a file (a Promise), stop syncing it, and choose the platforms it syncs to
const shareHandle = await client.cloud.shareFile('save.json')
client.cloud.forgetFile('save.json')
client.cloud.setSyncPlatforms('save.json', 0 /* SyncPlatform.None */)
  • getStringForActionOrigin and getGlyphForActionOrigin return an empty string for an origin number that Steam does not define.
  • getSyncPlatforms rejects when a file syncs to a combination of platforms, because a single SyncPlatform value cannot describe it.
  • shareFile resolves once Steam answers, which happens through runCallbacks(). init() runs it for you.

Release Process

This fork has its own release line and publishes to npm as @hagicode/steamworks.js. It does not follow upstream's release numbers. Releases are automated:

  • Dev builds: Every push to the main branch publishes a build to the npm dev dist-tag for testing
  • Release drafts: Every push to main updates one draft GitHub release for the next vX.Y.Z, drafted by hagi-release-drafter. It is never published automatically
  • Official releases: Publish the draft in the GitHub UI. That creates the vX.Y.Z tag, and the tag publishes the npm latest version

Release notes are automatically generated from Conventional Commit messages. See CONTRIBUTING.md for the commit message format.

About

A steamworks implementation for nw.js/electron games

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages