@zaisma/cli 0.32.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/chrome.mjs +152 -8
  2. package/package.json +1 -1
  3. package/zaisma.mjs +14 -0
package/chrome.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  // Headless Chrome, for `zaisma check` on a shader's folder and Zaisma's own scripts that look at pages in a real browser
2
2
  // (scripts/chrome.mjs), driven over its DevTools protocol with Node's own WebSocket (Node 22 or newer), so it needs no dependency and
3
3
  // never downloads a browser. Chrome is the one in CHROME_PATH, the system's, or one Playwright or @puppeteer/browsers downloaded.
4
- import { spawn } from "node:child_process";
5
- import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
4
+ import { spawn, spawnSync } from "node:child_process";
5
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { homedir, tmpdir } from "node:os";
7
7
  import { join } from "node:path";
8
8
 
@@ -54,9 +54,31 @@ function playwrightChromes() {
54
54
  * sessionId), listen(sessionId, onEvent) and close().
55
55
  */
56
56
  export async function openChrome(path, profilePrefix, { isGpu = false } = {}) {
57
- const profile = mkdtempSync(join(tmpdir(), profilePrefix));
57
+ await sweepOrphans();
58
+ // A folder for each Chrome: OWNER_FILE, which says whose it is, and Chrome's profile inside, removed before the folder so a profile
59
+ // that can't be removed yet keeps its owner for the next sweep.
60
+ const folder = mkdtempSync(join(tmpdir(), profilePrefix));
61
+ const profile = join(folder, "profile");
62
+ mkdirSync(profile);
58
63
  const webgl = isGpu ? ["--enable-gpu", "--ignore-gpu-blocklist", ...(process.platform === "darwin" ? ["--use-angle=metal"] : [])] : ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"];
59
- const child = spawn(path, ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", ...webgl, "--autoplay-policy=no-user-gesture-required", "--hide-scrollbars", "--disable-renderer-backgrounding", "--disable-background-timer-throttling", "--disable-backgrounding-occluded-windows", "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
64
+ let child;
65
+ try {
66
+ child = spawn(path, ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", ...webgl, "--autoplay-policy=no-user-gesture-required", "--hide-scrollbars", "--disable-renderer-backgrounding", "--disable-background-timer-throttling", "--disable-backgrounding-occluded-windows", "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
67
+ } catch (error) {
68
+ rmSync(folder, { recursive: true, force: true });
69
+ throw error;
70
+ }
71
+ const running = { child, folder, profile };
72
+ if (child.pid) {
73
+ writeFileSync(join(folder, OWNER_FILE), JSON.stringify({ owner_process_id: process.pid, chrome_process_id: child.pid }));
74
+ keepUntilExit(running);
75
+ }
76
+ const giveUp = (error) => {
77
+ child.kill("SIGKILL");
78
+ removeFolder(running);
79
+ letGo(running);
80
+ throw error;
81
+ };
60
82
  const address = await new Promise((resolve, reject) => {
61
83
  let output = "";
62
84
  child.stderr.on("data", (chunk) => {
@@ -66,9 +88,9 @@ export async function openChrome(path, profilePrefix, { isGpu = false } = {}) {
66
88
  });
67
89
  child.on("error", (error) => reject(error));
68
90
  child.on("exit", (code) => reject(new Error(`Chrome stopped (${code}): ${output.slice(-500)}`)));
69
- });
91
+ }).catch(giveUp);
70
92
  const socket = new WebSocket(address);
71
- await new Promise((resolve, reject) => ((socket.onopen = resolve), (socket.onerror = reject)));
93
+ await new Promise((resolve, reject) => ((socket.onopen = resolve), (socket.onerror = reject))).catch(giveUp);
72
94
  let nextMessageNumber = 1;
73
95
  const waiting = new Map();
74
96
  const listeners = new Set();
@@ -96,10 +118,132 @@ export async function openChrome(path, profilePrefix, { isGpu = false } = {}) {
96
118
  // Chrome writes to its profile until it has exited, so it goes after.
97
119
  close: async () => {
98
120
  socket.close();
99
- const exited = new Promise((resolve) => child.once("exit", resolve));
121
+ const exited = new Promise((resolve) => (child.exitCode !== null || child.signalCode !== null ? resolve() : child.once("exit", resolve)));
100
122
  child.kill();
101
123
  await exited;
102
- rmSync(profile, { recursive: true, force: true, maxRetries: 5 });
124
+ await endAndRemove([running]);
125
+ letGo(running);
103
126
  },
104
127
  };
105
128
  }
129
+
130
+ /** The file in each Chrome's folder that says whose it is: { owner_process_id, chrome_process_id }. */
131
+ const OWNER_FILE = "zaisma-chrome-owner.json";
132
+ const STOP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
133
+ /** The Chromes this process started and hasn't closed. */
134
+ const runningChromes = new Set();
135
+
136
+ // Chrome outlives the node process that started it unless something stops it: a script that exits without close(), or is stopped by a
137
+ // signal that skips its finally, would leave Chrome and its helpers running. So each one is killed when this process exits, and on
138
+ // SIGINT, SIGTERM and SIGHUP, which then end the process as they would have (a script with a handler of its own keeps its say).
139
+ function stopAll() {
140
+ const runnings = [...runningChromes];
141
+ runningChromes.clear();
142
+ // Nothing can be awaited on exit, so this waits in place, only as long as Chrome's processes take to end.
143
+ const deadlineMs = Date.now() + EXIT_TIME_LIMIT_MS;
144
+ const pause = new Int32Array(new SharedArrayBuffer(4));
145
+ while (killAll(runnings) && Date.now() < deadlineMs) Atomics.wait(pause, 0, 0, 50);
146
+ for (const running of runnings) removeFolder(running);
147
+ }
148
+ async function onSignal(signal) {
149
+ if (process.listenerCount(signal) > 1) return;
150
+ removeHandlers();
151
+ const runnings = [...runningChromes];
152
+ runningChromes.clear();
153
+ await endAndRemove(runnings);
154
+ process.kill(process.pid, signal);
155
+ }
156
+ function addHandlers() {
157
+ process.on("exit", stopAll);
158
+ for (const signal of STOP_SIGNALS) process.on(signal, onSignal);
159
+ }
160
+ function removeHandlers() {
161
+ process.off("exit", stopAll);
162
+ for (const signal of STOP_SIGNALS) process.off(signal, onSignal);
163
+ }
164
+ function keepUntilExit(running) {
165
+ if (!runningChromes.size) addHandlers();
166
+ runningChromes.add(running);
167
+ }
168
+ function letGo(running) {
169
+ if (runningChromes.delete(running) && !runningChromes.size) removeHandlers();
170
+ }
171
+
172
+ /** How long Chrome's processes get to end after SIGKILL before their folders are removed anyway: on exit, which holds the process up, and otherwise. */
173
+ const EXIT_TIME_LIMIT_MS = 2_000;
174
+ const END_TIME_LIMIT_MS = 5_000;
175
+
176
+ /**
177
+ * Sends SIGKILL to every process of these Chromes still running (the one started here, and each whose command line names its profile:
178
+ * the helpers, or a dead owner's Chrome), and says whether there were any. Chrome's helpers write to the profile until they've exited,
179
+ * so a folder is removed only once this finds none.
180
+ */
181
+ function killAll(runnings) {
182
+ const children = runnings.flatMap(({ child }) => (child && child.exitCode === null && child.signalCode === null ? [child] : []));
183
+ const processNumbers = profileProcessNumbers(runnings.map(({ profile }) => profile));
184
+ for (const child of children) child.kill("SIGKILL");
185
+ for (const processNumber of processNumbers) {
186
+ try {
187
+ process.kill(processNumber, "SIGKILL");
188
+ } catch {}
189
+ }
190
+ return children.length > 0 || processNumbers.length > 0;
191
+ }
192
+
193
+ /** Kills these Chromes and removes their folders once their processes have ended. */
194
+ async function endAndRemove(runnings) {
195
+ const deadlineMs = Date.now() + END_TIME_LIMIT_MS;
196
+ while (killAll(runnings) && Date.now() < deadlineMs) await new Promise((resolve) => setTimeout(resolve, 50));
197
+ for (const running of runnings) removeFolder(running);
198
+ }
199
+
200
+ /** The processes whose command line names one of these profiles; Windows has no ps, so none there. */
201
+ function profileProcessNumbers(profiles) {
202
+ if (process.platform === "win32" || !profiles.length) return [];
203
+ const listed = spawnSync("ps", ["-A", "-o", "pid=,command="], { encoding: "utf8" }).stdout ?? "";
204
+ return listed.split("\n").flatMap((line) => {
205
+ const [, processNumber, command] = line.match(/^\s*(\d+)\s+(.*)$/) ?? [];
206
+ return processNumber && profiles.some((profile) => command.includes(`--user-data-dir=${profile}`)) ? [Number(processNumber)] : [];
207
+ });
208
+ }
209
+
210
+ /** Removes a Chrome's profile, then its folder; one that can't be removed yet stays, with its owner, for the next sweep. */
211
+ function removeFolder({ folder, profile }) {
212
+ try {
213
+ rmSync(profile, { recursive: true, force: true, maxRetries: 5 });
214
+ rmSync(folder, { recursive: true, force: true });
215
+ } catch {}
216
+ }
217
+
218
+ const isAlive = (processNumber) => {
219
+ try {
220
+ process.kill(processNumber, 0);
221
+ return true;
222
+ } catch (error) {
223
+ return error.code === "EPERM";
224
+ }
225
+ };
226
+
227
+ /**
228
+ * Kills the Chromes, and removes the folders, of owners that died without closing them (SIGKILL, a crash), so the next openChrome
229
+ * cleans up after them; another run's Chrome, whose owner is alive, is left alone. A process is only killed when its command line names
230
+ * the dead owner's profile, so a reused process id is never hit; on Windows only the folder is removed.
231
+ */
232
+ async function sweepOrphans() {
233
+ let names;
234
+ try {
235
+ names = readdirSync(tmpdir());
236
+ } catch {
237
+ return;
238
+ }
239
+ const orphans = names.flatMap((name) => {
240
+ const folder = join(tmpdir(), name);
241
+ try {
242
+ const owner = JSON.parse(readFileSync(join(folder, OWNER_FILE), "utf8"));
243
+ return isAlive(owner.owner_process_id) ? [] : [{ child: null, folder, profile: join(folder, "profile") }];
244
+ } catch {
245
+ return [];
246
+ }
247
+ });
248
+ if (orphans.length) await endAndRemove(orphans);
249
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/cli",
3
- "version": "0.32.0",
3
+ "version": "0.34.0",
4
4
  "description": "Upload and publish browser games on Zaisma from the command line.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://zaisma.com",
package/zaisma.mjs CHANGED
@@ -207,6 +207,7 @@ const COMMANDS = {
207
207
  "items remove": { about: "Remove an item nobody bought or was granted", arguments: [{ name: "slug" }, { name: "item_name" }], flags: {} },
208
208
  "kept-rooms": { about: "A game's kept rooms (room.setKept), worlds that sleep with nobody in them: each one's code, name, size and when it was last played, and the game's storage", arguments: [{ name: "slug" }], flags: {} },
209
209
  "kept-rooms delete": { about: "Delete a kept room's world for good; players in it are sent out", arguments: [{ name: "slug" }, { name: "room_code" }], flags: {} },
210
+ rooms: { about: "A game's live rooms on Zaisma, newest first: each one's code, name, labels, players and spectators, and whether it's kept", arguments: [{ name: "slug" }], flags: {} },
210
211
  logs: {
211
212
  about: "What a game's server printed on Zaisma in the last 30 days, oldest first: the newest lines, older ones with --cursor, or new ones as they come with --follow",
212
213
  arguments: [{ name: "slug" }],
@@ -1932,6 +1933,18 @@ async function items(command, values) {
1932
1933
  console.log(`Refund policy: ${answer.refund_policy === "own_words" ? answer.refund_policy_text : (answer.refund_policy ?? "none yet (set_purchase_settings), needed before anything goes on sale")}`);
1933
1934
  }
1934
1935
 
1936
+ /** A game's live rooms (GET …/games/<slug>/rooms), as the MCP's list_rooms. */
1937
+ async function liveRooms(values) {
1938
+ const answer = await api("GET", `/games/${values.slug}/rooms`);
1939
+ if (isJson) return printJson(answer);
1940
+ if (!answer.rooms.length) console.log(`No live rooms on Zaisma right now.`);
1941
+ for (const room of answer.rooms) {
1942
+ const labels = Object.entries(room.labels).map(([labelName, labelValue]) => `${labelName}: ${labelValue}`).join(", ");
1943
+ console.log(`${room.room_code} ${(room.name ?? "").padEnd(24)} ${`${room.player_count}/${room.maximum_player_count}`.padStart(7)} players${room.spectator_count ? `, ${room.spectator_count} watching` : ""}${room.is_kept ? ", kept" : ""}${labels ? ` ${labels}` : ""}`);
1944
+ }
1945
+ if (answer.next_cursor) console.log(`${answer.room_count} rooms in all; --json, or list_rooms with cursor, gives the rest.`);
1946
+ }
1947
+
1935
1948
  /** A game's kept rooms (…/games/<slug>/kept-rooms…), as the MCP's list_kept_rooms and delete_kept_room. */
1936
1949
  async function keptRooms(command, values) {
1937
1950
  if (command === "kept-rooms") {
@@ -2168,6 +2181,7 @@ async function run({ command, values, flags, globalFlags, rest }) {
2168
2181
  else if (command === "links" || command.startsWith("links ")) await links(command, values, flags);
2169
2182
  else if (command === "secrets" || command.startsWith("secrets ")) await secrets(command, values);
2170
2183
  else if (command === "items" || command.startsWith("items ")) await items(command, values);
2184
+ else if (command === "rooms") await liveRooms(values);
2171
2185
  else if (command === "kept-rooms" || command.startsWith("kept-rooms ")) await keptRooms(command, values);
2172
2186
  else if (command === "logs") await logs(values, flags);
2173
2187
  else if (command === "database" || command.startsWith("database ")) await database(command, values, flags);