@team-antioch/sc2-finder-kit 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +36 -2
- package/dist/asker.d.ts +91 -0
- package/dist/asker.js +214 -0
- package/dist/cache-dir.d.ts +4 -0
- package/dist/cache-dir.js +17 -0
- package/dist/card.d.ts +35 -0
- package/dist/card.js +4 -0
- package/dist/credentials.d.ts +34 -0
- package/dist/credentials.js +33 -0
- package/dist/embedder.d.ts +39 -0
- package/dist/embedder.js +94 -0
- package/dist/embedding-index.d.ts +26 -0
- package/dist/embedding-index.js +129 -0
- package/dist/finder.d.ts +87 -0
- package/dist/finder.js +162 -0
- package/dist/gateway-translator.d.ts +21 -0
- package/dist/gateway-translator.js +62 -0
- package/dist/is-main.d.ts +6 -0
- package/dist/is-main.js +17 -0
- package/dist/jev-language-detector.d.ts +15 -0
- package/dist/jev-language-detector.js +44 -0
- package/dist/jev-ranker.d.ts +45 -0
- package/dist/jev-ranker.js +93 -0
- package/dist/key-file.d.ts +13 -0
- package/dist/key-file.js +62 -0
- package/dist/language-detector.d.ts +20 -0
- package/dist/language-detector.js +38 -0
- package/dist/load-together.d.ts +26 -0
- package/dist/load-together.js +39 -0
- package/dist/login.d.ts +34 -0
- package/dist/login.js +137 -0
- package/dist/narrow.d.ts +57 -0
- package/dist/narrow.js +74 -0
- package/dist/payload-log.d.ts +5 -0
- package/dist/payload-log.js +12 -0
- package/dist/ranker.d.ts +80 -0
- package/dist/ranker.js +40 -0
- package/dist/server.d.ts +178 -0
- package/dist/server.js +565 -0
- package/dist/settings.d.ts +7 -0
- package/dist/settings.js +20 -0
- package/dist/spend-cap.d.ts +14 -0
- package/dist/spend-cap.js +22 -0
- package/dist/test-asks.d.ts +60 -0
- package/dist/test-asks.js +107 -0
- package/dist/translator.d.ts +48 -0
- package/dist/translator.js +51 -0
- package/dist/tray.d.ts +22 -0
- package/dist/tray.js +12 -0
- package/package.json +45 -4
package/dist/server.js
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
1
|
+
// A finder's process (docs/adr/0001): an HTTP server on 127.0.0.1 only that serves the page and
|
|
2
|
+
// answers it. It holds the cards, the embeddings, the model and the ranker's credential; the page
|
|
3
|
+
// gets cards and levels, never a credential. Node's own http, no framework. What differs between
|
|
4
|
+
// finders is passed in: its page, how a card is shown, its tags, what a copy holds and any routes
|
|
5
|
+
// of its own (a doodad's sheet).
|
|
6
|
+
//
|
|
7
|
+
// GET / the page
|
|
8
|
+
// GET /status { finder: <its name>, pid, url, rankers: { on, off }, ...status }: how a
|
|
9
|
+
// caller tells a Finder from anything else on a port
|
|
10
|
+
// GET /events server-sent events: `state` on every change, and each ask's `narrowed`,
|
|
11
|
+
// `ranked`, `failed` and `capped`
|
|
12
|
+
// POST /ask { text, mode: type | enter | refresh, idleMs? }: see asker.ts
|
|
13
|
+
// POST /tick { ask, id, ticked }: ticks a card into the tray, or unticks it
|
|
14
|
+
// POST /clear empties the tray
|
|
15
|
+
// POST /choose { choice }: the badges' choice (a map, say), or null
|
|
16
|
+
// POST /tag { facet, value, action: pin | unpin | drop }
|
|
17
|
+
// POST /settings { idleMs }
|
|
18
|
+
// POST /action { index, inputs }: runs a tray action on the tray
|
|
19
|
+
//
|
|
20
|
+
// With objects (for sc2-adjutant, may change), the tray can be kept for one, named or reopened:
|
|
21
|
+
//
|
|
22
|
+
// POST /object { title }: starts an object for the badges' choice, keeping the tray's cards
|
|
23
|
+
// POST /reopen { key }: reopens an unfinished one, its ticks in the tray
|
|
24
|
+
// POST /put-away puts the open object away; the tray is empty again
|
|
25
|
+
// POST /line { ask, line }: edits the line of the open object's part an ask made
|
|
26
|
+
//
|
|
27
|
+
// The tray's copy text comes with each state, so the page copies it on the click itself.
|
|
28
|
+
//
|
|
29
|
+
// Requests must name this server as their Host, and a POST from a page must come from this
|
|
30
|
+
// server's own: another site open in the browser can't spend on the ranker or write files.
|
|
31
|
+
import { appendFile, mkdir } from "node:fs/promises";
|
|
32
|
+
import { createServer } from "node:http";
|
|
33
|
+
import path from "node:path";
|
|
34
|
+
import { ASK_TIMING, createAsker } from "./asker.js";
|
|
35
|
+
import { ticked } from "./tray.js";
|
|
36
|
+
/** How often a failure that lasts is said again in the log. */
|
|
37
|
+
const FAILURE_REPEAT_MS = 60_000;
|
|
38
|
+
/** A failed ask in words, the same on the page and in the log. */
|
|
39
|
+
export const failureText = ({ error, narrowed }) => {
|
|
40
|
+
const said = error.replace(/[.\s]+$/, "");
|
|
41
|
+
return narrowed ? `The ranker failed: ${said}. The narrowing's order is shown.` : `The search failed: ${said}.`;
|
|
42
|
+
};
|
|
43
|
+
/** How many asks' grades are kept for ticking from them. */
|
|
44
|
+
const KEPT_GRADES = 50;
|
|
45
|
+
/** An answer that is an error: its status and what the page is told. A finder's own route throws it too. */
|
|
46
|
+
export class HttpError extends Error {
|
|
47
|
+
status;
|
|
48
|
+
constructor(status, message) {
|
|
49
|
+
super(message);
|
|
50
|
+
this.status = status;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const readBody = async (request) => {
|
|
54
|
+
const chunks = [];
|
|
55
|
+
let size = 0;
|
|
56
|
+
for await (const chunk of request) {
|
|
57
|
+
size += chunk.length;
|
|
58
|
+
if (size > 64 * 1024)
|
|
59
|
+
throw new HttpError(413, "Too large");
|
|
60
|
+
chunks.push(chunk);
|
|
61
|
+
}
|
|
62
|
+
if (!chunks.length)
|
|
63
|
+
return {};
|
|
64
|
+
try {
|
|
65
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
66
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed))
|
|
67
|
+
return parsed;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
// Answered below.
|
|
71
|
+
}
|
|
72
|
+
throw new HttpError(400, "The body must be a JSON object");
|
|
73
|
+
};
|
|
74
|
+
const text = (body, field, required = true) => {
|
|
75
|
+
const value = body[field];
|
|
76
|
+
if (typeof value === "string")
|
|
77
|
+
return value;
|
|
78
|
+
if (value === undefined || value === null) {
|
|
79
|
+
if (required)
|
|
80
|
+
throw new HttpError(400, `${field} is missing`);
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
throw new HttpError(400, `${field} must be text`);
|
|
84
|
+
};
|
|
85
|
+
export async function startFinderServer(options) {
|
|
86
|
+
const { finder, ranker, badges, budget, objects, kind } = options;
|
|
87
|
+
const { levelName } = kind;
|
|
88
|
+
const actions = options.trayActions ?? [];
|
|
89
|
+
const timing = { ...ASK_TIMING, ...options.timing };
|
|
90
|
+
let settings = { ...options.settings };
|
|
91
|
+
let version = 1;
|
|
92
|
+
let tray = [];
|
|
93
|
+
let choices = { pinned: [], dropped: [] };
|
|
94
|
+
let choice;
|
|
95
|
+
let dependencies;
|
|
96
|
+
// The object the tray is kept for, as last saved; its lines by ask; what can be reopened.
|
|
97
|
+
let object;
|
|
98
|
+
let lines = {};
|
|
99
|
+
let unfinished = [];
|
|
100
|
+
// What the ranker cost this session: the spend cap's count, which also has calls answered but not read; this one's with no cap.
|
|
101
|
+
let uncapped = 0;
|
|
102
|
+
const spent = () => (budget ? budget.spent : uncapped);
|
|
103
|
+
const clients = new Set();
|
|
104
|
+
// Each ask's grades as the page was shown them, by its text: what a tick from it records.
|
|
105
|
+
const grades = new Map();
|
|
106
|
+
const send = (event, data) => {
|
|
107
|
+
const message = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
108
|
+
for (const client of clients)
|
|
109
|
+
client.write(message);
|
|
110
|
+
};
|
|
111
|
+
const tags = () => kind.tags(tray.map(({ id }) => finder.cards.get(id)).filter((card) => card !== undefined), choices);
|
|
112
|
+
const cardsOut = (candidates) => {
|
|
113
|
+
const provided = dependencies !== undefined ? badges?.provided : undefined;
|
|
114
|
+
// The asker holds its candidates as the kit's cards; they are this finder's.
|
|
115
|
+
const html = kind.renderCards(candidates.map(({ card }) => card), provided);
|
|
116
|
+
return candidates.map(({ id, level }, i) => ({
|
|
117
|
+
id,
|
|
118
|
+
html: html[i],
|
|
119
|
+
...(level !== undefined ? { level: Math.round(level * 100) / 100, levelName: levelName(level) } : {}),
|
|
120
|
+
}));
|
|
121
|
+
};
|
|
122
|
+
/** The last failure the log said, and when, so a lasting one isn't said on every ask. */
|
|
123
|
+
let lastFailure;
|
|
124
|
+
const emit = (event) => {
|
|
125
|
+
if (event.type === "failed") {
|
|
126
|
+
const line = failureText(event);
|
|
127
|
+
// A failure that lasts (a revoked key, an outage) comes again on every Enter and idle pause:
|
|
128
|
+
// said once a minute while it fails the same way, long numbers aside (a timeout's
|
|
129
|
+
// milliseconds; a status code still tells two failures apart). A ranking that works ends it.
|
|
130
|
+
const same = line.replace(/\d{4,}/g, "#");
|
|
131
|
+
const now = Date.now();
|
|
132
|
+
if (same !== lastFailure?.same || now - lastFailure.at >= FAILURE_REPEAT_MS) {
|
|
133
|
+
options.log?.(line);
|
|
134
|
+
lastFailure = { same, at: now };
|
|
135
|
+
}
|
|
136
|
+
return send("failed", { ...event, message: line });
|
|
137
|
+
}
|
|
138
|
+
if (event.type === "capped")
|
|
139
|
+
return send("capped", event);
|
|
140
|
+
if (event.type === "ranked") {
|
|
141
|
+
lastFailure = undefined;
|
|
142
|
+
grades.delete(event.text.trim());
|
|
143
|
+
grades.set(event.text.trim(), { tags: event.tags, levels: new Map(event.candidates.map(({ id, level }) => [id, level])) });
|
|
144
|
+
if (grades.size > KEPT_GRADES)
|
|
145
|
+
grades.delete(grades.keys().next().value);
|
|
146
|
+
return send("ranked", { text: event.text, ranker: event.ranker, ms: Math.round(event.ms), cost: event.cost, spend: spent(), cards: cardsOut(event.candidates) });
|
|
147
|
+
}
|
|
148
|
+
// The rank budget trimmed this ask's candidates: the log says so, and the page's event carries the count.
|
|
149
|
+
if (event.cut > 0)
|
|
150
|
+
options.log?.(`"${event.text.trim()}": ${event.cut} candidates cut to fit what the ranker takes in one request.`);
|
|
151
|
+
send("narrowed", { text: event.text, ms: Math.round(event.ms * 10) / 10, cut: event.cut, cards: cardsOut(event.candidates) });
|
|
152
|
+
};
|
|
153
|
+
const onRanking = (cost) => {
|
|
154
|
+
if (!budget)
|
|
155
|
+
uncapped += cost;
|
|
156
|
+
// The call that reached the cap: the page's ranker line says so now, not on the next change.
|
|
157
|
+
if (budget && !budget.allows())
|
|
158
|
+
changed();
|
|
159
|
+
};
|
|
160
|
+
const asker = createAsker({ narrow: (ask, narrowOptions) => finder.narrow(ask, narrowOptions), ranker, ...(budget ? { budget } : {}), emit, timing, onRanking: (ranking) => onRanking(ranking.cost) });
|
|
161
|
+
const askTags = () => tags().map(({ facet, value, pinned }) => ({ facet, value, ...(pinned ? { pinned } : {}) }));
|
|
162
|
+
const requestFor = (askText, mode, idleMs) => ({
|
|
163
|
+
text: askText,
|
|
164
|
+
mode,
|
|
165
|
+
version,
|
|
166
|
+
tags: askTags(),
|
|
167
|
+
object: object?.title,
|
|
168
|
+
dependencies,
|
|
169
|
+
...(idleMs !== undefined ? { idleMs } : {}),
|
|
170
|
+
});
|
|
171
|
+
const state = () => ({
|
|
172
|
+
version,
|
|
173
|
+
tags: tags(),
|
|
174
|
+
tray: {
|
|
175
|
+
items: tray.map((item) => ({
|
|
176
|
+
id: item.id,
|
|
177
|
+
name: item.name,
|
|
178
|
+
ask: item.ask,
|
|
179
|
+
...(item.level !== undefined ? { level: Math.round(item.level * 100) / 100, levelName: levelName(item.level) } : {}),
|
|
180
|
+
copy: kind.copy.item(item),
|
|
181
|
+
})),
|
|
182
|
+
copy: kind.copy.all(tray),
|
|
183
|
+
// With an object open, each ask its cards came from, and the line its part reads as.
|
|
184
|
+
...(object ? { asks: [...new Set(tray.map(({ ask }) => ask))].map((ask) => ({ ask, line: lines[ask] ?? ask })) } : {}),
|
|
185
|
+
},
|
|
186
|
+
objects: objects
|
|
187
|
+
? { label: objects.label, placeholder: objects.placeholder ?? "", open: object ? { title: object.title, choice: object.choice ?? null } : null, unfinished: object ? [] : unfinished }
|
|
188
|
+
: null,
|
|
189
|
+
actions: actions.map(({ label, title, inputs }) => ({ label, title: title ?? "", inputs: inputs ?? [] })),
|
|
190
|
+
badges: badges ? { label: badges.label, choices: badges.choices, chosen: choice ?? null } : null,
|
|
191
|
+
ranker: ranker ? ranker.name : null,
|
|
192
|
+
off: options.off ?? null,
|
|
193
|
+
idleMs: settings.idleMs ?? timing.idleMs,
|
|
194
|
+
spend: spent(),
|
|
195
|
+
budget: budget ? budget.limit : null,
|
|
196
|
+
capped: budget && !budget.allows() ? budget.reason : null,
|
|
197
|
+
tickLog: options.tickLog !== undefined,
|
|
198
|
+
});
|
|
199
|
+
// An ask is its text and the state version: the version moves only when what an ask runs with does.
|
|
200
|
+
const contextOf = () => JSON.stringify([askTags(), object?.title, dependencies]);
|
|
201
|
+
let context = contextOf();
|
|
202
|
+
const changed = () => {
|
|
203
|
+
const now = contextOf();
|
|
204
|
+
if (now !== context) {
|
|
205
|
+
context = now;
|
|
206
|
+
version++;
|
|
207
|
+
}
|
|
208
|
+
const next = state();
|
|
209
|
+
send("state", next);
|
|
210
|
+
return next;
|
|
211
|
+
};
|
|
212
|
+
const saveSettings = async (next) => {
|
|
213
|
+
settings = { ...settings, ...next };
|
|
214
|
+
await options.saveSettings?.(settings);
|
|
215
|
+
};
|
|
216
|
+
const choose = async (next) => {
|
|
217
|
+
if (next !== undefined && !badges?.choices.includes(next))
|
|
218
|
+
throw new HttpError(400, `${next} isn't one of the choices`);
|
|
219
|
+
dependencies = next !== undefined ? await badges.dependenciesOf(next) : undefined;
|
|
220
|
+
choice = next;
|
|
221
|
+
};
|
|
222
|
+
// The last choice, while it is still one.
|
|
223
|
+
if (badges && settings.lastChoice !== undefined && badges.choices.includes(settings.lastChoice))
|
|
224
|
+
await choose(settings.lastChoice);
|
|
225
|
+
const logTicks = async (ask) => {
|
|
226
|
+
if (!options.tickLog)
|
|
227
|
+
return;
|
|
228
|
+
const from = tray.filter((item) => item.ask === ask);
|
|
229
|
+
const line = {
|
|
230
|
+
ask,
|
|
231
|
+
tags: grades.get(ask)?.tags ?? from[0]?.tags ?? [],
|
|
232
|
+
ticked: from.map(({ id }) => id),
|
|
233
|
+
...(object ? { object: object.title } : {}),
|
|
234
|
+
...(grades.has(ask) && ranker ? { ranker: ranker.name } : {}),
|
|
235
|
+
at: new Date().toISOString(),
|
|
236
|
+
};
|
|
237
|
+
const file = options.tickLog(choice);
|
|
238
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
239
|
+
await appendFile(file, `${JSON.stringify(line)}\n`);
|
|
240
|
+
};
|
|
241
|
+
const pick = (list, picked, keep) => {
|
|
242
|
+
const rest = list.filter((known) => known.facet.toLowerCase() !== picked.facet.toLowerCase() || known.value.toLowerCase() !== picked.value.toLowerCase());
|
|
243
|
+
return keep ? [...rest, picked] : rest;
|
|
244
|
+
};
|
|
245
|
+
const levels = async (ask, askedTags) => {
|
|
246
|
+
const known = grades.get(ask.trim());
|
|
247
|
+
if (known)
|
|
248
|
+
return known.levels;
|
|
249
|
+
const ranked = await asker.ranked({ ...requestFor(ask, "enter"), tags: askedTags });
|
|
250
|
+
return new Map(ranked.candidates.map(({ id, level }) => [id, level]));
|
|
251
|
+
};
|
|
252
|
+
/** The tray's cards with the ranker's level each, ranked now for an ask that wasn't: what an object keeps. */
|
|
253
|
+
const levelled = async (items) => {
|
|
254
|
+
const known = new Map();
|
|
255
|
+
const out = [];
|
|
256
|
+
for (const item of items) {
|
|
257
|
+
if (item.level !== undefined) {
|
|
258
|
+
out.push(item);
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
if (!known.has(item.ask)) {
|
|
262
|
+
if (!ranker)
|
|
263
|
+
throw new HttpError(409, `An object keeps the ranker's level for each card, and no ranker is on: ${options.off ?? "no ranker"}`);
|
|
264
|
+
known.set(item.ask, await levels(item.ask, item.tags).catch((error) => Promise.reject(new HttpError(409, `An object keeps the ranker's level for each card, and "${item.ask}" has none: ${error.message}`))));
|
|
265
|
+
}
|
|
266
|
+
const level = known.get(item.ask).get(item.id);
|
|
267
|
+
if (level === undefined)
|
|
268
|
+
throw new HttpError(409, `${item.id} isn't among what "${item.ask}" finds now, so it has no level: untick it, or ask again and tick it`);
|
|
269
|
+
out.push({ ...item, level });
|
|
270
|
+
}
|
|
271
|
+
return out;
|
|
272
|
+
};
|
|
273
|
+
const trayItem = ({ id, ask, tags: tickTags, level }) => {
|
|
274
|
+
const card = finder.cards.get(id);
|
|
275
|
+
return { id, name: card?.name ?? id, ask, tags: tickTags, ...(level !== undefined ? { level } : {}), ...(card?.dependency !== undefined ? { dependency: card.dependency } : {}) };
|
|
276
|
+
};
|
|
277
|
+
// With an object open, every tray item has its level (levelled() gives it before a card goes in).
|
|
278
|
+
const tickOf = ({ id, ask, tags: tickTags, level }) => ({ id, ask, tags: tickTags, level: level });
|
|
279
|
+
/** Saves the open object as the tray is now. */
|
|
280
|
+
const keep = async () => {
|
|
281
|
+
if (!object || !objects)
|
|
282
|
+
return;
|
|
283
|
+
const asks = new Set(tray.map(({ ask }) => ask));
|
|
284
|
+
const next = { ...object, ticks: tray.map(tickOf), lines: Object.fromEntries(Object.entries(lines).filter(([ask]) => asks.has(ask))) };
|
|
285
|
+
await objects.save(next);
|
|
286
|
+
object = next;
|
|
287
|
+
};
|
|
288
|
+
const refreshUnfinished = async () => {
|
|
289
|
+
unfinished = objects && !object ? await objects.unfinished() : [];
|
|
290
|
+
};
|
|
291
|
+
/** Opens an object, with no wait from here on: its ticks in the tray, its pinned tags and its choice (chosen already). */
|
|
292
|
+
const openObject = (next) => {
|
|
293
|
+
object = next;
|
|
294
|
+
tray = next.ticks.map(trayItem);
|
|
295
|
+
lines = { ...next.lines };
|
|
296
|
+
choices = { pinned: [...(next.pinned ?? [])], dropped: [] };
|
|
297
|
+
};
|
|
298
|
+
/** A store's refusal, as the page's answer. */
|
|
299
|
+
const refused = (error) => Promise.reject(new HttpError(400, error.message));
|
|
300
|
+
const putAway = async () => {
|
|
301
|
+
object = undefined;
|
|
302
|
+
lines = {};
|
|
303
|
+
tray = [];
|
|
304
|
+
choices = { pinned: [], dropped: [] };
|
|
305
|
+
await refreshUnfinished();
|
|
306
|
+
};
|
|
307
|
+
const needObjects = () => {
|
|
308
|
+
if (!objects)
|
|
309
|
+
throw new HttpError(404, "Not found");
|
|
310
|
+
return objects;
|
|
311
|
+
};
|
|
312
|
+
const answer = async (route, body) => {
|
|
313
|
+
switch (route) {
|
|
314
|
+
case "/ask": {
|
|
315
|
+
const mode = text(body, "mode");
|
|
316
|
+
if (!["type", "enter", "refresh"].includes(mode))
|
|
317
|
+
throw new HttpError(400, "mode is type, enter or refresh");
|
|
318
|
+
const idleMs = typeof body.idleMs === "number" && body.idleMs >= 250 ? body.idleMs : (settings.idleMs ?? undefined);
|
|
319
|
+
asker.ask(requestFor(text(body, "text"), mode, idleMs));
|
|
320
|
+
return { ok: true };
|
|
321
|
+
}
|
|
322
|
+
case "/tick": {
|
|
323
|
+
const ask = text(body, "ask").trim();
|
|
324
|
+
const id = text(body, "id");
|
|
325
|
+
if (!ask)
|
|
326
|
+
throw new HttpError(400, "ask is empty");
|
|
327
|
+
const card = finder.cards.get(id);
|
|
328
|
+
if (body.ticked === false) {
|
|
329
|
+
tray = tray.filter((item) => item.id !== id);
|
|
330
|
+
}
|
|
331
|
+
else {
|
|
332
|
+
if (!card)
|
|
333
|
+
throw new HttpError(400, `No ${kind.noun} ${id}`);
|
|
334
|
+
const graded = grades.get(ask);
|
|
335
|
+
const level = graded?.levels.get(id);
|
|
336
|
+
const kept = object?.key;
|
|
337
|
+
let item = trayItem({ id, ask, tags: graded?.tags ?? askTags(), level });
|
|
338
|
+
// An object keeps each card's level: one ticked before its ask was ranked is ranked now.
|
|
339
|
+
if (kept !== undefined)
|
|
340
|
+
[item] = (await levelled([item]));
|
|
341
|
+
// The author may have put the object away, or opened another, while the card was ranked.
|
|
342
|
+
if (object?.key !== kept)
|
|
343
|
+
throw new HttpError(409, "The object changed while the card was being ranked");
|
|
344
|
+
tray = ticked(tray, item, true);
|
|
345
|
+
}
|
|
346
|
+
await keep();
|
|
347
|
+
await logTicks(ask);
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
case "/clear":
|
|
351
|
+
tray = [];
|
|
352
|
+
await keep();
|
|
353
|
+
break;
|
|
354
|
+
case "/choose": {
|
|
355
|
+
const next = text(body, "choice", false) || undefined;
|
|
356
|
+
if (object && next !== object.choice)
|
|
357
|
+
throw new HttpError(409, `${object.title} is for ${object.choice ?? "no " + (badges?.label ?? "choice")}: put it away to choose another`);
|
|
358
|
+
await choose(next);
|
|
359
|
+
await saveSettings({ lastChoice: next });
|
|
360
|
+
break;
|
|
361
|
+
}
|
|
362
|
+
case "/tag": {
|
|
363
|
+
const picked = { facet: text(body, "facet"), value: text(body, "value") };
|
|
364
|
+
const action = text(body, "action");
|
|
365
|
+
const { pinned, dropped } = choices;
|
|
366
|
+
if (action === "pin")
|
|
367
|
+
choices = { pinned: pick(pinned, picked, true), dropped: pick(dropped, picked, false) };
|
|
368
|
+
else if (action === "unpin")
|
|
369
|
+
choices = { pinned: pick(pinned, picked, false), dropped };
|
|
370
|
+
else if (action === "drop")
|
|
371
|
+
choices = { pinned: pick(pinned, picked, false), dropped: pick(dropped, picked, true) };
|
|
372
|
+
else
|
|
373
|
+
throw new HttpError(400, "action is pin, unpin or drop");
|
|
374
|
+
break;
|
|
375
|
+
}
|
|
376
|
+
case "/object": {
|
|
377
|
+
const store = needObjects();
|
|
378
|
+
if (object)
|
|
379
|
+
throw new HttpError(409, `${object.title} is open: put it away first`);
|
|
380
|
+
const title = text(body, "title").trim();
|
|
381
|
+
if (!title)
|
|
382
|
+
throw new HttpError(400, "title is empty");
|
|
383
|
+
// The tray's cards go into it, each with its level, those ticked while it was ranked too. They
|
|
384
|
+
// are levelled before it is started, so a tray that can't be levelled starts no object.
|
|
385
|
+
const done = new Map();
|
|
386
|
+
for (let todo = tray; todo.length; todo = tray.filter((item) => !done.has(item))) {
|
|
387
|
+
const items = await levelled(todo);
|
|
388
|
+
todo.forEach((item, i) => done.set(item, items[i]));
|
|
389
|
+
}
|
|
390
|
+
const started = await store.start(title, choice).catch(refused);
|
|
391
|
+
if (object)
|
|
392
|
+
throw new HttpError(409, `${object.title} was opened meanwhile`);
|
|
393
|
+
openObject({ ...started, ticks: [...started.ticks, ...tray.map((item) => tickOf(done.get(item)))], pinned: [...(started.pinned ?? []), ...choices.pinned] });
|
|
394
|
+
await keep();
|
|
395
|
+
break;
|
|
396
|
+
}
|
|
397
|
+
case "/reopen": {
|
|
398
|
+
const store = needObjects();
|
|
399
|
+
if (object)
|
|
400
|
+
throw new HttpError(409, `${object.title} is open: put it away first`);
|
|
401
|
+
if (tray.length)
|
|
402
|
+
throw new HttpError(409, "The tray has cards: clear it, or start an object with them, before reopening another");
|
|
403
|
+
const key = text(body, "key");
|
|
404
|
+
// An object whose choice (its map) is no longer one can't be opened for it: said before reopening.
|
|
405
|
+
const listed = unfinished.find((known) => known.key === key);
|
|
406
|
+
if (listed?.choice !== undefined && !badges?.choices.includes(listed.choice)) {
|
|
407
|
+
throw new HttpError(409, `${listed.title} is for ${listed.choice}, which isn't one of the ${(badges?.label ?? "choice").toLowerCase()}s any more`);
|
|
408
|
+
}
|
|
409
|
+
const next = await store.reopen(key).catch(refused);
|
|
410
|
+
if (object || tray.length)
|
|
411
|
+
throw new HttpError(409, "The tray changed while it was being reopened");
|
|
412
|
+
// Its choice is chosen; when the tray changes while that waits, the page's own choice comes back.
|
|
413
|
+
const before = { choice, dependencies };
|
|
414
|
+
await choose(next.choice);
|
|
415
|
+
if (object || tray.length) {
|
|
416
|
+
({ choice, dependencies } = before);
|
|
417
|
+
throw new HttpError(409, "The tray changed while it was being reopened");
|
|
418
|
+
}
|
|
419
|
+
openObject(next);
|
|
420
|
+
await saveSettings({ lastChoice: next.choice });
|
|
421
|
+
break;
|
|
422
|
+
}
|
|
423
|
+
case "/put-away":
|
|
424
|
+
needObjects();
|
|
425
|
+
if (!object)
|
|
426
|
+
throw new HttpError(409, "No object is open");
|
|
427
|
+
await putAway();
|
|
428
|
+
break;
|
|
429
|
+
case "/line": {
|
|
430
|
+
needObjects();
|
|
431
|
+
if (!object)
|
|
432
|
+
throw new HttpError(409, "No object is open");
|
|
433
|
+
const ask = text(body, "ask").trim();
|
|
434
|
+
const line = text(body, "line").trim();
|
|
435
|
+
if (!tray.some((item) => item.ask === ask))
|
|
436
|
+
throw new HttpError(400, `Nothing in the tray was ticked from "${ask}"`);
|
|
437
|
+
if (!line)
|
|
438
|
+
throw new HttpError(400, "A part needs a line");
|
|
439
|
+
lines = { ...lines, [ask]: line };
|
|
440
|
+
await keep();
|
|
441
|
+
break;
|
|
442
|
+
}
|
|
443
|
+
case "/settings": {
|
|
444
|
+
if (body.idleMs !== undefined) {
|
|
445
|
+
if (typeof body.idleMs !== "number" || !(body.idleMs >= 250))
|
|
446
|
+
throw new HttpError(400, "idleMs must be 250 or more");
|
|
447
|
+
await saveSettings({ idleMs: body.idleMs });
|
|
448
|
+
}
|
|
449
|
+
break;
|
|
450
|
+
}
|
|
451
|
+
case "/action": {
|
|
452
|
+
const index = body.index;
|
|
453
|
+
const action = typeof index === "number" ? actions[index] : undefined;
|
|
454
|
+
if (!action)
|
|
455
|
+
throw new HttpError(404, "No such tray action");
|
|
456
|
+
if (!tray.length)
|
|
457
|
+
throw new HttpError(409, `Tick a card before "${action.label}": it takes the tray's cards`);
|
|
458
|
+
const raw = typeof body.inputs === "object" && body.inputs !== null ? body.inputs : {};
|
|
459
|
+
const inputs = {};
|
|
460
|
+
for (const input of action.inputs ?? []) {
|
|
461
|
+
const value = typeof raw[input.name] === "string" ? raw[input.name].trim() : "";
|
|
462
|
+
if (input.required && !value)
|
|
463
|
+
throw new HttpError(400, `${input.label} is missing`);
|
|
464
|
+
inputs[input.name] = value;
|
|
465
|
+
}
|
|
466
|
+
let done;
|
|
467
|
+
try {
|
|
468
|
+
done = await action.run({ items: tray, choice, inputs, object, levels });
|
|
469
|
+
}
|
|
470
|
+
catch (error) {
|
|
471
|
+
throw new HttpError(409, error.message);
|
|
472
|
+
}
|
|
473
|
+
if (done.putAway)
|
|
474
|
+
await putAway();
|
|
475
|
+
else if (done.clearTray) {
|
|
476
|
+
tray = [];
|
|
477
|
+
choices = { pinned: [], dropped: [] };
|
|
478
|
+
await keep();
|
|
479
|
+
}
|
|
480
|
+
return { ...changed(), done };
|
|
481
|
+
}
|
|
482
|
+
default:
|
|
483
|
+
throw new HttpError(404, "Not found");
|
|
484
|
+
}
|
|
485
|
+
return changed();
|
|
486
|
+
};
|
|
487
|
+
await refreshUnfinished();
|
|
488
|
+
let origin = "";
|
|
489
|
+
const allowedHosts = new Set();
|
|
490
|
+
const handle = async (request, response) => {
|
|
491
|
+
const host = request.headers.host ?? "";
|
|
492
|
+
if (!allowedHosts.has(host))
|
|
493
|
+
throw new HttpError(403, "Wrong host");
|
|
494
|
+
const url = new URL(request.url ?? "/", origin);
|
|
495
|
+
if (request.method === "POST") {
|
|
496
|
+
const from = request.headers.origin;
|
|
497
|
+
if (from !== undefined && !allowedHosts.has(from.replace(/^http:\/\//, "")))
|
|
498
|
+
throw new HttpError(403, "Wrong origin");
|
|
499
|
+
if (!(request.headers["content-type"] ?? "").startsWith("application/json"))
|
|
500
|
+
throw new HttpError(415, "Send JSON");
|
|
501
|
+
const result = await answer(url.pathname, await readBody(request));
|
|
502
|
+
response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
|
|
503
|
+
return void response.end(JSON.stringify(result));
|
|
504
|
+
}
|
|
505
|
+
if (request.method !== "GET")
|
|
506
|
+
throw new HttpError(405, "GET or POST");
|
|
507
|
+
if (url.pathname === "/") {
|
|
508
|
+
response.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
509
|
+
return void response.end(kind.page());
|
|
510
|
+
}
|
|
511
|
+
if (url.pathname === "/state") {
|
|
512
|
+
response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
|
|
513
|
+
return void response.end(JSON.stringify(state()));
|
|
514
|
+
}
|
|
515
|
+
if (url.pathname === "/status") {
|
|
516
|
+
response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
|
|
517
|
+
const rankers = { on: ranker ? [ranker.name] : [], off: options.off ? [{ ranker: "jev", reason: options.off }] : [], ...(ranker && options.keySource ? { keySource: options.keySource } : {}) };
|
|
518
|
+
// The caller's additions first, so none can hide what tells a Finder apart.
|
|
519
|
+
return void response.end(JSON.stringify({ ...options.status, finder: kind.name, pid: process.pid, url: `${origin}/`, rankers }));
|
|
520
|
+
}
|
|
521
|
+
if (url.pathname === "/events") {
|
|
522
|
+
response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
|
|
523
|
+
await refreshUnfinished();
|
|
524
|
+
clients.add(response);
|
|
525
|
+
request.on("close", () => clients.delete(response));
|
|
526
|
+
return void response.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`);
|
|
527
|
+
}
|
|
528
|
+
if (kind.route && (await kind.route(url, request, response)))
|
|
529
|
+
return;
|
|
530
|
+
throw new HttpError(404, "Not found");
|
|
531
|
+
};
|
|
532
|
+
const server = createServer((request, response) => {
|
|
533
|
+
handle(request, response).catch((error) => {
|
|
534
|
+
const status = error instanceof HttpError ? error.status : 500;
|
|
535
|
+
if (!response.headersSent)
|
|
536
|
+
response.writeHead(status, { "content-type": "application/json" });
|
|
537
|
+
response.end(JSON.stringify({ error: error.message }));
|
|
538
|
+
});
|
|
539
|
+
});
|
|
540
|
+
await new Promise((resolve, reject) => {
|
|
541
|
+
server.once("error", reject);
|
|
542
|
+
server.listen(options.port ?? 0, "127.0.0.1", resolve);
|
|
543
|
+
});
|
|
544
|
+
const { port } = server.address();
|
|
545
|
+
origin = `http://127.0.0.1:${port}`;
|
|
546
|
+
for (const name of ["127.0.0.1", "localhost"])
|
|
547
|
+
allowedHosts.add(`${name}:${port}`);
|
|
548
|
+
return {
|
|
549
|
+
url: `${origin}/`,
|
|
550
|
+
get spend() {
|
|
551
|
+
return spent();
|
|
552
|
+
},
|
|
553
|
+
async close() {
|
|
554
|
+
asker.close();
|
|
555
|
+
for (const client of clients)
|
|
556
|
+
client.end();
|
|
557
|
+
clients.clear();
|
|
558
|
+
kind.close?.();
|
|
559
|
+
const closed = new Promise((resolve) => server.close(() => resolve()));
|
|
560
|
+
// A browser's kept-alive connections end with the server, not when the browser drops them.
|
|
561
|
+
server.closeAllConnections();
|
|
562
|
+
await closed;
|
|
563
|
+
},
|
|
564
|
+
};
|
|
565
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** What the page remembers between runs. */
|
|
2
|
+
export type FinderSettings = {
|
|
3
|
+
readonly lastChoice?: string | undefined;
|
|
4
|
+
readonly idleMs?: number | undefined;
|
|
5
|
+
};
|
|
6
|
+
export declare function readFinderSettings(file: string): Promise<FinderSettings>;
|
|
7
|
+
export declare function writeFinderSettings(file: string, settings: FinderSettings): Promise<void>;
|
package/dist/settings.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// What the Finder's page remembers between runs: the last badges choice and how long typing pauses
|
|
2
|
+
// before it ranks, as a small JSON file. A file that is missing or doesn't read is no settings.
|
|
3
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
export async function readFinderSettings(file) {
|
|
6
|
+
try {
|
|
7
|
+
const raw = JSON.parse(await readFile(file, "utf8"));
|
|
8
|
+
return {
|
|
9
|
+
...(typeof raw.lastChoice === "string" ? { lastChoice: raw.lastChoice } : {}),
|
|
10
|
+
...(typeof raw.idleMs === "number" && raw.idleMs >= 250 ? { idleMs: raw.idleMs } : {}),
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return {};
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export async function writeFinderSettings(file, settings) {
|
|
18
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
19
|
+
await writeFile(file, `${JSON.stringify(settings)}\n`);
|
|
20
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** US dollars a session may spend on Jev unless told otherwise. */
|
|
2
|
+
export declare const DEFAULT_BUDGET = 1;
|
|
3
|
+
export type SpendCap = {
|
|
4
|
+
readonly limit: number;
|
|
5
|
+
/** US dollars spent this session, estimated. */
|
|
6
|
+
readonly spent: number;
|
|
7
|
+
/** Whether another call is allowed. */
|
|
8
|
+
readonly allows: () => boolean;
|
|
9
|
+
record(cost: number): void;
|
|
10
|
+
/** Why no call is made once the cap is reached. */
|
|
11
|
+
readonly reason: string;
|
|
12
|
+
};
|
|
13
|
+
export declare const dollars: (amount: number) => string;
|
|
14
|
+
export declare function spendCap(limit?: number): SpendCap;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// The session's spend cap: the Finder calls Jev until its estimated spend this session
|
|
2
|
+
// reaches the cap ($1.00 unless `--budget` sets another), then shows the narrowing's order and
|
|
3
|
+
// says why. The check comes before each call, so the last call may take the spend a little past.
|
|
4
|
+
/** US dollars a session may spend on Jev unless told otherwise. */
|
|
5
|
+
export const DEFAULT_BUDGET = 1;
|
|
6
|
+
export const dollars = (amount) => `$${amount.toFixed(2)}`;
|
|
7
|
+
export function spendCap(limit = DEFAULT_BUDGET) {
|
|
8
|
+
if (!(limit >= 0))
|
|
9
|
+
throw new Error(`The spend cap takes US dollars, 0 or more, not ${limit}`);
|
|
10
|
+
let spent = 0;
|
|
11
|
+
return {
|
|
12
|
+
limit,
|
|
13
|
+
get spent() {
|
|
14
|
+
return spent;
|
|
15
|
+
},
|
|
16
|
+
allows: () => spent < limit,
|
|
17
|
+
record(cost) {
|
|
18
|
+
spent += cost;
|
|
19
|
+
},
|
|
20
|
+
reason: `the spend cap of ${dollars(limit)} for this session is reached, so Jev isn't called and the narrowing's order is shown. Start the Finder again with a higher --budget to rank more`,
|
|
21
|
+
};
|
|
22
|
+
}
|