atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
ec6fd4bb5b6028e1fe0ec1bc286e57748b9728dc
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/ui.htmlHtml463 lines17.5 KB
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<meta charset="utf-8">
5
<title>jelqd</title>
6
<style>
7
.frame { border: 2px inset; background: #fff; height: 85vh; overflow: scroll; padding: 4px; }
8
#log { white-space: pre-wrap; margin: 0; }
9
pre, li, p, td, label { overflow-wrap: anywhere; }
10
</style>
11
</head>
12
<body>
13
14
<h1>jelqd</h1>
15
<p>A roguelike played over HTTP. Pick a resource, pick a method, send it. The log on the right is everything the server has said to you.
16
Language <select id="locale"><option>en-GB</option><option>en-US</option><option>en-AU</option></select></p>
17
18
<table width="100%" cellspacing="6">
19
<tr>
20
<td width="45%" valign="top">
21
<div class="frame">
22
23
<div id="alerts"></div>
24
25
<form id="form">
26
<h3>Method</h3>
27
<div id="methods"></div>
28
29
<h3>Request</h3>
30
<table id="fields" cellpadding="2"></table>
31
32
<p><input type="submit" id="send" value="Send" style="font-size: 1.3em"></p>
33
34
<h3>Stats</h3>
35
<table id="stats" border="1" cellspacing="0" cellpadding="3"></table>
36
37
<h3>Resource</h3>
38
<div id="targets"></div>
39
</form>
40
41
<p><small>Every request goes through <code>/ui/send</code>, which replays it inside the server, so the page can show redirects and send methods and headers that browsers refuse.</small></p>
42
</div>
43
</td>
44
<td valign="top">
45
<div class="frame" id="frame"><pre id="log"></pre></div>
46
</td>
47
</tr>
48
</table>
49
50
<script>
51
const REL = "https://jelq.dev/rels/";
52
const METHODS = ["JELQ", "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE"];
53
const LUBES = ["", "application/baby-oil", "application/coconut-oil", "application/lotion", "application/vaseline", "text/plain; charset=spit", "image/jpeg"];
54
const DEATHS = ["vascular-event", "caught", "opened", "banned", "degloved", "zip", "run-ended"];
55
const STATS = [
56
  ["x-floor", "Floor"],
57
  ["x-self-reported-length", "Self-reported length"],
58
  ["x-girth", "Girth"],
59
  ["x-foreskin", "Foreskin"],
60
  ["x-eq", "EQ (aim for 50 to 70)"],
61
  ["x-stamina", "Stamina"],
62
  ["x-suspicion", "Suspicion"],
63
  ["x-shame", "Shame"],
64
  ["x-cash", "Cash"],
65
];
66
const MEASURED = ["x-length", "Length"];
67
const QUIET = new Set(["link", "set-cookie", "server", "x-powered-by", "cache-control", "content-length", "content-type", "date"].concat(STATS.map(s => s[0]), MEASURED[0]));
68
69
const FIELDS = {
70
  seed: { label: "seed (unranked)", kind: "text" },
71
  technique: { label: "technique", kind: "select" },
72
  also: { label: "combo with", kind: "select" },
73
  intensity: { label: "intensity, 1 to 10", kind: "number", value: "5" },
74
  lube: { label: "Content-Type", header: "Content-Type", kind: "select" },
75
  patch: { label: "body", kind: "textarea", value: '[{"op": "test", "path": "/length", "value": 6}]' },
76
  range: { label: "Range", header: "Range", kind: "text", placeholder: "inches=0-2" },
77
  ifMatch: { label: "If-Match", header: "If-Match", kind: "text" },
78
  ifNoneMatch: { label: "If-None-Match", header: "If-None-Match", kind: "text" },
79
  ifModifiedSince: { label: "If-Modified-Since", header: "If-Modified-Since", kind: "text", placeholder: "an HTTP-date" },
80
  proxy: { label: "Proxy-Authorization", header: "Proxy-Authorization", kind: "text", placeholder: "Ruler 5.4" },
81
  upgrade: { label: "Upgrade", header: "Upgrade", kind: "select", options: ["", "underhand", "overhand"] },
82
  authorization: { label: "Authorization", header: "Authorization", kind: "text", placeholder: 'Excuse "homework"' },
83
  extra: { label: "other headers, one per line", kind: "textarea", placeholder: "Expect: gains" },
84
};
85
const BY_TARGET = {
86
  "runs POST": ["seed"],
87
  "run PATCH": ["patch"],
88
  "length GET": ["range"],
89
  "length HEAD": ["range"],
90
  "foreskin DELETE": ["ifMatch"],
91
  "elder GET": ["proxy", "ifModifiedSince"],
92
  "grip GET": ["upgrade"],
93
  "diagnosis GET": ["authorization", "ifNoneMatch"],
94
};
95
const GROUPS = [
96
  ["play", "Play"],
97
  ["you", "You"],
98
  ["said", "From the last response"],
99
  ["reading", "Reading"],
100
  ["meta", "Meta"],
101
];
102
const GROUP_OF = { run: "play", floor: "play", drawer: "play", shop: "play", portal: "play", elder: "play", diagnosis: "play", length: "you", foreskin: "you", grip: "you", inventory: "you", footage: "you", techniques: "reading", thread: "reading" };
103
const NAMES = { run: "the run", thread: "the 2009 forum thread" };
104
const GLOBALS = [
105
  { key: "runs", group: "play", name: "start a new run", path: "/runs", methods: ["POST"] },
106
  { key: "global", group: "meta", name: "leaderboard", path: "/leaderboard", methods: ["GET", "HEAD", "OPTIONS"] },
107
  { key: "global", group: "meta", name: "graveyard", path: "/graveyard", methods: ["GET", "HEAD", "OPTIONS"] },
108
];
109
110
let run = null;
111
let linked = [];
112
let techniques = [];
113
let offered = [];
114
let challenged = false;
115
const etags = {};
116
let target = "/runs";
117
let method = "POST";
118
const values = {};
119
120
const $ = id => document.getElementById(id);
121
122
function short(path) {
123
  return path.replace(/[0-9a-f]{32}/, id => id.slice(0, 6) + "…");
124
}
125
126
function el(tag, props, ...children) {
127
  const node = Object.assign(document.createElement(tag), props || {});
128
  for (const child of children) node.append(child);
129
  return node;
130
}
131
132
function titled(text) {
133
  return text.charAt(0).toUpperCase() + text.slice(1);
134
}
135
136
function technique(name) {
137
  return techniques.find(t => t.name === name);
138
}
139
140
function clashes(a, b) {
141
  const rules = [a.lubricant, b.lubricant];
142
  return rules.includes("required") && rules.includes("forbidden");
143
}
144
145
// The options a field can take right now, or null for free text.
146
function options(name) {
147
  if (name === "technique") return techniques.map(t => t.name);
148
  if (name === "also") {
149
    const first = technique(fieldValue("technique"));
150
    if (!first || !first.lubricant) return [""];
151
    const partners = techniques.filter(t => t.lubricant && t.name !== first.name && !clashes(first, t));
152
    return [""].concat(partners.map(t => t.name));
153
  }
154
  if (name === "lube") return lubeRule() === "required" ? LUBES.filter(Boolean) : LUBES;
155
  return FIELDS[name].options || null;
156
}
157
158
function raw(name) {
159
  return values[name] ?? FIELDS[name].value ?? "";
160
}
161
162
function fieldValue(name) {
163
  const allowed = options(name);
164
  const value = raw(name);
165
  if (allowed && !allowed.includes(value)) return allowed[0] ?? "";
166
  return value;
167
}
168
169
function lubeRule() {
170
  const picked = [technique(fieldValue("technique")), technique(fieldValue("also"))].filter(Boolean);
171
  if (!picked.some(t => t.lubricant)) return "none";
172
  for (const rule of ["forbidden", "required"]) {
173
    if (picked.some(t => t.lubricant === rule)) return rule;
174
  }
175
  return "optional";
176
}
177
178
function allowedMethods(t) {
179
  return t.key === "run" && !techniques.length ? t.methods.filter(m => m !== "JELQ") : t.methods;
180
}
181
182
function targets() {
183
  const listed = run ? linked : [];
184
  const known = new Set(listed.concat(GLOBALS).map(t => t.path));
185
  const fresh = offered.filter((t, i) => !known.has(t.path) && offered.findIndex(o => o.path === t.path) === i);
186
  return listed.concat(fresh, GLOBALS);
187
}
188
189
function current() {
190
  return targets().find(t => t.path === target) || GLOBALS[0];
191
}
192
193
function chooseTarget(t) {
194
  const allowed = allowedMethods(t);
195
  target = t.path;
196
  method = allowed.includes("JELQ") ? "JELQ" : allowed.find(m => m !== "HEAD" && m !== "OPTIONS") || allowed[0];
197
  render();
198
}
199
200
function renderStats(headers) {
201
  const table = $("stats");
202
  table.replaceChildren();
203
  const stats = STATS.map(s => s[0] === "x-self-reported-length" && headers && MEASURED[0] in headers ? MEASURED : s);
204
  for (let i = 0; i < stats.length; i += 2) {
205
    const row = el("tr");
206
    for (const [name, label] of stats.slice(i, i + 2)) {
207
      const value = headers ? headers[name] : undefined;
208
      row.append(el("th", { align: "left", textContent: label }), el("td", { textContent: value === undefined ? "—" : value }));
209
    }
210
    table.append(row);
211
  }
212
}
213
214
function renderAlerts(list) {
215
  const box = $("alerts");
216
  box.replaceChildren();
217
  const alerts = [];
218
  for (const [name, value] of list || []) {
219
    if (name === "via") alerts.push(titled(value.split(" ").pop()) + " is at the door.");
220
    if (name === "x-observed-by") alerts.push((value === "cat" ? "The cat" : titled(value)) + " is watching.");
221
    if (name === "warning") {
222
      const text = (value.match(/"([^"]*)"/) || [, value])[1];
223
      alerts.push(titled(text) + ".");
224
    }
225
  }
226
  const stamina = (list || []).find(([name]) => name === "x-stamina");
227
  if (stamina && stamina[1].startsWith("0/")) alerts.push("Exhausted. Wait out the refractory period, then GET the run.");
228
  for (const alert of alerts) box.append(el("h2", { textContent: alert }));
229
}
230
231
function renderTargets() {
232
  const box = $("targets");
233
  box.replaceChildren();
234
  const all = targets();
235
  for (const [group, title] of GROUPS) {
236
    const members = all.filter(t => t.group === group);
237
    if (!members.length) continue;
238
    box.append(el("h4", { textContent: title }));
239
    for (const t of members) {
240
      const radio = el("input", { type: "radio", name: "target", checked: t.path === target, onchange: () => chooseTarget(t) });
241
      box.append(el("label", {}, radio, " " + t.name + " ", el("small", { textContent: short(t.path) })), el("br"));
242
    }
243
  }
244
}
245
246
function renderMethods() {
247
  const box = $("methods");
248
  box.replaceChildren();
249
  const allowed = allowedMethods(current());
250
  for (const m of METHODS.filter(m => allowed.includes(m))) {
251
    const radio = el("input", { type: "radio", name: "method", checked: m === method, onchange: () => { method = m; render(); } });
252
    const label = el("label", {}, radio, " ");
253
    label.append(m === "JELQ" ? el("big", {}, el("b", { textContent: "JELQ" })) : m);
254
    box.append(label, " ");
255
  }
256
}
257
258
function fieldNames() {
259
  const t = current();
260
  const key = t.key + " " + method;
261
  let names = BY_TARGET[key] || [];
262
  if (key === "run JELQ") {
263
    const chosen = technique(fieldValue("technique"));
264
    names = ["technique"];
265
    if (options("also").length > 1) names.push("also");
266
    if (chosen && chosen.lubricant) names.push("intensity");
267
    if (["required", "optional"].includes(lubeRule())) names.push("lube");
268
  }
269
  const scoped = run && !["runs", "global"].includes(t.key);
270
  const asked = challenged && scoped && !names.includes("authorization");
271
  return (asked ? ["authorization"] : []).concat(names);
272
}
273
274
function renderFields() {
275
  const table = $("fields");
276
  table.replaceChildren();
277
  for (const name of fieldNames()) {
278
    const f = FIELDS[name];
279
    let value = fieldValue(name);
280
    if (name === "ifMatch" && !value) value = values.ifMatch = etags[current().path] || "";
281
    const choices = options(name);
282
    let input;
283
    if (choices) {
284
      input = el("select", {}, ...choices.map(o => el("option", { value: o, textContent: o || "(none)", selected: o === value })));
285
    } else if (f.kind === "textarea") {
286
      input = el("textarea", { rows: 3, cols: 40, value, placeholder: f.placeholder || "" });
287
    } else {
288
      input = el("input", { type: f.kind, value, placeholder: f.placeholder || "", size: 30 });
289
    }
290
    input.oninput = () => { values[name] = input.value; };
291
    input.onchange = () => { values[name] = input.value; if (choices) renderFields(); };
292
    table.append(el("tr", {}, el("td", { align: "right", valign: "top", textContent: f.label }), el("td", {}, input)));
293
  }
294
  const extra = el("textarea", { rows: 3, cols: 40, value: raw("extra"), placeholder: FIELDS.extra.placeholder });
295
  extra.oninput = () => { values.extra = extra.value; };
296
  const more = el("details", { open: Boolean(values.extra) }, el("summary", { textContent: "more headers" }), extra);
297
  table.append(el("tr", {}, el("td"), el("td", {}, more)));
298
  $("send").value = method + " " + short(current().path);
299
}
300
301
function render() {
302
  if (!allowedMethods(current()).includes(method)) return chooseTarget(current());
303
  renderTargets();
304
  renderMethods();
305
  renderFields();
306
}
307
308
function parseLinks(header) {
309
  const resources = [];
310
  const moves = [];
311
  for (const match of header.matchAll(/<([^>]*)>((?:\s*;\s*[a-z-]+="[^"]*")*)/g)) {
312
    const params = Object.fromEntries([...match[2].matchAll(/([a-z-]+)="([^"]*)"/g)].map(p => [p[1], p[2]]));
313
    const name = (params.rel || "").replace(REL, "");
314
    if (name === "technique") {
315
      moves.push({ name: params.title, lubricant: params.lubricant || null });
316
      continue;
317
    }
318
    const methods = (params.allow || "GET").split(",").map(s => s.trim());
319
    resources.push({ key: name, group: GROUP_OF[name] || "play", name: NAMES[name] || params.title || name, path: match[1], methods });
320
  }
321
  return [resources, moves];
322
}
323
324
function hrefs(value, found) {
325
  if (value && typeof value === "object") {
326
    if (typeof value.href === "string") {
327
      const name = value.title || value.item || value.name || value.href.split("/").pop();
328
      found.push({ key: "offered", group: "said", name, path: value.href, methods: [value.method || "GET"] });
329
    }
330
    for (const key in value) hrefs(value[key], found);
331
  }
332
  return found;
333
}
334
335
function log(text) {
336
  $("log").prepend(text + "\n\n");
337
  $("frame").scrollTop = 0;
338
}
339
340
function describe(r) {
341
  const lines = ["< " + r.status + " " + r.reason];
342
  for (const [name, value] of r.headers) {
343
    if (!QUIET.has(name)) lines.push("< " + name + ": " + short(value));
344
  }
345
  let body = null;
346
  try { body = JSON.parse(r.body); } catch (e) {}
347
  if (body && typeof body === "object") {
348
    const rest = Object.assign({}, body);
349
    if (rest.detail) lines.push("  " + rest.detail);
350
    for (const key of ["type", "title", "status", "detail"]) delete rest[key];
351
    if (Object.keys(rest).length) lines.push(short(JSON.stringify(rest, null, 2)).replace(/^/gm, "  "));
352
  } else if (r.body) {
353
    const range = (r.headers.find(h => h[0] === "content-range") || [])[1] || "";
354
    const partial = r.status === 206 && range.match(/^bytes (\d+)-(\d+)\/(\d+)$/);
355
    lines.push("  " + r.body);
356
    if (partial) lines.push("  [bytes " + partial[1] + "-" + partial[2] + " of " + partial[3] + ". Half-mast.]");
357
  }
358
  return lines.join("\n");
359
}
360
361
function absorb(r, sentMethod, sentPath) {
362
  const headers = Object.fromEntries(r.headers.map(([n, v]) => [n.toLowerCase(), v]));
363
  if (headers.etag) etags[sentPath] = headers.etag;
364
  const digest = (headers["www-authenticate"] || "").match(/nonce="([^"]*)"/);
365
  if (digest && !(values.authorization || "").includes(digest[1])) {
366
    values.authorization = 'Digest username="", nonce="' + digest[1] + '"';
367
  }
368
  let body = null;
369
  try { body = JSON.parse(r.body); } catch (e) {}
370
  const problem = body && typeof body.type === "string" ? body.type.split("/").pop() : null;
371
  const started = r.status === 201 && (sentPath === "/runs" || sentPath.startsWith("/runs?"));
372
373
  if (started) {
374
    run = headers.location;
375
    log("--- a new run has started at " + short(run) + " ---");
376
  }
377
  if ("x-eq" in headers) {
378
    renderStats(headers);
379
    renderAlerts(r.headers);
380
    challenged = r.status === 401 || "via" in headers;
381
  }
382
  if (headers.link) [linked, techniques] = parseLinks(headers.link);
383
  offered = body ? hrefs(body, []) : [];
384
  if (headers.location && !started) {
385
    offered.unshift({ key: "offered", group: "said", name: short(headers.location).split("/").pop() + " (Location)", path: headers.location, methods: ["GET"] });
386
  }
387
  const abandoned = sentMethod === "DELETE" && sentPath === run && r.status === 204;
388
  if (run && (abandoned || DEATHS.includes(problem))) {
389
    log("--- the run has ended ---");
390
    renderAlerts(null);
391
    challenged = false;
392
    run = null;
393
    linked = [];
394
    techniques = [];
395
  }
396
  if (started || !targets().some(t => t.path === target)) {
397
    const home = linked.find(t => t.key === "run");
398
    chooseTarget(home || GLOBALS[0]);
399
  } else {
400
    render();
401
  }
402
}
403
404
async function go(event) {
405
  event.preventDefault();
406
  const t = current();
407
  const key = t.key + " " + method;
408
  const value = name => fieldValue(name).trim();
409
  const headers = [];
410
  let path = t.path;
411
  let body = "";
412
  for (const name of fieldNames()) {
413
    const f = FIELDS[name];
414
    if (f.header && value(name)) headers.push([f.header, value(name)]);
415
  }
416
  if (fieldNames().includes("upgrade") && value("upgrade")) headers.push(["Connection", "upgrade"]);
417
  for (const line of raw("extra").split("\n")) {
418
    const at = line.indexOf(":");
419
    if (at > 0) headers.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]);
420
  }
421
  if (key === "run JELQ") {
422
    const names = fieldNames();
423
    const chosen = [value("technique")].concat(names.includes("also") && value("also") ? [value("also")] : []);
424
    path += "?technique=" + encodeURIComponent(chosen.join(","));
425
    if (names.includes("intensity")) path += "&intensity=" + encodeURIComponent(value("intensity"));
426
  }
427
  if (key === "runs POST" && value("seed")) path += "?seed=" + encodeURIComponent(value("seed"));
428
  if (method === "PATCH") {
429
    headers.push(["Content-Type", "application/json-patch+json"]);
430
    body = value("patch");
431
  }
432
433
  const sent = ["> " + method + " " + short(path)].concat(headers.map(([name, v]) => "> " + name + ": " + v)).join("\n");
434
  headers.push(["Accept-Language", $("locale").value]);
435
  let r;
436
  try {
437
    const response = await fetch("/ui/send", {
438
      method: "POST",
439
      headers: { "Content-Type": "application/json" },
440
      body: JSON.stringify({ method, path, headers, body }),
441
    });
442
    r = await response.json();
443
  } catch (error) {
444
    log(sent + "\n! The server did not answer. Is jelqd still running? (" + error.message + ")");
445
    return;
446
  }
447
  if (!Array.isArray(r.headers)) {
448
    log(sent + "\n! The page could not read that reply:\n  " + JSON.stringify(r));
449
    return;
450
  }
451
  log(sent + "\n" + describe(r));
452
  absorb(r, method, path);
453
}
454
455
$("form").onsubmit = go;
456
$("locale").value = localStorage.getItem("locale") || "en-GB";
457
$("locale").onchange = () => localStorage.setItem("locale", $("locale").value);
458
renderStats(null);
459
render();
460
log("Welcome. Choose \"start a new run\" and send POST to begin. The newest turn is always at the top.");
461
</script>
462
</body>
463
</html>