@zaisma/cli 0.23.0 → 0.25.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.
- package/README.md +2 -0
- package/chrome.mjs +105 -0
- package/package.json +3 -1
- package/shader-check.mjs +953 -0
- package/zaisma.mjs +459 -6
package/zaisma.mjs
CHANGED
|
@@ -6,11 +6,13 @@ import { createHash } from "node:crypto";
|
|
|
6
6
|
import { createReadStream, createWriteStream, readFileSync } from "node:fs";
|
|
7
7
|
import { mkdir, mkdtemp, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
8
8
|
import { tmpdir } from "node:os";
|
|
9
|
-
import { dirname, extname, join, posix, relative, sep } from "node:path";
|
|
9
|
+
import { dirname, extname, join, posix, relative, resolve, sep } from "node:path";
|
|
10
10
|
import { pipeline } from "node:stream/promises";
|
|
11
11
|
import { createBrotliDecompress, createGunzip } from "node:zlib";
|
|
12
12
|
import { CHECKED_TEXT_EXTENSIONS, GAME_FILE_EXTENSIONS, PRECOMPRESSED_EXTENSIONS, checkGameFiles, extensionOf, findOutsideReferences } from "./check.mjs";
|
|
13
13
|
import { assetHeadSizes } from "./performance.mjs";
|
|
14
|
+
import { findChrome, openChrome } from "./chrome.mjs";
|
|
15
|
+
import { SHADER_CHECK_PAGE, SHADER_LIMITS, isShaderCheckPassing, shaderCheckPageExpressions, shaderDraftAnswer, shaderRenderFromPage, shaderRenderInputOf } from "./shader-check.mjs";
|
|
14
16
|
|
|
15
17
|
const API = (process.env.ZAISMA_API || "https://zaisma.com").replace(/\/+$/, "");
|
|
16
18
|
const KEY = process.env.ZAISMA_KEY || "";
|
|
@@ -38,8 +40,30 @@ const OUTSIDE_FOLDER = "zaisma-outside";
|
|
|
38
40
|
/** Files database export and import read and write as SQLite databases; any other name is SQL text. */
|
|
39
41
|
const SQLITE_EXTENSIONS = [".sqlite", ".sqlite3", ".db"];
|
|
40
42
|
|
|
43
|
+
/**
|
|
44
|
+
* A shader's folder (zaisma shader, and zaisma check on a folder with image.glsl): its passes, by file name (null is the image pass,
|
|
45
|
+
* otherwise the buffer's name), channels.json wiring each pass's iChannel0 to iChannel3, and the textures channels.json names. Nothing else.
|
|
46
|
+
*/
|
|
47
|
+
const SHADER_PASS_FILES = { "image.glsl": null, "buffer-a.glsl": "a", "buffer-b.glsl": "b", "buffer-c.glsl": "c", "buffer-d.glsl": "d" };
|
|
48
|
+
const CHANNELS_FILE = "channels.json";
|
|
49
|
+
const TEXTURE_EXTENSIONS = ["png", "jpg", "jpeg", "webp"];
|
|
50
|
+
/** A channel in channels.json: the API's channel, with the texture named by its file in the folder (texture_file) instead of an image_id. */
|
|
51
|
+
const CHANNEL_FIELDS = ["channel_index", "input_kind", "buffer_name", "texture_file", "filter", "wrap"];
|
|
52
|
+
const CHANNELS_FILE_EXAMPLE = {
|
|
53
|
+
image: [
|
|
54
|
+
{ channel_index: 0, input_kind: "buffer", buffer_name: "a" },
|
|
55
|
+
{ channel_index: 1, input_kind: "texture", texture_file: "noise.png", filter: "linear", wrap: "repeat" },
|
|
56
|
+
],
|
|
57
|
+
"buffer-a": [{ channel_index: 0, input_kind: "buffer", buffer_name: "a" }],
|
|
58
|
+
};
|
|
59
|
+
const CHANNELS_FIX = `Give channels.json as an object of passes ("image", "buffer-a" to "buffer-d"), each a list of up to 4 channels, like ${JSON.stringify(CHANNELS_FILE_EXAMPLE)}; filter linear or nearest, wrap clamp or repeat. zaisma help shows it.`;
|
|
60
|
+
/** How long shader and check wait for a texture image a person has to approve (image matching couldn't answer): 20 checks, 3 seconds apart; ZAISMA_SCAN_CHECK_INTERVAL_MS speeds it up in tests. */
|
|
61
|
+
const TEXTURE_CHECK_INTERVAL_MS = Number(process.env.ZAISMA_SCAN_CHECK_INTERVAL_MS) || 3000;
|
|
62
|
+
const TEXTURE_CHECK_COUNT = 20;
|
|
63
|
+
|
|
41
64
|
/** The choices the API takes, checked before anything is sent (test/node/cli.test.ts holds them to the API's lists). */
|
|
42
65
|
const VISIBILITIES = ["listed", "unlisted", "private", "draft"];
|
|
66
|
+
const SCREENS = ["wide", "phone"];
|
|
43
67
|
const TOPIC_KINDS = ["bug", "gap", "feature", "question", "talk"];
|
|
44
68
|
const MESSAGE_KINDS = ["bug", "gap", "feature", "question"];
|
|
45
69
|
const FORUM_CATEGORIES = ["publishing", "scans", "pages", "rooms", "servers", "passes", "sdk", "saves", "stats", "mcp", "api", "cli", "accounts", "dashboard", "reports", "rules", "docs", "other"];
|
|
@@ -52,7 +76,7 @@ const EXIT_CODES = {
|
|
|
52
76
|
held: { exitCode: 3, meaning: "upload: the version is held for a person at Zaisma to look at, usually within a day." },
|
|
53
77
|
rejected: { exitCode: 4, meaning: "upload: the version was rejected. Its review_reason and findings say why and how to fix it." },
|
|
54
78
|
still_scanning: { exitCode: 5, meaning: "upload: the version was still being scanned after 10 minutes. Check it later with zaisma versions <slug>." },
|
|
55
|
-
problems_found: { exitCode: 6, meaning: "check: something in the game won't work on Zaisma as it is, and the upload command doesn't fix it. The problems say what and how to fix it." },
|
|
79
|
+
problems_found: { exitCode: 6, meaning: "check: something in the game won't work on Zaisma as it is, and the upload command doesn't fix it; or the shader doesn't compile, is too slow or flashes. The problems say what and how to fix it." },
|
|
56
80
|
};
|
|
57
81
|
|
|
58
82
|
/** The errors only the command itself answers with; every other code is the API's (ERROR_CODES in packages/core/src/errors.ts). */
|
|
@@ -68,12 +92,18 @@ const COMMAND_ERROR_CODES = {
|
|
|
68
92
|
not_a_file: "The file given (of statements, a dump to import, or a save) can't be read.",
|
|
69
93
|
file_exists: "database export won't write over a file that's already there.",
|
|
70
94
|
folder_not_empty: "export saves only into a new or empty folder.",
|
|
71
|
-
needs_newer_node: "Reading or writing a .sqlite file needs Node 22.13 or newer.",
|
|
95
|
+
needs_newer_node: "Reading or writing a .sqlite file needs Node 22.13 or newer, and drawing a shader in a local Chrome Node 22.",
|
|
72
96
|
not_a_database: "The .sqlite file to import isn't a SQLite database.",
|
|
73
97
|
unknown_link: "links remove: the game has no link by that name.",
|
|
74
98
|
outside_file_unreachable: "upload: a file the game loads from an outside site couldn't be downloaded, so nothing was sent.",
|
|
75
99
|
too_many_outside_files: "upload: the game loads more than 500 files from outside sites, so nothing was sent.",
|
|
76
100
|
unpack_failed: "upload: a pre-compressed file couldn't be unpacked, so nothing was sent.",
|
|
101
|
+
no_image_pass: "shader: the folder has no image.glsl, the shader's image pass.",
|
|
102
|
+
unknown_shader_file: "A file in a shader's folder isn't one the command reads, or no channel in channels.json names it.",
|
|
103
|
+
bad_channels_file: "A shader's channels.json isn't JSON, or isn't an object of the folder's passes, each a list of channels.",
|
|
104
|
+
shader_texture_not_approved: "shader, check: a texture sent for the shader was rejected, or still waits for a person, so the shader wasn't sent.",
|
|
105
|
+
no_chrome: "check: there's no Chrome on this computer to draw the shader in, and no --game with ZAISMA_KEY to draw it on Zaisma.",
|
|
106
|
+
local_chrome_failed: "check: the Chrome on this computer couldn't draw the shader.",
|
|
77
107
|
server_unreachable: "Zaisma couldn't be reached: no connection, or a wrong ZAISMA_API.",
|
|
78
108
|
unexpected_answer: "Zaisma answered without JSON, like a page from a network in between.",
|
|
79
109
|
};
|
|
@@ -91,9 +121,16 @@ const COMMANDS = {
|
|
|
91
121
|
games: { about: "List your games", arguments: [], flags: {} },
|
|
92
122
|
new: { about: "Make a game (it starts as a draft)", arguments: [{ name: "title", isRest: true }], flags: { slug: { hasValue: true, placeholder: "<slug>", about: "Its link name, as in zaisma.com/g/<slug>; made from the title if left out" } } },
|
|
93
123
|
check: {
|
|
94
|
-
about:
|
|
124
|
+
about:
|
|
125
|
+
"Check a game's folder for anything Zaisma refuses or that won't work on Zaisma, with how to fix each, before anything is sent; needs no key. " +
|
|
126
|
+
"On a shader's folder (one with image.glsl, below), draw it as Zaisma's check does, in the Chrome on this computer (CHROME_PATH, the system's, or one Playwright or @puppeteer/browsers downloaded), " +
|
|
127
|
+
"saving its sheet picture beside the folder; with no Chrome, on Zaisma with --game and ZAISMA_KEY (up to 100 a day)",
|
|
95
128
|
arguments: [{ name: "folder" }],
|
|
96
|
-
flags: {
|
|
129
|
+
flags: {
|
|
130
|
+
game: { hasValue: true, placeholder: "<slug>", about: "The game it's for, so the fixes name it (and, with ZAISMA_KEY set, so its own servers count); for a shader's folder with no Chrome here, the game to draw it on Zaisma for" },
|
|
131
|
+
screen: { hasValue: true, choices: SCREENS, about: "A shader's folder only: the screen to draw it for, wide (desktops and tablets; the default) or phone" },
|
|
132
|
+
"draw-on-zaisma": { hasValue: false, about: "A shader's folder only: draw it on Zaisma's own renderer, with --game and ZAISMA_KEY, even when there's a Chrome here" },
|
|
133
|
+
},
|
|
97
134
|
},
|
|
98
135
|
upload: {
|
|
99
136
|
about: "Upload a version; only changed files are sent. It runs the check first, and downloads files the game loads from outside sites and unpacks pre-compressed builds in what it sends, never in the folder",
|
|
@@ -105,6 +142,16 @@ const COMMANDS = {
|
|
|
105
142
|
"match-update-mode": { hasValue: true, placeholder: "<next_match|now>", about: "With --publish-when-approved: when running matches get it: next_match (they finish on the version they started; the default) or now (every live match switches within seconds, in the same room)" },
|
|
106
143
|
},
|
|
107
144
|
},
|
|
145
|
+
shader: {
|
|
146
|
+
about:
|
|
147
|
+
"Send a shader for a game's background from its folder (below): each texture goes as an image of kind shader_texture (one the game has already, byte for byte, is used again) and is waited for, " +
|
|
148
|
+
"then the shader; Zaisma checks it in a minute or two, then set_background or the dashboard shows it",
|
|
149
|
+
arguments: [{ name: "folder" }],
|
|
150
|
+
flags: {
|
|
151
|
+
game: { hasValue: true, isRequired: true, placeholder: "<slug>", about: "The game it's for" },
|
|
152
|
+
screen: { hasValue: true, isRequired: true, choices: SCREENS, about: "wide (desktops and tablets) or phone (composed for a tall screen)" },
|
|
153
|
+
},
|
|
154
|
+
},
|
|
108
155
|
versions: { about: "List a game's versions and preview links", arguments: [{ name: "slug" }], flags: {} },
|
|
109
156
|
publish: {
|
|
110
157
|
about: "Publish a version that passed, or roll back to an older one",
|
|
@@ -136,6 +183,13 @@ const COMMANDS = {
|
|
|
136
183
|
secrets: { about: "A game's secrets, which its game server reads as server.secrets and room.secrets: their names and when each was set, never the values", arguments: [{ name: "slug" }], flags: {} },
|
|
137
184
|
"secrets set": { about: "Set a secret for a game's server, replacing one of the same name: the value piped in, or typed without showing; it's never shown again", arguments: [{ name: "slug" }, { name: "secret_name" }], flags: {} },
|
|
138
185
|
"secrets delete": { about: "Delete one of a game's secrets", arguments: [{ name: "slug" }, { name: "secret_name" }], flags: {} },
|
|
186
|
+
items: { about: "What a game sells or grants: each item's name, kind, category and price, and the game's refund policy", arguments: [{ name: "slug" }], flags: {} },
|
|
187
|
+
"items set": {
|
|
188
|
+
about: "Make a game's items match a JSON file (or piped in) of the whole list, as list_items answers its items: each changed item is set, and each one missing from the file removed, unless players own it",
|
|
189
|
+
arguments: [{ name: "slug" }, { name: "file", isOptional: true }],
|
|
190
|
+
flags: {},
|
|
191
|
+
},
|
|
192
|
+
"items remove": { about: "Remove an item nobody bought or was granted", arguments: [{ name: "slug" }, { name: "item_name" }], flags: {} },
|
|
139
193
|
"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: {} },
|
|
140
194
|
"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: {} },
|
|
141
195
|
logs: {
|
|
@@ -239,7 +293,7 @@ const COMMANDS = {
|
|
|
239
293
|
help: { about: "This help; with --json, every command, flag, exit code and error code", arguments: [], flags: {} },
|
|
240
294
|
};
|
|
241
295
|
/** Commands with a second word, like zaisma forum post. */
|
|
242
|
-
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"], "kept-rooms": ["delete"] };
|
|
296
|
+
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"] };
|
|
243
297
|
/** Flags every command takes. */
|
|
244
298
|
const GLOBAL_FLAGS = {
|
|
245
299
|
json: { hasValue: false, about: "Print the API's answer as JSON, as-is (on failure its { error }), and nothing else" },
|
|
@@ -373,6 +427,20 @@ function parseCommandLine(argv) {
|
|
|
373
427
|
return { command, values, flags, globalFlags, rest };
|
|
374
428
|
}
|
|
375
429
|
|
|
430
|
+
/** A shader's folder, as zaisma shader and zaisma check read it. */
|
|
431
|
+
const SHADER_FOLDER_HELP = [
|
|
432
|
+
"A shader's folder (zaisma shader, zaisma check):",
|
|
433
|
+
" image.glsl The image pass, Shadertoy's form in WebGL2's GLSL: void mainImage(out vec4 fragColor, in vec2 fragCoord) { … }.",
|
|
434
|
+
" buffer-a.glsl … buffer-d.glsl Buffers, if any: each drawn to a picture kept between frames, a to d, before the image pass.",
|
|
435
|
+
" channels.json If any pass reads a channel: what each pass's iChannel0 to iChannel3 read, by pass (image, buffer-a … buffer-d).",
|
|
436
|
+
" Each channel is the API's, with the texture named by its file in the folder (texture_file) instead of an image_id:",
|
|
437
|
+
` ${JSON.stringify(CHANNELS_FILE_EXAMPLE)}`,
|
|
438
|
+
" channel_index 0 to 3, each once in a pass; input_kind buffer (with buffer_name a to d, a buffer file in the folder) or texture (with texture_file);",
|
|
439
|
+
" filter linear (the default; a texture's with mipmaps) or nearest; wrap clamp (a buffer's default) or repeat (a texture's).",
|
|
440
|
+
` *.png, *.jpg, *.webp The textures channels.json names: up to ${SHADER_LIMITS.maximumShaderTextureCount}, each up to ${SHADER_LIMITS.maximumTextureSizeBytes / 1048576} MB and ${SHADER_LIMITS.maximumTextureSidePx} px a side.`,
|
|
441
|
+
" Any other file, a texture no channel names, or a field channels.json doesn't take is refused before anything is sent; hidden files are left out.",
|
|
442
|
+
];
|
|
443
|
+
|
|
376
444
|
function helpText() {
|
|
377
445
|
const lines = ["Usage:"];
|
|
378
446
|
for (const command of Object.keys(COMMANDS)) {
|
|
@@ -385,6 +453,8 @@ function helpText() {
|
|
|
385
453
|
"Every command takes --json: it prints the API's answer as-is (on failure, its { error }) and nothing else.",
|
|
386
454
|
"Categories: " + FORUM_CATEGORIES.join(", ") + ".",
|
|
387
455
|
"",
|
|
456
|
+
...SHADER_FOLDER_HELP,
|
|
457
|
+
"",
|
|
388
458
|
"Exit codes:",
|
|
389
459
|
...Object.values(EXIT_CODES).map((exit) => ` ${exit.exitCode} ${exit.meaning}`),
|
|
390
460
|
"",
|
|
@@ -406,6 +476,13 @@ function helpAnswer() {
|
|
|
406
476
|
flags: Object.entries(spec.flags).map(flagAnswer),
|
|
407
477
|
})),
|
|
408
478
|
global_flags: Object.entries(GLOBAL_FLAGS).map(flagAnswer),
|
|
479
|
+
shader_folder: {
|
|
480
|
+
pass_files: Object.keys(SHADER_PASS_FILES),
|
|
481
|
+
channels_file: CHANNELS_FILE,
|
|
482
|
+
channel_fields: CHANNEL_FIELDS,
|
|
483
|
+
channels_file_example: CHANNELS_FILE_EXAMPLE,
|
|
484
|
+
texture_extensions: TEXTURE_EXTENSIONS,
|
|
485
|
+
},
|
|
409
486
|
exit_codes: Object.entries(EXIT_CODES).map(([name, exit]) => ({ exit_code: exit.exitCode, name, meaning: exit.meaning })),
|
|
410
487
|
error_codes: Object.entries(COMMAND_ERROR_CODES).map(([code, meaning]) => ({ code, meaning })),
|
|
411
488
|
};
|
|
@@ -518,6 +595,10 @@ function printSmallerNotes(notes) {
|
|
|
518
595
|
|
|
519
596
|
/** zaisma check: the problems, or the answer with --json. Ends with problems_found when one isn't fixed by the upload command. */
|
|
520
597
|
async function checkFolder({ folder }, flags) {
|
|
598
|
+
if ((await stat(join(folder, "image.glsl")).catch(() => null))?.isFile()) return checkShaderFolder(folder, flags);
|
|
599
|
+
for (const name of ["screen", "draw-on-zaisma"]) {
|
|
600
|
+
if (flags[name]) refuse("unknown_field", { message: `--${name} is only for a shader's folder, and ${folder} has no image.glsl.`, field: `--${name}`, fix: `Leave --${name} out to check a game's folder, or give a shader's folder (zaisma help shows one).` });
|
|
601
|
+
}
|
|
521
602
|
const answer = await checkGame(await readGameFolder(folder), flags.game ?? null);
|
|
522
603
|
const hasProblems = answer.problems.some((problem) => !problem.is_fixed_by_upload_command);
|
|
523
604
|
if (isJson) printJson(answer);
|
|
@@ -534,6 +615,297 @@ async function checkFolder({ folder }, flags) {
|
|
|
534
615
|
return hasProblems ? EXIT_CODES.problems_found : EXIT_CODES.done;
|
|
535
616
|
}
|
|
536
617
|
|
|
618
|
+
// --- Shaders ------------------------------------------------------------------------------------------------------------------
|
|
619
|
+
|
|
620
|
+
const isPlainObject = (given) => typeof given === "object" && given !== null && !Array.isArray(given);
|
|
621
|
+
/** A texture's kind by its first bytes: PNG, JPEG or WebP, or null. */
|
|
622
|
+
const textureTypeOf = (bytes) =>
|
|
623
|
+
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
|
|
624
|
+
? "png"
|
|
625
|
+
: bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff
|
|
626
|
+
? "jpeg"
|
|
627
|
+
: String.fromCharCode(...bytes.subarray(0, 4)) === "RIFF" && String.fromCharCode(...bytes.subarray(8, 12)) === "WEBP"
|
|
628
|
+
? "webp"
|
|
629
|
+
: null;
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* A shader's folder, read and checked closed before anything is sent or drawn: { manifest, textures }. The manifest is the API's shape
|
|
633
|
+
* with each texture channel naming its file (texture_file); textures are the files channels.json names, each { textureFile, bytes }.
|
|
634
|
+
*/
|
|
635
|
+
async function readShaderFolder(folder) {
|
|
636
|
+
if (!(await stat(folder).catch(() => null))?.isDirectory()) refuse("not_a_folder", { message: `${folder} isn't a folder.`, field: "folder", fix: "Give the shader's folder, with its image.glsl at the top." });
|
|
637
|
+
const fileFix = (name) => `A shader's folder holds ${Object.keys(SHADER_PASS_FILES).join(", ")}, ${CHANNELS_FILE} and the textures it names (${TEXTURE_EXTENSIONS.map((extension) => `.${extension}`).join(", ")}); move ${name} out of it. zaisma help shows the folder.`;
|
|
638
|
+
const passSources = new Map();
|
|
639
|
+
const textureFiles = new Map();
|
|
640
|
+
let channelsText = null;
|
|
641
|
+
for (const entry of (await readdir(folder, { withFileTypes: true })).sort((first, second) => first.name.localeCompare(second.name))) {
|
|
642
|
+
if (JUNK.has(entry.name) || entry.name.startsWith(".")) continue;
|
|
643
|
+
const full = join(folder, entry.name);
|
|
644
|
+
if (!entry.isFile()) refuse("unknown_shader_file", { message: `${entry.name} is a folder; a shader's folder holds only its files.`, field: entry.name, fix: fileFix(entry.name) });
|
|
645
|
+
if (entry.name in SHADER_PASS_FILES) passSources.set(entry.name, await readFile(full, "utf8"));
|
|
646
|
+
else if (entry.name === CHANNELS_FILE) channelsText = await readFile(full, "utf8");
|
|
647
|
+
else if (TEXTURE_EXTENSIONS.includes(extensionOf(entry.name))) textureFiles.set(entry.name, full);
|
|
648
|
+
else refuse("unknown_shader_file", { message: `${entry.name} isn't a file a shader's folder holds.`, field: entry.name, fix: fileFix(entry.name) });
|
|
649
|
+
}
|
|
650
|
+
if (!passSources.has("image.glsl")) refuse("no_image_pass", { message: `${folder} has no image.glsl, the shader's image pass.`, field: "folder", fix: "Put the image pass in image.glsl: void mainImage(out vec4 fragColor, in vec2 fragCoord) { … }, Shadertoy's form in WebGL2's GLSL." });
|
|
651
|
+
for (const [fileName, source] of passSources) {
|
|
652
|
+
if (Buffer.byteLength(source) > SHADER_LIMITS.maximumPassSizeBytes) refuse("shader_too_big", { message: `${fileName} is over ${SHADER_LIMITS.maximumPassSizeBytes / 1024} KB.`, field: fileName, fix: "Take out unused functions and long comments, or move work into a buffer of its own (each pass gets 64 KB)." });
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
const bufferNames = Object.entries(SHADER_PASS_FILES).filter(([fileName, bufferName]) => bufferName && passSources.has(fileName)).map(([, bufferName]) => bufferName);
|
|
656
|
+
const passNames = ["image", ...bufferNames.map((bufferName) => `buffer-${bufferName}`)];
|
|
657
|
+
const channelsByPass = Object.fromEntries(passNames.map((passName) => [passName, []]));
|
|
658
|
+
if (channelsText !== null) {
|
|
659
|
+
let given;
|
|
660
|
+
try {
|
|
661
|
+
given = JSON.parse(channelsText);
|
|
662
|
+
} catch (error) {
|
|
663
|
+
refuse("bad_channels_file", { message: `${CHANNELS_FILE} isn't JSON: ${error.message}.`, field: CHANNELS_FILE, fix: CHANNELS_FIX });
|
|
664
|
+
}
|
|
665
|
+
if (!isPlainObject(given)) refuse("bad_channels_file", { message: `${CHANNELS_FILE} isn't a JSON object of passes.`, field: CHANNELS_FILE, fix: CHANNELS_FIX });
|
|
666
|
+
for (const [passName, givenChannels] of Object.entries(given)) {
|
|
667
|
+
const place = `${CHANNELS_FILE}: ${passName}`;
|
|
668
|
+
if (!passNames.includes(passName)) {
|
|
669
|
+
const isBufferName = /^buffer-[a-d]$/.test(passName);
|
|
670
|
+
refuse(isBufferName ? "bad_channels_file" : "unknown_field", {
|
|
671
|
+
message: isBufferName ? `${CHANNELS_FILE} wires ${passName}, and ${folder} has no ${passName}.glsl.` : `${JSON.stringify(passName)} in ${CHANNELS_FILE} isn't a pass.`,
|
|
672
|
+
field: place,
|
|
673
|
+
fix: `${CHANNELS_FILE} takes the folder's passes: ${passNames.join(", ")}.${isBufferName ? ` Add ${passName}.glsl, or take ${passName} out of ${CHANNELS_FILE}.` : ""}`,
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
if (!Array.isArray(givenChannels) || givenChannels.length > SHADER_LIMITS.maximumChannelCount) refuse("bad_channels_file", { message: `${place} isn't a list of up to ${SHADER_LIMITS.maximumChannelCount} channels.`, field: place, fix: CHANNELS_FIX });
|
|
677
|
+
for (const [channelIndex, givenChannel] of givenChannels.entries()) channelsByPass[passName].push(readChannel(givenChannel, `${place}[${channelIndex}]`, channelsByPass[passName], bufferNames, textureFiles));
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
const namedFiles = [...new Set(Object.values(channelsByPass).flatMap((channels) => channels.map((channel) => channel.texture_file).filter(Boolean)))];
|
|
682
|
+
const unnamedFile = [...textureFiles.keys()].find((name) => !namedFiles.includes(name));
|
|
683
|
+
if (unnamedFile) refuse("unknown_shader_file", { message: `No channel in ${CHANNELS_FILE} reads ${unnamedFile}.`, field: unnamedFile, fix: `Name it as a channel's texture_file in ${CHANNELS_FILE}, or move it out of the folder.` });
|
|
684
|
+
if (namedFiles.length > SHADER_LIMITS.maximumShaderTextureCount) {
|
|
685
|
+
refuse("too_many_shader_textures", { message: `${CHANNELS_FILE} names ${namedFiles.length} textures; a shader reads up to ${SHADER_LIMITS.maximumShaderTextureCount}.`, field: CHANNELS_FILE, fix: "Name at most 4 different textures across the image pass and its buffers; several channels can read the same one." });
|
|
686
|
+
}
|
|
687
|
+
const textures = [];
|
|
688
|
+
for (const textureFile of namedFiles) {
|
|
689
|
+
const bytes = new Uint8Array(await readFile(textureFiles.get(textureFile)));
|
|
690
|
+
if (bytes.length > SHADER_LIMITS.maximumTextureSizeBytes) refuse("shader_texture_too_big", { message: `${textureFile} is over ${SHADER_LIMITS.maximumTextureSizeBytes / 1048576} MB.`, field: textureFile, fix: "Save it smaller (a JPEG or WebP, or fewer pixels; a shader samples it with mipmaps)." });
|
|
691
|
+
if (!textureTypeOf(bytes)) refuse("not_an_image", { message: `${textureFile} isn't a PNG, JPEG or WebP image.`, field: textureFile, fix: "Save it as a PNG, JPEG or WebP file." });
|
|
692
|
+
textures.push({ textureFile, bytes });
|
|
693
|
+
}
|
|
694
|
+
const passOf = (passName, fileName) => ({ source: passSources.get(fileName), channels: channelsByPass[passName] });
|
|
695
|
+
return {
|
|
696
|
+
manifest: { image: passOf("image", "image.glsl"), buffers: bufferNames.map((bufferName) => ({ buffer_name: bufferName, ...passOf(`buffer-${bufferName}`, `buffer-${bufferName}.glsl`) })) },
|
|
697
|
+
textures,
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/** One channel of channels.json, checked closed, with the API's defaults filled in: filter linear, wrap repeat for a texture and clamp for a buffer. */
|
|
702
|
+
function readChannel(given, place, earlier, bufferNames, textureFiles) {
|
|
703
|
+
const bad = (field, message) => refuse("bad_shader_channel", { message, field, fix: CHANNELS_FIX });
|
|
704
|
+
if (!isPlainObject(given)) bad(place, `${place} isn't an object.`);
|
|
705
|
+
const unknown = Object.keys(given).find((key) => !CHANNEL_FIELDS.includes(key));
|
|
706
|
+
if (unknown !== undefined) {
|
|
707
|
+
refuse("unknown_field", { message: `${unknown} isn't a field of a channel in ${CHANNELS_FILE}.`, field: `${place}.${unknown}`, fix: `${unknown === "image_id" ? "In a folder, a texture channel names its file: texture_file. " : ""}Leave it out. A channel takes: ${CHANNEL_FIELDS.join(", ")}.` });
|
|
708
|
+
}
|
|
709
|
+
const { channel_index: channelIndex, input_kind: inputKind } = given;
|
|
710
|
+
if (!Number.isInteger(channelIndex) || channelIndex < 0 || channelIndex >= SHADER_LIMITS.maximumChannelCount) bad(`${place}.channel_index`, `${place}.channel_index isn't 0, 1, 2 or 3.`);
|
|
711
|
+
if (earlier.some((channel) => channel.channel_index === channelIndex)) bad(`${place}.channel_index`, `${place.replace(/\[\d+\]$/, "")} has channel_index ${channelIndex} twice.`);
|
|
712
|
+
if (inputKind !== "buffer" && inputKind !== "texture") bad(`${place}.input_kind`, `${place}.input_kind ${JSON.stringify(inputKind ?? null)} isn't buffer or texture.`);
|
|
713
|
+
const bufferName = given.buffer_name ?? null;
|
|
714
|
+
const textureFile = given.texture_file ?? null;
|
|
715
|
+
if (inputKind === "buffer") {
|
|
716
|
+
if (!bufferNames.includes(bufferName)) {
|
|
717
|
+
bad(`${place}.buffer_name`, bufferName === null ? `${place} reads a buffer but names none.` : `${place} reads buffer ${JSON.stringify(bufferName)}, and the folder has no buffer-${bufferName}.glsl${bufferNames.length ? ` (it has ${bufferNames.map((name) => `buffer-${name}.glsl`).join(", ")})` : ""}.`);
|
|
718
|
+
}
|
|
719
|
+
if (textureFile !== null) bad(`${place}.texture_file`, `${place} reads a buffer, so it takes no texture_file.`);
|
|
720
|
+
} else {
|
|
721
|
+
if (typeof textureFile !== "string" || !textureFiles.has(textureFile)) bad(`${place}.texture_file`, textureFile === null ? `${place} reads a texture but names no texture_file.` : `${place} reads ${JSON.stringify(textureFile)}, which isn't a texture in the folder.`);
|
|
722
|
+
if (bufferName !== null) bad(`${place}.buffer_name`, `${place} reads a texture, so it takes no buffer_name.`);
|
|
723
|
+
}
|
|
724
|
+
const filter = given.filter ?? "linear";
|
|
725
|
+
if (filter !== "linear" && filter !== "nearest") bad(`${place}.filter`, `${place}.filter ${JSON.stringify(filter)} isn't linear or nearest.`);
|
|
726
|
+
const wrap = given.wrap ?? (inputKind === "texture" ? "repeat" : "clamp");
|
|
727
|
+
if (wrap !== "clamp" && wrap !== "repeat") bad(`${place}.wrap`, `${place}.wrap ${JSON.stringify(wrap)} isn't clamp or repeat.`);
|
|
728
|
+
return { channel_index: channelIndex, input_kind: inputKind, buffer_name: inputKind === "buffer" ? bufferName : null, texture_file: inputKind === "texture" ? textureFile : null, filter, wrap };
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** The folder's manifest as the API takes it: each texture channel naming its image (imageIdOf its file) instead of its file. */
|
|
732
|
+
function manifestWithImageIds(manifest, imageIdOf) {
|
|
733
|
+
const passWith = (pass) => ({ ...pass, channels: pass.channels.map(({ texture_file: textureFile, ...channel }) => ({ ...channel, image_id: textureFile === null ? null : imageIdOf(textureFile) })) });
|
|
734
|
+
return { image: passWith(manifest.image), buffers: manifest.buffers.map(passWith) };
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* Sends each texture as an image of kind shader_texture, or uses an approved one the game has with the same bytes, and waits until each
|
|
739
|
+
* is approved (at once, unless image matching couldn't check it and a person looks). Answers each { texture_file, image_id, added_image },
|
|
740
|
+
* added_image being the API's answer as-is, or null for one used again.
|
|
741
|
+
*/
|
|
742
|
+
async function sendTextures(slug, textures) {
|
|
743
|
+
if (!textures.length) return [];
|
|
744
|
+
const { images } = await api("GET", `/games/${slug}`);
|
|
745
|
+
const textureImages = [];
|
|
746
|
+
for (const texture of textures) {
|
|
747
|
+
const textureHash = sha256Of(texture.bytes);
|
|
748
|
+
let imageId = null;
|
|
749
|
+
for (const image of images.filter((candidate) => candidate.kind === "shader_texture" && candidate.review_status === "approved" && candidate.size_bytes === texture.bytes.length)) {
|
|
750
|
+
const stored = await fetch(image.image_url).then((response) => (response.ok ? response.arrayBuffer() : null)).catch(() => null);
|
|
751
|
+
if (stored && sha256Of(new Uint8Array(stored)) === textureHash) {
|
|
752
|
+
imageId = image.id;
|
|
753
|
+
break;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
if (imageId) {
|
|
757
|
+
say(`Using ${texture.textureFile}: the game has it already (${imageId}).`);
|
|
758
|
+
textureImages.push({ texture_file: texture.textureFile, image_id: imageId, added_image: null });
|
|
759
|
+
continue;
|
|
760
|
+
}
|
|
761
|
+
say(`Sending ${texture.textureFile} (${readableSize(texture.bytes.length)})…`);
|
|
762
|
+
const added = await api("POST", `/games/${slug}/images?kind=shader_texture`, texture.bytes);
|
|
763
|
+
textureImages.push({ texture_file: texture.textureFile, image_id: added.image.id, added_image: added });
|
|
764
|
+
}
|
|
765
|
+
let waiting = textureImages.filter((textureImage) => textureImage.added_image && textureImage.added_image.image.review_status !== "approved");
|
|
766
|
+
if (waiting.length) say("Image matching couldn't check a texture just now, so a person at Zaisma looks; waiting a minute…");
|
|
767
|
+
for (let i = 0; i < TEXTURE_CHECK_COUNT && waiting.length; i++) {
|
|
768
|
+
await sleep(TEXTURE_CHECK_INTERVAL_MS);
|
|
769
|
+
const { images: checked } = await api("GET", `/games/${slug}`);
|
|
770
|
+
const statusOf = (textureImage) => checked.find((image) => image.id === textureImage.image_id)?.review_status ?? "rejected";
|
|
771
|
+
const rejected = waiting.find((textureImage) => statusOf(textureImage) === "rejected");
|
|
772
|
+
if (rejected) refuse("shader_texture_not_approved", { message: `${rejected.texture_file} (${rejected.image_id}) was rejected, so the shader wasn't sent.`, field: rejected.texture_file, fix: "The game's images (get_game) give its review_reason; use another texture." }, EXIT_CODES.failed);
|
|
773
|
+
waiting = waiting.filter((textureImage) => statusOf(textureImage) !== "approved");
|
|
774
|
+
}
|
|
775
|
+
if (waiting.length) {
|
|
776
|
+
refuse(
|
|
777
|
+
"shader_texture_not_approved",
|
|
778
|
+
{ message: `${waiting[0].texture_file} (${waiting[0].image_id}) waits for a person at Zaisma, usually within a day, so the shader wasn't sent.`, field: waiting[0].texture_file, fix: "Run the same command again once the game's images (get_game) show it approved: it's used then, not sent again." },
|
|
779
|
+
EXIT_CODES.failed,
|
|
780
|
+
);
|
|
781
|
+
}
|
|
782
|
+
return textureImages;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/** zaisma shader: sends the folder's textures, then the shader. With --json, { texture_images, added_shader }: the API's answers as-is. */
|
|
786
|
+
async function sendShader({ folder }, flags) {
|
|
787
|
+
const { manifest, textures } = await readShaderFolder(folder);
|
|
788
|
+
const textureImages = await sendTextures(flags.game, textures);
|
|
789
|
+
const imageIds = new Map(textureImages.map((textureImage) => [textureImage.texture_file, textureImage.image_id]));
|
|
790
|
+
const answer = await api("POST", `/games/${flags.game}/shaders`, { screen: flags.screen, ...manifestWithImageIds(manifest, (textureFile) => imageIds.get(textureFile)) });
|
|
791
|
+
if (isJson) return printAnswer({ texture_images: textureImages, added_shader: answer });
|
|
792
|
+
console.log(`Sent ${answer.shader.id} for ${answer.shader.screen}: ${answer.shader.review_status}.`);
|
|
793
|
+
if (answer.review_message) console.log(answer.review_message);
|
|
794
|
+
return EXIT_CODES.done;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/** Draws the shader as Zaisma's check does, in a headless Chrome on this computer, from the check's own page (shader-check.mjs). */
|
|
798
|
+
async function drawInChrome(chromePath, manifest, textures, screen) {
|
|
799
|
+
const input = shaderRenderInputOf(manifestWithImageIds(manifest, (textureFile) => textureFile), screen, textures.map((texture) => ({ imageId: texture.textureFile, bytes: texture.bytes })), true);
|
|
800
|
+
const { textureExpressions, checkExpression } = shaderCheckPageExpressions(input);
|
|
801
|
+
const failed = (error) => refuse("local_chrome_failed", { message: `Chrome on this computer couldn't draw the shader: ${error.message}`, field: process.env.CHROME_PATH ? "CHROME_PATH" : null, fix: "Set CHROME_PATH to another Chrome or Chromium; or give --game <slug> with ZAISMA_KEY set, and it's drawn on Zaisma instead." }, EXIT_CODES.failed);
|
|
802
|
+
say(`Drawing it for ${screen} as Zaisma's check does, in Chrome on this computer; this takes a minute or two…`);
|
|
803
|
+
let chrome;
|
|
804
|
+
try {
|
|
805
|
+
chrome = await openChrome(chromePath, "zaisma-shader-check-");
|
|
806
|
+
} catch (error) {
|
|
807
|
+
failed(error);
|
|
808
|
+
}
|
|
809
|
+
let timer;
|
|
810
|
+
try {
|
|
811
|
+
const { targetId } = await chrome.send("Target.createTarget", { url: "about:blank" });
|
|
812
|
+
const { sessionId } = await chrome.send("Target.attachToTarget", { targetId, flatten: true });
|
|
813
|
+
const send = (method, parameters) => chrome.send(method, parameters, sessionId);
|
|
814
|
+
// Nothing the check page asks for leaves it.
|
|
815
|
+
chrome.listen(sessionId, (method, parameters) => method === "Fetch.requestPaused" && send("Fetch.failRequest", { requestId: parameters.requestId, errorReason: "BlockedByClient" }).catch(() => {}));
|
|
816
|
+
await send("Fetch.enable", { patterns: [{ urlPattern: "*" }] });
|
|
817
|
+
const { frameTree } = await send("Page.getFrameTree");
|
|
818
|
+
await send("Page.setDocumentContent", { frameId: frameTree.frame.id, html: SHADER_CHECK_PAGE });
|
|
819
|
+
const evaluate = async (expression) => {
|
|
820
|
+
const { result: evaluated, exceptionDetails } = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
|
|
821
|
+
if (exceptionDetails) throw new Error(exceptionDetails.exception?.description?.split("\n")[0] ?? exceptionDetails.text);
|
|
822
|
+
return evaluated.value;
|
|
823
|
+
};
|
|
824
|
+
for (const expression of textureExpressions) await evaluate(expression);
|
|
825
|
+
const outOfTime = new Promise((resolve) => (timer = setTimeout(() => resolve(null), SHADER_LIMITS.checkTimeoutSec * 1000)));
|
|
826
|
+
const render = shaderRenderFromPage(await Promise.race([evaluate(checkExpression), outOfTime]), input);
|
|
827
|
+
return { rendererKind: "local_chrome", shaderCheck: await shaderDraftAnswer(render, screen), remainingShaderCheckCount: null, sheetPng: render.sheetPng, textureImages: [] };
|
|
828
|
+
} catch (error) {
|
|
829
|
+
if (error instanceof CommandError) throw error;
|
|
830
|
+
failed(error);
|
|
831
|
+
} finally {
|
|
832
|
+
clearTimeout(timer);
|
|
833
|
+
await chrome.close();
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/** Draws the shader on Zaisma, as a check before sending (POST /games/:slug/shader-checks), after sending its textures; downloads its sheet. */
|
|
838
|
+
async function drawOnZaisma(slug, manifest, textures, screen) {
|
|
839
|
+
const textureImages = await sendTextures(slug, textures);
|
|
840
|
+
const imageIds = new Map(textureImages.map((textureImage) => [textureImage.texture_file, textureImage.image_id]));
|
|
841
|
+
say(`Drawing it for ${screen} on Zaisma; this takes a minute or two…`);
|
|
842
|
+
const answer = await api("POST", `/games/${slug}/shader-checks`, { screen, ...manifestWithImageIds(manifest, (textureFile) => imageIds.get(textureFile)) });
|
|
843
|
+
let sheetPng = null;
|
|
844
|
+
if (answer.shader_check.sheet_url) {
|
|
845
|
+
const response = await fetch(answer.shader_check.sheet_url).catch(() => null);
|
|
846
|
+
if (response?.ok) sheetPng = new Uint8Array(await response.arrayBuffer());
|
|
847
|
+
}
|
|
848
|
+
return { rendererKind: "zaisma", shaderCheck: answer.shader_check, remainingShaderCheckCount: answer.remaining_shader_check_count, sheetPng, textureImages };
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* zaisma check on a shader's folder: drawn in Chrome on this computer when there is one, otherwise on Zaisma (--game and ZAISMA_KEY),
|
|
853
|
+
* with its sheet saved beside the folder. Ends with problems_found when it doesn't compile, is too slow at a level or flashes; its notes
|
|
854
|
+
* never change the exit code. --json prints { renderer_kind, shader_check, remaining_shader_check_count, sheet_file, texture_images }.
|
|
855
|
+
*/
|
|
856
|
+
async function checkShaderFolder(folder, flags) {
|
|
857
|
+
if (flags["draw-on-zaisma"] && !flags.game) refuse("missing_field", { message: "--draw-on-zaisma needs --game: the game to draw it for.", field: "--game", fix: `Run it as: zaisma check ${folder} --game <slug> --draw-on-zaisma, with ZAISMA_KEY set.` });
|
|
858
|
+
const { manifest, textures } = await readShaderFolder(folder);
|
|
859
|
+
const screen = flags.screen ?? "wide";
|
|
860
|
+
const canDrawOnZaisma = Boolean(flags.game && KEY);
|
|
861
|
+
const hasWebSocket = typeof globalThis.WebSocket === "function";
|
|
862
|
+
const chromePath = flags["draw-on-zaisma"] ? null : findChrome([join(process.cwd(), ".wrangler/chrome"), join(process.cwd(), "chrome")]);
|
|
863
|
+
let drawn = null;
|
|
864
|
+
if (chromePath && hasWebSocket) {
|
|
865
|
+
try {
|
|
866
|
+
drawn = await drawInChrome(chromePath, manifest, textures, screen);
|
|
867
|
+
} catch (error) {
|
|
868
|
+
if (!(error instanceof CommandError && error.error.code === "local_chrome_failed" && canDrawOnZaisma)) throw error;
|
|
869
|
+
say(`${error.error.message} Drawing it on Zaisma instead.`);
|
|
870
|
+
}
|
|
871
|
+
} else if (!canDrawOnZaisma && !flags["draw-on-zaisma"]) {
|
|
872
|
+
if (chromePath) refuse("needs_newer_node", { message: `Drawing a shader in Chrome on this computer needs Node 22 or newer; this is ${process.version}.`, field: null, fix: "Run it with Node 22 or newer; or give --game <slug> with ZAISMA_KEY set to draw it on Zaisma." }, EXIT_CODES.failed);
|
|
873
|
+
refuse("no_chrome", { message: "There's no Chrome on this computer to draw the shader in.", field: "--game", fix: "Install Chrome, or set CHROME_PATH to a Chrome or Chromium; or give --game <slug> with ZAISMA_KEY set to draw it on Zaisma (up to 100 checks a day)." }, EXIT_CODES.failed);
|
|
874
|
+
}
|
|
875
|
+
drawn ??= await drawOnZaisma(flags.game, manifest, textures, screen);
|
|
876
|
+
const sheetPath = drawn.sheetPng ? `${resolve(folder)}-${screen}-check.png` : null;
|
|
877
|
+
if (sheetPath) await writeFile(sheetPath, drawn.sheetPng);
|
|
878
|
+
const sheetFile = sheetPath ? relative(process.cwd(), sheetPath) || sheetPath : null;
|
|
879
|
+
const isPassing = isShaderCheckPassing(drawn.shaderCheck);
|
|
880
|
+
if (isJson) printJson({ renderer_kind: drawn.rendererKind, shader_check: drawn.shaderCheck, remaining_shader_check_count: drawn.remainingShaderCheckCount, sheet_file: sheetFile, texture_images: drawn.textureImages });
|
|
881
|
+
else printShaderCheck(drawn, { folder, screen, sheetFile, slug: flags.game ?? null, isPassing });
|
|
882
|
+
return isPassing ? EXIT_CODES.done : EXIT_CODES.problems_found;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
/** A shader check for people: what it measured against each limit, the glass, the notes and where its sheet is. */
|
|
886
|
+
function printShaderCheck({ rendererKind, shaderCheck, remainingShaderCheckCount }, { folder, screen, sheetFile, slug, isPassing }) {
|
|
887
|
+
console.log(rendererKind === "local_chrome" ? `Drawn for ${screen} in Chrome on this computer, in software, as Zaisma's check draws it.` : `Drawn for ${screen} on Zaisma (${remainingShaderCheckCount} checks left today).`);
|
|
888
|
+
if (shaderCheck.compile_error) {
|
|
889
|
+
console.log(` ${shaderCheck.compile_error} [shader_does_not_compile]\n Line numbers are the pass's own.`);
|
|
890
|
+
} else {
|
|
891
|
+
const levelCount = shaderCheck.quality_checks.length;
|
|
892
|
+
for (const qualityCheck of shaderCheck.quality_checks) {
|
|
893
|
+
const isTooSlow = qualityCheck.check_frame_ms > qualityCheck.maximum_check_frame_ms;
|
|
894
|
+
console.log(` ${levelCount > 1 ? `Quality ${qualityCheck.quality_level}` : "A frame"}: ${qualityCheck.check_frame_ms} ms in the check; the most is ${qualityCheck.maximum_check_frame_ms}${isTooSlow ? ". Too slow [shader_too_slow]" : "."}`);
|
|
895
|
+
}
|
|
896
|
+
if (shaderCheck.quality_checks.some((qualityCheck) => qualityCheck.check_frame_ms > qualityCheck.maximum_check_frame_ms)) console.log(" Fix: draw less (fewer steps, octaves or lights), or less where iQuality is lower.");
|
|
897
|
+
if (shaderCheck.flash_count !== null) {
|
|
898
|
+
const isFlashing = shaderCheck.flash_count > SHADER_LIMITS.maximumFlashCountPerSec;
|
|
899
|
+
console.log(` Flashes: at most ${shaderCheck.flash_count} in a second; the most is ${SHADER_LIMITS.maximumFlashCountPerSec}${isFlashing ? ". Too many [shader_flashes]: flashing can cause seizures; change brightness slowly." : "."}`);
|
|
900
|
+
}
|
|
901
|
+
if (shaderCheck.is_glass_smoked !== null) console.log(` The glass over it: ${shaderCheck.is_glass_smoked ? "smoked" : "light"}, tinted ${shaderCheck.glass_tint_pct}%.`);
|
|
902
|
+
}
|
|
903
|
+
for (const note of shaderCheck.notes) console.log(` · ${note.message} Fix: ${note.fix} [${note.code}]`);
|
|
904
|
+
if (sheetFile) console.log(`The sheet (wide and phone under Zaisma's glass, small, what changes between frames, and its pixels close up): ${sheetFile}`);
|
|
905
|
+
else if (shaderCheck.sheet_url) console.log(`The sheet, for a day: ${shaderCheck.sheet_url}`);
|
|
906
|
+
console.log(isPassing ? `Ready to send: zaisma shader ${folder} --game ${slug ?? "<slug>"} --screen ${screen}` : "Fix what's above, then check again.");
|
|
907
|
+
}
|
|
908
|
+
|
|
537
909
|
const sha256Of = (text) => createHash("sha256").update(text).digest("hex");
|
|
538
910
|
const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
539
911
|
/** A path's file kind for findOutsideReferences, or null when its text isn't read. */
|
|
@@ -1456,6 +1828,85 @@ async function secrets(command, values) {
|
|
|
1456
1828
|
if (answer.next_steps.some((step) => step.tool === "update_game")) console.log(`It calls no other servers yet: list the hosts it uses this with, like zaisma allowed-hosts ${values.slug} discord.com`);
|
|
1457
1829
|
}
|
|
1458
1830
|
|
|
1831
|
+
/** The fields of an item the file gives and set_item takes. */
|
|
1832
|
+
const ITEM_FILE_FIELDS = ["item_name", "title", "description", "item_kind", "item_category", "price_minor_units", "currency_code", "local_prices"];
|
|
1833
|
+
|
|
1834
|
+
/** A price as people read it, from minor units, for the list. */
|
|
1835
|
+
function itemPriceText(gameItem) {
|
|
1836
|
+
if (gameItem.price_minor_units === null) return "not sold";
|
|
1837
|
+
const isWhole = ["jpy", "krw"].includes(gameItem.currency_code);
|
|
1838
|
+
return `${(gameItem.price_minor_units / (isWhole ? 1 : 100)).toFixed(isWhole ? 0 : 2)} ${gameItem.currency_code.toUpperCase()}${gameItem.local_prices.length ? ` (+${gameItem.local_prices.length} local)` : ""}`;
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
/**
|
|
1842
|
+
* A game's items (…/games/<slug>/items…), as the MCP's list_items, set_item and remove_item. items set takes
|
|
1843
|
+
* the whole list from a file kept beside the game, so prices live in git: one call per changed item, and one
|
|
1844
|
+
* per item gone from the file, which the API refuses for an item players own.
|
|
1845
|
+
*/
|
|
1846
|
+
async function items(command, values) {
|
|
1847
|
+
const path = `/games/${values.slug}/items`;
|
|
1848
|
+
if (command === "items remove") {
|
|
1849
|
+
const answer = await api("DELETE", `${path}/${encodeURIComponent(values.item_name)}`);
|
|
1850
|
+
if (isJson) return printJson(answer);
|
|
1851
|
+
return console.log(`Removed ${values.item_name} from ${values.slug}.`);
|
|
1852
|
+
}
|
|
1853
|
+
if (command === "items set") {
|
|
1854
|
+
const text = values.file ? await readFile(values.file, "utf8").catch(() => refuse("not_a_file", { message: `Couldn't read ${values.file}.`, field: "file", fix: "Give the path of a JSON file of the game's items, or pipe it in." })) : await readInput();
|
|
1855
|
+
let wanted;
|
|
1856
|
+
try {
|
|
1857
|
+
wanted = JSON.parse(text);
|
|
1858
|
+
} catch {
|
|
1859
|
+
wanted = null;
|
|
1860
|
+
}
|
|
1861
|
+
const fileFix = 'Give a JSON list of whole items, like [{ "item_name": "revive", "title": "Revive", "description": "", "item_kind": "consumable", "item_category": "gameplay", "price_minor_units": 199, "currency_code": "usd", "local_prices": [] }].';
|
|
1862
|
+
if (!Array.isArray(wanted) || wanted.some((gameItem) => !gameItem || typeof gameItem !== "object" || typeof gameItem.item_name !== "string")) refuse("bad_item", { message: `${values.file ?? "What was piped in"} isn't a JSON list of items.`, field: "file", fix: fileFix });
|
|
1863
|
+
for (const gameItem of wanted) {
|
|
1864
|
+
const unknown = Object.keys(gameItem).find((key) => !ITEM_FILE_FIELDS.includes(key) && !["card_fee_note", "created_at", "updated_at"].includes(key));
|
|
1865
|
+
if (unknown) refuse("unknown_field", { message: `${gameItem.item_name} has ${unknown}, which isn't an item's field.`, field: "file", fix: `An item takes ${ITEM_FILE_FIELDS.join(", ")}.` });
|
|
1866
|
+
}
|
|
1867
|
+
const names = wanted.map((gameItem) => gameItem.item_name);
|
|
1868
|
+
const repeated = names.find((name, i) => names.indexOf(name) !== i);
|
|
1869
|
+
if (repeated) refuse("bad_item", { message: `${repeated} is in the file twice.`, field: "file", fix: "Give each item once." });
|
|
1870
|
+
const current = (await api("GET", path)).items;
|
|
1871
|
+
const same = (gameItem, existing) => ITEM_FILE_FIELDS.every((field) => JSON.stringify(gameItem[field] ?? null) === JSON.stringify(existing[field] ?? null));
|
|
1872
|
+
const changed = wanted.filter((gameItem) => { const existing = current.find((other) => other.item_name === gameItem.item_name); return !existing || !same(gameItem, existing); });
|
|
1873
|
+
const gone = current.filter((existing) => !names.includes(existing.item_name));
|
|
1874
|
+
const setNames = [];
|
|
1875
|
+
for (const gameItem of changed) {
|
|
1876
|
+
const { item_name: itemName, ...fields } = gameItem;
|
|
1877
|
+
for (const field of ITEM_FILE_FIELDS.slice(1)) if (!(field in fields)) fields[field] = field === "local_prices" ? [] : field === "description" ? "" : null;
|
|
1878
|
+
for (const key of ["card_fee_note", "created_at", "updated_at"]) delete fields[key];
|
|
1879
|
+
await api("PUT", `${path}/${encodeURIComponent(itemName)}`, fields);
|
|
1880
|
+
setNames.push(itemName);
|
|
1881
|
+
say(`Set ${itemName}.`);
|
|
1882
|
+
}
|
|
1883
|
+
const removedNames = [];
|
|
1884
|
+
const keptNames = [];
|
|
1885
|
+
for (const existing of gone) {
|
|
1886
|
+
try {
|
|
1887
|
+
await api("DELETE", `${path}/${encodeURIComponent(existing.item_name)}`);
|
|
1888
|
+
removedNames.push(existing.item_name);
|
|
1889
|
+
say(`Removed ${existing.item_name}.`);
|
|
1890
|
+
} catch (error) {
|
|
1891
|
+
if (!(error instanceof CommandError) || error.error.code !== "item_has_owners") throw error;
|
|
1892
|
+
keptNames.push(existing.item_name);
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
const answer = await api("GET", path);
|
|
1896
|
+
if (keptNames.length) {
|
|
1897
|
+
refuse("item_has_owners", { message: `Players own ${keptNames.join(", ")}, so ${keptNames.length === 1 ? "it stays" : "they stay"}; everything else matches the file.`, field: "file", fix: "Keep them in the file with price_minor_units and currency_code null to stop selling them." }, EXIT_CODES.failed);
|
|
1898
|
+
}
|
|
1899
|
+
if (isJson) return printJson({ ...answer, set_item_names: setNames, removed_item_names: removedNames });
|
|
1900
|
+
if (!setNames.length && !removedNames.length) console.log(`${values.slug}'s items already match the file.`);
|
|
1901
|
+
return;
|
|
1902
|
+
}
|
|
1903
|
+
const answer = await api("GET", path);
|
|
1904
|
+
if (isJson) return printJson(answer);
|
|
1905
|
+
if (!answer.items.length) console.log(`${values.slug} sells nothing yet. Set its items with: zaisma items set ${values.slug} items.json`);
|
|
1906
|
+
for (const gameItem of answer.items) console.log(`${gameItem.item_name.padEnd(24)} ${gameItem.item_kind.padEnd(11)} ${gameItem.item_category.padEnd(9)} ${itemPriceText(gameItem)}`);
|
|
1907
|
+
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")}`);
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1459
1910
|
/** A game's kept rooms (…/games/<slug>/kept-rooms…), as the MCP's list_kept_rooms and delete_kept_room. */
|
|
1460
1911
|
async function keptRooms(command, values) {
|
|
1461
1912
|
if (command === "kept-rooms") {
|
|
@@ -1648,6 +2099,7 @@ async function run({ command, values, flags, globalFlags, rest }) {
|
|
|
1648
2099
|
if (command === "check") return checkFolder(values, flags);
|
|
1649
2100
|
if (command === "export") return exportGame(values, flags);
|
|
1650
2101
|
if (command === "upload") return upload(values, flags);
|
|
2102
|
+
if (command === "shader") return sendShader(values, flags);
|
|
1651
2103
|
if (command === "versions") {
|
|
1652
2104
|
const answer = await api("GET", `/games/${values.slug}`);
|
|
1653
2105
|
if (isJson) return printAnswer(answer);
|
|
@@ -1689,6 +2141,7 @@ async function run({ command, values, flags, globalFlags, rest }) {
|
|
|
1689
2141
|
else if (command === "own-servers") await ownServers(values, flags);
|
|
1690
2142
|
else if (command === "links" || command.startsWith("links ")) await links(command, values, flags);
|
|
1691
2143
|
else if (command === "secrets" || command.startsWith("secrets ")) await secrets(command, values);
|
|
2144
|
+
else if (command === "items" || command.startsWith("items ")) await items(command, values);
|
|
1692
2145
|
else if (command === "kept-rooms" || command.startsWith("kept-rooms ")) await keptRooms(command, values);
|
|
1693
2146
|
else if (command === "logs") await logs(values, flags);
|
|
1694
2147
|
else if (command === "database" || command.startsWith("database ")) await database(command, values, flags);
|