soliterminal 0.0.0-stage → 0.2.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.
@@ -0,0 +1,93 @@
1
+ import { appendFileSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ export const culpritDir = (statsFile) => join(dirname(statsFile), 'culprits');
4
+ export function culpritPath(statsFile, d) {
5
+ const limit = Number.isFinite(d.limit) ? String(d.limit) : 'u';
6
+ return join(culpritDir(statsFile), `${d.seed}-d${d.drawMode}-r${limit}.jsonl`);
7
+ }
8
+ const isCulprit = (x) => typeof x === 'object' && x !== null && typeof x.key === 'string' && typeof x.proven === 'boolean';
9
+ /** The culprits written so far. A missing file is none; a damaged line is skipped. */
10
+ export function parseCulprits(text) {
11
+ const out = [];
12
+ for (const line of text.split('\n')) {
13
+ if (!line.trim())
14
+ continue;
15
+ try {
16
+ const c = JSON.parse(line);
17
+ if (isCulprit(c))
18
+ out.push({ key: c.key, proven: c.proven });
19
+ }
20
+ catch {
21
+ // A line cut short by a crash.
22
+ }
23
+ }
24
+ return out;
25
+ }
26
+ /** Adds culprits in a single write, each on a line of its own. Never throws. */
27
+ export function appendCulprits(path, culprits) {
28
+ if (culprits.length === 0)
29
+ return true;
30
+ try {
31
+ mkdirSync(dirname(path), { recursive: true });
32
+ // A leading newline keeps a line cut short from swallowing the first one written here.
33
+ appendFileSync(path, '\n' + culprits.map((c) => JSON.stringify({ key: c.key, proven: c.proven })).join('\n') + '\n');
34
+ return true;
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
40
+ /**
41
+ * Reads a deal's culprits when the file changed since `seen` (its size, as
42
+ * it only grows). Returns undefined when nothing new is there.
43
+ */
44
+ export function readCulpritsIfChanged(path, seen) {
45
+ let size;
46
+ try {
47
+ size = statSync(path).size;
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ if (size === seen)
53
+ return undefined;
54
+ try {
55
+ return { culprits: parseCulprits(readFileSync(path, 'utf8')), size };
56
+ }
57
+ catch {
58
+ return undefined;
59
+ }
60
+ }
61
+ export function removeCulprits(path) {
62
+ try {
63
+ rmSync(path, { force: true });
64
+ }
65
+ catch {
66
+ // Nothing worth stopping for.
67
+ }
68
+ }
69
+ /** Files older than this are from deals no window is playing any more. */
70
+ export const CULPRIT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
71
+ /** Removes old files, except `keep`: the deal being played, however long ago it was lost. */
72
+ export function removeOldCulprits(statsFile, keep, now = Date.now()) {
73
+ const dir = culpritDir(statsFile);
74
+ let names;
75
+ try {
76
+ names = readdirSync(dir);
77
+ }
78
+ catch {
79
+ return;
80
+ }
81
+ for (const name of names) {
82
+ const path = join(dir, name);
83
+ if (path === keep || !name.endsWith('.jsonl'))
84
+ continue;
85
+ try {
86
+ if (now - statSync(path).mtimeMs > CULPRIT_MAX_AGE_MS)
87
+ rmSync(path, { force: true });
88
+ }
89
+ catch {
90
+ // Removed by another window meanwhile.
91
+ }
92
+ }
93
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * The game in progress, kept on disk so it outlives the terminal: quit, and
3
+ * the next start carries on where it stopped. The file also lets other tools
4
+ * see the board without asking the running game.
5
+ *
6
+ * There is one such file, and whichever window saved last wins it. A game
7
+ * played in two windows at once keeps one name (its id), so however many of
8
+ * them finish it, the statistics count it once.
9
+ *
10
+ * Only the deal and the moves since are stored, as steps that replay with the
11
+ * game's own rules, so the file stays small and a damaged one is caught.
12
+ */
13
+ import { readFileSync, rmSync } from 'node:fs';
14
+ import { dirname, join } from 'node:path';
15
+ import { playTime } from './app.js';
16
+ import { GAME_ID, newGameId } from './stats.js';
17
+ import { writeWhole } from './stats-file.js';
18
+ import { FOUNDATIONS, TABLEAU_COLUMNS, deal, draw, move, steps } from './core/klondike.js';
19
+ /** Where the game in progress lives: SOLITERMINAL_GAME if set, else next to the statistics. */
20
+ export function savedGamePath(env, statsFile) {
21
+ return env.SOLITERMINAL_GAME ?? join(dirname(statsFile), 'current.json');
22
+ }
23
+ // ---------------------------------------------------------------------------
24
+ // Steps
25
+ /** Every card where it lies, foundations in place: unlike positionKey, which foundation holds what matters here. */
26
+ const exact = (s) => JSON.stringify([s.redealsLeft, s.stock, s.waste, s.foundations, s.tableau]);
27
+ const samePosition = (a, b) => exact(a) === exact(b);
28
+ /** The step that turns `before` into `after`, if one does. */
29
+ function stepBetween(before, after) {
30
+ const want = exact(after);
31
+ return steps(before).find((s) => exact(s.state) === want)?.step;
32
+ }
33
+ /** Steps found so far, by the position they lead to: each save only works out the new ones. */
34
+ const known = new WeakMap();
35
+ /** The steps along a game's path, from `states[0]` (the deal) to its last. Undefined if any link is not one step. */
36
+ export function stepsOf(states) {
37
+ const steps = [];
38
+ for (let i = 1; i < states.length; i++) {
39
+ const after = states[i];
40
+ const step = known.get(after) ?? stepBetween(states[i - 1], after);
41
+ if (!step)
42
+ return undefined;
43
+ known.set(after, step);
44
+ steps.push(step);
45
+ }
46
+ return steps;
47
+ }
48
+ /** Replays a saved game with the game's rules: every position from the deal on, or undefined if a step is not legal. */
49
+ export function replaySaved(saved) {
50
+ let s = deal(saved.seed, saved.drawMode, saved.redeals ?? Infinity);
51
+ const states = [s];
52
+ for (const step of saved.steps) {
53
+ const r = 'draw' in step ? draw(s) : move(s, step.from, step.to, step.count);
54
+ if (!r.ok)
55
+ return undefined;
56
+ s = r.state;
57
+ states.push(s);
58
+ }
59
+ return states;
60
+ }
61
+ /**
62
+ * What to write for `app`, or undefined when there is nothing to keep: a
63
+ * finished game, or one whose path cannot be put into steps.
64
+ */
65
+ export function snapshot(app, now) {
66
+ if (app.finishedAt !== undefined || app.play === 'won')
67
+ return undefined;
68
+ const states = [...app.history, app.game];
69
+ const first = states[0];
70
+ const steps = stepsOf(states);
71
+ if (!steps || !samePosition(first, deal(first.seed, first.drawMode, first.redealsLeft)))
72
+ return undefined;
73
+ const w = winnableAt(app, states);
74
+ return {
75
+ version: 2,
76
+ savedAt: new Date(now).toISOString(),
77
+ id: app.gameId,
78
+ ...(app.gameAt === undefined ? {} : { at: app.gameAt }),
79
+ seed: first.seed,
80
+ drawMode: first.drawMode,
81
+ redeals: Number.isFinite(first.redealsLeft) ? first.redealsLeft : null,
82
+ verified: app.verified,
83
+ play: app.play,
84
+ ms: Math.round(playTime(app, now)),
85
+ steps,
86
+ ...(w === undefined ? {} : { winnable: w }),
87
+ };
88
+ }
89
+ /** Where along `states` the app's last winnable position is, if it is on the path. */
90
+ function winnableAt(app, states) {
91
+ const at = app.lastWinnable?.history.length;
92
+ return at !== undefined && states[at] === app.lastWinnable.game ? at : undefined;
93
+ }
94
+ // ---------------------------------------------------------------------------
95
+ // Reading what is on disk
96
+ const isPile = (p) => {
97
+ if (typeof p !== 'object' || p === null)
98
+ return false;
99
+ const { kind, index } = p;
100
+ if (kind === 'waste')
101
+ return true;
102
+ const limit = kind === 'foundation' ? FOUNDATIONS : kind === 'tableau' ? TABLEAU_COLUMNS : 0;
103
+ return Number.isInteger(index) && index >= 0 && index < limit;
104
+ };
105
+ const isStep = (s) => {
106
+ if (typeof s !== 'object' || s === null)
107
+ return false;
108
+ const o = s;
109
+ if (o.draw === true)
110
+ return true;
111
+ return isPile(o.from) && isPile(o.to) && Number.isInteger(o.count) && o.count >= 1 && o.count <= 13;
112
+ };
113
+ /** Checks the shape of what was read; anything odd means there is no saved game. */
114
+ export function parseSavedGame(data) {
115
+ if (typeof data !== 'object' || data === null)
116
+ return undefined;
117
+ const o = data;
118
+ // Version 1 also named the process that wrote it; that is no longer needed.
119
+ if (o.version !== 1 && o.version !== 2)
120
+ return undefined;
121
+ if (!Number.isInteger(o.seed) || (o.drawMode !== 1 && o.drawMode !== 3))
122
+ return undefined;
123
+ if (o.redeals !== null && !(Number.isInteger(o.redeals) && o.redeals >= 0))
124
+ return undefined;
125
+ if (o.play !== 'fresh' && o.play !== 'counted')
126
+ return undefined;
127
+ if (!Array.isArray(o.steps) || !o.steps.every(isStep))
128
+ return undefined;
129
+ return {
130
+ version: 2,
131
+ savedAt: typeof o.savedAt === 'string' ? o.savedAt : '',
132
+ id: typeof o.id === 'string' && GAME_ID.test(o.id) ? o.id : newGameId(),
133
+ ...(Number.isInteger(o.at) && o.at > 0 ? { at: o.at } : {}),
134
+ seed: o.seed,
135
+ drawMode: o.drawMode,
136
+ redeals: o.redeals,
137
+ verified: o.verified === true,
138
+ play: o.play,
139
+ ms: typeof o.ms === 'number' && o.ms >= 0 ? o.ms : 0,
140
+ steps: o.steps,
141
+ ...(Number.isInteger(o.winnable) && o.winnable >= 0 && o.winnable <= o.steps.length ? { winnable: o.winnable } : {}),
142
+ };
143
+ }
144
+ /** A missing, damaged or unreadable file means no saved game. */
145
+ export function loadSavedGame(path) {
146
+ try {
147
+ return parseSavedGame(JSON.parse(readFileSync(path, 'utf8')));
148
+ }
149
+ catch {
150
+ return undefined;
151
+ }
152
+ }
153
+ /** Says whether the game was written; a crash never leaves half a game. Never throws. */
154
+ export function writeSavedGame(path, game) {
155
+ return writeWhole(path, JSON.stringify(game) + '\n');
156
+ }
157
+ export function removeSavedGame(path) {
158
+ try {
159
+ rmSync(path, { force: true });
160
+ }
161
+ catch {
162
+ // Nothing to do: the next save or start sorts it out.
163
+ }
164
+ }
package/dist/share.js ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Sharing results for Klondike research, only ever when the player agrees.
3
+ *
4
+ * Nothing is collected on its own. Each time the finished games reach a new
5
+ * hundred (100, 200, …) the player is asked once. Yes sends the games not
6
+ * sent yet; no waits for the next hundred, which then sends them all. There is
7
+ * no way to send smaller batches: a server that takes a game at a time from
8
+ * everyone is a server under needless load.
9
+ *
10
+ * What goes out is the deal and how it went, and a random name for the
11
+ * installation so a batch sent twice counts once. Nothing about the player or
12
+ * their computer: no names, paths, addresses or clock times beyond the day.
13
+ */
14
+ import { randomUUID } from 'node:crypto';
15
+ import { DEFAULT_REDEALS } from './core/klondike.js';
16
+ import { withSent } from './stats.js';
17
+ /** Games per question, and the smallest batch ever sent. */
18
+ export const SHARE_EVERY = 100;
19
+ /** The most games one batch carries; any more wait for the next. */
20
+ export const MAX_BATCH = 1000;
21
+ /** Where results go: SOLITERMINAL_SHARE_URL if set, else the project's own server. */
22
+ export const SHARE_URL = 'https://soliterminal-share.dayliver.workers.dev/v1/games';
23
+ export function shareUrl(env) {
24
+ return env.SOLITERMINAL_SHARE_URL || SHARE_URL;
25
+ }
26
+ /** Finished games not sent yet, oldest first: the next batch. */
27
+ export function unsent(stats) {
28
+ return stats.games.filter((g) => !g.sent).reverse();
29
+ }
30
+ /** Every game finished so far, sent or not. */
31
+ export function finishedGames(stats) {
32
+ return stats.games.length;
33
+ }
34
+ const state = (stats) => stats.share ?? { id: randomUUID(), asked: 0, pending: false };
35
+ /** Whether to ask now: the finished games have passed a hundred not asked about, and a full batch waits. */
36
+ export function shareDue(stats) {
37
+ const total = finishedGames(stats);
38
+ const asked = stats.share?.asked ?? 0;
39
+ return !stats.share?.pending && unsent(stats).length >= SHARE_EVERY && Math.floor(total / SHARE_EVERY) > Math.floor(asked / SHARE_EVERY);
40
+ }
41
+ /** The player said yes: the batch is sent as soon as possible, and again on later starts until it goes through. */
42
+ export function acceptShare(stats) {
43
+ return { ...stats, share: { ...state(stats), asked: finishedGames(stats), pending: true } };
44
+ }
45
+ /** The player said no: ask again at the next hundred. */
46
+ export function declineShare(stats) {
47
+ return { ...stats, share: { ...state(stats), asked: finishedGames(stats), pending: false } };
48
+ }
49
+ /** The batch waiting to go out, if the player agreed to send one. */
50
+ export function sharePayload(stats, client) {
51
+ if (!stats.share?.pending)
52
+ return undefined;
53
+ const waiting = unsent(stats);
54
+ if (waiting.length < SHARE_EVERY)
55
+ return undefined;
56
+ const games = waiting.slice(0, MAX_BATCH);
57
+ const shared = games.map((g) => ({
58
+ id: g.id,
59
+ seed: g.seed,
60
+ draw: g.drawMode,
61
+ // A record from before limits were kept was played with the default.
62
+ limit: g.limit === undefined ? DEFAULT_REDEALS : g.limit,
63
+ result: g.result,
64
+ ms: g.ms,
65
+ moves: g.moves,
66
+ ...(g.redeals === undefined ? {} : { redeals: g.redeals }),
67
+ ...(g.lostAt === undefined ? {} : { lostAt: g.lostAt }),
68
+ ...(g.level === undefined ? {} : { level: g.level }),
69
+ day: new Date(g.at).toISOString().slice(0, 10),
70
+ }));
71
+ return { payload: { v: 1, id: stats.share.id, client, games: shared }, games };
72
+ }
73
+ /** The batch went through: its games are marked sent. */
74
+ export function markShared(stats, ids) {
75
+ return { ...withSent(stats, ids), share: { ...state(stats), pending: false } };
76
+ }
77
+ /** Posts a batch. Resolves to an error message, or undefined once the server has it. Never throws. */
78
+ export async function postShare(url, payload, timeoutMs = 30_000) {
79
+ try {
80
+ const res = await fetch(url, {
81
+ method: 'POST',
82
+ headers: { 'content-type': 'application/json', 'user-agent': payload.client },
83
+ body: JSON.stringify(payload),
84
+ signal: AbortSignal.timeout(timeoutMs),
85
+ });
86
+ if (res.ok)
87
+ return undefined;
88
+ // One batch a day per installation: another window, or an earlier try that did get through.
89
+ if (res.status === 429)
90
+ return 'the server takes one batch a day';
91
+ return `the server said ${res.status}`;
92
+ }
93
+ catch (e) {
94
+ return e.name === 'TimeoutError' ? 'no answer from the server' : 'no connection to the server';
95
+ }
96
+ }
@@ -0,0 +1,125 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ /**
3
+ * JavaScript heap for one solver worker, which bounds the TypeScript search.
4
+ * The WebAssembly engine's memory is outside it and has its own limit (see solver-wasm.ts).
5
+ */
6
+ const WORKER_MEMORY_MB = 1024;
7
+ function job(req, done) {
8
+ return { req, done: done };
9
+ }
10
+ /** A failed judge job gets the answer that claims nothing, so play goes on as if the solver ran out of time. */
11
+ const judging = (state, deep, done) => job({ type: 'judge', state, deep }, (a) => done(a?.verdict ?? 'unclear', a?.next));
12
+ /** One solver worker and the jobs waiting for it, run one at a time. */
13
+ class Lane {
14
+ #worker;
15
+ #queue = [];
16
+ #running;
17
+ #closed = false;
18
+ /** Adds a job. `replace` drops waiting jobs of the same type first, so only the newest is done. */
19
+ add(job, front, replace) {
20
+ if (replace)
21
+ this.#queue = this.#queue.filter((j) => j.req.type !== job.req.type);
22
+ if (front)
23
+ this.#queue.unshift(job);
24
+ else
25
+ this.#queue.push(job);
26
+ this.#pump();
27
+ }
28
+ /** Drops everything, stopping the job in progress. Its answer never arrives. */
29
+ cancel() {
30
+ this.#queue = [];
31
+ if (this.#running) {
32
+ this.#running = undefined;
33
+ void this.#worker?.terminate();
34
+ this.#worker = undefined;
35
+ }
36
+ }
37
+ close() {
38
+ this.#closed = true;
39
+ this.#queue = [];
40
+ return this.#worker?.terminate() ?? Promise.resolve(0);
41
+ }
42
+ #start() {
43
+ // From source this file is .ts; in the published package it is compiled .js.
44
+ const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
45
+ // A search that would take more memory than this ends the worker, not the game.
46
+ const worker = new Worker(new URL(`./solver-worker${ext}`, import.meta.url), { resourceLimits: { maxOldGenerationSizeMb: WORKER_MEMORY_MB } });
47
+ worker.unref();
48
+ // An error ends the worker; 'exit' below deals with what it was doing.
49
+ worker.on('error', () => { });
50
+ worker.on('exit', () => {
51
+ if (worker !== this.#worker || this.#closed)
52
+ return; // cancelled or closed: nobody waits
53
+ this.#worker = undefined;
54
+ this.#finish(undefined);
55
+ });
56
+ worker.on('message', (res) => {
57
+ if (worker === this.#worker)
58
+ this.#finish(res.answer); // else cancelled
59
+ });
60
+ return worker;
61
+ }
62
+ #finish(answer) {
63
+ const job = this.#running;
64
+ this.#running = undefined;
65
+ job?.done(answer);
66
+ this.#pump();
67
+ }
68
+ #pump() {
69
+ if (this.#running || this.#queue.length === 0)
70
+ return;
71
+ this.#running = this.#queue.shift();
72
+ this.#worker ??= this.#start();
73
+ this.#worker.postMessage(this.#running.req);
74
+ }
75
+ }
76
+ /**
77
+ * Talks to the solver workers. One judges each new position quickly and finds
78
+ * deals; only the newest position is worth judging, so a waiting judge request
79
+ * is replaced by a newer one. The second takes the long looks at positions the
80
+ * quick judge could not settle, so those never hold up the quick ones. The
81
+ * third looks one move ahead while the player thinks, and the fourth rates
82
+ * finished deals. A worker that fails is replaced; its job gets an answer that
83
+ * claims nothing (`unclear`, no seed, or level 0).
84
+ */
85
+ export class SolverClient {
86
+ #main = new Lane();
87
+ #deep = new Lane();
88
+ #ahead = new Lane();
89
+ #rate = new Lane();
90
+ /**
91
+ * Resolves with the verdict, and with `winnable` the first move of a win,
92
+ * or never if a newer position replaced this one first.
93
+ */
94
+ judge(state, done) {
95
+ this.#main.add(judging(state, false, done), true, true);
96
+ }
97
+ /** A long look at one position. Replaces any earlier long look, finished or not. */
98
+ judgeDeeply(state, done) {
99
+ this.#deep.cancel();
100
+ this.#deep.add(judging(state, true, done), false, false);
101
+ }
102
+ /** Stops the long look, if one is running; its answer will not arrive. */
103
+ cancelDeep() {
104
+ this.#deep.cancel();
105
+ }
106
+ /** Queues a look at a position the player could move to next; quick ones first. */
107
+ lookAhead(state, deep, done) {
108
+ this.#ahead.add(judging(state, deep, done), false, false);
109
+ }
110
+ /** Drops every look ahead: the player has moved and they no longer apply. */
111
+ cancelAhead() {
112
+ this.#ahead.cancel();
113
+ }
114
+ /** A seed whose deal, with `redeals` allowed, the solver has won. */
115
+ deal(drawMode, redeals, done) {
116
+ this.#main.add(job({ type: 'deal', drawMode, redeals }, done), false, false);
117
+ }
118
+ /** Rates a finished deal on a worker of its own, so play never waits for it. */
119
+ rate(state, done) {
120
+ this.#rate.add(job({ type: 'rate', state }, (level) => done(level ?? 0)), false, false);
121
+ }
122
+ async close() {
123
+ await Promise.all([this.#main.close(), this.#deep.close(), this.#ahead.close(), this.#rate.close()]);
124
+ }
125
+ }
@@ -0,0 +1,47 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { useEngine } from './core/solver.js';
3
+ /**
4
+ * The solver's search compiled from Rust (`solver/`) to WebAssembly: the same
5
+ * search as `core/solver.ts`, several times faster and in a fraction of the
6
+ * memory. `solver.wasm` sits next to this file, in `src/` and in `dist/`.
7
+ */
8
+ /** A search stops, unanswered, once its memory passes this. */
9
+ const MEMORY_LIMIT = 1024 ** 3;
10
+ /** WebAssembly memory only grows, so after a search that took more than this the next one starts afresh. */
11
+ const KEEP_BELOW = 64 * 1024 ** 2;
12
+ const STATUS = ['unknown', 'solved', 'unsolvable'];
13
+ export function wasmEngine(bytes) {
14
+ const module = new WebAssembly.Module(bytes);
15
+ const start = () => new WebAssembly.Instance(module, { env: { now: Date.now } }).exports;
16
+ let wasm;
17
+ return (root, columns, drawMode, maxNodes, timeLimitMs, exhaustive) => {
18
+ wasm ??= start();
19
+ new Uint8Array(wasm.memory.buffer, wasm.input(), root.length).set(root);
20
+ let at;
21
+ try {
22
+ at = wasm.run(columns, drawMode, maxNodes, timeLimitMs, exhaustive ? 1 : 0, MEMORY_LIMIT);
23
+ }
24
+ catch (e) {
25
+ wasm = undefined; // a trapped instance is in no state to use again
26
+ throw e;
27
+ }
28
+ const [status, nodes, count] = new Uint32Array(wasm.memory.buffer, at, 3);
29
+ const moves = Array.from(new Uint32Array(wasm.memory.buffer, at + 12, count));
30
+ if (wasm.memory.buffer.byteLength > KEEP_BELOW)
31
+ wasm = undefined;
32
+ return { status: STATUS[status], nodes: nodes, moves };
33
+ };
34
+ }
35
+ /**
36
+ * Makes every search in this thread use the WebAssembly engine. False when it
37
+ * could not be loaded, in which case the TypeScript search carries on as before.
38
+ */
39
+ export function installWasmEngine() {
40
+ try {
41
+ useEngine(wasmEngine(readFileSync(new URL('./solver.wasm', import.meta.url))));
42
+ return true;
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Runs the solver off the main thread so the screen never freezes while it
3
+ * thinks. Requests are handled one at a time, in order.
4
+ */
5
+ import { parentPort } from 'node:worker_threads';
6
+ import { randomSeed } from './core/deck.js';
7
+ import { findWinnableSeed, judge, judgeDeeply, limitMemory, rateDeal } from './core/solver.js';
8
+ import { installWasmEngine } from './solver-wasm.js';
9
+ installWasmEngine();
10
+ /**
11
+ * Bun, which the standalone binaries run on, ignores a worker's heap limit, so
12
+ * there the search itself stops once the whole process uses this much.
13
+ */
14
+ const BUN_PROCESS_MEMORY = 2 * 1024 ** 3;
15
+ if (process.versions.bun)
16
+ limitMemory(() => process.memoryUsage.rss() > BUN_PROCESS_MEMORY);
17
+ function answer(req) {
18
+ switch (req.type) {
19
+ case 'judge': {
20
+ const { verdict, next } = (req.deep ? judgeDeeply : judge)(req.state);
21
+ return { verdict, next };
22
+ }
23
+ case 'rate':
24
+ return rateDeal(req.state).level;
25
+ case 'deal':
26
+ return findWinnableSeed(req.drawMode, randomSeed, { redeals: req.redeals });
27
+ }
28
+ }
29
+ parentPort.on('message', (req) => parentPort.postMessage({ answer: answer(req) }));
Binary file
@@ -0,0 +1,112 @@
1
+ import { appendFileSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { eventLine, foldLog, parseLegacyStats, parseShare } from './stats.js';
5
+ /**
6
+ * Where statistics live: SOLITERMINAL_STATS if set, else the usual place for
7
+ * app state, %LOCALAPPDATA% on Windows and $XDG_STATE_HOME (~/.local/state)
8
+ * elsewhere. It is a log, one line per finished game, only ever appended to,
9
+ * so several windows playing at once never write over each other's games.
10
+ */
11
+ export function statsPath(env, platform = process.platform, home = homedir()) {
12
+ if (env.SOLITERMINAL_STATS)
13
+ return env.SOLITERMINAL_STATS;
14
+ if (platform === 'win32')
15
+ return join(env.LOCALAPPDATA ?? join(home, 'AppData', 'Local'), 'soliterminal', 'games.jsonl');
16
+ return join(env.XDG_STATE_HOME ?? join(home, '.local', 'state'), 'soliterminal', 'games.jsonl');
17
+ }
18
+ /** Where sharing stands, next to the log. Small, and rewritten whole. */
19
+ export const sharePath = (statsFile) => join(dirname(statsFile), 'share.json');
20
+ /** The statistics file of earlier versions, next to the log. */
21
+ const legacyPath = (statsFile) => join(dirname(statsFile), 'stats.json');
22
+ /** Writes through a temporary file, so a crash never leaves half a file. Never throws. */
23
+ export function writeWhole(path, text) {
24
+ try {
25
+ mkdirSync(dirname(path), { recursive: true });
26
+ const tmp = `${path}.${process.pid}.tmp`;
27
+ writeFileSync(tmp, text);
28
+ renameSync(tmp, path);
29
+ return true;
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ }
35
+ /**
36
+ * Moves the games of an earlier version's `stats.json` into the log, once:
37
+ * only while there is no log yet. The old file is left where it is.
38
+ */
39
+ function migrate(path) {
40
+ if (existsSync(path))
41
+ return;
42
+ let old;
43
+ try {
44
+ old = parseLegacyStats(JSON.parse(readFileSync(legacyPath(path), 'utf8')));
45
+ }
46
+ catch {
47
+ return;
48
+ }
49
+ // Oldest first, as the log is written.
50
+ writeWhole(path, [...old.games].reverse().map((game) => eventLine({ game })).join(''));
51
+ if (old.share && !existsSync(sharePath(path)))
52
+ saveShare(path, old.share);
53
+ }
54
+ /** A missing or damaged file just means no games yet. */
55
+ export function loadStats(path) {
56
+ migrate(path);
57
+ let stats;
58
+ try {
59
+ stats = foldLog(readFileSync(path, 'utf8'));
60
+ }
61
+ catch {
62
+ stats = { games: [] };
63
+ }
64
+ let share;
65
+ try {
66
+ share = parseShare(JSON.parse(readFileSync(sharePath(path), 'utf8')));
67
+ }
68
+ catch {
69
+ share = undefined;
70
+ }
71
+ return share ? { ...stats, share } : stats;
72
+ }
73
+ /**
74
+ * Adds events to the log in a single write, so lines from two windows never
75
+ * interleave. A line cut short by a crash is skipped on reading. Never throws.
76
+ */
77
+ export function appendStats(path, events) {
78
+ if (events.length === 0)
79
+ return true;
80
+ try {
81
+ mkdirSync(dirname(path), { recursive: true });
82
+ // After a write cut short, start on a line of its own rather than finish the broken one.
83
+ const lead = endsMidLine(path) ? '\n' : '';
84
+ appendFileSync(path, lead + events.map(eventLine).join(''));
85
+ return true;
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ function endsMidLine(path) {
92
+ let fd;
93
+ try {
94
+ fd = openSync(path, 'r');
95
+ const size = fstatSync(fd).size;
96
+ if (size === 0)
97
+ return false;
98
+ const last = Buffer.alloc(1);
99
+ readSync(fd, last, 0, 1, size - 1);
100
+ return last[0] !== 0x0a;
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ finally {
106
+ if (fd !== undefined)
107
+ closeSync(fd);
108
+ }
109
+ }
110
+ export function saveShare(statsFile, share) {
111
+ return writeWhole(sharePath(statsFile), JSON.stringify(share, null, 2) + '\n');
112
+ }