@zaisma/cli 0.40.0 → 0.42.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 +47 -13
  2. package/package.json +1 -1
  3. package/zaisma.mjs +46 -4
package/chrome.mjs CHANGED
@@ -60,12 +60,35 @@ export function chromeFlags({ isDrawingOnCpu = false } = {}) {
60
60
 
61
61
  /**
62
62
  * Headless Chrome at path, without the machine's GPU (chromeFlags), and a DevTools connection to it: send(method, parameters, sessionId),
63
- * listen(sessionId, onEvent) and close().
63
+ * listen(sessionId, onEvent) and close(). A Chrome that doesn't answer is started again (startWithinTries), and then fails by name.
64
64
  */
65
- export async function openChrome(path, profilePrefix, { isDrawingOnCpu = false, ...others } = {}) {
65
+ export async function openChrome(path, profilePrefix, { isDrawingOnCpu = false, startLimitMs = CHROME_START_LIMIT_MS, ...others } = {}) {
66
66
  const unknownOptions = Object.keys(others);
67
- if (unknownOptions.length) throw new Error(`openChrome has no option ${unknownOptions.join(", ")}: its only option is isDrawingOnCpu, and every Chrome runs without the machine's GPU.`);
67
+ if (unknownOptions.length) throw new Error(`openChrome has no option ${unknownOptions.join(", ")}: its options are isDrawingOnCpu and startLimitMs, and every Chrome runs without the machine's GPU.`);
68
68
  await sweepOrphans();
69
+ return startWithinTries(() => startChrome(path, profilePrefix, isDrawingOnCpu, startLimitMs));
70
+ }
71
+
72
+ /** How long a Chrome may take to answer on its DevTools connection. It takes seconds; on GitHub's runners one in ten takes 40 or more, and one now and then never answers. */
73
+ export const CHROME_START_LIMIT_MS = 60_000;
74
+ const CHROME_START_TRY_COUNT = 3;
75
+
76
+ /** A Chrome that never answered, which says nothing about what it was started to look at. */
77
+ export class ChromeStartStalled extends Error {}
78
+
79
+ /** What startOnce answers, starting it again when it stalled, and saying so: the last try's stall, or any other failure, is thrown. */
80
+ export async function startWithinTries(startOnce, say = (line) => process.stderr.write(`${line}\n`)) {
81
+ for (let tryNumber = 1; ; tryNumber++) {
82
+ try {
83
+ return await startOnce();
84
+ } catch (error) {
85
+ if (!(error instanceof ChromeStartStalled) || tryNumber === CHROME_START_TRY_COUNT) throw error;
86
+ say(`${process.env.GITHUB_ACTIONS ? "::warning::" : ""}${error.message} It's started again.`);
87
+ }
88
+ }
89
+ }
90
+
91
+ async function startChrome(path, profilePrefix, isDrawingOnCpu, startLimitMs) {
69
92
  // A folder for each Chrome: OWNER_FILE, which says whose it is, and Chrome's profile inside, removed before the folder so a profile
70
93
  // that can't be removed yet keeps its owner for the next sweep.
71
94
  const folder = mkdtempSync(join(tmpdir(), profilePrefix));
@@ -89,8 +112,12 @@ export async function openChrome(path, profilePrefix, { isDrawingOnCpu = false,
89
112
  letGo(running);
90
113
  throw error;
91
114
  };
92
- const address = await new Promise((resolve, reject) => {
93
- let output = "";
115
+ let output = "";
116
+ let limitTimer;
117
+ const stalled = new Promise((_, reject) => {
118
+ limitTimer = setTimeout(() => reject(new ChromeStartStalled(`Chrome didn't answer within ${startLimitMs / 1000} s. It said: ${output.slice(-500) || "nothing"}.`)), startLimitMs);
119
+ });
120
+ const address = await Promise.race([stalled, new Promise((resolve, reject) => {
94
121
  child.stderr.on("data", (chunk) => {
95
122
  output += chunk;
96
123
  const match = output.match(/DevTools listening on (ws:\/\/\S+)/);
@@ -98,9 +125,9 @@ export async function openChrome(path, profilePrefix, { isDrawingOnCpu = false,
98
125
  });
99
126
  child.on("error", (error) => reject(error));
100
127
  child.on("exit", (code) => reject(new Error(`Chrome stopped (${code}): ${output.slice(-500)}`)));
101
- }).catch(giveUp);
128
+ })]).catch(giveUp);
102
129
  const socket = new WebSocket(address);
103
- await new Promise((resolve, reject) => ((socket.onopen = resolve), (socket.onerror = reject))).catch(giveUp);
130
+ await Promise.race([stalled, new Promise((resolve, reject) => ((socket.onopen = resolve), (socket.onerror = reject)))]).catch(giveUp);
104
131
  let nextMessageNumber = 1;
105
132
  const waiting = new Map();
106
133
  const listeners = new Set();
@@ -113,13 +140,20 @@ export async function openChrome(path, profilePrefix, { isDrawingOnCpu = false,
113
140
  else resolve(message.result);
114
141
  } else if (message.method) for (const listener of listeners) listener(message);
115
142
  };
143
+ const send = (method, parameters = {}, sessionId) =>
144
+ new Promise((resolve, reject) => {
145
+ const id = nextMessageNumber++;
146
+ waiting.set(id, { resolve, reject });
147
+ socket.send(JSON.stringify({ id, method, params: parameters, ...(sessionId ? { sessionId } : {}) }));
148
+ });
149
+ // Its first answer: only then is it up.
150
+ await Promise.race([stalled, send("Browser.getVersion")]).catch((error) => {
151
+ socket.close();
152
+ giveUp(error);
153
+ });
154
+ clearTimeout(limitTimer);
116
155
  return {
117
- send: (method, parameters = {}, sessionId) =>
118
- new Promise((resolve, reject) => {
119
- const id = nextMessageNumber++;
120
- waiting.set(id, { resolve, reject });
121
- socket.send(JSON.stringify({ id, method, params: parameters, ...(sessionId ? { sessionId } : {}) }));
122
- }),
156
+ send,
123
157
  listen: (sessionId, onEvent) => {
124
158
  const listener = (message) => message.sessionId === sessionId && onEvent(message.method, message.params);
125
159
  listeners.add(listener);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/cli",
3
- "version": "0.40.0",
3
+ "version": "0.42.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
@@ -213,7 +213,13 @@ const COMMANDS = {
213
213
  "items remove": { about: "Remove an item nobody bought or was granted", arguments: [{ name: "slug" }, { name: "item_name" }], flags: {} },
214
214
  "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: {} },
215
215
  "kept-rooms delete": { about: "Delete a kept room's world; players in it are sent out, and it waits a week before it's erased", arguments: [{ name: "slug" }, { name: "room_code" }], flags: {} },
216
- "kept-rooms bring-back": { about: "Bring back a kept room's world waiting to be erased, as it was", arguments: [{ name: "slug" }, { name: "room_code" }], flags: {} },
216
+ "kept-rooms bring-back": { about: "Bring back a deleted kept room's world: as it was during its week, then from its last copy for about 28 days", arguments: [{ name: "slug" }, { name: "room_code" }], flags: {} },
217
+ "kept-rooms restore": { about: "Put a kept room's world back as it was at a moment in the last 30 days (an ISO time, like 2026-10-18T14:05:00Z), live; undo it with kept-rooms undo-restore", arguments: [{ name: "slug" }, { name: "room_code" }, { name: "restore_to_at" }], flags: {} },
218
+ "kept-rooms undo-restore": { about: "Undo a kept room's restore: back to just before it, live", arguments: [{ name: "slug" }, { name: "room_code" }, { name: "kept_room_restore_id" }], flags: {} },
219
+ "kept-rooms restores": { about: "How far back a kept room's world can go, and its restores", arguments: [{ name: "slug" }, { name: "room_code" }], flags: {} },
220
+ "kept-rooms restore-all": { about: "Put every kept room's world back as it was at a moment in the last 30 days, a few hundred a minute; undo it with kept-rooms undo-restore-all", arguments: [{ name: "slug" }, { name: "restore_to_at" }], flags: {} },
221
+ "kept-rooms restore-all-status": { about: "How a restore of every kept room is going", arguments: [{ name: "slug" }, { name: "kept_room_restore_batch_id" }], flags: {} },
222
+ "kept-rooms undo-restore-all": { about: "Undo a restore of every kept room: each back to just before it", arguments: [{ name: "slug" }, { name: "kept_room_restore_batch_id" }], flags: {} },
217
223
  "kept-rooms erase-now": { about: "Erase a waiting kept room's world at once; answers a link where the developer approves with a passkey tap", arguments: [{ name: "slug" }, { name: "room_code" }], flags: {} },
218
224
  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: {} },
219
225
  logs: {
@@ -317,7 +323,7 @@ const COMMANDS = {
317
323
  help: { about: "This help; with --json, every command, flag, exit code and error code", arguments: [], flags: {} },
318
324
  };
319
325
  /** Commands with a second word, like zaisma forum post. */
320
- const SUBCOMMANDS = { links: ["set", "remove"], forum: ["post", "message", "reply"], database: ["query", "batch", "export", "import", "restore", "undo-restore"], saves: ["get", "change", "replace", "reset", "copies", "copy", "restore"], secrets: ["set", "delete"], items: ["set", "remove"], "kept-rooms": ["delete", "bring-back", "erase-now"] };
326
+ const SUBCOMMANDS = { links: ["set", "remove"], forum: ["post", "message", "reply"], database: ["query", "batch", "export", "import", "restore", "undo-restore"], saves: ["get", "change", "replace", "reset", "copies", "copy", "restore"], secrets: ["set", "delete"], items: ["set", "remove"], "kept-rooms": ["delete", "bring-back", "erase-now", "restore", "undo-restore", "restores", "restore-all", "restore-all-status", "undo-restore-all"] };
321
327
  /** Flags every command takes. */
322
328
  const GLOBAL_FLAGS = {
323
329
  json: { hasValue: false, about: "Print the API's answer as JSON, as-is (on failure its { error }), and nothing else" },
@@ -1950,7 +1956,7 @@ async function liveRooms(values) {
1950
1956
  if (answer.next_cursor) console.log(`${answer.room_count} rooms in all; --json, or list_rooms with cursor, gives the rest.`);
1951
1957
  }
1952
1958
 
1953
- /** A game's kept rooms (…/games/<slug>/kept-rooms…), as the MCP's list_kept_rooms, delete_kept_room, bring_back_kept_room and erase_kept_room_now. */
1959
+ /** A game's kept rooms (…/games/<slug>/kept-rooms…), as the MCP's list_kept_rooms, delete_kept_room, bring_back_kept_room, erase_kept_room_now and its restores' tools. */
1954
1960
  async function keptRooms(command, values) {
1955
1961
  if (command === "kept-rooms") {
1956
1962
  const answer = await api("GET", `/games/${values.slug}/kept-rooms`);
@@ -1958,15 +1964,51 @@ async function keptRooms(command, values) {
1958
1964
  if (!answer.kept_rooms.length) console.log(`No kept rooms. A game server keeps one with room.setKept(true).`);
1959
1965
  for (const keptRoom of answer.kept_rooms) console.log(`${keptRoom.room_code} ${(keptRoom.name ?? "").padEnd(24)} ${sizeText(keptRoom.saved_size_bytes).padStart(9)} played ${keptRoom.erases_at ? `waiting, erased ${when(keptRoom.erases_at)} ` : ""}${keptRoom.last_played_at ? when(keptRoom.last_played_at) : "never"}`);
1960
1966
  console.log(`Storage: ${sizeText(answer.storage_size_bytes)} of the ${sizeText(answer.maximum_storage_size_bytes)} a game can keep (database and kept rooms).`);
1967
+ if (answer.deleted_kept_rooms.length) console.log(`Deleted, and can come back from their last copy: ${answer.deleted_kept_rooms.map((deleted) => `${deleted.room_code} until ${when(deleted.bring_back_ends_at)}`).join(", ")}`);
1968
+ return;
1969
+ }
1970
+ // Every world of the game.
1971
+ if (command === "kept-rooms restore-all" || command === "kept-rooms undo-restore-all" || command === "kept-rooms restore-all-status") {
1972
+ const batchPath = `/games/${values.slug}/kept-room-restores`;
1973
+ const answer =
1974
+ command === "kept-rooms restore-all"
1975
+ ? await api("POST", batchPath, { restore_to_at: values.restore_to_at })
1976
+ : command === "kept-rooms undo-restore-all"
1977
+ ? await api("POST", `${batchPath}/${encodeURIComponent(values.kept_room_restore_batch_id)}/undo`)
1978
+ : await api("GET", `${batchPath}/${encodeURIComponent(values.kept_room_restore_batch_id)}`);
1979
+ if (isJson) return printJson(answer);
1980
+ const batch = answer.kept_room_restore_batch;
1981
+ console.log(`${values.slug}'s worlds to ${batch.restore_to_at}: ${batch.restored_room_count} of ${batch.kept_room_count} back, ${batch.skipped_room_count} left as they are, ${batch.failed_room_count} failed${batch.finished_at ? "." : ", still going."}`);
1982
+ if (batch.failed_room_codes.length) console.log(`Failed: ${batch.failed_room_codes.join(", ")}`);
1983
+ if (answer.live_version_published_since) console.log(answer.live_version_published_since.message);
1984
+ if (command === "kept-rooms restore-all") console.log(`Status: zaisma kept-rooms restore-all-status ${values.slug} ${batch.id}\nUndo it until ${batch.undo_expires_at}: zaisma kept-rooms undo-restore-all ${values.slug} ${batch.id}`);
1961
1985
  return;
1962
1986
  }
1963
1987
  const roomPath = `/games/${values.slug}/kept-rooms/${encodeURIComponent(values.room_code)}`;
1964
1988
  const code = values.room_code.toUpperCase();
1989
+ if (command === "kept-rooms restores") {
1990
+ const answer = await api("GET", `${roomPath}/restores`);
1991
+ if (isJson) return printJson(answer);
1992
+ console.log(`${code} can go back to any minute since ${answer.earliest_restore_to_at}.`);
1993
+ for (const restore of answer.restores) console.log(`${restore.id} ${restore.restored_at} ${restore.undoes_kept_room_restore_id ? `undid ${restore.undoes_kept_room_restore_id}` : `back to ${restore.restore_to_at}`}`);
1994
+ return;
1995
+ }
1996
+ if (command === "kept-rooms restore" || command === "kept-rooms undo-restore") {
1997
+ const isUndo = command === "kept-rooms undo-restore";
1998
+ const answer = isUndo ? await api("POST", `${roomPath}/restores/${encodeURIComponent(values.kept_room_restore_id)}/undo`) : await api("POST", `${roomPath}/restores`, { restore_to_at: values.restore_to_at });
1999
+ if (isJson) return printJson(answer);
2000
+ const restore = answer.kept_room_restore;
2001
+ console.log(isUndo ? `Undid restore ${values.kept_room_restore_id}: ${code} is back to ${restore.restore_to_at}.` : `Restored ${code} of ${values.slug} to ${restore.restore_to_at}.`);
2002
+ if (answer.live_version_published_since) console.log(answer.live_version_published_since.message);
2003
+ console.log(`Undo it until ${restore.undo_expires_at}: zaisma kept-rooms undo-restore ${values.slug} ${code} ${restore.id}`);
2004
+ return;
2005
+ }
1965
2006
  if (command === "kept-rooms bring-back" || command === "kept-rooms erase-now") {
1966
2007
  const isBringingBack = command === "kept-rooms bring-back";
1967
2008
  const answer = await api("POST", `${roomPath}/${isBringingBack ? "bring-back" : "erase-now"}`);
1968
2009
  if (isJson) return printJson(answer);
1969
- console.log(isBringingBack ? `Kept room ${code} of ${values.slug} is back, as it was.` : `Erased kept room ${code} of ${values.slug} for good.`);
2010
+ if (answer.is_bringing_back) console.log(`Kept room ${code} of ${values.slug} is coming back from its last copy${answer.copy_saved_at ? `, made ${when(answer.copy_saved_at)}` : ""}. zaisma kept-rooms ${values.slug} has it when it's back.`);
2011
+ else console.log(isBringingBack ? `Kept room ${code} of ${values.slug} is back, as it was.` : `Erased kept room ${code} of ${values.slug}. Its last copy can bring it back for about 28 days after it was deleted: zaisma kept-rooms bring-back ${values.slug} ${code}`);
1970
2012
  return;
1971
2013
  }
1972
2014
  const answer = await api("DELETE", roomPath);