Spielerando

Twine-Geschichte prüfen

Liest deine Twine-Geschichte so, wie du sie gespeichert hast, als Twee-Datei oder als HTML-Datei aus Twine, und findet Links zu Passagen, die es nicht gibt, Passagen, die kein Spieler erreicht, Sackgassen und Variablen, die gelesen, aber nie gesetzt werden. Jeder Fund nennt die Passage und den Weg, auf dem ein Spieler vom Start dorthin kommt.

Fünf Karten als Pixel Art auf dunklem Brett, eine für jede Passage einer Geschichte: Tür, Apfel, Brücke, Wassertropfen und Fahne. Jede Karte zeigt ihren Namen als Reihe farbiger Kacheln und ihre Links als Zeilen mit Klammern um die Kacheln des Namens, auf den sie zeigen; einer hat runde Klammern. Die Karten leuchten nacheinander auf, und von jedem Link wächst ein Pfeil zur Karte mit denselben Kacheln. Der runde Link zeigt auf eine leere, rot gestrichelte Karte mit Fragezeichen, ein Strichpfeil führt zur Fahne.
Ein Link nennt die Passage, zu der er führt; jede Kachel ist ein Buchstabe. Die Prüfung liest Links in eckigen Klammern und in den Makros des Story-Formats, die die Story-Karte von Twine auslässt. Dem Namen des Makro-Links fehlt ein Buchstabe: Keine Passage heißt so, und der Bericht sagt, welche vermutlich gemeint war.
Oben zwei Karten als Pixel Art, ein Apfel und eine Brücke. Aus der Apfelkarte fließt Honig in ein Glas, dessen Name eine Reihe farbiger Kacheln ist; auf der Brückenkarte sucht ein Auge ein Glas, dessen Name eine Kachel weniger hat. Beide Gläser kommen auf ein Regal herunter. Das volle Glas, das niemand ansieht, bekommt einen orangen Rahmen. Das leere Glas, das das Auge will und niemand füllt, blinkt rot mit Fragezeichen, und eine gestrichelte Linie verbindet die beiden Namen.
Eine Variable ist ein Glas mit Namen. Der Markt füllt eines; die Brücke liest eines, dessen Name einen Buchstaben zu wenig hat. Das füllt nie etwas, also nennt die Prüfung es zusammen mit der Variable, die vermutlich gemeint war, und auch das volle Glas, das nichts liest.

Wann du das brauchst

Bevor du eine Twine-Geschichte teilst, und nach jeder Änderung, die eine Passage umbenennt oder löscht. Die Story-Karte von Twine markiert einen kaputten Link in doppelten eckigen Klammern, aber sie liest die Makros von Harlowe, SugarCube und Chapbook nicht und sagt dir nicht, welche Passagen niemand erreicht oder wo ein Spieler stecken bleibt. Lass es auf der Prüfseite in deinem Browser laufen, oder lass deine KI denselben Code in deinem Projekt ausführen, wobei der Story-Wege-Check die Wege abgeht.

Im Browser ausprobieren

Das sagst du deiner KI

Nimm den Twine-Check von Spielerando für meine Story-Datei, mit dem Story-Wege-Check von Spielerando für das Abgehen der Wege. Zeig mir jeden kaputten Link, jede Passage, die kein Spieler erreicht, jede Sackgasse und jede Variable, die gelesen, aber nie gesetzt oder gesetzt, aber nie gelesen wird, jeweils mit der Passage, in der sie steht, und dem Weg vom Start dorthin.

Der Knopf kopiert diesen Text zusammen mit dem getesteten Code unten, damit deine KI alles hat.

Einstellungen

Der Code

Getestetes TypeScript ohne fremde Teile. Kopier es in dein Spiel oder gib es deiner KI zusammen mit dem Text oben.

/* Twine story check: reads a Twine story as it is saved, a Twee 3 file or the HTML Twine 2 writes
   (a published story or a library archive), and finds what breaks it for a player: links to
   passages that do not exist, passages no player can reach, dead ends, and variables that are read
   but never set, or set but never read. Every finding names the passage, and where a player can
   get there, the passages that lead there from the start.

   It does not walk the story itself. It turns the passages and their links into the shape of the
   story-graph-check recipe and hands that to its walk, which you pass in. So the same code finds
   dead ends here and in a story written as plain data.

   Usage, with checkStoryGraph from the story-graph-check recipe's code:
     const reports = checkTwineText(fileText, { walk: checkStoryGraph });
     reports[0].ok;                    // false when anything was found
     reports[0].findings[0];           // { kind, passage, path, message, ... }
     reports[0].text;                  // the whole report in plain words

   What it reads:
     Twee 3          ":: Name [tags] {metadata}" headers, StoryTitle, StoryData (start, format)
     Twine 2 HTML    <tw-storydata> with its <tw-passagedata>, one story or a whole archive
   Links, in every story format, as Twine's own story map reads them:
     [[Target]]  [[Text|Target]]  [[Text->Target]]  [[Target<-Text]]
   and per story format:
     Harlowe     (goto:) (link-goto:) (link-reveal-goto:) (click-goto:) (mouseover-goto:)
                 (mouseout-goto:) (redirect:) (display:) (undo:) (link-undo:) (restart:) (reload:)
     SugarCube   <<link>> <<button>> <<goto>> <<include>> <<display>> <<actions>> <<choice>>
                 <<back>> <<return>> (with or without a passage), the passage of <<textbox>> and
                 <<numberbox>>, previous() as a link target, data-passage="...", Engine.play() in
                 <<script>>, widgets
     Chapbook    {link to:} {back link} {restart link} {embed passage:} {reveal link: ..., passage:}
   Variables, per story format:
     Harlowe     (set: $x to ...), (put: ... into $x), (move: ... into $x), (unpack:), bind $x
     SugarCube   <<set>>, <<run>>, the setter of [[Text|Target][$x to 1]], <<for>>, the input
                 macros (<<textbox "$x">> and the like), State.variables.x in the story JavaScript
     Chapbook    the vars section above "--", {x}, [if x], [unless x], {text input for: 'x'} and the
                 other inserts "for" a variable, engine.state.set and get in [JavaScript]
   Temporary variables (_x) live in one passage only and are left out.

   What it does not do:
   - It does not work out conditions. A link inside (if:) or <<if>> counts as always there.
   - A link or include whose passage is named by a variable, such as (goto: $next), cannot be
     followed. The report lists each one, a passage with one is not called a dead end, and a
     passage that looks unreachable may be reached through one.

   Which passages are endings: those tagged "end" or "ending" (upper or lower case does not
   matter), and any you name in `endings`. A passage that is not an ending and has no way on is a
   dead end. A way back (<<return>>, (undo:), {back link}) counts as a way on, to every passage
   that links here.

   Passages the story format shows on its own are not checked for links in or out, but their
   variables count, and so do their links where the player sees them:
     shown with every passage, so their links count for each one:  Harlowe header and footer tags,
       SugarCube PassageHeader and PassageFooter
     shown beside the story, so what they link to can be reached:   SugarCube StoryMenu,
       StoryCaption, StoryBanner, StorySubtitle, StoryAuthor, StoryDisplayTitle, StoryShare,
       StoryInterface
     run before the story or between passages, variables only:     Harlowe startup tag, SugarCube
       StoryInit, PassageReady, PassageDone and the init tag
     never shown:  StoryTitle, StoryData, script, stylesheet, SugarCube widget passages
   A passage that is only ever shown inside another one, with (display:), <<include>> or {embed
   passage}, is part of that one: its links count there, and it is not checked on its own.

   SPDX-License-Identifier: MIT
   Copyright (c) 2026 Spielerando, https://spielerando.com */

export const DEFAULTS = {
  /** Tags that make a passage an ending, separated by spaces. Upper or lower case does not matter. */
  endingTags: "end ending",
};

export type Format = "harlowe" | "sugarcube" | "chapbook" | "snowman" | "unknown";

export interface Passage {
  name: string;
  tags: string[];
  text: string;
  /** The line of its header in a Twee file. */
  line?: number;
}

export interface TwineStory {
  from: "twee" | "html";
  name: string;
  /** The story format as the file names it, such as "Harlowe", and its version; "" when it names none. */
  format: string;
  formatVersion: string;
  /** The start passage as the file names it; "" when it names none. */
  start: string;
  startFrom: "story-data" | "start-node" | "named-start" | "none";
  passages: Passage[];
  /** The story JavaScript. */
  script: string;
  /** What could not be read in the file: StoryData that is not JSON, a start node with no passage. */
  problems: { problem: "story-data" | "start-node"; line?: number; detail: string; message: string }[];
}

/** One way from a passage to another, and the markup it came from. */
export interface Way {
  to: string;
  /** The words a player clicks, when there are any. */
  text: string;
  markup: string;
}

/** What a passage holds, as far as this check is concerned. */
export interface PassageParts {
  /** Ways to another passage. */
  links: Way[];
  /** Passages shown inside this one. */
  includes: Way[];
  /** Ways back to where the player came from. */
  back: string[];
  /** Ways back to the start. */
  restart: string[];
  /** Links and includes whose passage is named by a variable or worked out while playing. */
  unknown: string[];
  /** Variables set and read here, as written in the format: $gold, or gold in Chapbook. */
  sets: string[];
  reads: string[];
  /** Widgets this passage uses (SugarCube). */
  widgets: string[];
}

/* ---------- reading the file ---------- */

/** Every story in a Twee file or a Twine 2 HTML file. Throws with a plain message if there is none. */
export function readTwine(text: string): TwineStory[] {
  const source = text.replace(/^/, "");
  if (/<tw-storydata\b/i.test(source)) {
    const stories = readTwineHtml(source);
    if (stories.length > 0) return stories;
  }
  if (/^::/m.test(source)) return [readTwee(source)];
  if (/<div\s+tiddler=/i.test(source)) throw new TwineFileError("twine-1", "This is a Twine 1 file. This check reads Twee and Twine 2 files: open the story in Twine 2 and publish it again, or save it as Twee.");
  throw new TwineFileError("no-passages", 'No passages found. A Twee file starts each passage with a line such as ":: Start", and a Twine 2 file holds <tw-storydata>.');
}

/** A file that holds no story this check can read; `code` says why. */
export class TwineFileError extends Error {
  code: "twine-1" | "no-passages";
  constructor(code: "twine-1" | "no-passages", message: string) {
    super(message);
    this.code = code;
  }
}

const unescapeTwee = (text: string) => text.replace(/\\(.)/g, "$1");

/** The index of the first or last character `char` that is not escaped with a backslash. */
function unescapedIndex(text: string, char: string, last: boolean): number {
  const at: number[] = [];
  for (let i = 0; i < text.length; i++) {
    if (text[i] === "\\") i++;
    else if (text[i] === char) at.push(i);
  }
  return at.length === 0 ? -1 : last ? at[at.length - 1] : at[0];
}

/** A Twee 3 file, as the Twee 3 specification describes it. */
export function readTwee(text: string): TwineStory {
  const lines = text.replace(/^/, "").split(/\r?\n/);
  const raw: { name: string; tags: string[]; line: number; body: string[] }[] = [];
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    if (line.startsWith("::")) {
      let header = line.slice(2);
      // metadata is an inline JSON object at the end, tags a block in square brackets before it
      const open = unescapedIndex(header, "{", false);
      if (open >= 0 && header.trimEnd().endsWith("}")) header = header.slice(0, open);
      let tags: string[] = [];
      const tagOpen = unescapedIndex(header, "[", true);
      const tagClose = unescapedIndex(header, "]", true);
      if (tagOpen >= 0 && tagClose > tagOpen && header.slice(tagClose + 1).trim() === "") {
        tags = header.slice(tagOpen + 1, tagClose).split(/\s+/).filter(Boolean).map(unescapeTwee);
        header = header.slice(0, tagOpen);
      }
      raw.push({ name: unescapeTwee(header.trim()), tags, line: i + 1, body: [] });
    } else if (raw.length > 0) raw[raw.length - 1].body.push(line);
  }
  const story: TwineStory = { from: "twee", name: "", format: "", formatVersion: "", start: "", startFrom: "none", passages: [], script: "", problems: [] };
  for (const item of raw) {
    while (item.body.length > 0 && item.body[item.body.length - 1].trim() === "") item.body.pop();
    const body = item.body.join("\n");
    if (item.name === "StoryTitle") story.name = body.trim();
    else if (item.name === "StoryData") {
      try {
        const data = JSON.parse(body) as Record<string, unknown>;
        if (typeof data.format === "string") story.format = data.format;
        if (typeof data["format-version"] === "string") story.formatVersion = data["format-version"];
        if (typeof data.start === "string" && data.start.trim() !== "") {
          story.start = data.start;
          story.startFrom = "story-data";
        }
      } catch (error) {
        const detail = error instanceof Error ? error.message : String(error);
        story.problems.push({ problem: "story-data", line: item.line, detail, message: `StoryData (line ${item.line}) is not valid JSON, so its start passage and story format could not be read: ${detail}` });
      }
    } else {
      if (item.tags.includes("script")) story.script += body + "\n";
      story.passages.push({ name: item.name, tags: item.tags, text: body, line: item.line });
    }
  }
  if (story.startFrom === "none" && story.passages.some((passage) => passage.name === "Start")) {
    story.start = "Start";
    story.startFrom = "named-start";
  }
  return story;
}

const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: "\u00a0" };

function decodeHtml(text: string): string {
  return text.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, code: string) => {
    if (code[0] === "#") {
      const n = code[1] === "x" || code[1] === "X" ? parseInt(code.slice(2), 16) : parseInt(code.slice(1), 10);
      return Number.isFinite(n) && n >= 0 && n <= 0x10ffff ? String.fromCodePoint(n) : whole;
    }
    return ENTITIES[code.toLowerCase()] ?? whole;
  });
}

function attributes(text: string): Record<string, string> {
  const out: Record<string, string> = {};
  for (const m of text.matchAll(/([\w:-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g)) out[m[1].toLowerCase()] = decodeHtml(m[2] ?? m[3] ?? m[4] ?? "");
  return out;
}

/** The stories in a Twine 2 HTML file: a published story holds one, a library archive many. */
export function readTwineHtml(html: string): TwineStory[] {
  const stories: TwineStory[] = [];
  // the story format's own code in a published file could hold the words "<tw-storydata" too, so
  // each story is the last <tw-storydata ...> before a </tw-storydata>
  for (const m of html.matchAll(/<tw-storydata\b((?:(?!<tw-storydata\b)[^>])*)>((?:(?!<tw-storydata\b)[\s\S])*?)<\/tw-storydata>/gi)) {
    const attrs = attributes(m[1]);
    const inner = m[2];
    const story: TwineStory = { from: "html", name: attrs.name ?? "", format: attrs.format ?? "", formatVersion: attrs["format-version"] ?? "", start: "", startFrom: "none", passages: [], script: "", problems: [] };
    const byPid = new Map<string, string>();
    for (const p of inner.matchAll(/<tw-passagedata\b([^>]*)>([\s\S]*?)<\/tw-passagedata>/gi)) {
      const a = attributes(p[1]);
      const name = a.name ?? "";
      if (a.pid) byPid.set(a.pid, name);
      story.passages.push({ name, tags: (a.tags ?? "").split(/\s+/).filter(Boolean), text: decodeHtml(p[2]) });
    }
    for (const s of inner.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
      if (/text\/twine-javascript/i.test(s[1]) || /role\s*=\s*["']?script/i.test(s[1])) story.script += decodeHtml(s[2]) + "\n";
    }
    if (attrs.startnode) {
      const name = byPid.get(attrs.startnode);
      if (name !== undefined) {
        story.start = name;
        story.startFrom = "start-node";
      } else story.problems.push({ problem: "start-node", detail: attrs.startnode, message: `The story says it starts at passage number ${attrs.startnode}, and the file has no passage with that number.` });
    }
    stories.push(story);
  }
  return stories;
}

/** The story format, from what the file says or, when it says nothing, from the markup it uses. */
export function storyFormat(story: TwineStory): { format: Format; declared: boolean } {
  const named = story.format.toLowerCase();
  for (const format of ["harlowe", "sugarcube", "chapbook", "snowman"] as const) if (named.includes(format)) return { format, declared: true };
  if (named !== "") return { format: "unknown", declared: true };
  const all = story.passages.map((passage) => passage.text).join("\n");
  const score = {
    harlowe: (all.match(/\((?:set|put|if|unless|else-?if|link-?goto|goto|display|print|either|link|move|unpack):/gi) ?? []).length,
    sugarcube: (all.match(/<<\/?[A-Za-z][\w-]*/g) ?? []).length,
    chapbook: (all.match(/\{(?:back link|restart link|link to:|embed passage|reveal link|[\w ]+ for:)|^\[(?:if|unless|else)\b/gm) ?? []).length + story.passages.filter((passage) => varsSection(passage.text) !== null).length,
  };
  const best = (Object.entries(score) as [Format, number][]).sort((a, b) => b[1] - a[1])[0];
  return { format: best[1] > 0 ? best[0] : "unknown", declared: false };
}

/* ---------- reading code inside a passage ---------- */

/** Spans of string literals in a piece of code. In Harlowe, 's after a name is "of", not a string. */
function literalSpans(code: string, harlowe: boolean): { start: number; end: number; value: string }[] {
  const spans: { start: number; end: number; value: string }[] = [];
  for (let i = 0; i < code.length; i++) {
    const c = code[i];
    if (c !== '"' && c !== "'" && c !== "`") continue;
    if (harlowe && c === "'" && /[\p{L}\p{N}_)\]]/u.test(code[i - 1] ?? "") && /^s(?![\p{L}\p{N}_])/u.test(code.slice(i + 1, i + 3))) continue;
    if (harlowe && c === "`") continue;
    let j = i + 1;
    let value = "";
    while (j < code.length && code[j] !== c) {
      if (code[j] === "\\" && j + 1 < code.length) {
        value += code[j + 1];
        j += 2;
      } else value += code[j++];
    }
    spans.push({ start: i, end: Math.min(j, code.length - 1), value });
    i = j;
  }
  return spans;
}

/** The code with every string literal blanked out, the same length, so positions still match. */
function maskStrings(code: string, harlowe: boolean): string {
  let out = code;
  for (const s of literalSpans(code, harlowe)) out = out.slice(0, s.start) + " ".repeat(s.end - s.start + 1) + out.slice(s.end + 1);
  return out;
}

/** Splits code at a separator that is outside strings and brackets: "," or a word such as "to". */
function splitTop(code: string, separator: string, harlowe: boolean): string[] {
  const masked = maskStrings(code, harlowe);
  const word = /^\w+$/.test(separator);
  const parts: string[] = [];
  let depth = 0;
  let from = 0;
  for (let i = 0; i < masked.length; i++) {
    const c = masked[i];
    if ("([{".includes(c)) depth++;
    else if (")]}".includes(c)) depth = Math.max(0, depth - 1);
    else if (depth === 0 && masked.startsWith(separator, i)) {
      if (word && (/\w/.test(masked[i - 1] ?? "") || /\w/.test(masked[i + separator.length] ?? ""))) continue;
      parts.push(code.slice(from, i));
      from = i + separator.length;
      i += separator.length - 1;
    }
  }
  parts.push(code.slice(from));
  return parts;
}

/** The value of an argument that is one string literal and nothing else, or null. */
function onlyString(arg: string, harlowe: boolean): string | null {
  const trimmed = arg.trim();
  const spans = literalSpans(trimmed, harlowe);
  return spans.length === 1 && spans[0].start === 0 && spans[0].end === trimmed.length - 1 ? spans[0].value : null;
}

const VAR = /(?<![\p{L}\p{N}_$\\])\$([\p{L}_][\p{L}\p{N}_]*)/gu;

/** Story variables ($name) in code, outside its strings. */
function dollarVars(code: string, harlowe: boolean): string[] {
  return [...maskStrings(code, harlowe).matchAll(VAR)].map((m) => `$${m[1]}`);
}

/** Story variables in plain passage text, where a $name prints the variable. */
const textVars = (text: string) => [...text.matchAll(VAR)].map((m) => `$${m[1]}`);

/** Where a piece of code that starts at `from` with an opening bracket ends, or -1. */
function closing(text: string, from: number, open: string, close: string, harlowe: boolean): number {
  let depth = 0;
  for (let i = from; i < text.length; i++) {
    const c = text[i];
    if (c === '"' || c === "'" || (c === "`" && !harlowe)) {
      if (harlowe && c === "'" && /[\p{L}\p{N}_)\]]/u.test(text[i - 1] ?? "") && /^s(?![\p{L}\p{N}_])/u.test(text.slice(i + 1, i + 3))) continue;
      let j = i + 1;
      while (j < text.length && text[j] !== c) j += text[j] === "\\" ? 2 : 1;
      i = j;
    } else if (c === open) depth++;
    else if (c === close && --depth === 0) return i;
  }
  return -1;
}

/** The [[...]] links of a passage, read as Twine's story map reads them: the rightmost "->", the
    leftmost "<-", the last "|", and a setter in a second pair of brackets is not part of the name. */
function wikiLinks(text: string): { target: string; text: string; setter: string; markup: string; start: number; end: number }[] {
  const out: { target: string; text: string; setter: string; markup: string; start: number; end: number }[] = [];
  for (const m of text.matchAll(/\[\[(.*?)\]\]/g)) {
    let inner = m[1];
    let setter = "";
    const split = inner.indexOf("][");
    if (split >= 0) {
      setter = inner.slice(split + 2);
      inner = inner.slice(0, split);
    }
    let target = inner;
    let shown = inner;
    const arrow = inner.lastIndexOf("->");
    const back = inner.indexOf("<-");
    const bar = inner.lastIndexOf("|");
    if (arrow >= 0) {
      target = inner.slice(arrow + 2);
      shown = inner.slice(0, arrow);
    } else if (back >= 0) {
      target = inner.slice(0, back);
      shown = inner.slice(back + 2);
    } else if (bar >= 0) {
      target = inner.slice(bar + 1);
      shown = inner.slice(0, bar);
    }
    if (target === "" || /^\w+:\/\/\/?\w/i.test(target)) continue;
    out.push({ target, text: shown, setter, markup: m[0], start: m.index, end: m.index + m[0].length });
  }
  return out;
}

const blank = (text: string, start: number, end: number) => text.slice(0, start) + " ".repeat(end - start) + text.slice(end);
const stripHtmlComments = (text: string) => text.replace(/<!--[\s\S]*?-->/g, (c) => " ".repeat(c.length));

function emptyParts(): PassageParts {
  return { links: [], includes: [], back: [], restart: [], unknown: [], sets: [], reads: [], widgets: [] };
}

/** A target as a link names it: a passage name, a way back, or something only known while playing. */
function addTarget(parts: PassageParts, kind: "links" | "includes", target: string, text: string, markup: string, format: Format) {
  if (format === "sugarcube" && /^previous\(\s*\)$/.test(target.trim())) parts.back.push(markup);
  else if (/^[$_]/.test(target) || (format === "sugarcube" && /\(.*\)/.test(target))) parts.unknown.push(markup);
  else parts[kind].push({ to: target, text, markup });
}

/* Harlowe */

const harloweName = (name: string) => name.toLowerCase().replace(/[-_]/g, "");

/** Variables in a Harlowe assignment target: a plain $x is set, $x's y or 1st of $x only reads $x. */
function harloweTarget(target: string, parts: PassageParts, value: string) {
  const plain = /^\s*(?:[\p{L}-]+-type\s+)?\$([\p{L}_][\p{L}\p{N}_]*)\s*$/u.exec(target);
  if (plain) {
    parts.sets.push(`$${plain[1]}`);
    // "it" in the value is the variable being set
    if (/(?<![\p{L}\p{N}_$])it(?![\p{L}\p{N}_])/u.test(maskStrings(value, true))) parts.reads.push(`$${plain[1]}`);
  } else parts.reads.push(...dollarVars(target, true));
}

function readHarlowe(source: string, parts: PassageParts) {
  let text = stripHtmlComments(source);
  for (const link of wikiLinks(text)) {
    addTarget(parts, "links", link.target, link.text, link.markup, "harlowe");
    parts.reads.push(...textVars(link.text));
    text = blank(text, link.start, link.end);
  }
  const macro = /\(([A-Za-z][\w-]*):/g;
  let m: RegExpExecArray | null;
  while ((m = macro.exec(text))) {
    const end = closing(text, m.index, "(", ")", true);
    if (end < 0) continue;
    const name = harloweName(m[1]);
    const args = text.slice(m.index + m[0].length, end);
    const markup = text.slice(m.index, end + 1);
    const list = splitTop(args, ",", true);
    // bind $x and 2bind $x set a variable from what the player does
    const binds = [...maskStrings(args, true).matchAll(/(?<![\p{L}\p{N}_])(2?)bind\s+\$([\p{L}_][\p{L}\p{N}_]*)/gu)];
    for (const b of binds) {
      parts.sets.push(`$${b[2]}`);
      if (b[1] === "2") parts.reads.push(`$${b[2]}`);
    }
    const rest = binds.reduce((code, b) => code.replace(b[0], " "), maskStrings(args, true));
    if (name === "set") {
      for (const item of list) {
        const [target, ...value] = splitTop(item, "to", true);
        if (value.length === 0) continue;
        harloweTarget(target, parts, value.join("to"));
        parts.reads.push(...dollarVars(value.join("to"), true));
      }
    } else if (name === "put" || name === "move" || name === "unpack") {
      for (const item of list) {
        const pieces = splitTop(item, "into", true);
        if (pieces.length < 2) continue;
        const target = pieces.pop() as string;
        parts.reads.push(...dollarVars(pieces.join("into"), true));
        if (name === "unpack") parts.sets.push(...dollarVars(target, true));
        else harloweTarget(target, parts, pieces.join("into"));
      }
    } else {
      parts.reads.push(...[...rest.matchAll(VAR)].map((v) => `$${v[1]}`));
      const target = (i: number) => {
        const arg = list[i];
        if (arg === undefined) return;
        const value = onlyString(arg, true);
        if (value === null) parts.unknown.push(markup);
        else addTarget(parts, name === "display" ? "includes" : "links", value, name === "linkgoto" || name === "linkrevealgoto" ? (onlyString(list[0], true) ?? "") : "", markup, "harlowe");
      };
      if (name === "goto" || name === "redirect" || name === "display") target(0);
      else if (name === "linkgoto" || name === "linkrevealgoto") target(list.length > 1 ? 1 : 0);
      else if (name === "clickgoto" || name === "mouseovergoto" || name === "mouseoutgoto") target(1);
      else if (name === "undo" || name === "linkundo") parts.back.push(markup);
      else if (name === "restart" || name === "reload") parts.restart.push(markup);
    }
    text = blank(text, m.index, end + 1);
    macro.lastIndex = m.index + 1;
  }
  parts.reads.push(...textVars(text));
}

/* SugarCube */

/** SugarCube macro arguments: strings, [[links]], `expressions` and plain words, split by spaces. */
function sugarArgs(args: string): string[] {
  const out: string[] = [];
  let i = 0;
  while (i < args.length) {
    if (/\s/.test(args[i])) {
      i++;
      continue;
    }
    let end: number;
    if (args[i] === '"' || args[i] === "'" || args[i] === "`") {
      end = i + 1;
      while (end < args.length && args[end] !== args[i]) end += args[end] === "\\" ? 2 : 1;
      end++;
    } else if (args.startsWith("[[", i)) {
      end = args.indexOf("]]", i);
      end = end < 0 ? args.length : end + 2;
    } else {
      end = i;
      while (end < args.length && !/\s/.test(args[end])) end++;
    }
    out.push(args.slice(i, end));
    i = end;
  }
  return out;
}

/** A SugarCube assignment list, as <<set>> and <<run>> take it: $x to 1, $y += 2, $z++. A link's
    setter may also separate them with ";". */
function sugarAssignments(code: string, parts: PassageParts) {
  for (const item of splitTop(code, ";", false).flatMap((part) => splitTop(part, ",", false))) {
    const masked = maskStrings(item, false);
    const op = /(?<![=!<>])(\+\+|--|\*\*=|[-+*/%]=|\?\?=|\|\|=|&&=|=(?![=>])|\bto\b)/.exec(masked);
    if (!op) {
      parts.reads.push(...dollarVars(item, false));
      continue;
    }
    const target = item.slice(0, op.index);
    const value = item.slice(op.index + op[0].length);
    const plain = /^\s*\$([\p{L}_][\p{L}\p{N}_]*)\s*$/u.exec(target);
    if (op[0] === "++" || op[0] === "--") {
      // $x++ or ++$x counts it up: a read and a set; $x.n++ only reads $x
      const counted = plain ? `$${plain[1]}` : /^\s*\$([\p{L}_][\p{L}\p{N}_]*)\s*$/u.exec(value)?.[1];
      if (counted) parts.sets.push(counted.startsWith("$") ? counted : `$${counted}`);
      parts.reads.push(...dollarVars(item, false));
      continue;
    }
    if (plain) {
      parts.sets.push(`$${plain[1]}`);
      if (op[0] !== "=" && op[0] !== "to") parts.reads.push(`$${plain[1]}`);
    } else parts.reads.push(...dollarVars(target, false));
    parts.reads.push(...dollarVars(value, false));
  }
}

/** State.variables.x and variables().x in JavaScript: an assignment sets it, anything else reads it. */
function scriptVars(code: string, parts: PassageParts) {
  for (const m of code.matchAll(/\b(?:State\.variables|variables\(\s*\))\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*["']([^"']+)["']\s*\])(\s*(?:[-+*/%]?=(?!=)|\+\+|--))?/g)) {
    const name = `$${m[1] ?? m[2]}`;
    if (m[3]) {
      parts.sets.push(name);
      if (m[3].trim() !== "=") parts.reads.push(name);
    } else parts.reads.push(name);
  }
}

const SUGAR_INPUTS = new Set(["textbox", "textarea", "numberbox", "checkbox", "radiobutton", "listbox", "cycle"]);

function readSugarCube(source: string, parts: PassageParts) {
  let text = source.replace(/\/\*[\s\S]*?\*\/|\/%[\s\S]*?%\/|<!--[\s\S]*?-->/g, (c) => " ".repeat(c.length));
  // <<script>> holds plain JavaScript
  text = text.replace(/<<script>>([\s\S]*?)<<\/script>>/g, (whole, code: string) => {
    scriptVars(code, parts);
    for (const play of code.matchAll(/Engine\.play\(\s*(["'])((?:\\.|(?!\1).)*)\1/g)) parts.links.push({ to: play[2], text: "", markup: play[0] });
    return " ".repeat(whole.length);
  });
  // <<include>> and <<display>> show a passage inside this one: their [[...]] is not a link
  for (const m of text.matchAll(/<<(include|display)\s+([^>]*?)>>/g)) {
    const first = sugarArgs(m[2])[0] ?? "";
    const link = wikiLinks(first)[0];
    const value = link ? link.target : onlyString(first, false);
    if (value === null) parts.unknown.push(m[0]);
    else addTarget(parts, "includes", value, "", m[0], "sugarcube");
    text = blank(text, m.index, m.index + m[0].length);
  }
  for (const link of wikiLinks(text)) {
    addTarget(parts, "links", link.target, link.text, link.markup, "sugarcube");
    if (link.setter) sugarAssignments(link.setter, parts);
    text = blank(text, link.start, link.end);
  }
  for (const m of text.matchAll(/\bdata-passage\s*=\s*(["'])(.*?)\1/g)) {
    addTarget(parts, "links", decodeHtml(m[2]), "", m[0], "sugarcube");
    text = blank(text, m.index, m.index + m[0].length);
  }
  for (const m of text.matchAll(/\bdata-setter\s*=\s*(["'])(.*?)\1/g)) {
    sugarAssignments(decodeHtml(m[2]), parts);
    text = blank(text, m.index, m.index + m[0].length);
  }
  const macro = /<<(?!\/)([A-Za-z][\w-]*|[=-])/g;
  let m: RegExpExecArray | null;
  while ((m = macro.exec(text))) {
    // the macro ends at the first >> outside its strings
    let end = -1;
    for (let i = m.index + m[0].length; i < text.length - 1; i++) {
      const c = text[i];
      if (c === '"' || c === "'" || c === "`") {
        let j = i + 1;
        while (j < text.length && text[j] !== c) j += text[j] === "\\" ? 2 : 1;
        i = j;
      } else if (c === ">" && text[i + 1] === ">") {
        end = i;
        break;
      }
    }
    if (end < 0) break;
    const name = m[1];
    const args = text.slice(m.index + m[0].length, end);
    // the text keeps every position, so this is the macro as written, with any [[link]] in it
    const markup = source.slice(m.index, end + 2);
    const list = sugarArgs(args);
    const target = (arg: string | undefined, kind: "links" | "includes", shown: string) => {
      if (arg === undefined) return;
      const value = onlyString(arg, false);
      if (value !== null && arg.trim()[0] !== "`") addTarget(parts, kind, value, shown, markup, "sugarcube");
      else if (arg.startsWith("`")) addTarget(parts, kind, arg.slice(1, -1), shown, markup, "sugarcube");
      else if (!arg.startsWith("[[")) parts.unknown.push(markup);
    };
    if (name === "set" || name === "run") {
      sugarAssignments(args, parts);
      scriptVars(args, parts);
    } else if (name === "unset") {
      // removes a variable: neither a read nor a set
    } else if (SUGAR_INPUTS.has(name)) {
      // the variable is named in quotes: <<textbox "$name" "Ann">>
      const receiver = onlyString(list[0] ?? "", false);
      if (receiver && /^\$/.test(receiver)) parts.sets.push(receiver.replace(/[.[].*$/, ""));
      parts.reads.push(...dollarVars(list.slice(1).join(" "), false));
      // <<textbox>> and <<numberbox>> can go to a passage when the player presses Enter
      if ((name === "textbox" || name === "numberbox") && list[2] !== undefined && list[2] !== "autofocus") target(list[2], "links", "");
    } else if (name === "for") {
      const range = splitTop(args, "range", false);
      if (range.length === 2) {
        parts.sets.push(...dollarVars(range[0], false));
        parts.reads.push(...dollarVars(range[1], false));
      } else {
        const [init = "", condition = "", step = ""] = args.split(";");
        sugarAssignments(init, parts);
        parts.reads.push(...dollarVars(condition, false));
        sugarAssignments(step, parts);
      }
    } else if (name === "widget") {
      // the widget's name, not a variable
    } else {
      parts.reads.push(...dollarVars(args, false));
      // a [[link]] in the macro was read as a link above, and its place is blank in `list`
      if (name === "link" || name === "button") {
        if (list.length >= 2) target(list[1], "links", onlyString(list[0], false) ?? "");
      } else if (name === "goto") target(list[0], "links", "");
      else if (name === "actions") for (const arg of list) target(arg, "links", "");
      else if (name === "choice") target(list[0], "links", onlyString(list[1] ?? "", false) ?? "");
      else if (name === "back" || name === "return") {
        // <<back "Leave" "Camp">> goes to Camp; without a passage it goes back
        if (list.length >= 2) target(list[1], "links", onlyString(list[0], false) ?? "");
        else if (!markup.includes("[[")) parts.back.push(markup);
      } else if (/^[A-Za-z]/.test(name)) parts.widgets.push(name);
    }
    text = blank(text, m.index, end + 2);
    macro.lastIndex = m.index + 1;
  }
  parts.reads.push(...textVars(text));
}

/* Chapbook */

/** The vars section of a Chapbook passage: the lines above the first "--" line, if each is a variable. */
function varsSection(text: string): { lines: string[]; body: string } | null {
  const lines = text.split("\n");
  const cut = lines.findIndex((line) => line.trim() === "--");
  if (cut <= 0) return null;
  const head = lines.slice(0, cut).filter((line) => line.trim() !== "");
  if (head.length === 0 || !head.every((line) => /^\s*[A-Za-z_$][\w$.]*\s*(\([^)]*\))?\s*:/.test(line))) return null;
  return { lines: head, body: lines.slice(cut + 1).join("\n") };
}

const JS_WORDS = new Set([
  "true", "false", "null", "undefined", "NaN", "Infinity", "typeof", "instanceof", "new", "in", "of", "void", "delete", "this", "return", "if", "else", "let", "const", "var", "function",
  "Math", "Date", "JSON", "Number", "String", "Boolean", "Array", "Object", "window", "document", "console", "parseInt", "parseFloat", "isNaN",
  // Chapbook's own lookups and settings
  "browser", "engine", "now", "passage", "random", "story", "config",
]);

/** The variables a JavaScript expression reads: names outside strings, not after a dot, and not
    the keys of an object such as { a: 1 }. */
function jsReads(code: string): string[] {
  const masked = maskStrings(code, false).replace(/([{,]\s*)[A-Za-z_$][\w$]*(\s*:)/g, (_, before: string, after: string) => before + " " + after);
  return [...masked.matchAll(/(?<![\w$.])([A-Za-z_$][\w$]*)/g)].map((m) => m[1]).filter((name) => !JS_WORDS.has(name));
}

function readChapbook(source: string, parts: PassageParts) {
  let text = stripHtmlComments(source);
  const vars = varsSection(text);
  if (vars) {
    for (const line of vars.lines) {
      const m = /^\s*([A-Za-z_$][\w$]*)[\w$.]*\s*(?:\(([^)]*)\))?\s*:(.*)$/.exec(line) as RegExpExecArray;
      if (m[1] !== "config") parts.sets.push(m[1]);
      parts.reads.push(...jsReads(m[2] ?? ""), ...jsReads(m[3]));
    }
    text = vars.body;
  }
  // [note] blocks are notes to the author, [CSS] blocks are styles, [JavaScript] blocks are code
  const blocks = text.split(/^(\s*\[[^\[\]\n]+\]\s*)$/m);
  text = "";
  for (let i = 0; i < blocks.length; i++) {
    const modifier = /^\s*\[([^\]]+)\]\s*$/.exec(blocks[i]);
    if (modifier && i % 2 === 1) {
      for (const part of modifier[1].split(";")) {
        const condition = /^\s*(?:if|unless|else\s+if)\s+(.+)$/i.exec(part);
        if (condition) parts.reads.push(...jsReads(condition[1]));
      }
      const name = modifier[1].trim().toLowerCase();
      const next = blocks[i + 1] ?? "";
      if (/^(note|note to myself|n\.b\.|fixme|todo|css)$/.test(name)) blocks[i + 1] = "";
      else if (name === "javascript") {
        for (const m of next.matchAll(/engine\.state\.(set|get)\(\s*(["'])([\w$.]+)\2/g)) (m[1] === "set" ? parts.sets : parts.reads).push(m[3].replace(/\..*$/, ""));
        blocks[i + 1] = "";
      }
      text += " ".repeat(blocks[i].length);
    } else text += blocks[i];
  }
  for (const link of wikiLinks(text)) {
    addTarget(parts, "links", link.target, link.text, link.markup, "chapbook");
    text = blank(text, link.start, link.end);
  }
  for (let at = text.indexOf("{"); at >= 0; at = text.indexOf("{", at + 1)) {
    const end = closing(text, at, "{", "}", false);
    if (end < 0) break;
    const inner = text.slice(at + 1, end);
    const markup = text.slice(at, end + 1);
    const variable = /^\s*([A-Za-z_$][\w$]*)(?:\.[A-Za-z_$][\w$]*)*\s*$/.exec(inner);
    if (variable) {
      if (!JS_WORDS.has(variable[1])) parts.reads.push(variable[1]);
    } else {
      const props = splitTop(inner, ",", false).map((item) => {
        const colon = maskStrings(item, false).indexOf(":");
        return colon < 0 ? { key: item.trim().toLowerCase(), value: "" } : { key: item.slice(0, colon).trim().toLowerCase().replace(/\s+/g, " "), value: item.slice(colon + 1) };
      });
      const first = props[0]?.key ?? "";
      const value = (key: string) => props.find((p) => p.key === key || p.key.endsWith(` ${key}`))?.value;
      const go = (kind: "links" | "includes", arg: string | undefined, shown: string) => {
        if (arg === undefined) return;
        const name = onlyString(arg, false);
        if (name === null) parts.unknown.push(markup);
        else addTarget(parts, kind, name, shown, markup, "chapbook");
      };
      for (const p of props) parts.reads.push(...jsReads(p.value));
      if (first === "back link") parts.back.push(markup);
      else if (first === "restart link") parts.restart.push(markup);
      else if (first === "link to") go("links", value("link to"), onlyString(value("label") ?? "", false) ?? "");
      else if (first === "embed passage" || first === "embed passage named") go("includes", props[0].value, "");
      else if (first === "reveal link") go("includes", value("passage"), "");
      // {text input for: 'name'} and {cycling link for 'mood', ...}: Chapbook's guide writes both
      const receiver = /^\s*[a-z][a-z ]*?\s+for\s*:?\s*(["'])((?:\\.|(?!\1).)*)\1/i.exec(inner);
      if (receiver) parts.sets.push(receiver[2].replace(/\..*$/, ""));
    }
    at = end;
  }
}

/* Snowman and stories whose format is not known: links only. */
function readLinksOnly(source: string, parts: PassageParts) {
  let text = stripHtmlComments(source);
  for (const link of wikiLinks(text)) {
    addTarget(parts, "links", link.target, link.text, link.markup, "unknown");
    text = blank(text, link.start, link.end);
  }
  for (const m of text.matchAll(/\bdata-passage\s*=\s*(["'])(.*?)\1/g)) addTarget(parts, "links", decodeHtml(m[2]), "", m[0], "unknown");
}

/** What one passage links to, shows inside itself, sets and reads, read as the given story format. */
export function readPassage(text: string, format: Format): PassageParts {
  const parts = emptyParts();
  if (format === "harlowe") readHarlowe(text, parts);
  else if (format === "sugarcube") readSugarCube(text, parts);
  else if (format === "chapbook") readChapbook(text, parts);
  else readLinksOnly(text, parts);
  return parts;
}

/** Whether variables are checked for a story format. */
export const checksVariables = (format: Format) => format === "harlowe" || format === "sugarcube" || format === "chapbook";

/* ---------- the special passages of each story format ---------- */

type Role = "every" | "beside" | "before" | "hidden";

const SUGAR_NAMES: Record<string, Role> = {
  PassageHeader: "every", PassageFooter: "every",
  StoryMenu: "beside", StoryCaption: "beside", StoryBanner: "beside", StorySubtitle: "beside", StoryAuthor: "beside", StoryDisplayTitle: "beside", StoryShare: "beside",
  // StoryInterface replaces the page around the story; its data-passage attributes name passages
  StoryInterface: "beside",
  StoryInit: "before", PassageReady: "before", PassageDone: "before",
};
const HARLOWE_TAGS: Record<string, Role> = { header: "every", footer: "every", startup: "before", "debug-header": "before", "debug-footer": "before", "debug-startup": "before" };
const SUGAR_TAGS: Record<string, Role> = { widget: "hidden", init: "before" };

/** What a passage is to the story format: a story passage (null) or one it shows on its own. */
export function passageRole(passage: Passage, format: Format): Role | null {
  if (passage.tags.includes("script") || passage.tags.includes("stylesheet") || passage.tags.some((tag) => tag.startsWith("Twine."))) return "hidden";
  const sugar = format === "sugarcube" || format === "unknown";
  const harlowe = format === "harlowe" || format === "unknown";
  if (sugar && SUGAR_NAMES[passage.name]) return SUGAR_NAMES[passage.name];
  for (const tag of passage.tags) {
    if (harlowe && HARLOWE_TAGS[tag]) return HARLOWE_TAGS[tag];
    if (sugar && SUGAR_TAGS[tag]) return SUGAR_TAGS[tag];
  }
  return null;
}

/* ---------- the check ---------- */

/** The story in the shape the story-graph-check recipe walks. */
export interface GraphStory {
  start: string;
  scenes: Record<string, { title?: string; ending?: boolean; choices?: { text?: string; to: string }[] }>;
}

/** The part of the story-graph-check report this check reads. */
export interface GraphReport {
  complete: boolean;
  problems: { kind: string; scene?: string; path: { scene: string; choice?: string }[] }[];
  endings: { scene: string; path: { scene: string; choice?: string }[] }[];
}

/** The story-graph-check recipe's checkStoryGraph, or anything that walks the same shape. */
export type Walk = (story: GraphStory) => GraphReport;

export interface CheckOptions {
  walk: Walk;
  /** Passages that are endings, besides those with an ending tag. */
  endings?: string[];
  /** Tags that make a passage an ending, separated by spaces. */
  endingTags?: string;
  /** Read the story as this format, whatever the file says. */
  format?: Format;
}

export type FindingKind =
  | "file-problem" | "no-start" | "start-missing" | "duplicate-passage" | "missing-passage" | "dead-end" | "no-way-to-an-ending" | "unreachable" | "no-endings"
  | "read-never-set" | "set-never-read";

/** The order of the report. */
export const KIND_ORDER: FindingKind[] = ["file-problem", "no-start", "start-missing", "duplicate-passage", "missing-passage", "dead-end", "no-way-to-an-ending", "unreachable", "no-endings", "read-never-set", "set-never-read"];

export interface Finding {
  kind: FindingKind;
  /** The passage to look at. */
  passage?: string;
  /** Its header line in a Twee file. */
  line?: number;
  /** missing-passage: the name the link uses. */
  target?: string;
  /** missing-passage: the markup of the link. */
  markup?: string;
  /** read-never-set, set-never-read: the variable as written. */
  variable?: string;
  /** Where the variable is read or set, or where the links into an unreachable passage are. */
  places?: string[];
  /** A name that does exist and is close to the one written. */
  suggestion?: string;
  /** missing-passage: a link, or a passage shown inside this one; spaces: the name only has
      spaces around it that the passage does not. */
  via?: "link" | "include";
  spaces?: boolean;
  /** dead-end: the passages its links go to, which do not exist. */
  broken?: string[];
  /** unreachable: links elsewhere whose name is close to this passage's. */
  meant?: { target: string; passage: string }[];
  /** file-problem: what could not be read, and the detail, such as the JSON error. */
  problem?: "story-data" | "start-node";
  detail?: string;
  /** duplicate-passage: the lines of both passages in a Twee file. */
  lines?: number[];
  /** The passages from the start to here, when a player can get here. */
  path: string[];
  /** The finding in one plain English sentence. */
  message: string;
}

export interface TwineReport {
  /** True when nothing was found. */
  ok: boolean;
  story: string;
  from: "twee" | "html";
  format: { name: Format; declared: boolean; written: string; version: string };
  start: string | null;
  /** Story passages, checked for links in and out. */
  passages: number;
  /** Story passages a player can reach from the start; null when there was no start to walk from. */
  reached: number | null;
  /** Passages the story format shows on its own, with what it does with them. */
  special: { passage: string; role: Role }[];
  /** Passages only ever shown inside other ones. */
  parts: string[];
  endings: { passage: string; path: string[] }[];
  findings: Finding[];
  /** Links and includes whose passage is named while playing, which the check could not follow. */
  notFollowed: { passage: string; markup: string }[];
  variablesChecked: boolean;
  variables: number;
  text: string;
}

const ROOT = "\u0002start";
const ANYWHERE = "\u0002anywhere";
const ENDS = "\u0002ends";

const FORMAT_NAMES: Record<Format, string> = { harlowe: "Harlowe", sugarcube: "SugarCube", chapbook: "Chapbook", snowman: "Snowman", unknown: "an unknown story format" };

/** How far apart two names are, in letters added, removed, changed or swapped with the next one. */
function distance(a: string, b: string): number {
  const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
  for (let i = 1; i <= a.length; i++) {
    for (let j = 1; j <= b.length; j++) {
      d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
      if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
    }
  }
  return d[a.length][b.length];
}

/** The existing name closest to one that is not there, if it is close: the same but for upper and
    lower case or spaces around it, or one letter off (two in a longer name). */
function closest(name: string, names: Iterable<string>): string | undefined {
  let best: string | undefined;
  let bestScore = Infinity;
  const plain = (s: string) => s.trim().toLowerCase();
  for (const candidate of names) {
    if (candidate === name) continue;
    const score = plain(candidate) === plain(name) ? 0 : distance(plain(candidate), plain(name));
    if (score <= (plain(name).length <= 5 ? 1 : 2) && score < bestScore) {
      best = candidate;
      bestScore = score;
    }
  }
  return best;
}

const quote = (name: string) => `"${name}"`;
const listOf = (names: string[]) => names.map(quote).join(", ");

function merge(into: PassageParts, from: PassageParts) {
  into.links.push(...from.links);
  into.back.push(...from.back);
  into.restart.push(...from.restart);
  into.unknown.push(...from.unknown);
}

/** Checks one story. */
export function checkTwine(story: TwineStory, options: CheckOptions): TwineReport {
  const detected = storyFormat(story);
  const format = options.format ?? detected.format;
  const endingTags = (options.endingTags ?? DEFAULTS.endingTags).toLowerCase().split(/\s+/).filter(Boolean);
  const findings: Finding[] = [];
  for (const p of story.problems) findings.push({ kind: "file-problem", problem: p.problem, detail: p.detail, line: p.line, path: [], message: p.message });

  // the passages by name; a second passage of the same name is reported and left out
  const passages = new Map<string, Passage>();
  for (const passage of story.passages) {
    const first = passages.get(passage.name);
    if (first) {
      const lines = first.line && passage.line ? [first.line, passage.line] : undefined;
      const where = lines ? ` (lines ${lines[0]} and ${lines[1]})` : "";
      findings.push({ kind: "duplicate-passage", passage: passage.name, line: passage.line, lines, path: [], message: `There are two passages named ${quote(passage.name)}${where}. Links go to only one of them: rename or merge the other.` });
    } else passages.set(passage.name, passage);
  }
  const names = [...passages.keys()];
  const lineOf = (name: string) => passages.get(name)?.line;
  const parts = new Map(names.map((name) => [name, readPassage((passages.get(name) as Passage).text, format)]));
  const role = new Map(names.map((name) => [name, passageRole(passages.get(name) as Passage, format)]));
  const widgetPassage = (name: string) => (passages.get(name)?.tags ?? []).includes("widget");

  // SugarCube widgets: what a widget holds counts where the widget is used
  const widgets = new Map<string, PassageParts>();
  if (format === "sugarcube" || format === "unknown") {
    for (const name of names.filter(widgetPassage)) {
      for (const m of (passages.get(name) as Passage).text.matchAll(/<<widget\s+(["'])([\w-]+)\1[^>]*>>([\s\S]*?)<<\/widget>>/g)) widgets.set(m[2], readPassage(m[3], "sugarcube"));
    }
  }

  /** What a passage holds, with the passages it shows inside itself and the widgets it uses. */
  const whole = (name: string, seen = new Set<string>()): PassageParts => {
    const own = parts.get(name) ?? emptyParts();
    const out = emptyParts();
    merge(out, own);
    seen.add(name);
    for (const include of own.includes) if (passages.has(include.to) && !seen.has(include.to)) merge(out, whole(include.to, seen));
    for (const widget of own.widgets) {
      const inner = widgets.get(widget);
      if (inner) merge(out, inner);
    }
    return out;
  };

  // passages that are only ever shown inside others are part of those, not passages of their own
  const linked = new Set<string>([story.start]);
  const included = new Set<string>();
  for (const [name, p] of parts) {
    for (const link of p.links) linked.add(link.to);
    for (const include of p.includes) if (include.to !== name) included.add(include.to);
  }
  for (const inner of widgets.values()) for (const link of inner.links) linked.add(link.to);
  const pieces = names.filter((name) => included.has(name) && !linked.has(name) && role.get(name) === null);
  const storyPassages = names.filter((name) => (role.get(name) === null && !pieces.includes(name)) || name === story.start);
  const inStory = new Set(storyPassages);
  const isEnding = (name: string) => (options.endings ?? []).includes(name) || (passages.get(name)?.tags ?? []).some((tag) => endingTags.includes(tag.toLowerCase()));

  // links to passages that do not exist, and links the check cannot follow, wherever they are written
  const read = (name: string) => role.get(name) !== "hidden" || widgetPassage(name);
  const missing: Finding[] = [];
  const notFollowed: { passage: string; markup: string }[] = [];
  for (const name of names.filter(read)) {
    const own = parts.get(name) as PassageParts;
    const seen = new Set<string>();
    for (const way of [...own.links, ...own.includes]) {
      if (passages.has(way.to) || seen.has(way.to)) continue;
      seen.add(way.to);
      const spaces = way.to.trim() !== way.to && passages.has(way.to.trim());
      const suggestion = spaces ? way.to.trim() : closest(way.to, names);
      const hint = suggestion === undefined ? "" : spaces ? ` There is a passage ${quote(suggestion)}: the link has spaces around the name, and Twine counts them.` : ` Did you mean ${quote(suggestion)}?`;
      const via = own.includes.includes(way) ? "include" : "link";
      missing.push({
        kind: "missing-passage", passage: name, line: lineOf(name), target: way.to, markup: way.markup, suggestion, via, spaces, path: [],
        message: `${quote(name)} ${via === "include" ? "shows" : "links to"} ${quote(way.to)} with ${way.markup}, and there is no passage of that name.${hint}`,
      });
    }
    for (const markup of own.unknown) notFollowed.push({ passage: name, markup });
  }

  // the walk, by the story-graph-check recipe
  const endings: { passage: string; path: string[] }[] = [];
  let reached: Set<string> | null = null;
  const startOk = story.start !== "" && passages.has(story.start);
  if (story.start === "") findings.push({ kind: "no-start", path: [], message: story.from === "twee" ? 'The story names no start passage: StoryData has no "start", and no passage is called "Start".' : "The story names no start passage." });
  else if (!startOk) findings.push({ kind: "start-missing", passage: story.start, path: [], message: `The story starts at ${quote(story.start)}, and there is no passage of that name.` });
  if (startOk) {
    const every = names.filter((name) => role.get(name) === "every").map((name) => whole(name));
    const beside = names.filter((name) => role.get(name) === "beside").flatMap((name) => whole(name).links).filter((link) => inStory.has(link.to));
    // a choice for every way on: links, restarts, and one stand-in for all links named while playing
    const forward = new Map<string, { text: string; to: string }[]>();
    const back = new Map<string, string>();
    for (const name of storyPassages) {
      const all = whole(name);
      for (const extra of every) merge(all, extra);
      const list = all.links.filter((link) => inStory.has(link.to) || !passages.has(link.to)).map((link) => ({ text: link.text || link.to, to: link.to }));
      for (const markup of all.restart) list.push({ text: markup, to: story.start });
      if (all.unknown.length > 0) list.push({ text: all.unknown[0], to: ANYWHERE });
      forward.set(name, list);
      if (all.back.length > 0) back.set(name, all.back[0]);
    }
    // a way back leads to wherever the player came from: any passage that links here, or, for a
    // passage linked from beside the story, any passage at all, which the start stands in for
    const comesFrom = new Map<string, Set<string>>();
    for (const [name, list] of forward) for (const choice of list) (comesFrom.get(choice.to) ?? comesFrom.set(choice.to, new Set()).get(choice.to))?.add(name);
    for (const link of beside) (comesFrom.get(link.to) ?? comesFrom.set(link.to, new Set()).get(link.to))?.add(ROOT);
    const graph: GraphStory = { start: ROOT, scenes: { [ROOT]: { choices: [{ text: "start", to: story.start }, ...beside.map((link) => ({ text: link.text || link.to, to: link.to }))] } } };
    for (const name of storyPassages) {
      const list = [...(forward.get(name) ?? [])];
      const way = back.get(name);
      if (way !== undefined) for (const from of comesFrom.get(name) ?? []) if (from !== name) list.push({ text: way, to: from });
      // an ending with links on is an ending and still leads on: the walk sees it as a passage
      // with one more way, to its ending
      if (isEnding(name) && list.length > 0) list.push({ text: "the end", to: `${ENDS}${name}` });
      graph.scenes[name] = isEnding(name) && list.length === 0 ? { ending: true } : { choices: list };
      if (isEnding(name) && list.length > 1) graph.scenes[`${ENDS}${name}`] = { ending: true };
    }
    if ([...forward.values()].some((list) => list.some((choice) => choice.to === ANYWHERE))) graph.scenes[ANYWHERE] = { ending: true };
    const report = options.walk(graph);
    const steps = (path: { scene: string }[]) => path.map((step) => step.scene).filter((scene) => scene !== ROOT && !scene.startsWith(ENDS));
    const lost = new Set<string>();
    for (const problem of report.problems) {
      const scene = problem.scene === ROOT ? story.start : problem.scene;
      if (scene === undefined || scene === ANYWHERE) continue;
      if (problem.kind === "missing-scene") {
        // the finding belongs where the link is written: the passage, or what it shows inside itself
        const from = steps(problem.path).at(-1);
        const finding = missing.find((item) => item.target === scene && item.passage === from) ?? missing.find((item) => item.target === scene && item.path.length === 0);
        if (finding && finding.path.length === 0) finding.path = steps(problem.path);
      } else if (problem.kind === "dead-end") {
        const broken = [...new Set(whole(scene).links.filter((link) => !passages.has(link.to)).map((link) => link.to))];
        const why = broken.length === 0 ? "it has no link out" : `its links lead only to passages that do not exist (${listOf(broken)})`;
        findings.push({ kind: "dead-end", passage: scene, line: lineOf(scene), broken, path: steps(problem.path), message: `Dead end at ${quote(scene)}: ${why}, and it is not tagged as an ending.` });
      } else if (problem.kind === "no-way-to-an-ending") {
        findings.push({ kind: "no-way-to-an-ending", passage: scene, line: lineOf(scene), path: steps(problem.path), message: `From ${quote(scene)} a player can only go round in circles: there are links, but none of them leads to an ending any more.` });
      } else if (problem.kind === "unreachable-scene" || problem.kind === "unreachable-ending") lost.add(scene);
    }
    for (const ending of report.endings) {
      const name = ending.scene.startsWith(ENDS) ? ending.scene.slice(ENDS.length) : ending.scene;
      if (name !== ANYWHERE) endings.push({ passage: name, path: steps(ending.path) });
    }
    reached = new Set(storyPassages.filter((name) => !lost.has(name)));
    for (const name of storyPassages) {
      if (reached.has(name)) continue;
      const from = [...(comesFrom.get(name) ?? [])].filter((source) => source !== ROOT && source !== name);
      const why = from.length === 0 ? "no link leads to it" : `the only links to it are in ${listOf(from)}, which no player can reach either`;
      const meant = missing.filter((item) => item.suggestion === name).map((item) => ({ target: item.target as string, passage: item.passage as string }));
      const misspelt = meant.map((item) => ` The link to ${quote(item.target)} in ${quote(item.passage)} looks meant for it.`).join("");
      const unless = notFollowed.length > 0 ? " That is, unless one of the links the check could not follow leads here." : "";
      findings.push({ kind: "unreachable", passage: name, line: lineOf(name), places: from, meant, path: [], message: `No player can reach ${quote(name)}: ${why}.${misspelt}${unless}` });
    }
    if (!storyPassages.some(isEnding)) findings.push({ kind: "no-endings", path: [], message: `No passage is tagged as an ending (${endingTags.join(" or ")}), so every passage without a way on counts as a dead end.` });
  }
  findings.push(...missing);

  // variables: read somewhere and set nowhere, or set somewhere and read nowhere
  const variablesChecked = checksVariables(format);
  const sets = new Map<string, string[]>();
  const reads = new Map<string, string[]>();
  const note = (map: Map<string, string[]>, variable: string, where: string) => {
    const list = map.get(variable) ?? map.set(variable, []).get(variable) as string[];
    if (!list.includes(where)) list.push(where);
  };
  if (variablesChecked) {
    for (const name of names.filter(read)) {
      const p = parts.get(name) as PassageParts;
      for (const variable of p.sets) note(sets, variable, name);
      for (const variable of p.reads) note(reads, variable, name);
    }
    if (format === "sugarcube") {
      const script = emptyParts();
      scriptVars(story.script, script);
      for (const variable of script.sets) note(sets, variable, "Story JavaScript");
      for (const variable of script.reads) note(reads, variable, "Story JavaScript");
    }
    for (const [variable, where] of reads) {
      if (sets.has(variable)) continue;
      const suggestion = closest(variable, sets.keys());
      findings.push({ kind: "read-never-set", variable, passage: where[0], line: lineOf(where[0]), places: where, suggestion, path: [], message: `${variable} is read in ${listOf(where)}, and nothing in the story sets it.${suggestion ? ` Did you mean ${suggestion}? That one is set.` : ""}` });
    }
    for (const [variable, where] of sets) {
      if (reads.has(variable)) continue;
      const suggestion = closest(variable, reads.keys());
      findings.push({ kind: "set-never-read", variable, passage: where[0], line: lineOf(where[0]), places: where, suggestion, path: [], message: `${variable} is set in ${listOf(where)}, and nothing in the story reads it.${suggestion ? ` Did you mean ${suggestion}? That one is read.` : ""}` });
    }
  }

  // a broken link comes before what it causes, such as a passage nobody can reach any more
  findings.sort((a, b) => KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind));
  const special = names.filter((name) => role.get(name) !== null).map((name) => ({ passage: name, role: role.get(name) as Role }));
  const report: TwineReport = {
    ok: findings.length === 0,
    story: story.name,
    from: story.from,
    format: { name: format, declared: options.format !== undefined || detected.declared, written: story.format, version: story.formatVersion },
    start: startOk ? story.start : null,
    passages: storyPassages.length,
    reached: reached === null ? null : reached.size,
    special,
    parts: pieces,
    endings,
    findings,
    notFollowed,
    variablesChecked,
    variables: new Set([...sets.keys(), ...reads.keys()]).size,
    text: "",
  };
  const version = detected.declared && options.format === undefined && story.formatVersion ? ` ${story.formatVersion}` : "";
  const lines = [
    `${story.name ? `Story ${quote(story.name)}` : "The story"}, read as ${FORMAT_NAMES[format]}${version} (${options.format ? "as asked" : detected.declared ? "as the file says" : "guessed from the markup"}).`,
    report.ok ? "No problems found." : `Found ${findings.length} problem${findings.length === 1 ? "" : "s"}.`,
    `Start: ${report.start === null ? "none" : quote(report.start)}. Story passages: ${report.passages}${report.reached === null ? "" : `, ${report.reached} of them reached from the start`}.`,
  ];
  if (special.length > 0) lines.push(`Used by the story format on its own: ${special.map((item) => item.passage).join(", ")}.`);
  if (pieces.length > 0) lines.push(`Only shown inside other passages: ${pieces.join(", ")}.`);
  lines.push(variablesChecked ? `Variables: ${report.variables}.` : "Variables were not checked: this check reads them in Harlowe, SugarCube and Chapbook.");
  for (const finding of findings) {
    lines.push(`${finding.kind}: ${finding.message}${finding.line ? ` (line ${finding.line})` : ""}`);
    if (finding.path.length > 0) lines.push(`  Path: ${finding.path.join(" > ")}`);
  }
  for (const ending of endings) lines.push(`Ending ${quote(ending.passage)}: ${ending.path.join(" > ")}`);
  for (const item of notFollowed) lines.push(`Not followed: ${item.markup} in ${quote(item.passage)} goes to a passage named while playing.`);
  report.text = lines.join("\n");
  return report;
}

/** Reads a file and checks every story in it. Throws with a plain message if it holds no story. */
export function checkTwineText(text: string, options: CheckOptions): TwineReport[] {
  return readTwine(text).map((story) => checkTwine(story, options));
}
Die Tests, die dieser Code besteht
import assert from "node:assert/strict";
import test from "node:test";
import { checkStoryGraph } from "../story-graph-check/code.ts";
import { DEFAULTS, type CheckOptions, type Finding, type TwineReport, checkTwine, checkTwineText, readPassage, readTwee, readTwine, readTwineHtml, storyFormat } from "./code.ts";

/* Every finding is planted in a small story and must be caught; a clean story must give none. The
   walk is the story-graph-check recipe's, as on the check page. */

const walk = checkStoryGraph;
const check = (text: string, options: Partial<CheckOptions> = {}): TwineReport => checkTwineText(text, { walk, ...options })[0];
const kinds = (report: TwineReport) => report.findings.map((f) => f.kind).sort();
const find = (report: TwineReport, kind: Finding["kind"], passage?: string) => report.findings.find((f) => f.kind === kind && (passage === undefined || f.passage === passage));

/** A Twee 3 story in a given format, from passages written as "Name [tags]" and their text. */
function twee(format: string, start: string, passages: Record<string, string>): string {
  const data = JSON.stringify({ ifid: "8A2E5D10-1C1B-4F55-9A0E-3C1F00000001", format, "format-version": "1.0.0", start });
  return [":: StoryTitle", "Test", "", ":: StoryData", data, "", ...Object.entries(passages).flatMap(([header, text]) => [`:: ${header}`, text, ""])].join("\n");
}

const CLEAN_HARLOWE = twee("Harlowe", "Gate", {
  Gate: "A guard blocks the gate.\n[[Work for a coin->Market]]\n[[Slip past the guard->Bridge]]",
  Market: "(set: $coins to it + 1)You earn a coin.\n[[Go to the bridge->Bridge]]",
  Bridge: "You have $coins coins.\n(link-goto: \"Pay the toll\", \"City\")\n[[Swim->River]]",
  River: "(if: $coins > 0)[You keep your coin dry.]\n[[City<-Climb out]]",
  "City [end]": "You made it.",
});

test("a story with no mistakes gives no findings, and the report says what was read", () => {
  const report = check(CLEAN_HARLOWE);
  assert.equal(report.ok, true, report.text);
  assert.deepEqual(report.findings, []);
  assert.equal(report.start, "Gate");
  assert.equal(report.passages, 5);
  assert.equal(report.reached, 5);
  assert.equal(report.format.name, "harlowe");
  assert.equal(report.format.declared, true);
  assert.equal(report.variables, 1);
  assert.deepEqual(report.endings, [{ passage: "City", path: ["Gate", "Bridge", "City"] }]);
  assert.match(report.text, /^Story "Test", read as Harlowe 1\.0\.0 \(as the file says\)\.\nNo problems found\./);
});

test("each planted mistake is caught and names its passage, with the path where a player gets there", () => {
  const report = check(
    twee("Harlowe", "Gate", {
      Gate: "[[Work for a coin->Market]]\n[[Slip past the guard->Bridge]]",
      Market: "(set: $coins to 1)\n[[Go to the bridge->Bridge]]",
      // the variable is misspelt, and the link to the city too
      Bridge: "(if: $coin is 1)[ [[Pay the toll->Cty]] ]\n[[Wait->Toll booth]]",
      // a dead end: no link out, and not tagged as an ending
      "Toll booth": "The booth is empty.",
      "City [end]": "You made it.",
      // nothing links here
      Vault: "Gold!\n[[Leave->Gate]]",
    }),
  );
  assert.equal(report.ok, false);
  assert.deepEqual(kinds(report), ["dead-end", "missing-passage", "read-never-set", "set-never-read", "unreachable", "unreachable"]);
  const missing = find(report, "missing-passage");
  assert.equal(missing?.passage, "Bridge");
  assert.equal(missing?.target, "Cty");
  assert.equal(missing?.suggestion, "City");
  assert.deepEqual(missing?.path, ["Gate", "Bridge"]);
  assert.equal(missing?.message, '"Bridge" links to "Cty" with [[Pay the toll->Cty]], and there is no passage of that name. Did you mean "City"?');
  const stuck = find(report, "dead-end");
  assert.equal(stuck?.passage, "Toll booth");
  assert.deepEqual(stuck?.path, ["Gate", "Bridge", "Toll booth"]);
  assert.equal(stuck?.message, 'Dead end at "Toll booth": it has no link out, and it is not tagged as an ending.');
  // the city is only reached through the broken link, and the vault through nothing
  assert.match(find(report, "unreachable", "Vault")?.message ?? "", /no link leads to it/);
  assert.ok(find(report, "unreachable", "City"));
  const unset = find(report, "read-never-set");
  assert.equal(unset?.variable, "$coin");
  assert.equal(unset?.suggestion, "$coins");
  assert.deepEqual(unset?.places, ["Bridge"]);
  assert.equal(find(report, "set-never-read")?.variable, "$coins");
  // the line in the Twee file, to find the passage
  assert.equal(find(report, "dead-end")?.line, 19);
});

test("a dead end whose only link is broken says so", () => {
  const report = check(twee("Harlowe", "A", { A: "[[B]]", B: "[[Onward->C]]", "D [ending]": "" }));
  const stuck = find(report, "dead-end", "B");
  assert.equal(stuck?.message, 'Dead end at "B": its links lead only to passages that do not exist ("C"), and it is not tagged as an ending.');
  assert.deepEqual(stuck?.path, ["A", "B"]);
});

test("a loop with no way out to an ending is caught", () => {
  const report = check(twee("Harlowe", "Hall", { Hall: "[[Left]]\n[[Right]]", Left: "[[Hall]]", Right: "[[Maze]]", Maze: "[[Right]]", "Exit [end]": "", Door: "[[Exit]]" }));
  const circle = find(report, "no-way-to-an-ending");
  assert.equal(circle?.passage, "Hall");
  assert.match(circle?.message ?? "", /only go round in circles/);
  assert.match(find(report, "unreachable", "Door")?.message ?? "", /no link leads to it/);
  assert.match(find(report, "unreachable", "Exit")?.message ?? "", /the only links to it are in "Door", which no player can reach either/);
});

test("the start: from StoryData, else the passage named Start, else a finding", () => {
  assert.equal(readTwee(":: Start\nHello\n\n:: Next\n").start, "Start");
  assert.equal(readTwee(":: Start\nHello\n\n:: Next\n").startFrom, "named-start");
  const none = check(":: Begin\n[[End]]\n\n:: End [end]\n");
  assert.equal(find(none, "no-start")?.message, 'The story names no start passage: StoryData has no "start", and no passage is called "Start".');
  assert.equal(none.reached, null);
  const gone = check(twee("Harlowe", "Opening", { Begin: "[[End]]", "End [end]": "" }));
  assert.equal(find(gone, "start-missing")?.message, 'The story starts at "Opening", and there is no passage of that name.');
});

test("two passages of the same name are caught, with both lines", () => {
  const report = check(":: Start\n[[Cave]]\n\n:: Cave [end]\nDark.\n\n:: Cave\nLight.\n");
  const twice = find(report, "duplicate-passage");
  assert.equal(twice?.passage, "Cave");
  assert.match(twice?.message ?? "", /\(lines 4 and 7\)/);
});

test("StoryData that is not JSON is reported, and the rest is still read", () => {
  const report = check(':: StoryData\n{"format": "Harlowe", start: Gate}\n\n:: Start\n[[End]]\n\n:: End [end]\n');
  assert.match(find(report, "file-problem")?.message ?? "", /^StoryData \(line 1\) is not valid JSON/);
  assert.equal(report.start, "Start");
});

test("links are read as Twine's story map reads them", () => {
  const parts = readPassage("[[A]] [[go|B]] [[go->C]] [[D<-go]] [[a->b->E]] [[F<-x<-y]] [[x|y|G]] [[https://example.com]] [[t|H][$x to 1]]", "unknown");
  assert.deepEqual(parts.links.map((l) => l.to), ["A", "B", "C", "D", "E", "F", "G", "H"]);
  assert.deepEqual(parts.links.map((l) => l.text), ["A", "go", "go", "go", "a->b", "x<-y", "x|y", "t"]);
});

test("a link name with spaces around it is caught, and the passage it meant is named", () => {
  const report = check(twee("Harlowe", "A", { A: "[[Go-> B]]", "B [end]": "" }));
  assert.equal(find(report, "missing-passage")?.suggestion, "B");
  assert.match(find(report, "missing-passage")?.message ?? "", /spaces around the name/);
});

test("Twee headers: tags, metadata, escaped brackets, and content lines that start with ::", () => {
  const story = readTwee(':: A \\[draft\\] name [one two] {"position":"100,200","size":"100,100"}\nText\n\\:: not a header\n\n\n:: B\n');
  assert.deepEqual(story.passages.map((p) => [p.name, p.tags, p.text, p.line]), [
    // a content line written as \:: is not a header, and is kept as written, as Extwee keeps it
    ["A [draft] name", ["one", "two"], "Text\n\\:: not a header", 1],
    ["B", [], "", 6],
  ]);
});

/** The HTML Twine 2 writes: passage text and attributes escaped, the start by passage number. */
function html(stories: { name: string; format: string; start: number; script?: string; passages: [string, string, string][] }[], wrap = (s: string) => s) {
  const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
  return wrap(
    stories
      .map(
        (s) =>
          `<tw-storydata name="${esc(s.name)}" startnode="${s.start}" creator="Twine" creator-version="2.10.0" format="${s.format}" format-version="2.37.3" ifid="0E1B7A30-0000-4000-8000-00000000000${s.start}" options="" tags="" zoom="1" hidden>` +
          `<style role="stylesheet" id="twine-user-stylesheet" type="text/twine-css"></style>` +
          `<script role="script" id="twine-user-script" type="text/twine-javascript">${esc(s.script ?? "")}</script>` +
          s.passages.map(([name, tags, text], i) => `<tw-passagedata pid="${i + 1}" name="${esc(name)}" tags="${esc(tags)}" position="${100 * i},100" size="100,100">${esc(text)}</tw-passagedata>`).join("") +
          `</tw-storydata>`,
      )
      .join("\n"),
  );
}

test("a published Twine 2 story is read, even when the story format's code mentions <tw-storydata", () => {
  const page = (body: string) => `<!DOCTYPE html><html><head><title>Q</title><script>var x = "<tw-storydata"; document.querySelector("tw-storydata");</script></head><body>${body}</body></html>`;
  const file = html([{ name: "Rock & Roll", format: "SugarCube", start: 2, passages: [["Intro", "", "[[Begin]]"], ["Begin", "", 'Say "hi" & <<link "Go on" "Road">><</link>>'], ["Road", "end", "Done."]] }], page);
  const [story] = readTwine(file);
  assert.equal(story.from, "html");
  assert.equal(story.name, "Rock & Roll");
  assert.equal(story.start, "Begin");
  assert.equal(story.startFrom, "start-node");
  assert.equal(story.passages[1].text, 'Say "hi" & <<link "Go on" "Road">><</link>>');
  const report = checkTwine(story, { walk });
  assert.deepEqual(kinds(report), ["unreachable"]);
  assert.equal(find(report, "unreachable")?.passage, "Intro");
});

test("a library archive holds many stories, and each is checked", () => {
  const file = html([
    { name: "One", format: "Harlowe", start: 1, passages: [["A", "", "[[B]]"], ["B", "end", ""]] },
    { name: "Two", format: "Chapbook", start: 1, passages: [["A", "", "{link to: 'Gone'}"]] },
  ]);
  const reports = checkTwineText(file, { walk });
  assert.deepEqual(reports.map((r) => [r.story, r.ok, r.format.name]), [["One", true, "harlowe"], ["Two", false, "chapbook"]]);
  assert.equal(find(reports[1], "missing-passage")?.markup, "{link to: 'Gone'}");
});

test("a start node that names no passage is reported", () => {
  const file = html([{ name: "X", format: "Harlowe", start: 9, passages: [["A", "", ""]] }]);
  const report = checkTwineText(file, { walk })[0];
  assert.match(find(report, "file-problem")?.message ?? "", /passage number 9/);
  assert.ok(find(report, "no-start"));
});

test("files that are not Twee or Twine 2 say what they are", () => {
  assert.throws(() => readTwine('<html><div id="storeArea"><div tiddler="Start">x</div></div></html>'), /Twine 1 file/);
  assert.throws(() => readTwine("Once upon a time."), /No passages found/);
  assert.deepEqual(readTwineHtml("<p>nothing</p>"), []);
});

/* Harlowe */

test("Harlowe: every macro that goes to or shows a passage is followed", () => {
  const parts = readPassage(
    '(goto: "A")(go-to: \'B\')(link-goto: "C")(link-goto: "text", "D")(link-reveal-goto: "t", "E")[x](click-goto: ?h, "F")(mouseover-goto: ?h, "G")(redirect: "H")(display: "I")(undo:)(link-undo: "Back")(restart:)(goto: $next)(link-goto: "x", "a" + $b)',
    "harlowe",
  );
  assert.deepEqual(parts.links.map((l) => l.to), ["A", "B", "C", "D", "E", "F", "G", "H"]);
  assert.deepEqual(parts.links.map((l) => l.text), ["", "", "C", "text", "t", "", "", ""]);
  assert.deepEqual(parts.includes.map((l) => l.to), ["I"]);
  assert.deepEqual(parts.back, ["(undo:)", '(link-undo: "Back")']);
  assert.deepEqual(parts.restart, ["(restart:)"]);
  assert.deepEqual(parts.unknown, ["(goto: $next)", '(link-goto: "x", "a" + $b)']);
});

test("Harlowe: what sets a variable and what only reads it", () => {
  const parts = readPassage(
    "(set: $a to 1, $b to $c + 1)(set: $d to it + 1)(set: num-type $e to 0)(set: $f's name to \"x\")(put: $g into $h)(move: $i's 1st into $j)(unpack: (a: 1, 2) into (a: $k, $l))(input-box: bind $m)(cycling-link: 2bind $n, \"a\", \"b\")(print: \"$notvar\")(if: $o is \"to\")[$p] costs $5 <!-- $q -->",
    "harlowe",
  );
  assert.deepEqual([...new Set(parts.sets)].sort(), ["$a", "$b", "$d", "$e", "$h", "$j", "$k", "$l", "$m", "$n"]);
  assert.deepEqual([...new Set(parts.reads)].sort(), ["$c", "$d", "$f", "$g", "$i", "$n", "$o", "$p"]);
});

test("Harlowe: a header or footer's links count for every passage, and startup only sets variables", () => {
  const report = check(twee("Harlowe", "A", { "Init [startup]": "(set: $hp to 3)", "Bar [footer]": "HP: $hp [[Map]]", A: "Hello", Map: "[[A]]\n[[Home]]", "Home [end]": "" }));
  assert.deepEqual(report.findings, [], report.text);
  assert.deepEqual(report.special, [{ passage: "Init", role: "before" }, { passage: "Bar", role: "every" }]);
  const lost = check(twee("Harlowe", "A", { "Bar [header]": "(goto: \"Missing\")", A: "[[End]]", "End [end]": "" }));
  assert.equal(find(lost, "missing-passage")?.passage, "Bar");
});

test("Harlowe: a passage only shown with (display:) is part of the one that shows it", () => {
  const report = check(twee("Harlowe", "A", { A: '(display: "Exits")', Exits: "[[North]]", "North [end]": "" }));
  assert.deepEqual(report.findings, [], report.text);
  assert.deepEqual(report.parts, ["Exits"]);
});

test("Harlowe: a way back keeps a passage from being a dead end, and a link named by a variable too", () => {
  const report = check(twee("Harlowe", "A", { A: "(set: $exit to \"End\")[[Shelf]]\n[[Out]]", Shelf: "(link-undo: \"Put it back\")", Out: "(goto: $exit)", "End [end]": "" }));
  assert.deepEqual(kinds(report), ["unreachable"]);
  assert.match(find(report, "unreachable", "End")?.message ?? "", /unless one of the links the check could not follow leads here/);
  assert.deepEqual(report.notFollowed, [{ passage: "Out", markup: "(goto: $exit)" }]);
});

test("Harlowe: (restart:) leads back to the start", () => {
  const report = check(twee("Harlowe", "A", { A: "[[B]]", B: "(link: \"Again\")[(restart:)]", "C [end]": "", D: "[[C]]" }));
  assert.ok(!find(report, "dead-end"), report.text);
  // B goes round to A and back, and never reaches an ending
  assert.equal(find(report, "no-way-to-an-ending")?.passage, "A");
});

/* SugarCube */

test("SugarCube: every macro that goes to or shows a passage is followed", () => {
  const parts = readPassage(
    '<<link "Go on" "A">><</link>><<link [[t|B]]>><</link>><<button "Push" \'C\'>><</button>><<goto "D">><<goto [[E]]>><<include "F">><<include [[G]]>><<display "H">><<actions "I" [[J]]>><<choice "K" "take it">><<back>><<return "Leave">><<link "Back" `previous()`>><</link>>[[Back|previous()]]<a data-passage="L">x</a><<goto $where>><<link "x">><<goto "M">><</link>>',
    "sugarcube",
  );
  assert.deepEqual(parts.links.map((l) => l.to).sort(), ["A", "B", "C", "D", "E", "I", "J", "K", "L", "M"]);
  assert.deepEqual(parts.includes.map((l) => l.to), ["F", "G", "H"]);
  assert.deepEqual(parts.back, ["[[Back|previous()]]", "<<back>>", '<<return "Leave">>', '<<link "Back" `previous()`>>']);
  assert.deepEqual(parts.unknown, ["<<goto $where>>"]);
});

test("SugarCube: what sets a variable and what only reads it", () => {
  const parts = readPassage(
    '<<set $a to 1, $b = $c>><<set $d += 1>><<set $e++>><<set $f.hp to 2>><<set $g[0] to 1>><<run $h = 5>><<textbox "$i" "Ann">><<checkbox "$j" false true>><<for _k, $l range $m>><</for>><<unset $n>>[[Go|X][$o to $p]]<<if $q is "$r">>$s.name<</if>> $$t /* $u */ /% $v %/ <<script>>State.variables.w = 1; variables().x2;<</script>><<print $y>>',
    "sugarcube",
  );
  assert.deepEqual([...new Set(parts.sets)].sort(), ["$a", "$b", "$d", "$e", "$h", "$i", "$j", "$l", "$o", "$w"]);
  assert.deepEqual([...new Set(parts.reads)].sort(), ["$c", "$d", "$e", "$f", "$g", "$m", "$p", "$q", "$s", "$x2", "$y"]);
});

test("SugarCube: <<back>> and <<return>> with a passage go there, and so does a text box on Enter", () => {
  const parts = readPassage('<<back "Leave" "Camp">><<return "Home" `previous()`>><<textbox "$name" "Ann" "Greeting">><<numberbox "$age" 9 autofocus>>', "sugarcube");
  assert.deepEqual(parts.links.map((l) => [l.to, l.text]), [["Camp", "Leave"], ["Greeting", ""]]);
  assert.deepEqual(parts.back, ['<<return "Home" `previous()`>>']);
  assert.deepEqual([...new Set(parts.sets)].sort(), ["$age", "$name"]);
});

test("SugarCube: a link's setter may hold several assignments, split by ; or ,", () => {
  const parts = readPassage("[[Buy|Shop][$gold -= 5; $sword to true, $buys++]] <<set $box.count++>>", "sugarcube");
  assert.deepEqual([...new Set(parts.sets)].sort(), ["$buys", "$gold", "$sword"]);
  assert.deepEqual([...new Set(parts.reads)].sort(), ["$box", "$buys", "$gold"]);
});

test("SugarCube: StoryInit sets, the StoryMenu leads somewhere, a footer link counts everywhere", () => {
  const report = check(
    twee("SugarCube", "Camp", {
      StoryInit: "<<set $food to 3>>",
      StoryMenu: "[[Backpack]]",
      PassageFooter: "<<if $food lt 1>>[[Starve]]<</if>>",
      Camp: "Food: $food",
      Backpack: "<<return>>",
      "Starve [end]": "",
    }),
  );
  assert.deepEqual(report.findings, [], report.text);
  assert.deepEqual(report.special.map((s) => [s.passage, s.role]), [["StoryInit", "before"], ["StoryMenu", "beside"], ["PassageFooter", "every"]]);
});

test("SugarCube: a StoryMenu link is not a way on, so a passage with nothing else is still a dead end", () => {
  const report = check(twee("SugarCube", "Camp", { StoryMenu: "[[Backpack]]", Camp: "Nothing here.", Backpack: "<<return>>", "End [end]": "" }));
  assert.equal(find(report, "dead-end")?.passage, "Camp");
  assert.ok(!find(report, "unreachable", "Backpack"));
});

test("SugarCube: a widget's links count where the widget is used, and its variables count", () => {
  const report = check(
    twee("SugarCube", "A", {
      "Widgets [widget]": '<<widget "exits">>[[North]] <<set $moves to $moves + 1>><</widget>>',
      StoryInit: "<<set $moves to 0>>",
      A: "<<exits>>",
      "North [end]": "",
    }),
  );
  assert.deepEqual(report.findings, [], report.text);
});

test("SugarCube: variables set in the story JavaScript count", () => {
  const file = html([{ name: "S", format: "SugarCube", start: 1, script: "State.variables.gold = 5;", passages: [["A", "", "Gold: $gold [[B]]"], ["B", "end", ""]] }]);
  assert.deepEqual(checkTwineText(file, { walk })[0].findings, []);
});

/* Chapbook */

test("Chapbook: inserts that go to or show a passage are followed", () => {
  const parts = readPassage("{link to: 'A', label: 'Go'} {link to: \"B\"} {back link} {back link, label: 'Return'} {restart link} {embed passage: 'C'} {embed passage named: 'D'} {reveal link: 'Look', passage: 'E'} {link to: next} [[F]]", "chapbook");
  assert.deepEqual(parts.links.map((l) => [l.to, l.text]), [["F", "F"], ["A", "Go"], ["B", ""]]);
  assert.deepEqual(parts.includes.map((l) => l.to), ["C", "D", "E"]);
  assert.equal(parts.back.length, 2);
  assert.deepEqual(parts.restart, ["{restart link}"]);
  assert.deepEqual(parts.unknown, ["{link to: next}"]);
});

test("Chapbook: the vars section sets, inserts and conditions read", () => {
  const parts = readPassage(
    "hp: 10\nmood (hp < 5): 'grim'\nplayer.name: 'Ann'\nconfig.style.page.font: 'serif'\n--\nYou have {hp} and {player.name}. {passage.name}\n[if gold > 1; align center]\nRich.\n[else]\nPoor.\n[note]\n{secret}\n[CSS]\n.page { color: red }\n[continue]\n{text input for: 'nick'} {cycling link for 'tone', choices: ['a', 'b']} {dropdown menu for: 'size', choices: ['s']} {link to: 'X', label: 'Go'}\n[JavaScript]\nengine.state.set('lamp', true); engine.state.get('oil');\n[continue]\nEnd.",
    "chapbook",
  );
  assert.deepEqual([...new Set(parts.sets)].sort(), ["hp", "lamp", "mood", "nick", "player", "size", "tone"]);
  assert.deepEqual([...new Set(parts.reads)].sort(), ["gold", "hp", "oil", "player"]);
});

test("Chapbook: a misspelt variable and an unused one are caught", () => {
  const report = check(twee("Chapbook", "A", { A: "torch: true\n--\n[if torhc]\nYou see.\n[continue]\n[[B]]", "B [end]": "" }));
  assert.deepEqual(kinds(report), ["read-never-set", "set-never-read"]);
  assert.equal(find(report, "read-never-set")?.suggestion, "torch");
});

/* endings, formats and the rest */

test("endings: the tags end and ending in any case, and passages ticked on the page", () => {
  const story = twee("Harlowe", "A", { A: "[[B]]\n[[C]]\n[[D]]", "B [End]": "", "C [ENDING]": "", D: "The last page." });
  assert.equal(find(check(story), "dead-end")?.passage, "D");
  assert.deepEqual(check(story, { endings: ["D"] }).findings, []);
  assert.equal(DEFAULTS.endingTags, "end ending");
  assert.ok(find(check(story, { endingTags: "fin" }), "no-endings"));
});

test("endings: an ending with links on still leads on", () => {
  const report = check(twee("Harlowe", "A", { A: "[[Chapter end]]", "Chapter end [end]": "[[Chapter two]]", "Chapter two": "[[Final]]", "Final [end]": "" }));
  assert.deepEqual(report.findings, [], report.text);
  assert.deepEqual(report.endings.map((e) => e.passage).sort(), ["Chapter end", "Final"]);
});

test("no ending at all is said once, besides the dead ends it causes", () => {
  const report = check(twee("Harlowe", "A", { A: "[[B]]", B: "The end." }));
  assert.deepEqual(kinds(report), ["dead-end", "no-endings"]);
});

test("the story format: from the file, or guessed from the markup, or not known", () => {
  const plain = (text: string) => readTwee(`:: Start\n${text}\n`);
  assert.deepEqual(storyFormat(plain("(set: $a to 1)")), { format: "harlowe", declared: false });
  assert.deepEqual(storyFormat(plain("<<set $a to 1>>")), { format: "sugarcube", declared: false });
  assert.deepEqual(storyFormat(plain("a: 1\n--\n{a}")), { format: "chapbook", declared: false });
  assert.deepEqual(storyFormat(plain("[[Go]]")), { format: "unknown", declared: false });
  const unknown = check(":: Start\n$a <<set $b to 1>> (set: $c to 1) [[Go]]\n\n:: Go [end]\n", { format: "unknown" });
  assert.equal(unknown.variablesChecked, false);
  assert.deepEqual(unknown.findings, []);
  assert.match(unknown.text, /Variables were not checked/);
  assert.deepEqual(storyFormat(readTwee(twee("Paperthin", "A", { A: "" }))), { format: "unknown", declared: true });
});

test("Snowman: links are followed, variables are not checked", () => {
  const report = check(twee("Snowman", "A", { A: "<% s.x = 1 %>[[B]] <a data-passage=\"C\">c</a>", "B [end]": "", "C [end]": "" }));
  assert.deepEqual(report.findings, []);
  assert.equal(report.variablesChecked, false);
});

test("a link inside a comment does not count", () => {
  const harlowe = check(twee("Harlowe", "A", { A: "<!-- [[Old]] -->[[B]]", "B [end]": "" }));
  assert.deepEqual(harlowe.findings, []);
  const sugar = check(twee("SugarCube", "A", { A: "/* [[Old]] */ /% [[Older]] %/ [[B]]", "B [end]": "" }));
  assert.deepEqual(sugar.findings, []);
});

test("each finding carries what the check page needs to say it in another language", () => {
  const report = check(':: StoryData\n{"format": "Harlowe", "start": "A"}\n\n:: A\n[[Go->Cav]]\n[[Hut]]\n(display: "Gone")\n\n:: Hut\n[[Nowhere]]\n\n:: Cave [end]\n\n:: Cave\n');
  const link = report.findings.find((f) => f.kind === "missing-passage" && f.target === "Cav");
  assert.deepEqual([link?.via, link?.suggestion, link?.spaces], ["link", "Cave", false]);
  assert.equal(report.findings.find((f) => f.target === "Gone")?.via, "include");
  assert.deepEqual(find(report, "dead-end", "Hut")?.broken, ["Nowhere"]);
  assert.deepEqual(find(report, "unreachable", "Cave")?.meant, [{ target: "Cav", passage: "A" }]);
  assert.deepEqual(find(report, "duplicate-passage")?.lines, [12, 14]);
  const bad = check(':: StoryData\n{"start": }\n\n:: Start [end]\n');
  assert.deepEqual([find(bad, "file-problem")?.problem, find(bad, "file-problem")?.line], ["story-data", 1]);
  assert.throws(() => readTwine("plain words"), (error: Error & { code?: string }) => error.code === "no-passages");
});

test("the report in words lists every finding with its line and path", () => {
  const report = check(twee("Harlowe", "A", { A: "[[B]]", B: "", "C [end]": "" }));
  assert.match(report.text, /^dead-end: Dead end at "B": it has no link out, and it is not tagged as an ending\. \(line \d+\)\n {2}Path: A > B$/m);
  assert.match(report.text, /^unreachable: No player can reach "C": no link leads to it\./m);
});

Häufige Fragen

wie finde ich sackgassen in meiner twine geschichte

Gib deinen Enden das Tag end oder ending und lass den Check laufen. Jede Passage, die ein Spieler erreicht, die keinen Link nach draußen hat und nicht als Ende markiert ist, steht in der Liste, mit den Passagen, die vom Start dorthin führen.

wie finde ich kaputte links in twine

Die Story-Karte von Twine zeichnet einen kaputten Link in doppelten eckigen Klammern als rote Linie. Dieser Check liest auch die Links und Einbindungen aus den Makros von Harlowe, SugarCube und Chapbook und nennt die Passage, in der jeder kaputte Link steht, dazu einen ähnlichen Passagennamen, der gemeint sein könnte.

wie finde ich twine variablen die nie gesetzt werden

Der Check nennt jede Variable, die eine Passage liest und keine Passage setzt, meist ein Tippfehler, und dazu die Variable, die vermutlich gemeint war. Er nennt auch Variablen, die gesetzt und nie gelesen werden.

War diese Seite hilfreich?

Ein Klick, ohne Konto. So sehen wir, welche Seiten helfen.

Nächster Schritt

Anleitung

Prüf deine Twine-Geschichte auf Sackgassen und kaputte Links

Füg deine Twine-Geschichte ein oder öffne ihre Datei, und ein Check in deinem Browser nennt kaputte Links, unerreichbare Passagen, Sackgassen und vertippte Variablen.