atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
d46f9d0b953a8d854b9d7f39453d483164282ea4
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/ui.htmlHtml456 lines17.2 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
let target = "/runs";
116
let method = "POST";
117
const values = {};
118
119
const $ = id => document.getElementById(id);
120
121
function short(path) {
122
  return path.replace(/[0-9a-f]{32}/, id => id.slice(0, 6) + "…");
123
}
124
125
function el(tag, props, ...children) {
126
  const node = Object.assign(document.createElement(tag), props || {});
127
  for (const child of children) node.append(child);
128
  return node;
129
}
130
131
function titled(text) {
132
  return text.charAt(0).toUpperCase() + text.slice(1);
133
}
134
135
function technique(name) {
136
  return techniques.find(t => t.name === name);
137
}
138
139
function clashes(a, b) {
140
  const rules = [a.lubricant, b.lubricant];
141
  return rules.includes("required") && rules.includes("forbidden");
142
}
143
144
// The options a field can take right now, or null for free text.
145
function options(name) {
146
  if (name === "technique") return techniques.map(t => t.name);
147
  if (name === "also") {
148
    const first = technique(fieldValue("technique"));
149
    if (!first || !first.lubricant) return [""];
150
    const partners = techniques.filter(t => t.lubricant && t.name !== first.name && !clashes(first, t));
151
    return [""].concat(partners.map(t => t.name));
152
  }
153
  if (name === "lube") return lubeRule() === "required" ? LUBES.filter(Boolean) : LUBES;
154
  return FIELDS[name].options || null;
155
}
156
157
function raw(name) {
158
  return values[name] ?? FIELDS[name].value ?? "";
159
}
160
161
function fieldValue(name) {
162
  const allowed = options(name);
163
  const value = raw(name);
164
  if (allowed && !allowed.includes(value)) return allowed[0] ?? "";
165
  return value;
166
}
167
168
function lubeRule() {
169
  const picked = [technique(fieldValue("technique")), technique(fieldValue("also"))].filter(Boolean);
170
  if (!picked.length || !picked[0].lubricant) return "none";
171
  for (const rule of ["forbidden", "required"]) {
172
    if (picked.some(t => t.lubricant === rule)) return rule;
173
  }
174
  return "optional";
175
}
176
177
function allowedMethods(t) {
178
  return t.key === "run" && !techniques.length ? t.methods.filter(m => m !== "JELQ") : t.methods;
179
}
180
181
function targets() {
182
  const listed = run ? linked : [];
183
  const known = new Set(listed.concat(GLOBALS).map(t => t.path));
184
  const fresh = offered.filter((t, i) => !known.has(t.path) && offered.findIndex(o => o.path === t.path) === i);
185
  return listed.concat(fresh, GLOBALS);
186
}
187
188
function current() {
189
  return targets().find(t => t.path === target) || GLOBALS[0];
190
}
191
192
function chooseTarget(t) {
193
  const allowed = allowedMethods(t);
194
  target = t.path;
195
  method = allowed.includes("JELQ") ? "JELQ" : allowed.find(m => m !== "HEAD" && m !== "OPTIONS") || allowed[0];
196
  render();
197
}
198
199
function renderStats(headers) {
200
  const table = $("stats");
201
  table.replaceChildren();
202
  const stats = STATS.map(s => s[0] === "x-self-reported-length" && headers && MEASURED[0] in headers ? MEASURED : s);
203
  for (let i = 0; i < stats.length; i += 2) {
204
    const row = el("tr");
205
    for (const [name, label] of stats.slice(i, i + 2)) {
206
      const value = headers ? headers[name] : undefined;
207
      row.append(el("th", { align: "left", textContent: label }), el("td", { textContent: value === undefined ? "—" : value }));
208
    }
209
    table.append(row);
210
  }
211
}
212
213
function renderAlerts(list) {
214
  const box = $("alerts");
215
  box.replaceChildren();
216
  const alerts = [];
217
  for (const [name, value] of list || []) {
218
    if (name === "via") alerts.push(titled(value.split(" ").pop()) + " is at the door.");
219
    if (name === "x-observed-by") alerts.push((value === "cat" ? "The cat" : titled(value)) + " is watching.");
220
    if (name === "warning") {
221
      const text = (value.match(/"([^"]*)"/) || [, value])[1];
222
      alerts.push(titled(text) + ".");
223
    }
224
  }
225
  const stamina = (list || []).find(([name]) => name === "x-stamina");
226
  if (stamina && stamina[1].startsWith("0/")) alerts.push("Exhausted. Wait out the refractory period, then GET the run.");
227
  for (const alert of alerts) box.append(el("h2", { textContent: alert }));
228
}
229
230
function renderTargets() {
231
  const box = $("targets");
232
  box.replaceChildren();
233
  const all = targets();
234
  for (const [group, title] of GROUPS) {
235
    const members = all.filter(t => t.group === group);
236
    if (!members.length) continue;
237
    box.append(el("h4", { textContent: title }));
238
    for (const t of members) {
239
      const radio = el("input", { type: "radio", name: "target", checked: t.path === target, onchange: () => chooseTarget(t) });
240
      box.append(el("label", {}, radio, " " + t.name + " ", el("small", { textContent: short(t.path) })), el("br"));
241
    }
242
  }
243
}
244
245
function renderMethods() {
246
  const box = $("methods");
247
  box.replaceChildren();
248
  const allowed = allowedMethods(current());
249
  for (const m of METHODS.filter(m => allowed.includes(m))) {
250
    const radio = el("input", { type: "radio", name: "method", checked: m === method, onchange: () => { method = m; render(); } });
251
    const label = el("label", {}, radio, " ");
252
    label.append(m === "JELQ" ? el("big", {}, el("b", { textContent: "JELQ" })) : m);
253
    box.append(label, " ");
254
  }
255
}
256
257
function fieldNames() {
258
  const t = current();
259
  const key = t.key + " " + method;
260
  let names = BY_TARGET[key] || [];
261
  if (key === "run JELQ") {
262
    const chosen = technique(fieldValue("technique"));
263
    names = ["technique"];
264
    if (options("also").length > 1) names.push("also");
265
    if (chosen && chosen.lubricant) names.push("intensity");
266
    if (["required", "optional"].includes(lubeRule())) names.push("lube");
267
  }
268
  const scoped = run && !["runs", "global"].includes(t.key);
269
  const asked = challenged && scoped && !names.includes("authorization");
270
  return (asked ? ["authorization"] : []).concat(names);
271
}
272
273
function renderFields() {
274
  const table = $("fields");
275
  table.replaceChildren();
276
  for (const name of fieldNames()) {
277
    const f = FIELDS[name];
278
    const value = fieldValue(name);
279
    const choices = options(name);
280
    let input;
281
    if (choices) {
282
      input = el("select", {}, ...choices.map(o => el("option", { value: o, textContent: o || "(none)", selected: o === value })));
283
    } else if (f.kind === "textarea") {
284
      input = el("textarea", { rows: 3, cols: 40, value, placeholder: f.placeholder || "" });
285
    } else {
286
      input = el("input", { type: f.kind, value, placeholder: f.placeholder || "", size: 30 });
287
    }
288
    input.oninput = () => { values[name] = input.value; };
289
    input.onchange = () => { values[name] = input.value; if (choices) renderFields(); };
290
    table.append(el("tr", {}, el("td", { align: "right", valign: "top", textContent: f.label }), el("td", {}, input)));
291
  }
292
  const extra = el("textarea", { rows: 3, cols: 40, value: raw("extra"), placeholder: FIELDS.extra.placeholder });
293
  extra.oninput = () => { values.extra = extra.value; };
294
  const more = el("details", { open: Boolean(values.extra) }, el("summary", { textContent: "more headers" }), extra);
295
  table.append(el("tr", {}, el("td"), el("td", {}, more)));
296
  $("send").value = method + " " + short(current().path);
297
}
298
299
function render() {
300
  if (!allowedMethods(current()).includes(method)) return chooseTarget(current());
301
  renderTargets();
302
  renderMethods();
303
  renderFields();
304
}
305
306
function parseLinks(header) {
307
  const resources = [];
308
  const moves = [];
309
  for (const match of header.matchAll(/<([^>]*)>((?:\s*;\s*[a-z-]+="[^"]*")*)/g)) {
310
    const params = Object.fromEntries([...match[2].matchAll(/([a-z-]+)="([^"]*)"/g)].map(p => [p[1], p[2]]));
311
    const name = (params.rel || "").replace(REL, "");
312
    if (name === "technique") {
313
      moves.push({ name: params.title, lubricant: params.lubricant || null });
314
      continue;
315
    }
316
    const methods = (params.allow || "GET").split(",").map(s => s.trim());
317
    resources.push({ key: name, group: GROUP_OF[name] || "play", name: NAMES[name] || params.title || name, path: match[1], methods });
318
  }
319
  return [resources, moves];
320
}
321
322
function hrefs(value, found) {
323
  if (value && typeof value === "object") {
324
    if (typeof value.href === "string") {
325
      const name = value.title || value.item || value.name || value.href.split("/").pop();
326
      found.push({ key: "offered", group: "said", name, path: value.href, methods: [value.method || "GET"] });
327
    }
328
    for (const key in value) hrefs(value[key], found);
329
  }
330
  return found;
331
}
332
333
function log(text) {
334
  $("log").prepend(text + "\n\n");
335
  $("frame").scrollTop = 0;
336
}
337
338
function describe(r) {
339
  const lines = ["< " + r.status + " " + r.reason];
340
  for (const [name, value] of r.headers) {
341
    if (!QUIET.has(name)) lines.push("< " + name + ": " + short(value));
342
  }
343
  let body = null;
344
  try { body = JSON.parse(r.body); } catch (e) {}
345
  if (body && typeof body === "object") {
346
    const rest = Object.assign({}, body);
347
    if (rest.detail) lines.push("  " + rest.detail);
348
    for (const key of ["type", "title", "status", "detail"]) delete rest[key];
349
    if (Object.keys(rest).length) lines.push(short(JSON.stringify(rest, null, 2)).replace(/^/gm, "  "));
350
  } else if (r.body) {
351
    const range = (r.headers.find(h => h[0] === "content-range") || [])[1] || "";
352
    const partial = r.status === 206 && range.match(/^bytes (\d+)-(\d+)\/(\d+)$/);
353
    lines.push("  " + r.body);
354
    if (partial) lines.push("  [bytes " + partial[1] + "-" + partial[2] + " of " + partial[3] + ". A 206 carries only part of the representation, as RFC 9110 requires.]");
355
  }
356
  return lines.join("\n");
357
}
358
359
function absorb(r, sentMethod, sentPath) {
360
  const headers = Object.fromEntries(r.headers.map(([n, v]) => [n.toLowerCase(), v]));
361
  let body = null;
362
  try { body = JSON.parse(r.body); } catch (e) {}
363
  const problem = body && typeof body.type === "string" ? body.type.split("/").pop() : null;
364
  const started = r.status === 201 && (sentPath === "/runs" || sentPath.startsWith("/runs?"));
365
366
  if (started) {
367
    run = headers.location;
368
    log("--- a new run has started at " + short(run) + " ---");
369
  }
370
  if ("x-eq" in headers) {
371
    renderStats(headers);
372
    renderAlerts(r.headers);
373
    challenged = r.status === 401 || "via" in headers;
374
  }
375
  if (headers.link) [linked, techniques] = parseLinks(headers.link);
376
  offered = body ? hrefs(body, []) : [];
377
  if (headers.location && !started) {
378
    offered.unshift({ key: "offered", group: "said", name: short(headers.location).split("/").pop() + " (Location)", path: headers.location, methods: ["GET"] });
379
  }
380
  const abandoned = sentMethod === "DELETE" && sentPath === run && r.status === 204;
381
  if (run && (abandoned || DEATHS.includes(problem))) {
382
    log("--- the run has ended ---");
383
    renderAlerts(null);
384
    challenged = false;
385
    run = null;
386
    linked = [];
387
    techniques = [];
388
  }
389
  if (started || !targets().some(t => t.path === target)) {
390
    const home = linked.find(t => t.key === "run");
391
    chooseTarget(home || GLOBALS[0]);
392
  } else {
393
    render();
394
  }
395
}
396
397
async function go(event) {
398
  event.preventDefault();
399
  const t = current();
400
  const key = t.key + " " + method;
401
  const value = name => fieldValue(name).trim();
402
  const headers = [];
403
  let path = t.path;
404
  let body = "";
405
  for (const name of fieldNames()) {
406
    const f = FIELDS[name];
407
    if (f.header && value(name)) headers.push([f.header, value(name)]);
408
  }
409
  if (fieldNames().includes("upgrade") && value("upgrade")) headers.push(["Connection", "upgrade"]);
410
  for (const line of raw("extra").split("\n")) {
411
    const at = line.indexOf(":");
412
    if (at > 0) headers.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]);
413
  }
414
  if (key === "run JELQ") {
415
    const names = fieldNames();
416
    const chosen = [value("technique")].concat(names.includes("also") && value("also") ? [value("also")] : []);
417
    path += "?technique=" + encodeURIComponent(chosen.join(","));
418
    if (names.includes("intensity")) path += "&intensity=" + encodeURIComponent(value("intensity"));
419
  }
420
  if (key === "runs POST" && value("seed")) path += "?seed=" + encodeURIComponent(value("seed"));
421
  if (method === "PATCH") {
422
    headers.push(["Content-Type", "application/json-patch+json"]);
423
    body = value("patch");
424
  }
425
426
  const sent = ["> " + method + " " + short(path)].concat(headers.map(([name, v]) => "> " + name + ": " + v)).join("\n");
427
  headers.push(["Accept-Language", $("locale").value]);
428
  let r;
429
  try {
430
    const response = await fetch("/ui/send", {
431
      method: "POST",
432
      headers: { "Content-Type": "application/json" },
433
      body: JSON.stringify({ method, path, headers, body }),
434
    });
435
    r = await response.json();
436
  } catch (error) {
437
    log(sent + "\n! The server did not answer. Is jelqd still running? (" + error.message + ")");
438
    return;
439
  }
440
  if (!Array.isArray(r.headers)) {
441
    log(sent + "\n! The page could not read that reply:\n  " + JSON.stringify(r));
442
    return;
443
  }
444
  log(sent + "\n" + describe(r));
445
  absorb(r, method, path);
446
}
447
448
$("form").onsubmit = go;
449
$("locale").value = localStorage.getItem("locale") || "en-GB";
450
$("locale").onchange = () => localStorage.setItem("locale", $("locale").value);
451
renderStats(null);
452
render();
453
log("Welcome. Choose \"start a new run\" and send POST to begin. The newest turn is always at the top.");
454
</script>
455
</body>
456
</html>