atagen

jelq

public

an http based roguelike rpg about jelqing

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