atagen

jelq

public

an http based roguelike rpg about jelqing

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