@rohal12/twee-ts 1.15.2 → 1.15.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5348,6 +5348,1101 @@ function storyToJSON(story) {
5348
5348
  obj.passages = storyPassages;
5349
5349
  return JSON.stringify(obj, null, 2);
5350
5350
  }
5351
+ const SINGLE_ESCAPES = /* @__PURE__ */ new Map([
5352
+ ["b", "\b"],
5353
+ ["f", "\f"],
5354
+ ["n", "\n"],
5355
+ ["r", "\r"],
5356
+ ["t", " "],
5357
+ ["v", "\v"]
5358
+ ]);
5359
+ const HEX_RE = /^[0-9A-Fa-f]+$/;
5360
+ const DIGIT_RE = /^[0-9]$/;
5361
+ const LINE_TERMINATORS = "\n\r\u2028\u2029";
5362
+ /**
5363
+ * The value of a quoted JavaScript string literal (quotes included), as strict-mode JavaScript
5364
+ * evaluates it: `\"`, `\'`, `\\`, `\n`, `\xHH`, `\uHHHH`, `\u{H…}`, line continuations, and a
5365
+ * backslash before any other character gives that character. Returns `undefined` for what
5366
+ * strict mode rejects, such as `\1` or a raw carriage return.
5367
+ */
5368
+ function evalStringLiteral(literal) {
5369
+ const quote = literal[0];
5370
+ const last = literal.length - 1;
5371
+ if (quote !== "\"" && quote !== "'" || last < 1 || literal[last] !== quote) return;
5372
+ return cookEscapes(literal.slice(1, last), quote);
5373
+ }
5374
+ /**
5375
+ * Decodes the body of a string literal, given its quote, or a piece of a template literal
5376
+ * (`quote` undefined), as strict-mode JavaScript does. A string may not hold its own quote or a
5377
+ * raw line feed or carriage return; a template piece may, and turns `\r\n` and `\r` into `\n`.
5378
+ */
5379
+ function cookEscapes(body, quote) {
5380
+ let value = "";
5381
+ let i = 0;
5382
+ while (i < body.length) {
5383
+ const ch = body.charAt(i);
5384
+ if (ch !== "\\") {
5385
+ if (quote !== void 0 && (ch === quote || ch === "\n" || ch === "\r")) return;
5386
+ if (ch === "\r") {
5387
+ value += "\n";
5388
+ i += body.charAt(i + 1) === "\n" ? 2 : 1;
5389
+ } else {
5390
+ value += ch;
5391
+ i += 1;
5392
+ }
5393
+ continue;
5394
+ }
5395
+ if (i + 1 >= body.length) return;
5396
+ const escaped = body.charAt(i + 1);
5397
+ i += 2;
5398
+ const single = SINGLE_ESCAPES.get(escaped);
5399
+ if (single !== void 0) {
5400
+ value += single;
5401
+ continue;
5402
+ }
5403
+ switch (escaped) {
5404
+ case "0":
5405
+ if (DIGIT_RE.test(body.charAt(i))) return;
5406
+ value += "\0";
5407
+ break;
5408
+ case "1":
5409
+ case "2":
5410
+ case "3":
5411
+ case "4":
5412
+ case "5":
5413
+ case "6":
5414
+ case "7":
5415
+ case "8":
5416
+ case "9": return;
5417
+ case "x": {
5418
+ const hex = body.slice(i, i + 2);
5419
+ if (hex.length !== 2 || !HEX_RE.test(hex)) return;
5420
+ value += String.fromCharCode(parseInt(hex, 16));
5421
+ i += 2;
5422
+ break;
5423
+ }
5424
+ case "u": {
5425
+ const unicode = readUnicodeEscape(body, i);
5426
+ if (unicode === void 0) return;
5427
+ value += unicode.char;
5428
+ i = unicode.end;
5429
+ break;
5430
+ }
5431
+ case "\r":
5432
+ if (body[i] === "\n") i += 1;
5433
+ break;
5434
+ case "\n":
5435
+ case "\u2028":
5436
+ case "\u2029": break;
5437
+ default: value += escaped;
5438
+ }
5439
+ }
5440
+ return value;
5441
+ }
5442
+ /** Reads the part of `\uHHHH` or `\u{H…}` after the `u`. */
5443
+ function readUnicodeEscape(body, from) {
5444
+ if (body[from] === "{") {
5445
+ const close = body.indexOf("}", from + 1);
5446
+ if (close === -1) return;
5447
+ const hex = body.slice(from + 1, close);
5448
+ if (!HEX_RE.test(hex)) return;
5449
+ const codePoint = parseInt(hex, 16);
5450
+ return codePoint > 1114111 ? void 0 : {
5451
+ char: String.fromCodePoint(codePoint),
5452
+ end: close + 1
5453
+ };
5454
+ }
5455
+ const hex = body.slice(from, from + 4);
5456
+ if (hex.length !== 4 || !HEX_RE.test(hex)) return;
5457
+ return {
5458
+ char: String.fromCharCode(parseInt(hex, 16)),
5459
+ end: from + 4
5460
+ };
5461
+ }
5462
+ const REGEX_KEYWORDS = /* @__PURE__ */ new Set([
5463
+ "await",
5464
+ "case",
5465
+ "delete",
5466
+ "do",
5467
+ "else",
5468
+ "in",
5469
+ "instanceof",
5470
+ "new",
5471
+ "of",
5472
+ "return",
5473
+ "throw",
5474
+ "typeof",
5475
+ "void",
5476
+ "yield"
5477
+ ]);
5478
+ const WORD_RE = /[$\p{ID_Continue}\u200c\u200d]+/uy;
5479
+ const WHITESPACE_RE = /\s/;
5480
+ const LINE_TERMINATOR_RE$1 = /[\n\r\u2028\u2029]/g;
5481
+ /**
5482
+ * The values of the string and template literals in JavaScript source. A template literal's
5483
+ * value keeps its text and has `SUBSTITUTION` where each `${…}` was; the strings inside a
5484
+ * substitution are values of their own. Comments and regular expression literals are skipped;
5485
+ * whether a `/` starts a regular expression is judged from the token before it. Malformed
5486
+ * source is read on as far as it can be.
5487
+ */
5488
+ function javaScriptStrings(source) {
5489
+ const strings = [];
5490
+ const frames = [{
5491
+ kind: "code",
5492
+ braces: 0
5493
+ }];
5494
+ let regexAllowed = true;
5495
+ let afterDot = false;
5496
+ const failedUntil = /* @__PURE__ */ new Map();
5497
+ let i = 0;
5498
+ while (i < source.length) {
5499
+ const frame = frames[frames.length - 1];
5500
+ if (frame === void 0) break;
5501
+ const ch = source.charAt(i);
5502
+ const next = source.charAt(i + 1);
5503
+ if (frame.kind === "template") {
5504
+ if (ch === "`" || ch === "$" && next === "{") {
5505
+ const piece = cookEscapes(source.slice(frame.pieceStart, i), void 0);
5506
+ const value = frame.value + (piece ?? "");
5507
+ const valid = frame.valid && piece !== void 0;
5508
+ frames.pop();
5509
+ if (ch === "`") {
5510
+ if (valid) strings.push(value);
5511
+ i += 1;
5512
+ regexAllowed = false;
5513
+ afterDot = false;
5514
+ } else {
5515
+ frames.push({
5516
+ kind: "template",
5517
+ value: value + "﷐",
5518
+ pieceStart: -1,
5519
+ valid
5520
+ });
5521
+ frames.push({
5522
+ kind: "code",
5523
+ braces: 0
5524
+ });
5525
+ i += 2;
5526
+ regexAllowed = true;
5527
+ afterDot = false;
5528
+ }
5529
+ } else i += ch === "\\" ? 2 : 1;
5530
+ continue;
5531
+ }
5532
+ if (ch === "/" && next === "/") {
5533
+ const lineEnd = searchFrom$1(LINE_TERMINATOR_RE$1, source, i + 2);
5534
+ i = lineEnd === -1 ? source.length : lineEnd;
5535
+ continue;
5536
+ }
5537
+ if (ch === "/" && next === "*") {
5538
+ const close = source.indexOf("*/", i + 2);
5539
+ i = close === -1 ? source.length : close + 2;
5540
+ continue;
5541
+ }
5542
+ if (ch === "/" && regexAllowed && i >= (failedUntil.get("/") ?? 0)) {
5543
+ const end = endOfRegularExpression(source, i);
5544
+ if (end.end !== void 0) {
5545
+ i = end.end;
5546
+ regexAllowed = false;
5547
+ afterDot = false;
5548
+ continue;
5549
+ }
5550
+ failedUntil.set("/", end.stop);
5551
+ }
5552
+ if ((ch === "\"" || ch === "'") && i >= (failedUntil.get(ch) ?? 0)) {
5553
+ const end = endOfJavaScriptString(source, i);
5554
+ if (end.end !== void 0) {
5555
+ const value = evalStringLiteral(source.slice(i, end.end));
5556
+ if (value !== void 0) strings.push(value);
5557
+ i = end.end;
5558
+ regexAllowed = false;
5559
+ afterDot = false;
5560
+ continue;
5561
+ }
5562
+ failedUntil.set(ch, end.stop);
5563
+ }
5564
+ if (ch === "`") {
5565
+ frames.push({
5566
+ kind: "template",
5567
+ value: "",
5568
+ pieceStart: i + 1,
5569
+ valid: true
5570
+ });
5571
+ i += 1;
5572
+ continue;
5573
+ }
5574
+ const word = wordAt(source, i);
5575
+ if (word !== null) {
5576
+ regexAllowed = !afterDot && REGEX_KEYWORDS.has(word[0]);
5577
+ afterDot = false;
5578
+ i += word[0].length;
5579
+ continue;
5580
+ }
5581
+ if ((ch === "+" || ch === "-") && next === ch) {
5582
+ regexAllowed = false;
5583
+ afterDot = false;
5584
+ i += 2;
5585
+ continue;
5586
+ }
5587
+ if (frame.kind === "code" && frames.length > 1 && (ch === "{" || ch === "}")) {
5588
+ if (ch === "{") frames[frames.length - 1] = {
5589
+ kind: "code",
5590
+ braces: frame.braces + 1
5591
+ };
5592
+ else if (frame.braces > 0) frames[frames.length - 1] = {
5593
+ kind: "code",
5594
+ braces: frame.braces - 1
5595
+ };
5596
+ else {
5597
+ frames.pop();
5598
+ const template = frames.pop();
5599
+ if (template?.kind === "template") frames.push({
5600
+ ...template,
5601
+ pieceStart: i + 1
5602
+ });
5603
+ i += 1;
5604
+ continue;
5605
+ }
5606
+ }
5607
+ if (!WHITESPACE_RE.test(ch)) {
5608
+ regexAllowed = !")]}".includes(ch);
5609
+ afterDot = ch === ".";
5610
+ }
5611
+ i += 1;
5612
+ }
5613
+ return strings;
5614
+ }
5615
+ /** The name, keyword or number that starts at `pos`, if one does. */
5616
+ function wordAt(source, pos) {
5617
+ const code = source.charCodeAt(pos);
5618
+ if (code < 128 && !(code >= 48 && code <= 57 || (code | 32) >= 97 && (code | 32) <= 122 || code === 95 || code === 36)) return null;
5619
+ WORD_RE.lastIndex = pos;
5620
+ return WORD_RE.exec(source);
5621
+ }
5622
+ /** Index of the first match of a global `re` at or after `from`, or -1. */
5623
+ function searchFrom$1(re, text, from) {
5624
+ re.lastIndex = from;
5625
+ const m = re.exec(text);
5626
+ return m === null ? -1 : m.index;
5627
+ }
5628
+ /**
5629
+ * Where a string literal that opens at `pos` ends, or, if it doesn't close on its line, where
5630
+ * the scan stopped. A string with the same quote that starts before that stop, inside this one,
5631
+ * doesn't close either.
5632
+ */
5633
+ function endOfJavaScriptString(source, pos) {
5634
+ const quote = source.charAt(pos);
5635
+ let i = pos + 1;
5636
+ while (i < source.length) {
5637
+ const ch = source.charAt(i);
5638
+ if (ch === quote) return {
5639
+ end: i + 1,
5640
+ stop: i
5641
+ };
5642
+ if (ch === "\n" || ch === "\r") return {
5643
+ end: void 0,
5644
+ stop: i
5645
+ };
5646
+ if (ch === "\\") i += source.startsWith("\r\n", i + 1) ? 3 : 2;
5647
+ else i += 1;
5648
+ }
5649
+ return {
5650
+ end: void 0,
5651
+ stop: source.length
5652
+ };
5653
+ }
5654
+ /**
5655
+ * Where a regular expression literal that opens at `pos` ends, flags included, or, if none
5656
+ * closes on the line, where the line ends. A `/` before that is then read as a division.
5657
+ */
5658
+ function endOfRegularExpression(source, pos) {
5659
+ let inClass = false;
5660
+ let i = pos + 1;
5661
+ while (i < source.length) {
5662
+ const ch = source.charAt(i);
5663
+ if (LINE_TERMINATORS.includes(ch)) return {
5664
+ end: void 0,
5665
+ stop: i
5666
+ };
5667
+ if (ch === "\\") {
5668
+ const escaped = source.charAt(i + 1);
5669
+ if (escaped === "" || LINE_TERMINATORS.includes(escaped)) return {
5670
+ end: void 0,
5671
+ stop: i + 1
5672
+ };
5673
+ i += 2;
5674
+ continue;
5675
+ }
5676
+ if (ch === "[") inClass = true;
5677
+ else if (ch === "]") inClass = false;
5678
+ else if (ch === "/" && !inClass) {
5679
+ WORD_RE.lastIndex = i + 1;
5680
+ const flags = WORD_RE.exec(source);
5681
+ return {
5682
+ end: i + 1 + (flags === null ? 0 : flags[0].length),
5683
+ stop: i
5684
+ };
5685
+ }
5686
+ i += 1;
5687
+ }
5688
+ return {
5689
+ end: void 0,
5690
+ stop: source.length
5691
+ };
5692
+ }
5693
+ //#endregion
5694
+ //#region src/sugarcube-macros.ts
5695
+ /**
5696
+ * Reads SugarCube 2 macro calls the way SugarCube 2.37.3 does, so the link check sees the same
5697
+ * passage names that `<<link>>` and `<<goto>>` use when the story plays.
5698
+ *
5699
+ * Each step follows a part of SugarCube's macro parser:
5700
+ * - `findMacroTags` finds where a tag starts and ends (the parser's `lookahead` pattern);
5701
+ * - `parseMacroArgs` splits the text after the macro name into arguments (`parseArgs`);
5702
+ * - quoted arguments are evaluated as strict-mode JavaScript strings (`evalStringLiteral`).
5703
+ *
5704
+ * Of the rest of the wikifier, only comments, `<script>` elements and `<<script>>` bodies are
5705
+ * told apart; other markup, such as verbatim text, is read as markup (see
5706
+ * `findMacroPassageLinks`).
5707
+ */
5708
+ const NAME_RE = /\/?[A-Za-z][\w-]*|[=-]/y;
5709
+ const SPACES_RE = /\s*/y;
5710
+ const LINE_TERMINATOR_RE = /[\n\r\u2028\u2029]/g;
5711
+ const SQUARE_BRACKET_OPEN_RE = /\[(?:[<>]?[Ii][Mm][Gg])?\[/y;
5712
+ const SPACE_RE = /[\s\u180e]/g;
5713
+ const NOT_SPACE_RE = /[^\s\u180e]/g;
5714
+ const VARIABLE_RE = /^[$_][$A-Z_a-z][$0-9A-Z_a-z]*/;
5715
+ const SETTINGS_OR_SETUP_RE = /^(?:settings|setup)[.[]/;
5716
+ const IMAGE_MARKUP_CHARS = "<>IiMmGg";
5717
+ /**
5718
+ * Macros that SugarCube doesn't split into arguments (`skipArgs` in 2.37.3), with their child
5719
+ * tags that do the same: `<<elseif>>` and `<<else>>` of `<<if>>`, and `<<optionsfrom>>` of
5720
+ * `<<cycle>>` and `<<listbox>>`. Their argument text is TwineScript, or for `<<capture>>`,
5721
+ * `<<unset>>` and `<<for>>` a syntax of their own; either way its strings are JavaScript strings.
5722
+ */
5723
+ const RAW_ARGUMENT_MACROS = /* @__PURE__ */ new Set([
5724
+ "break",
5725
+ "capture",
5726
+ "continue",
5727
+ "done",
5728
+ "else",
5729
+ "elseif",
5730
+ "for",
5731
+ "if",
5732
+ "nobr",
5733
+ "optionsfrom",
5734
+ "print",
5735
+ "=",
5736
+ "-",
5737
+ "run",
5738
+ "set",
5739
+ "silent",
5740
+ "silently",
5741
+ "stop",
5742
+ "switch",
5743
+ "unset",
5744
+ "waitforaudio"
5745
+ ]);
5746
+ /**
5747
+ * How deep strings inside macro arguments are read for further calls. Stories nest two or three
5748
+ * levels; the limit keeps the work linear in the size of the text on any input.
5749
+ */
5750
+ const MAX_STRING_DEPTH = 10;
5751
+ /** A context for reading `text`: the closer search may read four times it, plus an allowance. */
5752
+ function readContext(text) {
5753
+ return {
5754
+ depth: 0,
5755
+ budget: { left: 4 * text.length + 1e5 }
5756
+ };
5757
+ }
5758
+ function deeper(context) {
5759
+ return {
5760
+ depth: context.depth + 1,
5761
+ budget: context.budget
5762
+ };
5763
+ }
5764
+ /** Index of the first match of a global `re` at or after `from`, or -1. */
5765
+ function searchFrom(re, text, from) {
5766
+ re.lastIndex = from;
5767
+ const m = re.exec(text);
5768
+ return m === null ? -1 : m.index;
5769
+ }
5770
+ /**
5771
+ * Finds the macro tags in text, in order, trying a tag at every `<<` as SugarCube's macro
5772
+ * parser does. A tag that doesn't parse is skipped, and the search goes on after its `<<`.
5773
+ *
5774
+ * Gives the same tags as SugarCube's pattern, without its backtracking: that pattern takes
5775
+ * exponential time when no `>>` follows a `<<name`, which a script passage can contain (`1<<n`).
5776
+ */
5777
+ function findMacroTags(text) {
5778
+ return scanTags(text).map((scanned) => scanned.tag);
5779
+ }
5780
+ function scanTags(text) {
5781
+ const matchTagAt = tagMatcher(text);
5782
+ const tags = [];
5783
+ let start = text.indexOf("<<");
5784
+ while (start !== -1) {
5785
+ const scanned = matchTagAt(start);
5786
+ if (scanned === void 0) start = text.indexOf("<<", start + 2);
5787
+ else {
5788
+ tags.push(scanned);
5789
+ start = text.indexOf("<<", scanned.tag.end);
5790
+ }
5791
+ }
5792
+ return tags;
5793
+ }
5794
+ /**
5795
+ * Returns a function that matches a tag at a `<<` in `text`. It must be called for positions in
5796
+ * increasing order.
5797
+ *
5798
+ * The arguments may contain comments, backquoted expressions, quoted strings and link markup,
5799
+ * whose `>>` doesn't end the tag. SugarCube's pattern treats such a part as a unit only if a
5800
+ * `>>` still follows it, and otherwise as plain characters; `lastClose`, the last `>>` in the
5801
+ * text, answers that in constant time. Once a part is read as plain characters, a part of the
5802
+ * same kind that starts inside it can't end before `lastClose` either, in this tag or a later
5803
+ * one, so it isn't scanned again: `scanFrom` records where each kind may next be scanned. This
5804
+ * keeps the search linear. `onWork` is told how many characters each step reads. (Exported for
5805
+ * tests; the module is not part of the package's API.)
5806
+ */
5807
+ function tagMatcher(text, lastClose = text.lastIndexOf(">>"), onWork = () => {}) {
5808
+ const scanFrom = /* @__PURE__ */ new Map();
5809
+ return (start) => {
5810
+ NAME_RE.lastIndex = start + 2;
5811
+ const nameMatch = NAME_RE.exec(text);
5812
+ if (nameMatch === null) {
5813
+ onWork(2);
5814
+ return;
5815
+ }
5816
+ SPACES_RE.lastIndex = NAME_RE.lastIndex;
5817
+ SPACES_RE.exec(text);
5818
+ const argsStart = SPACES_RE.lastIndex;
5819
+ onWork(argsStart - start);
5820
+ let innerCall;
5821
+ let pos = argsStart;
5822
+ while (pos <= lastClose) {
5823
+ if (text.startsWith(">>", pos)) return {
5824
+ tag: {
5825
+ name: nameMatch[0],
5826
+ args: text.slice(argsStart, pos),
5827
+ start,
5828
+ end: pos + 2
5829
+ },
5830
+ innerCall
5831
+ };
5832
+ const kind = argumentPartKindAt(text, pos);
5833
+ const from = kind === void 0 ? void 0 : scanFrom.get(kind);
5834
+ if (kind !== void 0 && (from === void 0 || pos >= from)) {
5835
+ const part = scanArgumentPart(text, pos, kind);
5836
+ onWork(part.stop - pos);
5837
+ if (part.end !== void 0 && part.end <= lastClose) {
5838
+ pos = part.end;
5839
+ continue;
5840
+ }
5841
+ scanFrom.set(kind, part.stop);
5842
+ }
5843
+ if (innerCall === void 0 && startsPassageLinkCall(text, pos)) innerCall = pos;
5844
+ onWork(1);
5845
+ pos += 1;
5846
+ }
5847
+ };
5848
+ }
5849
+ /** Whether a `<<link` or `<<goto` tag, and not a longer macro name, starts at `pos`. */
5850
+ function startsPassageLinkCall(text, pos) {
5851
+ if (!text.startsWith("<<", pos)) return false;
5852
+ NAME_RE.lastIndex = pos + 2;
5853
+ const name = NAME_RE.exec(text)?.[0];
5854
+ return name === "link" || name === "goto";
5855
+ }
5856
+ /** The kind of argument part that opens at `pos`, if one does. */
5857
+ function argumentPartKindAt(text, pos) {
5858
+ const ch = text[pos];
5859
+ switch (ch) {
5860
+ case "/": {
5861
+ const next = text[pos + 1];
5862
+ return next === "*" ? "/*" : next === "/" ? "//" : void 0;
5863
+ }
5864
+ case "`":
5865
+ case "\"":
5866
+ case "'":
5867
+ case "[": return ch;
5868
+ default: return;
5869
+ }
5870
+ }
5871
+ function scanArgumentPart(text, pos, kind) {
5872
+ switch (kind) {
5873
+ case "/*": {
5874
+ const close = text.indexOf("*/", pos + 2);
5875
+ return close === -1 ? {
5876
+ end: void 0,
5877
+ stop: text.length
5878
+ } : {
5879
+ end: close + 2,
5880
+ stop: close
5881
+ };
5882
+ }
5883
+ case "//": {
5884
+ const lineEnd = searchFrom(LINE_TERMINATOR_RE, text, pos + 2);
5885
+ if (lineEnd === -1) return {
5886
+ end: void 0,
5887
+ stop: text.length
5888
+ };
5889
+ return {
5890
+ end: text[lineEnd] === "\n" ? lineEnd + 1 : void 0,
5891
+ stop: lineEnd
5892
+ };
5893
+ }
5894
+ case "`":
5895
+ case "\"":
5896
+ case "'": return scanQuoted(text, pos, kind);
5897
+ case "[": return scanSquareBracketed(text, pos);
5898
+ default: throw new Error(`unhandled argument part: ${String(kind)}`);
5899
+ }
5900
+ }
5901
+ /** A quoted part of a tag: a backslash escapes any character except a line terminator. */
5902
+ function scanQuoted(text, pos, quote) {
5903
+ let i = pos + 1;
5904
+ while (i < text.length) {
5905
+ const ch = text[i];
5906
+ if (ch === quote) return {
5907
+ end: i + 1,
5908
+ stop: i
5909
+ };
5910
+ if (ch === "\\") {
5911
+ const next = text[i + 1];
5912
+ if (next === void 0 || "\n\r\u2028\u2029".includes(next)) return {
5913
+ end: void 0,
5914
+ stop: i
5915
+ };
5916
+ i += 2;
5917
+ } else i += 1;
5918
+ }
5919
+ return {
5920
+ end: void 0,
5921
+ stop: text.length
5922
+ };
5923
+ }
5924
+ /** Link or image markup in a tag: up to the first `]]` on the same line, plus any further `]`. */
5925
+ function scanSquareBracketed(text, pos) {
5926
+ SQUARE_BRACKET_OPEN_RE.lastIndex = pos;
5927
+ if (!SQUARE_BRACKET_OPEN_RE.test(text)) return {
5928
+ end: void 0,
5929
+ stop: pos + 1
5930
+ };
5931
+ for (let i = SQUARE_BRACKET_OPEN_RE.lastIndex; i < text.length; i++) {
5932
+ const ch = text[i];
5933
+ if (ch === "\n" || ch === "\r") return {
5934
+ end: void 0,
5935
+ stop: i
5936
+ };
5937
+ if (ch === "]" && text[i + 1] === "]") {
5938
+ let end = i + 2;
5939
+ while (text[end] === "]") end += 1;
5940
+ return {
5941
+ end,
5942
+ stop: i
5943
+ };
5944
+ }
5945
+ }
5946
+ return {
5947
+ end: void 0,
5948
+ stop: text.length
5949
+ };
5950
+ }
5951
+ function lexMacroArgs(raw) {
5952
+ const args = [];
5953
+ let pos = searchFrom(NOT_SPACE_RE, raw, 0);
5954
+ while (pos !== -1) {
5955
+ const lexed = lexArgument(raw, pos);
5956
+ if (lexed === void 0) return;
5957
+ args.push(lexed.arg);
5958
+ pos = searchFrom(NOT_SPACE_RE, raw, lexed.end);
5959
+ }
5960
+ return args;
5961
+ }
5962
+ function lexArgument(raw, pos) {
5963
+ const first = raw[pos];
5964
+ switch (first) {
5965
+ case "`": {
5966
+ const end = slurpQuote(raw, pos + 1, "`");
5967
+ return end === void 0 ? void 0 : {
5968
+ arg: {
5969
+ kind: "expression",
5970
+ code: raw.slice(pos + 1, end - 1)
5971
+ },
5972
+ end
5973
+ };
5974
+ }
5975
+ case "\"":
5976
+ case "'": {
5977
+ const end = slurpQuote(raw, pos + 1, first);
5978
+ if (end === void 0) return;
5979
+ const value = evalStringLiteral(raw.slice(pos, end));
5980
+ return value === void 0 ? void 0 : {
5981
+ arg: {
5982
+ kind: "string",
5983
+ value
5984
+ },
5985
+ end
5986
+ };
5987
+ }
5988
+ case "[": {
5989
+ const end = lexSquareBracketed(raw, pos + 1);
5990
+ return end === void 0 ? void 0 : {
5991
+ arg: { kind: "markup" },
5992
+ end
5993
+ };
5994
+ }
5995
+ default: {
5996
+ const space = searchFrom(SPACE_RE, raw, pos + 1);
5997
+ const end = space === -1 ? raw.length : space;
5998
+ return {
5999
+ arg: {
6000
+ kind: "word",
6001
+ text: raw.slice(pos, end)
6002
+ },
6003
+ end
6004
+ };
6005
+ }
6006
+ }
6007
+ }
6008
+ /**
6009
+ * Reads a quoted argument from just after its opening quote. A newline, or a backslash before a
6010
+ * newline, ends it unterminated. Returns the index after the closing quote.
6011
+ */
6012
+ function slurpQuote(raw, from, endQuote) {
6013
+ let i = from;
6014
+ while (i < raw.length) {
6015
+ const ch = raw[i];
6016
+ if (ch === endQuote) return i + 1;
6017
+ if (ch === "\n") return;
6018
+ if (ch === "\\") {
6019
+ const next = raw[i + 1];
6020
+ if (next === void 0 || next === "\n") return;
6021
+ i += 2;
6022
+ } else i += 1;
6023
+ }
6024
+ }
6025
+ /**
6026
+ * Reads link or image markup from just after its first `[`, counting nested brackets.
6027
+ * Returns the index after the closing `]]`.
6028
+ */
6029
+ function lexSquareBracketed(raw, from) {
6030
+ let i = from;
6031
+ while (i < raw.length && IMAGE_MARKUP_CHARS.includes(raw.charAt(i))) i += 1;
6032
+ if (raw[i] !== "[") return;
6033
+ i += 1;
6034
+ let depth = 2;
6035
+ while (i < raw.length) {
6036
+ const ch = raw[i];
6037
+ i += 1;
6038
+ switch (ch) {
6039
+ case "\\": {
6040
+ const next = raw[i];
6041
+ if (next === void 0 || next === "\n") return;
6042
+ i += 1;
6043
+ break;
6044
+ }
6045
+ case "\n": return;
6046
+ case "[":
6047
+ depth += 1;
6048
+ break;
6049
+ case "]":
6050
+ depth -= 1;
6051
+ if (depth < 0) return;
6052
+ if (depth === 1 && raw[i] === "]") return i + 1;
6053
+ }
6054
+ }
6055
+ }
6056
+ /** An argument's value, following SugarCube's conversions. */
6057
+ function argValue(arg) {
6058
+ switch (arg.kind) {
6059
+ case "string": return {
6060
+ type: "string",
6061
+ value: arg.value
6062
+ };
6063
+ case "expression": return { type: "other" };
6064
+ case "markup": return { type: "markup" };
6065
+ case "word": return bareWord(arg.text);
6066
+ default: throw new Error(`unhandled macro argument: ${JSON.stringify(arg)}`);
6067
+ }
6068
+ }
6069
+ /** A bare word's value, following SugarCube's conversions. */
6070
+ function bareWord(word) {
6071
+ if (VARIABLE_RE.test(word) || SETTINGS_OR_SETUP_RE.test(word)) return { type: "other" };
6072
+ switch (word) {
6073
+ case "null": return { type: "null" };
6074
+ case "undefined":
6075
+ case "true":
6076
+ case "false": return { type: "other" };
6077
+ case "NaN": return {
6078
+ type: "number",
6079
+ value: NaN
6080
+ };
6081
+ default: {
6082
+ const value = Number(word);
6083
+ return Number.isNaN(value) ? {
6084
+ type: "string",
6085
+ value: word
6086
+ } : {
6087
+ type: "number",
6088
+ value
6089
+ };
6090
+ }
6091
+ }
6092
+ }
6093
+ /** The passage name an argument gives, if it can be known without playing the story. */
6094
+ function passageName(arg) {
6095
+ switch (arg.type) {
6096
+ case "string": return arg.value.includes("﷐") ? void 0 : arg.value;
6097
+ case "number": return String(arg.value);
6098
+ case "markup":
6099
+ case "null":
6100
+ case "other": return;
6101
+ default: throw new Error(`unhandled macro argument: ${JSON.stringify(arg)}`);
6102
+ }
6103
+ }
6104
+ /**
6105
+ * The argument that names the passage in a `<<link>>` or `<<goto>>` call:
6106
+ * - `<<link linkText [passageName]>>`, unless the first argument is link or image markup, which
6107
+ * then names the passage itself and any further argument is ignored;
6108
+ * - `<<goto passageName>>`.
6109
+ *
6110
+ * In text built from a template literal, a bare word with a `${…}` in it may become several
6111
+ * words in play, so no argument after it is known.
6112
+ */
6113
+ function passageArgument(macro, lexed) {
6114
+ const index = macro === "link" ? 1 : 0;
6115
+ if (lexed.slice(0, index + 1).some((arg) => arg.kind === "word" && arg.text.includes("﷐"))) return;
6116
+ const args = lexed.map(argValue);
6117
+ switch (macro) {
6118
+ case "link": {
6119
+ const [label, passage] = args;
6120
+ return label === void 0 || label.type === "markup" || label.type === "null" ? void 0 : passage;
6121
+ }
6122
+ case "goto": return args[0];
6123
+ default: throw new Error(`unhandled macro: ${String(macro)}`);
6124
+ }
6125
+ }
6126
+ function isPassageLinkMacro(name) {
6127
+ return name === "goto" || name === "link";
6128
+ }
6129
+ /** The passage a `<<link>>` or `<<goto>>` tag names itself, if it can be known before play. */
6130
+ function ownPassageLink(tag, lexed) {
6131
+ if (!isPassageLinkMacro(tag.name)) return;
6132
+ const arg = passageArgument(tag.name, lexed);
6133
+ const passage = arg === void 0 ? void 0 : passageName(arg);
6134
+ return passage === void 0 ? void 0 : {
6135
+ macro: tag.name,
6136
+ passage
6137
+ };
6138
+ }
6139
+ /**
6140
+ * The passages a tag names: its own, if it is a `<<link>>` or `<<goto>>` call, then those of the
6141
+ * calls inside the strings of its arguments, which the macro may print or pass on
6142
+ * (`<<set _out to '<<link "Go" "Room">><</link>>'>>`). The arguments of the macros SugarCube
6143
+ * doesn't split are read as JavaScript; in others, a backquoted expression is.
6144
+ */
6145
+ function tagPassageLinks(tag, context) {
6146
+ if (RAW_ARGUMENT_MACROS.has(tag.name)) return javaScriptPassageLinks(tag.args, context);
6147
+ const lexed = lexMacroArgs(tag.args);
6148
+ if (lexed === void 0) return [];
6149
+ const own = ownPassageLink(tag, lexed);
6150
+ const inner = lexed.flatMap((arg) => {
6151
+ switch (arg.kind) {
6152
+ case "string": return markupPassageLinks(arg.value, deeper(context));
6153
+ case "expression": return javaScriptPassageLinks(arg.code, context);
6154
+ case "markup":
6155
+ case "word": return [];
6156
+ default: throw new Error(`unhandled macro argument: ${JSON.stringify(arg)}`);
6157
+ }
6158
+ });
6159
+ return own === void 0 ? inner : [own, ...inner];
6160
+ }
6161
+ /**
6162
+ * The passage named by a `<<link>>` or `<<goto>>` that appears unquoted inside another tag's
6163
+ * arguments, at `start`. SugarCube never sees such an outer "tag" when its `<<` lies in text it
6164
+ * reads as something else, such as link markup (`[[<<-- Back|Prev]]`); the call inside it then
6165
+ * runs. The call ends where the outer tag ends.
6166
+ */
6167
+ function innerPassageLink(matchTagAt, start) {
6168
+ const inner = matchTagAt(start)?.tag;
6169
+ const lexed = inner === void 0 ? void 0 : lexMacroArgs(inner.args);
6170
+ return inner === void 0 || lexed === void 0 ? void 0 : ownPassageLink(inner, lexed);
6171
+ }
6172
+ const REGION_OPEN_RE = /\/\/|\/\*|\/%|<!--|<[Ss][Cc][Rr][Ii][Pp][Tt]/g;
6173
+ const HAS_SCRIPT_OPEN_RE = /<[Ss][Cc][Rr][Ii][Pp][Tt]/;
6174
+ const SCRIPT_CLOSE_RE = /<\/[Ss][Cc][Rr][Ii][Pp][Tt]>|[\r\u2028\u2029]/g;
6175
+ const COMMENT_CLOSE_RES = {
6176
+ "/*": /\*\/|[\r\u2028\u2029]/g,
6177
+ "/%": /%\/|[\r\u2028\u2029]/g,
6178
+ "<!--": /-->|[\r\u2028\u2029]/g
6179
+ };
6180
+ /**
6181
+ * Returns a function that finds where a comment that opens at `start` ends, as SugarCube's
6182
+ * `commentByBlock` parser reads it, or `undefined` if it isn't closed. Calls of one kind must come
6183
+ * in increasing order: a search that fails stops at a line terminator or the end, and a later one
6184
+ * of the same kind that starts before that stop fails too, so it isn't made.
6185
+ */
6186
+ function commentReader(text) {
6187
+ const failedUntil = /* @__PURE__ */ new Map();
6188
+ return (kind, start) => {
6189
+ if (start < (failedUntil.get(kind) ?? -1)) return;
6190
+ const re = COMMENT_CLOSE_RES[kind];
6191
+ re.lastIndex = start + kind.length;
6192
+ const m = re.exec(text);
6193
+ if (m !== null && m[0].length > 1) return m.index + m[0].length;
6194
+ failedUntil.set(kind, m === null ? text.length : m.index);
6195
+ };
6196
+ }
6197
+ /**
6198
+ * Returns a function that reads a `<script>` element whose opener starts at a position, as
6199
+ * SugarCube's `verbatimScriptTag` parser reads it: the opener up to its `>`, then the content
6200
+ * up to the first `<\/script>`. Calls must come in increasing order; each part of the text is
6201
+ * searched once.
6202
+ */
6203
+ function scriptElementReader(text) {
6204
+ let angle = -1;
6205
+ let noAngleAfter = Infinity;
6206
+ let failedBefore = -1;
6207
+ let noCloseAfter = Infinity;
6208
+ return (start) => {
6209
+ if (start + 7 >= noAngleAfter) return {
6210
+ openerEnd: void 0,
6211
+ close: void 0
6212
+ };
6213
+ if (angle < start + 7) {
6214
+ angle = text.indexOf(">", start + 7);
6215
+ if (angle === -1) {
6216
+ noAngleAfter = start + 7;
6217
+ return {
6218
+ openerEnd: void 0,
6219
+ close: void 0
6220
+ };
6221
+ }
6222
+ }
6223
+ const openerEnd = angle + 1;
6224
+ if (openerEnd < failedBefore || openerEnd >= noCloseAfter) return {
6225
+ openerEnd,
6226
+ close: void 0
6227
+ };
6228
+ SCRIPT_CLOSE_RE.lastIndex = openerEnd;
6229
+ const m = SCRIPT_CLOSE_RE.exec(text);
6230
+ if (m === null) {
6231
+ noCloseAfter = openerEnd;
6232
+ return {
6233
+ openerEnd,
6234
+ close: void 0
6235
+ };
6236
+ }
6237
+ if (m[0].length === 1) {
6238
+ failedBefore = m.index;
6239
+ return {
6240
+ openerEnd,
6241
+ close: void 0
6242
+ };
6243
+ }
6244
+ return {
6245
+ openerEnd,
6246
+ close: m.index
6247
+ };
6248
+ };
6249
+ }
6250
+ /**
6251
+ * Returns a function that finds the tag closing the `<<script>>` body that `opener` opens, as
6252
+ * SugarCube's `parseBody` finds it: scanning tags from every `<<` after the opener, without
6253
+ * skipping anything, for the first `<<\/script>>` or `<<endscript>>` that isn't matched by a
6254
+ * later `<<script>>`. (It doesn't reproduce parseBody's rejection of a closing tag with
6255
+ * arguments, nor its resuming inside the arguments of a tag whose name starts with `/` or
6256
+ * `end`.)
6257
+ *
6258
+ * The tags found from the start of the text are those parseBody finds from any opener among
6259
+ * them, so for such an opener the answer takes constant time. An opener the walk reached after
6260
+ * a comment may not be among them, when a tag that starts in the comment runs over it; then the
6261
+ * scan starts at the body and goes on until it finds the closer or reaches a tag of that list,
6262
+ * whose answers it then uses. All such scans in one reading of a passage, strings included, stop
6263
+ * once they have read four times as many characters as the passage has, plus a fixed allowance
6264
+ * (`budget`, see `readContext`); on input built to make them read more, the openers after that
6265
+ * are taken as unclosed. That keeps the time linear. (Exported for tests; the module is not part
6266
+ * of the package's API.)
6267
+ */
6268
+ function scriptBodyCloser(text, budget) {
6269
+ const tags = findMacroTags(text);
6270
+ const indexByStart = new Map(tags.map((tag, index) => [tag.start, index]));
6271
+ const lastClose = text.lastIndexOf(">>");
6272
+ const spend = (characters) => {
6273
+ budget.left -= characters;
6274
+ };
6275
+ const step = (tag) => tag.name === "script" ? 1 : tag.name === "/script" || tag.name === "endscript" ? -1 : 0;
6276
+ const balance = [0];
6277
+ tags.forEach((tag, k) => balance.push((balance[k] ?? 0) + step(tag)));
6278
+ const firstBelow = [];
6279
+ const candidates = [];
6280
+ for (let k = balance.length - 1; k >= 0; k--) {
6281
+ const here = balance[k] ?? 0;
6282
+ let top = candidates[candidates.length - 1];
6283
+ while (top !== void 0 && (balance[top] ?? 0) >= here) {
6284
+ candidates.pop();
6285
+ top = candidates[candidates.length - 1];
6286
+ }
6287
+ firstBelow[k] = top;
6288
+ candidates.push(k);
6289
+ }
6290
+ /**
6291
+ * The closer when `open` bodies are open just before `tags[index]`: each hop to
6292
+ * `firstBelow` closes one. `open` is at most one more than the openers scanned to get here.
6293
+ */
6294
+ const closeFrom = (index, open) => {
6295
+ let k = index;
6296
+ for (let left = open; left > 0 && k !== void 0; left--) k = firstBelow[k];
6297
+ return k === void 0 ? void 0 : tags[k - 1];
6298
+ };
6299
+ return (opener) => {
6300
+ const index = indexByStart.get(opener.start);
6301
+ if (index !== void 0) return closeFrom(index + 1, 1);
6302
+ const matchTagAt = tagMatcher(text, lastClose, spend);
6303
+ let open = 1;
6304
+ let from = opener.end;
6305
+ while (budget.left >= 0) {
6306
+ const start = text.indexOf("<<", from);
6307
+ spend((start === -1 ? text.length : start) - from);
6308
+ if (start === -1) return;
6309
+ const known = indexByStart.get(start);
6310
+ if (known !== void 0) return closeFrom(known, open);
6311
+ const tag = matchTagAt(start)?.tag;
6312
+ if (tag === void 0) {
6313
+ from = start + 2;
6314
+ continue;
6315
+ }
6316
+ open += step(tag);
6317
+ if (open === 0) return tag;
6318
+ from = tag.end;
6319
+ }
6320
+ };
6321
+ }
6322
+ /** Adds `more` to the end of `links`, without spreading, which fails for very long lists. */
6323
+ function append(links, more) {
6324
+ for (const link of more) links.push(link);
6325
+ }
6326
+ /**
6327
+ * The passages that `<<link>>` and `<<goto>>` calls in passage markup name. Calls whose passage
6328
+ * is known only in play (a variable or an expression) are left out. A tag's own passage comes
6329
+ * before those of the calls inside its arguments' strings.
6330
+ *
6331
+ * The markup is walked in order, as SugarCube's wikifier walks it, with a tag tried at each
6332
+ * `<<` the walk reaches. Of the wikifier's other parsers, only those whose text holds no call
6333
+ * are told apart: comments (`/* … *` + `/`, `/% … %/`, `<!-- … -->`), whose calls never run,
6334
+ * and `<script>` elements and `<<script>>` bodies, which are JavaScript: only the calls in their
6335
+ * strings are read (see `findJavaScriptPassageLinks`). Everything else, verbatim text included,
6336
+ * is read as markup.
6337
+ *
6338
+ * Where this differs from SugarCube:
6339
+ * - a comment or a `<<script>>` body is skipped whole, even where `parseBody` ends a container
6340
+ * such as `<<if>>` at a closing tag inside it and the rest then runs;
6341
+ * - a `/*`, `<!--` or `<script` inside other markup that holds no call, such as link markup or a
6342
+ * `<style>` element, still starts a comment or an element;
6343
+ * - a `<<` in such other markup still starts a tag. When that tag runs over a `<<link` or
6344
+ * `<<goto` outside the parts of its arguments that the tag pattern reads as units, that call
6345
+ * is still read (see `innerPassageLink`), even where the tag's arguments would be JavaScript,
6346
+ * as the check always read it. One that such a part covers is lost: a quoted string, or a `//`
6347
+ * part up to a line feed (italics, a URL) when a `>>` follows later; and a `<<script>>` body
6348
+ * the tag runs over is read as markup. The same recovery also reads a call inside a stray tag
6349
+ * that SugarCube does see, and rejects as an unknown macro (`<<Back <<goto R>>`);
6350
+ * - a `<<script>>` body's end is found as `parseBody` finds it, except that parseBody rejects a
6351
+ * closing tag with arguments, and resumes inside the arguments of a tag whose name starts with
6352
+ * `/` or `end`;
6353
+ * - the lines of a `<<nobr>>` body, and of every passage when a story sets
6354
+ * `Config.passages.nobr`, are not joined before they are read (see `storyInspect` for passages
6355
+ * tagged `nobr`).
6356
+ */
6357
+ function findMacroPassageLinks(text) {
6358
+ return markupPassageLinks(text, readContext(text));
6359
+ }
6360
+ function markupPassageLinks(text, context) {
6361
+ if (context.depth > MAX_STRING_DEPTH || !text.includes("<<") && !HAS_SCRIPT_OPEN_RE.test(text)) return [];
6362
+ const matchTagAt = tagMatcher(text);
6363
+ const matchInnerTagAt = tagMatcher(text);
6364
+ const readComment = commentReader(text);
6365
+ const readScriptElement = scriptElementReader(text);
6366
+ let findScriptCloser;
6367
+ const links = [];
6368
+ /** Reads the region `opener` opens, adding the calls in a `<script>` element; returns where the walk goes on. */
6369
+ const regionEnd = (opener) => {
6370
+ const start = opener.index;
6371
+ const kind = opener[0];
6372
+ switch (kind) {
6373
+ case "//": return start + 2;
6374
+ case "/*":
6375
+ case "/%":
6376
+ case "<!--": return readComment(kind, start) ?? start + kind.length;
6377
+ default: {
6378
+ const element = readScriptElement(start);
6379
+ if (element.openerEnd === void 0) return start + 1;
6380
+ if (element.close === void 0) return element.openerEnd;
6381
+ append(links, javaScriptPassageLinks(text.slice(element.openerEnd, element.close), context));
6382
+ return element.close + 9;
6383
+ }
6384
+ }
6385
+ };
6386
+ let macro = -2;
6387
+ let region;
6388
+ let pos = 0;
6389
+ for (;;) {
6390
+ if (macro !== -1 && macro < pos) macro = text.indexOf("<<", pos);
6391
+ if (region !== null && (region === void 0 || region.index < pos)) {
6392
+ REGION_OPEN_RE.lastIndex = pos;
6393
+ region = REGION_OPEN_RE.exec(text);
6394
+ }
6395
+ if (region !== null && (macro === -1 || region.index < macro)) {
6396
+ pos = regionEnd(region);
6397
+ continue;
6398
+ }
6399
+ if (macro === -1) return links;
6400
+ const scanned = matchTagAt(macro);
6401
+ if (scanned === void 0) {
6402
+ pos = macro + 2;
6403
+ continue;
6404
+ }
6405
+ const { tag, innerCall } = scanned;
6406
+ append(links, tagPassageLinks(tag, context));
6407
+ if (innerCall !== void 0) {
6408
+ const inner = innerPassageLink(matchInnerTagAt, innerCall);
6409
+ if (inner !== void 0) links.push(inner);
6410
+ }
6411
+ pos = tag.end;
6412
+ if (tag.name === "script") {
6413
+ findScriptCloser ??= scriptBodyCloser(text, context.budget);
6414
+ const closer = findScriptCloser(tag);
6415
+ if (closer !== void 0) {
6416
+ append(links, javaScriptPassageLinks(text.slice(tag.end, closer.start), context));
6417
+ pos = closer.end;
6418
+ }
6419
+ }
6420
+ }
6421
+ }
6422
+ /**
6423
+ * The passages that `<<link>>` and `<<goto>>` calls in the strings of JavaScript source name,
6424
+ * such as a script passage or a `<<script>>` body: `$.wiki('<<goto "Room">>')`. Code outside
6425
+ * the strings isn't markup, so a call put together while the story plays, such as
6426
+ * `'<<goto "' + target + '">>'`, names no passage here.
6427
+ */
6428
+ function findJavaScriptPassageLinks(source) {
6429
+ return javaScriptPassageLinks(source, readContext(source));
6430
+ }
6431
+ /**
6432
+ * What JavaScript source must contain for one of its string or template literals to hold a call
6433
+ * that is read. A value holding `<<`: each `<` in it is written as `<`, `\<`, `\x3c`, `\u003c` or
6434
+ * `\u{…}`, two can be next to each other with only line continuations between, and the first
6435
+ * is `<` or `\<` (then the source holds `<<` or `<\`) or one of the others. Or a value holding a
6436
+ * `<script>` element, whose own strings can make `<<` from escapes the outer string encodes.
6437
+ */
6438
+ const MAY_HOLD_MACRO_RE = /<<|<\\|\\x3c|\\u003c|\\u\{|<script/i;
6439
+ function javaScriptPassageLinks(source, context) {
6440
+ if (context.depth >= MAX_STRING_DEPTH || !MAY_HOLD_MACRO_RE.test(source)) return [];
6441
+ const inner = deeper(context);
6442
+ const links = [];
6443
+ for (const value of javaScriptStrings(source)) append(links, markupPassageLinks(value, inner));
6444
+ return links;
6445
+ }
5351
6446
  //#endregion
5352
6447
  //#region src/inspect.ts
5353
6448
  /**
@@ -5359,8 +6454,15 @@ function storyToJSON(story) {
5359
6454
  * - `[[Display Text|PassageName]]` (Twine 1 / Harlowe pipe)
5360
6455
  * - `<<goto "PassageName">>` (SugarCube macro)
5361
6456
  * - `<<link "Display" "PassageName">>` (SugarCube macro)
6457
+ *
6458
+ * SugarCube macro arguments may be double- or single-quoted, with backslash escapes, or bare
6459
+ * words; a passage named by a variable or an expression is known only in play and is skipped.
6460
+ * Macro calls are also read inside the quoted strings of other macros' arguments, and inside the
6461
+ * strings of `<<script>>` bodies and `<script>` elements; calls in comments are not read. A
6462
+ * script passage (`isScript`) is JavaScript, so its macro calls are read only inside its strings.
6463
+ * See `sugarcube-macros.ts` for the details and the known differences from SugarCube.
5362
6464
  */
5363
- function extractLinksFromText(text) {
6465
+ function extractLinksFromText(text, isScript) {
5364
6466
  const targets = /* @__PURE__ */ new Set();
5365
6467
  const wikiLinkRe = /\[\[([^\]]+)\]\]/g;
5366
6468
  let m;
@@ -5378,12 +6480,36 @@ function extractLinksFromText(text) {
5378
6480
  }
5379
6481
  targets.add(content.trim());
5380
6482
  }
5381
- const gotoRe = /<<goto\s+["']([^"']+)["']\s*>>/g;
5382
- while ((m = gotoRe.exec(text)) !== null) targets.add(m[1]);
5383
- const linkMacroRe = /<<link\s+["'][^"']*["']\s+["']([^"']+)["']\s*>>/g;
5384
- while ((m = linkMacroRe.exec(text)) !== null) targets.add(m[1]);
6483
+ const macroLinks = isScript ? findJavaScriptPassageLinks(text) : findMacroPassageLinks(text);
6484
+ for (const macro of ["goto", "link"]) for (const link of macroLinks) if (link.macro === macro) targets.add(link.passage);
5385
6485
  return [...targets];
5386
6486
  }
6487
+ /** Passages SugarCube runs from their raw text, never joining their lines. */
6488
+ const RAW_TEXT_PASSAGES = /* @__PURE__ */ new Set([
6489
+ "StoryInit",
6490
+ "PassageReady",
6491
+ "PassageDone"
6492
+ ]);
6493
+ /**
6494
+ * A passage's text as SugarCube reads it for its links. A passage tagged `nobr` has its line
6495
+ * breaks joined (`Passage.processText`): leading and trailing ones removed, each run inside made
6496
+ * one space. Script passages, `init`-tagged passages, StoryInit, PassageReady and PassageDone are
6497
+ * run from their raw text, so they keep theirs.
6498
+ */
6499
+ function textAsRead(p) {
6500
+ return hasTag(p, "nobr") && !hasTag(p, "script") && !hasTag(p, "init") && !RAW_TEXT_PASSAGES.has(p.name) ? joinLines(p.text) : p.text;
6501
+ }
6502
+ /**
6503
+ * What SugarCube's `text.replace(/^\n+|\n+$/g, '').replace(/\n+/g, ' ')` gives, without that
6504
+ * pattern's backtracking, which takes quadratic time on a long run of line feeds.
6505
+ */
6506
+ function joinLines(text) {
6507
+ let start = 0;
6508
+ while (text[start] === "\n") start += 1;
6509
+ let end = text.length;
6510
+ while (end > start && text[end - 1] === "\n") end -= 1;
6511
+ return text.slice(start, end).replace(/\n+/g, " ");
6512
+ }
5387
6513
  /**
5388
6514
  * Inspect a story and return its full structural map.
5389
6515
  *
@@ -5423,7 +6549,7 @@ function storyInspect(story) {
5423
6549
  }
5424
6550
  list.push(p.name);
5425
6551
  }
5426
- const targets = extractLinksFromText(p.text);
6552
+ const targets = extractLinksFromText(textAsRead(p), hasTag(p, "script"));
5427
6553
  links.set(p.name, targets);
5428
6554
  }
5429
6555
  const brokenLinks = [];