Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(build): Steam as a channel on the desktop target

esengine745bf17dcc8f
diff --git a/build-tools/tests/verify-vdf.py b/build-tools/tests/verify-vdf.py
new file mode 100644
index 000000000..78c626e04
--- /dev/null
+++ b/build-tools/tests/verify-vdf.py
@@ -0,0 +1,163 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+# SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+"""A second implementation of Valve's KeyValues reader, for checking ours.
+
+The writer in build-tools/utils/vdf.js has one real consumer, steamcmd, and
+steamcmd needs a Steam account to run — so it cannot be the check. This parser is
+written from the format instead: quoted tokens, brace-nested sections, backslash
+escapes. Nothing here imports the writer, which is the point.
+
+ python3 verify-vdf.py <file.vdf> [--expect key=value ...]
+
+Exits non-zero with a reason. Also asserts what a SteamPipe script must be true
+of, since a syntactically fine script that uploads the wrong tree is the failure
+that matters:
+
+ * an AppBuild names every depot script it lists, and they exist beside it;
+ * Preview is on (an upload nobody asked for is not recoverable by uploading
+ again), unless --allow-live says the caller meant it;
+ * every FileMapping is anchored — a LocalPath of "*" at a content root that
+ also holds loose files would upload them all.
+"""
+import sys
+import os
+
+
+def tokenize(text):
+ i, n = 0, len(text)
+ while i < n:
+ c = text[i]
+ if c in ' \t\r\n':
+ i += 1
+ continue
+ if c == '/' and i + 1 < n and text[i + 1] == '/':
+ while i < n and text[i] != '\n':
+ i += 1
+ continue
+ if c in '{}':
+ yield c
+ i += 1
+ continue
+ if c == '"':
+ i += 1
+ out = []
+ while i < n and text[i] != '"':
+ if text[i] == '\\' and i + 1 < n:
+ nxt = text[i + 1]
+ out.append({'n': '\n', 't': '\t'}.get(nxt, nxt))
+ i += 2
+ continue
+ out.append(text[i])
+ i += 1
+ if i >= n:
+ raise ValueError('unterminated quoted token')
+ i += 1
+ yield ('str', ''.join(out))
+ continue
+ start = i
+ while i < n and text[i] not in ' \t\r\n{}"':
+ i += 1
+ yield ('str', text[start:i])
+
+
+def parse(text):
+ tokens = list(tokenize(text))
+ pos = 0
+
+ def value():
+ nonlocal pos
+ tok = tokens[pos]
+ if tok == '{':
+ pos += 1
+ section = {}
+ while tokens[pos] != '}':
+ key = tokens[pos]
+ if not isinstance(key, tuple):
+ raise ValueError(f'expected a key, got {key!r}')
+ pos += 1
+ section[key[1]] = value()
+ pos += 1
+ return section
+ pos += 1
+ return tok[1]
+
+ doc = {}
+ while pos < len(tokens):
+ key = tokens[pos]
+ if not isinstance(key, tuple):
+ raise ValueError(f'expected a key at top level, got {key!r}')
+ pos += 1
+ doc[key[1]] = value()
+ return doc
+
+
+def fail(message):
+ print(f'verify-vdf: {message}')
+ sys.exit(1)
+
+
+def main(argv):
+ if not argv:
+ fail('usage: verify-vdf.py <file.vdf> [--expect key=value ...] [--allow-live]')
+ path = argv[0]
+ expects = [a.split('=', 1) for a in argv[1:] if a.startswith('--expect=') is False and '=' in a]
+ allow_live = '--allow-live' in argv
+
+ with open(path, 'r', encoding='utf-8') as handle:
+ doc = parse(handle.read())
+
+ if len(doc) != 1:
+ fail(f'expected exactly one root section, got {list(doc)}')
+ root_key, root = next(iter(doc.items()))
+ if not isinstance(root, dict):
+ fail(f'root {root_key!r} is not a section')
+
+ for key, want in expects:
+ got = root
+ for part in key.split('.'):
+ if not isinstance(got, dict) or part not in got:
+ fail(f'{key} is missing')
+ got = got[part]
+ if str(got) != want:
+ fail(f'{key} is {got!r}, expected {want!r}')
+
+ if root_key == 'AppBuild':
+ if not allow_live and root.get('Preview') != '1':
+ fail('AppBuild has Preview off — an upload that goes live cannot be taken back')
+ if root.get('SetLive'):
+ fail(f'AppBuild sets a live branch ({root["SetLive"]!r}); publishing is a separate decision')
+ depots = root.get('Depots')
+ if not isinstance(depots, dict) or not depots:
+ fail('AppBuild lists no depots')
+ for depot_id, script in depots.items():
+ beside = os.path.join(os.path.dirname(os.path.abspath(path)), script)
+ if not os.path.exists(beside):
+ fail(f'depot {depot_id} names {script}, which is not there')
+ with open(beside, 'r', encoding='utf-8') as handle:
+ sub = parse(handle.read())
+ config = sub.get('DepotBuildConfig')
+ if not isinstance(config, dict):
+ fail(f'{script} is not a DepotBuildConfig')
+ if config.get('DepotID') != depot_id:
+ fail(f'{script} says DepotID {config.get("DepotID")!r}, listed as {depot_id!r}')
+
+ if root_key == 'DepotBuildConfig':
+ mapping = root.get('FileMapping')
+ if not isinstance(mapping, dict):
+ fail('DepotBuildConfig has no FileMapping')
+ local = mapping.get('LocalPath', '')
+ root_dir = root.get('ContentRoot', '')
+ if local == '*' and root_dir:
+ loose = [e for e in os.listdir(root_dir)
+ if os.path.isfile(os.path.join(root_dir, e))]
+ if loose:
+ fail(f'LocalPath "*" over a content root holding loose files ({loose[:3]}) '
+ 'would upload them')
+
+ print(f'verify-vdf: {os.path.basename(path)} parses as {root_key} and holds together.')
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv[1:]))
diff --git a/build-tools/utils/steamChannel.d.ts b/build-tools/utils/steamChannel.d.ts
new file mode 100644
index 000000000..cf4a42c98
--- /dev/null
+++ b/build-tools/utils/steamChannel.d.ts
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Types for steamChannel.js, which is plain ESM so the CLI runs it unbuilt.
+
+export const STEAM_DIR: string;
+
+/** `appId + 1 + index` — the usual shape of what Valve assigns, never a fact. */
+export function defaultDepotId(appId: number, index: number): number;
+
+export function emitSteamBuild(options: {
+ /** The export directory, which is also the depot's content root. */
+ outDir: string;
+ appId: number;
+ /** Names the executable a depot maps and Steam launches. */
+ appName: string;
+ depots: { os: string; depotId: number }[];
+ description?: string;
+}): Promise<{ scripts: string[]; checklist: string }>;
diff --git a/build-tools/utils/steamChannel.js b/build-tools/utils/steamChannel.js
new file mode 100644
index 000000000..be050e306
--- /dev/null
+++ b/build-tools/utils/steamChannel.js
@@ -0,0 +1,166 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Steam as a CHANNEL on the desktop target: the depot scripts SteamPipe
+ * takes, and the values only the partner backend can be told.
+ *
+ * Not a platform (docs/REARCH_STEAM.md §1). Steam defines no runtime, no renderer
+ * and no asset format — it defines where a desktop build goes. A second channel
+ * (itch, a direct download) would be a sibling of this file, not a fork of the
+ * export.
+ */
+
+import path from 'path';
+import { mkdir, writeFile } from 'fs/promises';
+import { writeVdf } from './vdf.js';
+
+/** Where the scripts and steamcmd's own output live, inside the export. */
+export const STEAM_DIR = 'steam';
+
+/**
+ * Where each OS keeps save data: as SDL_GetPrefPath answers it (see
+ * native/host/platform/desktop.cpp) and as Auto-Cloud spells the same place.
+ *
+ * They have to agree or the cloud syncs nothing, and neither can be read off the
+ * other, so both are written here.
+ */
+const CLOUD_ROOTS = {
+ macos: { root: 'MacHome', prefix: 'Library/Application Support/Estella' },
+ windows: { root: 'WinAppDataRoaming', prefix: 'Estella' },
+ linux: { root: 'LinuxHome', prefix: '.local/share/Estella' },
+};
+
+/** What Steam launches, per OS, relative to the depot root. */
+function launchTarget(os, appName) {
+ if (os === 'macos') return `${appName}.app`;
+ return os === 'windows' ? `${appName}.exe` : appName;
+}
+
+/** What the depot takes from the export directory. Everything else that is there
+ * — the loose cooked content the app already carries — is excluded by not being
+ * mapped, rather than by a rule someone has to maintain. */
+function depotMapping(os, appName) {
+ const target = launchTarget(os, appName);
+ return os === 'macos'
+ ? { LocalPath: `${target}/*`, DepotPath: `${target}/`, recursive: '1' }
+ : { LocalPath: '*', DepotPath: '.', recursive: '1' };
+}
+
+/**
+ * The depot id an OS gets when the project has not been told the real ones.
+ *
+ * Valve ASSIGNS depot ids; appid+1, appid+2 is only the usual shape of what it
+ * assigns. So this is a starting point that the checklist tells you to check,
+ * never a fact — an upload to a depot that is not yours simply fails.
+ */
+export function defaultDepotId(appId, index) {
+ return appId + 1 + index;
+}
+
+/**
+ * Write the SteamPipe build scripts and the checklist for @p oses.
+ *
+ * @param {object} options
+ * @param {string} options.outDir The export directory; also the content root.
+ * @param {number} options.appId The Steam application id.
+ * @param {string} options.appName The app's name, which names its executable.
+ * @param {{os: string, depotId: number}[]} options.depots
+ * @param {string} [options.description] Build description shown in the backend.
+ * @returns {Promise<{scripts: string[], checklist: string}>}
+ */
+export async function emitSteamBuild(options) {
+ const { outDir, appId, appName, depots } = options;
+ const steamDir = path.join(outDir, STEAM_DIR);
+ await mkdir(path.join(steamDir, 'output'), { recursive: true });
+
+ const scripts = [];
+ const depotEntries = {};
+ for (const { os, depotId } of depots) {
+ const file = `depot_${depotId}_${os}.vdf`;
+ await writeFile(path.join(steamDir, file), writeVdf('DepotBuildConfig', {
+ DepotID: String(depotId),
+ ContentRoot: outDir,
+ FileMapping: depotMapping(os, appName),
+ }));
+ scripts.push(path.join(steamDir, file));
+ depotEntries[String(depotId)] = file;
+ }
+
+ const appFile = path.join(steamDir, `app_build_${appId}.vdf`);
+ await writeFile(appFile, writeVdf('AppBuild', {
+ AppID: String(appId),
+ Desc: options.description || `${appName} — built by Estella`,
+ // A first run must not be able to publish. Uploading and going live are
+ // two decisions, and only one of them can be undone by uploading again.
+ Preview: '1',
+ SetLive: '',
+ ContentRoot: outDir,
+ BuildOutput: path.join(steamDir, 'output'),
+ Depots: depotEntries,
+ }));
+ scripts.push(appFile);
+
+ const checklist = path.join(outDir, 'STEAM.md');
+ await writeFile(checklist, checklistFor({ appId, appName, depots, appFile }));
+ return { scripts, checklist };
+}
+
+/**
+ * The build's own values, for the settings only the partner backend holds.
+ *
+ * Generic instructions belong in the docs; what cannot be looked up is what THIS
+ * build needs pasted where — the launch string, the depot ids, the cloud path.
+ */
+function checklistFor({ appId, appName, depots, appFile }) {
+ const rows = depots.map(({ os, depotId }) =>
+ `| ${os} | \`${depotId}\` | \`${launchTarget(os, appName)}\` |`).join('\n');
+ const cloud = depots.map(({ os }) => {
+ const c = CLOUD_ROOTS[os];
+ return `| ${os} | \`${c.root}\` | \`${c.prefix}/${appName}\` | \`*\` |`;
+ }).join('\n');
+
+ return `# Publishing ${appName} on Steam
+
+Everything here lives in the partner backend, which no build can write to. These
+are this build's values.
+
+## App and depots
+
+| OS | Depot ID | Launch executable |
+|---|---|---|
+${rows}
+
+The depot ids above are a guess (\`appid + 1\`, …). Valve ASSIGNS them — check
+them against **SteamPipe → Depots** and set \`packaging.platforms.desktop.steam.depots\`
+if they differ. An upload to a depot that is not yours fails rather than going
+somewhere wrong.
+
+## Cloud saves
+
+The game writes its saves where the OS says it should, which is a path Steam
+Auto-Cloud can sync with no code in the game. Under **Steam Cloud → Auto-Cloud**:
+
+| OS | Root | Subdirectory | Pattern |
+|---|---|---|---|
+${cloud}
+
+## Upload
+
+ steamcmd +login <your-account> +run_app_build "${appFile}" +quit
+
+Log in once interactively first (\`steamcmd +login <your-account>\`) so Steam Guard
+is satisfied and cached; nothing here stores a password.
+
+The script is written with \`Preview "1"\`, so the first run uploads NOTHING — it
+reports what it would do. Remove it to upload for real. \`SetLive\` is deliberately
+empty: publishing to a branch is a separate decision, made in the backend.
+
+## Before you ship
+
+- \`steam_appid.txt\` is **not** in the depot, and this export never writes one.
+ It exists only to run a build outside Steam; shipping it disables the check
+ that the game was launched by Steam.
+- The macOS app is signed ad-hoc. Notarize it with your own Developer ID before
+ a public release.
+`;
+}
diff --git a/build-tools/utils/vdf.d.ts b/build-tools/utils/vdf.d.ts
new file mode 100644
index 000000000..bfac955a4
--- /dev/null
+++ b/build-tools/utils/vdf.d.ts
@@ -0,0 +1,7 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Types for vdf.js, which is plain ESM so the CLI runs it unbuilt.
+
+/** Serialize `value` as Valve KeyValues under `rootKey`. */
+export function writeVdf(rootKey: string, value: Record<string, unknown>): string;
diff --git a/build-tools/utils/vdf.js b/build-tools/utils/vdf.js
new file mode 100644
index 000000000..6dd17de3a
--- /dev/null
+++ b/build-tools/utils/vdf.js
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Valve's KeyValues text format, written.
+ *
+ * SteamPipe's build scripts are KeyValues, and the only reader that matters is
+ * steamcmd's — so what this has to get right is quoting and nesting, and nothing
+ * else. Written rather than depended on for the reason every other format here is:
+ * a package must be producible without installing anything.
+ */
+
+/**
+ * Escape a value for a quoted KeyValues token.
+ *
+ * Backslashes matter and are the reason this exists: a Windows content root
+ * pasted in raw turns `C:\build` into a `\b`, and steamcmd then looks for a
+ * directory nobody named.
+ */
+function token(text) {
+ return `"${String(text).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+/**
+ * Serialize @p value as KeyValues under @p rootKey.
+ *
+ * Objects nest; everything else is a leaf. Key ORDER is the object's own, which
+ * matters only for how a human reads the result — steamcmd does not care, and a
+ * diff does.
+ *
+ * @param {string} rootKey
+ * @param {Record<string, unknown>} value
+ * @returns {string} the document, newline-terminated.
+ */
+export function writeVdf(rootKey, value) {
+ const lines = [];
+ const emit = (key, node, depth) => {
+ const pad = '\t'.repeat(depth);
+ if (node !== null && typeof node === 'object' && !Array.isArray(node)) {
+ lines.push(`${pad}${token(key)}`, `${pad}{`);
+ for (const [k, v] of Object.entries(node)) emit(k, v, depth + 1);
+ lines.push(`${pad}}`);
+ return;
+ }
+ lines.push(`${pad}${token(key)}\t\t${token(node)}`);
+ };
+ emit(rootKey, value, 0);
+ return `${lines.join('\n')}\n`;
+}
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index 120f7b882..06a53bd78 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -47,8 +47,10 @@ import { androidTemplateSources } from '../../build-tools/utils/nativeTemplate.j
import { assembleApk, apkFileName } from '../../build-tools/utils/apk.js';
import { assembleAab, aabFileName } from '../../build-tools/utils/aab.js';
import { assembleMacApp } from '../../build-tools/utils/desktopApp.js';
+import { emitSteamBuild, defaultDepotId } from '../../build-tools/utils/steamChannel.js';
import { debugSigningKey, type SigningKey } from '../../build-tools/utils/androidKeystore.js';
import { isNativePlatform, type ExportPlatform } from '../src/project/platforms';
+import type { DesktopPackaging, SteamPackaging } from '../src/project/format';
import type { SizeBudget } from '../src/project/sizeBudget';
import { measureBuild, type BuildSizeReport } from './sizeReport';
import { loadProjectModules, sideModuleDeclarations, stageProjectModules } from './projectModules';
@@ -206,6 +208,9 @@ export interface ExportGameResult {
/** Desktop: the assembled app bundle. Absent when no desktop runtime template
* is installed (the export still carries its content). */
appBundle?: string;
+ /** Desktop, Steam channel: the checklist naming this build's depot ids, launch
+ * string and cloud paths — the settings only the partner backend holds. */
+ steamChecklist?: string;
/** Playable, zip-delivery networks: the archive written beside the HTML — the file
* the network takes an upload of. */
zipFile?: string;
@@ -349,6 +354,11 @@ export interface ExportGameOptions {
* (the template ids are per-OS where the platform id is not). Omitted (or
* null) exports content only. */
desktopTemplate?: string | null;
+ /** Desktop: where this build goes (`packaging.platforms.desktop.channel`).
+ * Absent ⇒ standalone, which writes the app and nothing else. */
+ desktopChannel?: DesktopPackaging['channel'];
+ /** Desktop, Steam channel: what only the partner backend can tell you. */
+ steam?: SteamPackaging;
/**
* What an Android export produces. 'package' assembles the APK (and the App
* Bundle beside it when asked); 'project' writes an Android Studio project the
@@ -545,6 +555,8 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
let aabFile: string | undefined;
/** Desktop: the assembled `<name>.app`. */
let appBundle: string | undefined;
+ /** Desktop, Steam channel: the per-build checklist written beside the scripts. */
+ let steamChecklist: string | undefined;
await mkdir(payloadDir, { recursive: true });
const common: BuildOptions = {
bundle: true,
@@ -721,6 +733,25 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
iconPng: opts.appIcon ? path.join(opts.root, opts.appIcon) : undefined,
warn: (m: string) => warnings.push(m),
});
+ if (opts.desktopChannel === 'steam') {
+ const appId = opts.steam?.appId;
+ if (!appId) {
+ warnings.push('The Steam channel is selected but no App ID is set (Project Settings → '
+ + 'Packaging → Desktop), so no depot scripts were written — scripts built around a '
+ + 'guessed id would name someone else\'s game.');
+ } else {
+ progress({ phase: 'Writing the Steam build scripts' });
+ const os = 'macos';
+ const emitted = await emitSteamBuild({
+ outDir: absOut,
+ appId,
+ appName: appConfig.name,
+ description: opts.steam?.description,
+ depots: [{ os, depotId: opts.steam?.depots?.[os] ?? defaultDepotId(appId, 0) }],
+ });
+ steamChecklist = emitted.checklist;
+ }
+ }
} else {
warnings.push(`Assembling a desktop app on ${process.platform} is not written yet — the `
+ 'content is here, and a macOS editor packages it.');
@@ -758,5 +789,6 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
warnings, errors, ...(xcodeProject ? { xcodeProject } : {}), ...(androidProject ? { androidProject } : {}),
...(apkFile ? { apkFile } : {}), ...(aabFile ? { aabFile } : {}),
...(appBundle ? { appBundle } : {}),
+ ...(steamChecklist ? { steamChecklist } : {}),
};
}
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 72a1f94c6..25b97f7c5 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -1208,6 +1208,8 @@ ipcMain.handle(
desktopTemplate: opts?.platform === 'desktop'
? (resolveNativeTemplate(desktopTemplateFor(process.platform), app.getVersion())?.dir ?? null)
: null,
+ desktopChannel: plat?.desktop?.channel,
+ steam: plat?.desktop?.steam,
androidOutput: plat?.android?.output,
onProgress: (p) => e.sender.send('project:exportProgress', p),
});
diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.ts
index 894bff88f..84e75e67b 100644
--- a/desktop/src/project/format.ts
+++ b/desktop/src/project/format.ts
@@ -165,7 +165,31 @@ export type CameraScaleMode = 'none' | 'fixed-width' | 'fixed-height' | 'expand'
* Orientation is NOT here — it is one project-wide {@link ProjectPackaging.orientation}
* consumed by every target (a landscape build is landscape everywhere). */
export interface WeChatPackaging { appid?: string; }
-export interface DesktopPackaging { appId?: string; productName?: string; }
+export interface DesktopPackaging {
+ appId?: string;
+ productName?: string;
+ /**
+ * Where this build goes. A CHANNEL, not a platform: Steam defines no runtime and
+ * no asset format, only a depot layout, a set of services and an upload — so it
+ * rides the desktop target the way an ad network rides the playable one
+ * (docs/REARCH_STEAM.md §1). Absent ⇒ standalone: just the app.
+ */
+ channel?: 'standalone' | 'steam';
+ steam?: SteamPackaging;
+}
+
+/** What only Valve can tell you, kept so a build can write its own scripts. */
+export interface SteamPackaging {
+ /** The application id from the partner backend. Without it nothing is emitted:
+ * a depot script with a guessed appid uploads to someone else's game or, more
+ * likely, to nothing at all. */
+ appId?: number;
+ /** Depot ids per OS. Valve assigns these; absent ⇒ `appId + 1`, …, which the
+ * generated checklist tells you to check rather than trust. */
+ depots?: Partial<Record<'macos' | 'windows' | 'linux', number>>;
+ /** Build description shown in the backend's build list. */
+ description?: string;
+}
/** Android's slice of the app identity. `appId` is the manifest package — the
* identity a store keeps forever; `versionCode` is the integer Play orders builds
@@ -568,6 +592,27 @@ export function parseManifest(raw: unknown): ProjectManifest {
const d: DesktopPackaging = {};
if (typeof dt.appId === 'string') d.appId = dt.appId;
if (typeof dt.productName === 'string') d.productName = dt.productName;
+ if (dt.channel === 'steam' || dt.channel === 'standalone') d.channel = dt.channel;
+ const st = dt.steam as Record<string, unknown> | undefined;
+ if (st && typeof st === 'object') {
+ const steam: SteamPackaging = {};
+ // A non-integer or non-positive appid is not a typo to carry forward:
+ // every script written from it would name a game that is not this one.
+ if (typeof st.appId === 'number' && Number.isInteger(st.appId) && st.appId > 0) {
+ steam.appId = st.appId;
+ }
+ if (typeof st.description === 'string') steam.description = st.description;
+ const dp = st.depots as Record<string, unknown> | undefined;
+ if (dp && typeof dp === 'object') {
+ const depots: NonNullable<SteamPackaging['depots']> = {};
+ for (const os of ['macos', 'windows', 'linux'] as const) {
+ const id = dp[os];
+ if (typeof id === 'number' && Number.isInteger(id) && id > 0) depots[os] = id;
+ }
+ if (Object.keys(depots).length > 0) steam.depots = depots;
+ }
+ if (Object.keys(steam).length > 0) d.steam = steam;
+ }
if (Object.keys(d).length > 0) platforms.desktop = d;
}
const an = pl.android as Record<string, unknown> | undefined;
diff --git a/desktop/tests/steam-channel.test.ts b/desktop/tests/steam-channel.test.ts
new file mode 100644
index 000000000..1377fb2d8
--- /dev/null
+++ b/desktop/tests/steam-channel.test.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Steam as a channel on the desktop target: the depot scripts, and the two
+ * things about them that are dangerous rather than merely wrong.
+ *
+ * A script that parses is not a script that is safe. Uploading is not reversible
+ * by uploading again, and a mapping that takes the whole content root would put
+ * the loose cooked content in the depot beside the app that already contains it.
+ * Both are pinned here; the format itself is cross-checked by
+ * build-tools/tests/verify-vdf.py, which is a reader written from the format.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { emitSteamBuild, defaultDepotId } from '../../build-tools/utils/steamChannel.js';
+import { writeVdf } from '../../build-tools/utils/vdf.js';
+
+let out: string;
+
+beforeEach(() => { out = mkdtempSync(path.join(tmpdir(), 'estella-steam-')); });
+afterEach(() => { rmSync(out, { recursive: true, force: true }); });
+
+const emit = () => emitSteamBuild({
+ outDir: out, appId: 480, appName: 'Physics Spinner',
+ depots: [{ os: 'macos', depotId: defaultDepotId(480, 0) }],
+});
+
+describe('the Steam channel', () => {
+ it('never writes a script that can publish on its first run', async () => {
+ await emit();
+ const build = readFileSync(path.join(out, 'steam', 'app_build_480.vdf'), 'utf8');
+ expect(build).toContain('"Preview"\t\t"1"');
+ // Empty, not a branch name: uploading and going live are two decisions and
+ // only one of them can be undone by uploading again.
+ expect(build).toContain('"SetLive"\t\t""');
+ });
+
+ it('maps only the app, so the loose content beside it is not uploaded', async () => {
+ // The export dir holds the cooked content AND the app that contains it;
+ // a depot that took both would ship every asset twice.
+ writeFileSync(path.join(out, 'game.config.json'), '{}');
+ await emit();
+ const depot = readFileSync(path.join(out, 'steam', 'depot_481_macos.vdf'), 'utf8');
+ expect(depot).toContain('"LocalPath"\t\t"Physics Spinner.app/*"');
+ expect(depot).not.toContain('"LocalPath"\t\t"*"');
+ });
+
+ it('never writes steam_appid.txt — shipping one disables the Steam check', async () => {
+ await emit();
+ const listed = readFileSync(path.join(out, 'STEAM.md'), 'utf8');
+ expect(existsSync(path.join(out, 'steam_appid.txt'))).toBe(false);
+ expect(listed).toContain('steam_appid.txt'); // named as a thing NOT to ship
+ });
+
+ it('tells this build what the backend needs, not what a manual would', async () => {
+ const { checklist } = await emit();
+ const text = readFileSync(checklist, 'utf8');
+ expect(text).toContain('`481`'); // the depot id in use
+ expect(text).toContain('`Physics Spinner.app`'); // the launch string
+ // The save path the engine actually writes to, in the words Auto-Cloud uses.
+ expect(text).toContain('`MacHome`');
+ expect(text).toContain('Library/Application Support/Estella/Physics Spinner');
+ });
+
+ it('says the depot ids are a guess, because Valve assigns them', async () => {
+ const { checklist } = await emit();
+ expect(readFileSync(checklist, 'utf8')).toMatch(/guess|assigns/i);
+ });
+
+ it('honours depot ids the project was given', async () => {
+ await emitSteamBuild({
+ outDir: out, appId: 480, appName: 'G', depots: [{ os: 'macos', depotId: 90210 }],
+ });
+ expect(existsSync(path.join(out, 'steam', 'depot_90210_macos.vdf'))).toBe(true);
+ expect(readFileSync(path.join(out, 'steam', 'app_build_480.vdf'), 'utf8'))
+ .toContain('"90210"\t\t"depot_90210_macos.vdf"');
+ });
+});
+
+describe('the KeyValues writer', () => {
+ it('escapes what would otherwise change the path', () => {
+ // A Windows content root is the reason this exists: raw, `C:\build` carries
+ // a \b into whatever reads it.
+ const text = writeVdf('R', { ContentRoot: 'C:\\build\\out', Desc: 'a "quoted" name' });
+ expect(text).toContain('"C:\\\\build\\\\out"');
+ expect(text).toContain('a \\"quoted\\" name');
+ });
+
+ it('nests objects and leaves everything else a leaf', () => {
+ expect(writeVdf('R', { a: '1', b: { c: '2' } })).toBe(
+ '"R"\n{\n\t"a"\t\t"1"\n\t"b"\n\t{\n\t\t"c"\t\t"2"\n\t}\n}\n',
+ );
+ });
+});
diff --git a/native/host/platform/desktop.cpp b/native/host/platform/desktop.cpp
index 6e9ab2f9c..e684b938d 100644
--- a/native/host/platform/desktop.cpp
+++ b/native/host/platform/desktop.cpp
@@ -275,6 +275,9 @@ int main(int argc, char** argv) {
const std::string name = appName(argc, argv);
g_platform.contentRoot = resolveContentRoot(argc, argv);
+ // The directory a store's cloud save syncs. Its shape per OS is written down a
+ // second time in build-tools/utils/steamChannel.js (CLOUD_ROOTS), because the
+ // backend has to be told it in its own words — change one and change that.
if (char* pref = SDL_GetPrefPath("Estella", name.c_str())) {
g_platform.prefPath = pref;
SDL_free(pref);