squiffy-compiler 6.0.1 → 7.0.0-beta.11

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.
Files changed (62) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +96 -0
  3. package/dist/analyse.js +951 -0
  4. package/dist/compiler.d.ts +32 -40
  5. package/dist/compiler.js +26 -691
  6. package/dist/css-urls.d.ts +4 -0
  7. package/dist/css-urls.js +59 -0
  8. package/dist/emit.d.ts +71 -0
  9. package/dist/emit.js +192 -0
  10. package/dist/helpers.d.ts +1 -0
  11. package/dist/helpers.js +14 -0
  12. package/dist/ignore.d.ts +8 -0
  13. package/dist/ignore.js +71 -0
  14. package/dist/infix-expressions.d.ts +19 -0
  15. package/dist/infix-expressions.js +713 -0
  16. package/dist/language-service.d.ts +90 -0
  17. package/dist/language-service.js +883 -0
  18. package/dist/node.d.ts +23 -0
  19. package/dist/node.js +122 -0
  20. package/dist/parse.d.ts +22 -0
  21. package/dist/parse.js +316 -0
  22. package/dist/project.d.ts +129 -0
  23. package/dist/project.js +488 -0
  24. package/dist/quest/aslx.d.ts +51 -0
  25. package/dist/quest/aslx.js +184 -0
  26. package/dist/quest/convert.d.ts +20 -0
  27. package/dist/quest/convert.js +552 -0
  28. package/dist/quest/script.d.ts +92 -0
  29. package/dist/quest/script.js +453 -0
  30. package/dist/quest/scripts.d.ts +24 -0
  31. package/dist/quest/scripts.js +506 -0
  32. package/dist/quest/text.d.ts +18 -0
  33. package/dist/quest/text.js +323 -0
  34. package/dist/section-labels.d.ts +4 -0
  35. package/dist/section-labels.js +64 -0
  36. package/dist/setters.d.ts +49 -0
  37. package/dist/setters.js +477 -0
  38. package/dist/story-graph.d.ts +71 -0
  39. package/dist/story-graph.js +445 -0
  40. package/dist/syntax.d.ts +198 -0
  41. package/dist/syntax.js +8 -0
  42. package/dist/templates.d.ts +17 -0
  43. package/dist/templates.js +180 -0
  44. package/dist/text.d.ts +44 -0
  45. package/dist/text.js +348 -0
  46. package/dist/twine/audio.d.ts +21 -0
  47. package/dist/twine/audio.js +80 -0
  48. package/dist/twine/convert.d.ts +131 -0
  49. package/dist/twine/convert.js +1057 -0
  50. package/dist/twine/expression.d.ts +88 -0
  51. package/dist/twine/expression.js +318 -0
  52. package/dist/twine/harlowe.d.ts +27 -0
  53. package/dist/twine/harlowe.js +2341 -0
  54. package/dist/twine/settings.d.ts +9 -0
  55. package/dist/twine/settings.js +322 -0
  56. package/dist/twine/story.d.ts +24 -0
  57. package/dist/twine/story.js +231 -0
  58. package/dist/twine/sugarcube.d.ts +40 -0
  59. package/dist/twine/sugarcube.js +2172 -0
  60. package/dist/v5.js +2 -1
  61. package/package.json +35 -6
  62. package/syntaxes/squiffy.tmLanguage.json +1003 -0
@@ -0,0 +1,2172 @@
1
+ // Converts a SugarCube passage to Squiffy text.
2
+ //
3
+ // The passage is parsed into a tree of text, <<macros>> (with the bodies of container macros
4
+ // such as <<if>>...<</if>>), links and naked variables, which is then written out as Squiffy:
5
+ // <<if>> becomes {{#if}}, <<set>> becomes @set or {{set}}, links with setters become links with
6
+ // setters, and <<link>> and friends become links to generated passages and sections.
7
+ import { delayValue, display, isDynamicTarget, isListCall, lengthOf, member as memberOf, print, quote, randomInteger, skipString, targetName, Tokens, Unconvertible, unescapeString } from "./expression.js";
8
+ import { audioHelper, leadingAudio, pickSource, STOP_ALL_AUDIO } from "./audio.js";
9
+ import { dynamicSectionLink, escapeText, isUrl, urlLink, passageLink, sectionLink, setter, passageHtmlBlock, readHtmlBlock, topScripts } from "./convert.js";
10
+ const containers = new Set([
11
+ "if", "for", "switch", "link", "button", "linkreplace", "linkappend", "linkprepend", "nobr", "silently", "capture",
12
+ "script", "timed", "repeat", "widget", "cycle", "listbox", "append", "prepend", "replace", "type", "done", "do",
13
+ "click", "createplaylist", "createaudiogroup",
14
+ ]);
15
+ const childMacros = {
16
+ if: ["elseif", "else"],
17
+ switch: ["case", "default"],
18
+ timed: ["next"],
19
+ cycle: ["option", "optionsfrom"],
20
+ listbox: ["option", "optionsfrom"],
21
+ repeat: [],
22
+ };
23
+ class Parser {
24
+ // The story's container widgets (#450), whose calls wrap text like <<say "Ann">>Hi<</say>>
25
+ constructor(src, containerWidgets = new Set()) {
26
+ Object.defineProperty(this, "src", {
27
+ enumerable: true,
28
+ configurable: true,
29
+ writable: true,
30
+ value: src
31
+ });
32
+ Object.defineProperty(this, "containerWidgets", {
33
+ enumerable: true,
34
+ configurable: true,
35
+ writable: true,
36
+ value: containerWidgets
37
+ });
38
+ }
39
+ // Parses until the end, or until the end of the container, or one of its child macros
40
+ parse(start, container) {
41
+ const src = this.src;
42
+ const nodes = [];
43
+ let text = "";
44
+ const flush = () => {
45
+ if (text)
46
+ nodes.push({ t: "text", s: text });
47
+ text = "";
48
+ };
49
+ let i = start;
50
+ while (i < src.length) {
51
+ const rest = src.substring(i, i + 300);
52
+ if (rest.startsWith("<<")) {
53
+ const macro = readMacro(src, i);
54
+ if (macro) {
55
+ const close = /^\/(\w+)$|^end\s*(\w+)$/.exec(macro.name);
56
+ if (close) {
57
+ const closing = close[1] ?? close[2];
58
+ if (container && closing == container) {
59
+ flush();
60
+ return { nodes, end: macro.end, stop: { name: closing, args: "", raw: macro.raw, close: true } };
61
+ }
62
+ // A stray closing tag: left out
63
+ flush();
64
+ i = macro.end;
65
+ continue;
66
+ }
67
+ const name = macro.name == "else" && /^\s*if\b/.test(macro.args) ? "elseif" : macro.name;
68
+ const args = name == "elseif" && macro.name == "else" ? macro.args.replace(/^\s*if\b/, "") : macro.args;
69
+ if (container && childMacros[container]?.includes(name)) {
70
+ flush();
71
+ return { nodes, end: macro.end, stop: { name, args, raw: macro.raw, close: false } };
72
+ }
73
+ flush();
74
+ if (containers.has(name) || this.containerWidgets.has(name)) {
75
+ const node = { t: "macro", name, args, raw: macro.raw, clauses: [] };
76
+ let clause = { name, args, raw: macro.raw, nodes: [] };
77
+ let j = macro.end;
78
+ for (;;) {
79
+ const body = this.parse(j, name);
80
+ clause.nodes = body.nodes;
81
+ node.clauses.push(clause);
82
+ j = body.end;
83
+ if (!body.stop || body.stop.close) {
84
+ node.raw = src.substring(i, j);
85
+ break;
86
+ }
87
+ clause = { name: body.stop.name, args: body.stop.args, raw: body.stop.raw, nodes: [] };
88
+ }
89
+ nodes.push(node);
90
+ i = j;
91
+ continue;
92
+ }
93
+ nodes.push({ t: "macro", name, args, raw: macro.raw });
94
+ i = macro.end;
95
+ continue;
96
+ }
97
+ }
98
+ if (rest.startsWith("/*") || rest.startsWith("/%")) {
99
+ const closer = rest.startsWith("/*") ? "*/" : "%/";
100
+ const end = src.indexOf(closer, i + 2);
101
+ flush();
102
+ i = end == -1 ? src.length : end + 2;
103
+ continue;
104
+ }
105
+ if (rest.startsWith("<!--")) {
106
+ const end = src.indexOf("-->", i + 4);
107
+ const stop = end == -1 ? src.length : end + 3;
108
+ flush();
109
+ nodes.push({ t: "raw", s: src.substring(i, stop).replace(/\n/g, " ") });
110
+ i = stop;
111
+ continue;
112
+ }
113
+ if (rest.startsWith("\"\"\"")) {
114
+ const end = src.indexOf("\"\"\"", i + 3);
115
+ if (end != -1) {
116
+ flush();
117
+ nodes.push({ t: "raw", s: escapeText(escapeHtml(src.substring(i + 3, end))) });
118
+ i = end + 3;
119
+ continue;
120
+ }
121
+ }
122
+ if (/^<nowiki>/i.test(rest)) {
123
+ const end = src.toLowerCase().indexOf("</nowiki>", i);
124
+ if (end != -1) {
125
+ flush();
126
+ nodes.push({ t: "raw", s: escapeText(src.substring(i + 8, end)) });
127
+ i = end + 9;
128
+ continue;
129
+ }
130
+ }
131
+ if (rest.startsWith("{{{")) {
132
+ const end = src.indexOf("}}}", i + 3);
133
+ if (end != -1) {
134
+ flush();
135
+ nodes.push({ t: "raw", s: `<code>${escapeText(escapeHtml(src.substring(i + 3, end)))}</code>` });
136
+ i = end + 3;
137
+ continue;
138
+ }
139
+ }
140
+ const html = readHtmlBlock(src, i);
141
+ if (html) {
142
+ flush();
143
+ nodes.push(html.block);
144
+ i = html.end;
145
+ continue;
146
+ }
147
+ const image = /^\[[<>]?img\[(?:([^|\]]*)\|)?([^\]]*)\](?:\[([^\]]*)\])?\]/i.exec(rest);
148
+ if (image) {
149
+ flush();
150
+ nodes.push({ t: "image", raw: image[0], title: image[1], src: image[2], link: image[3] });
151
+ i += image[0].length;
152
+ continue;
153
+ }
154
+ const link = /^\[\[((?:[^\]]|\](?!\]|\[))*)\](?:\[((?:[^\]]|\](?!\]))*)\])?\]/.exec(rest);
155
+ if (link) {
156
+ flush();
157
+ nodes.push(parseLink(link[1], link[0], link[2]));
158
+ i += link[0].length;
159
+ continue;
160
+ }
161
+ const tag = src[i] == "<" ? /^<\/?[A-Za-z][^<>]*>/.exec(src.substring(i, i + 2000)) : null;
162
+ if (tag) {
163
+ // An HTML tag is text: target="_blank" isn't a temporary variable
164
+ text += tag[0];
165
+ i += tag[0].length;
166
+ continue;
167
+ }
168
+ const variable = /^(?:\$[A-Za-z_]|_[A-Za-z])\w*(?:\.[A-Za-z_$][\w$]*|\[(?:[^\]\n]+)\])*/.exec(rest);
169
+ if (variable && (rest[0] == "$" || !/\w/.test(src[i - 1] ?? "")) && !/\w/.test(src[i - 1] ?? "")) {
170
+ flush();
171
+ nodes.push({ t: "var", raw: variable[0] });
172
+ i += variable[0].length;
173
+ continue;
174
+ }
175
+ text += src[i];
176
+ i++;
177
+ }
178
+ flush();
179
+ return { nodes, end: i };
180
+ }
181
+ }
182
+ // Reads <<name args>> at start, or null if it isn't a macro
183
+ function readMacro(src, start) {
184
+ const head = /^<<(\/?[A-Za-z][\w-]*|=|-|end\s+\w+)/.exec(src.substring(start, start + 100));
185
+ if (!head)
186
+ return null;
187
+ let i = start + head[0].length;
188
+ while (i < src.length) {
189
+ const c = src[i];
190
+ if (c == "\"" || c == "'" || c == "`") {
191
+ const end = skipString(src, i);
192
+ if (end == -1)
193
+ return null;
194
+ i = end;
195
+ continue;
196
+ }
197
+ if (src.startsWith("[[", i)) {
198
+ const end = src.indexOf("]]", i);
199
+ if (end == -1)
200
+ return null;
201
+ i = end + 2;
202
+ continue;
203
+ }
204
+ if (src.startsWith("/*", i)) {
205
+ const end = src.indexOf("*/", i + 2);
206
+ if (end == -1)
207
+ return null;
208
+ i = end + 2;
209
+ continue;
210
+ }
211
+ if (src.startsWith(">>", i)) {
212
+ const name = head[1] == "=" || head[1] == "-" ? "print" : head[1].replace(/\s+/g, "");
213
+ return { name: name.toLowerCase(), args: src.substring(start + head[0].length, i).trim(), raw: src.substring(start, i + 2), end: i + 2 };
214
+ }
215
+ i++;
216
+ }
217
+ return null;
218
+ }
219
+ function parseLink(inner, raw, setter) {
220
+ let text;
221
+ let target;
222
+ const bar = inner.lastIndexOf("|");
223
+ const arrow = inner.lastIndexOf("->");
224
+ const back = inner.indexOf("<-");
225
+ if (bar != -1) {
226
+ text = inner.substring(0, bar);
227
+ target = inner.substring(bar + 1);
228
+ }
229
+ else if (arrow != -1) {
230
+ text = inner.substring(0, arrow);
231
+ target = inner.substring(arrow + 2);
232
+ }
233
+ else if (back != -1) {
234
+ target = inner.substring(0, back);
235
+ text = inner.substring(back + 2);
236
+ }
237
+ else {
238
+ text = target = inner;
239
+ }
240
+ return { t: "link", raw, text, target: target.trim(), ...(setter === undefined ? {} : { setter }) };
241
+ }
242
+ function escapeHtml(s) {
243
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
244
+ }
245
+ const symbols = [
246
+ "===", "!==", "**", "==", "!=", ">=", "<=", "&&", "||", "+=", "-=", "*=", "/=", "%=", "++", "--", "=>",
247
+ "+", "-", "*", "/", "%", ">", "<", "=", "!", "?", ":", "(", ")", "[", "]", "{", "}", ",", ".", ";", "&", "|",
248
+ ];
249
+ const wordOperators = {
250
+ to: "=", eq: "==", neq: "!=", is: "===", isnot: "!==", gt: ">", gte: ">=", lt: "<", lte: "<=",
251
+ and: "&&", or: "||", not: "!", def: "def", ndef: "ndef", typeof: "typeof", new: "new", instanceof: "instanceof",
252
+ };
253
+ function tokenize(s) {
254
+ const tokens = [];
255
+ let i = 0;
256
+ while (i < s.length) {
257
+ const c = s[i];
258
+ if (/\s/.test(c)) {
259
+ i++;
260
+ continue;
261
+ }
262
+ if (c == "\"" || c == "'") {
263
+ const end = skipString(s, i);
264
+ if (end == -1)
265
+ throw new Unconvertible("an expression with a string that isn't closed");
266
+ tokens.push({ type: "str", text: s.substring(i, end), value: unescapeString(s.substring(i, end)) });
267
+ i = end;
268
+ continue;
269
+ }
270
+ if (s.startsWith("/*", i)) {
271
+ const end = s.indexOf("*/", i + 2);
272
+ i = end == -1 ? s.length : end + 2;
273
+ continue;
274
+ }
275
+ if (c == "`")
276
+ throw new Unconvertible("a JavaScript template literal");
277
+ const num = /^(\d+(?:\.\d+)?|\.\d+)(ms|s)?(?![\w])/i.exec(s.substring(i));
278
+ if (num) {
279
+ let value = parseFloat(num[1]);
280
+ if (num[2]?.toLowerCase() == "s")
281
+ value *= 1000;
282
+ tokens.push({ type: "num", text: num[0], value });
283
+ i += num[0].length;
284
+ continue;
285
+ }
286
+ const variable = /^([$_])([A-Za-z_]\w*)/.exec(s.substring(i));
287
+ if (variable && (variable[1] == "$" || !/\w/.test(s[i - 1] ?? ""))) {
288
+ tokens.push({ type: variable[1] == "$" ? "var" : "temp", text: variable[0], value: variable[2] });
289
+ i += variable[0].length;
290
+ continue;
291
+ }
292
+ const word = /^[A-Za-z_$][\w$]*/.exec(s.substring(i));
293
+ if (word) {
294
+ const op = wordOperators[word[0]];
295
+ tokens.push(op ? { type: "op", text: op } : { type: "ident", text: word[0] });
296
+ i += word[0].length;
297
+ continue;
298
+ }
299
+ const symbol = symbols.find(o => s.startsWith(o, i));
300
+ if (symbol) {
301
+ // & and | on true and false work as && and ||, and are usually a typo for them
302
+ const text = symbol == "&" ? "&&" : symbol == "|" ? "||" : symbol;
303
+ tokens.push({ type: "(),[]{}.;:?".includes(symbol) ? "punct" : "op", text });
304
+ i += symbol.length;
305
+ continue;
306
+ }
307
+ throw new Unconvertible(`an expression Squiffy can't read ("${s.substring(i, i + 10)}")`);
308
+ }
309
+ return tokens;
310
+ }
311
+ export class SugarCubeExpressions {
312
+ constructor(ctx) {
313
+ Object.defineProperty(this, "ctx", {
314
+ enumerable: true,
315
+ configurable: true,
316
+ writable: true,
317
+ value: ctx
318
+ });
319
+ // Whether a container widget's body is being converted
320
+ Object.defineProperty(this, "inContainerWidget", {
321
+ enumerable: true,
322
+ configurable: true,
323
+ writable: true,
324
+ value: false
325
+ });
326
+ }
327
+ attribute(name, temp) {
328
+ return this.ctx.story.attribute(name, temp);
329
+ }
330
+ variable(name, temp) {
331
+ // Inside a container widget, the text its call wraps (#450)
332
+ if (temp && name == "contents" && this.inContainerWidget)
333
+ return { k: "call", fn: "content", args: [] };
334
+ return this.ctx.story.variable(name, temp);
335
+ }
336
+ parse(source) {
337
+ const tokens = new Tokens(tokenize(source));
338
+ const e = new ExpressionParser(this, tokens).expression();
339
+ if (!tokens.done)
340
+ throw new Unconvertible(`an expression Squiffy can't read (at "${tokens.peek().text}")`);
341
+ return e;
342
+ }
343
+ // Statements, as in <<set>> and <<run>>: assignments and changes to arrays
344
+ statements(source) {
345
+ const tokens = new Tokens(tokenize(source));
346
+ const parser = new ExpressionParser(this, tokens);
347
+ const result = [];
348
+ while (!tokens.done) {
349
+ result.push(...parser.statement());
350
+ if (!tokens.accept(",") && !tokens.accept(";"))
351
+ break;
352
+ }
353
+ if (!tokens.done)
354
+ throw new Unconvertible(`a statement Squiffy can't read (at "${tokens.peek().text}")`);
355
+ return result;
356
+ }
357
+ // A value used as a passage name, for <<goto>>, <<include>> and links
358
+ passageName(source) {
359
+ const link = /^\[\[(.*)\]\]$/.exec(source.trim());
360
+ if (link) {
361
+ const node = parseLink(link[1], source);
362
+ return { name: node.target };
363
+ }
364
+ // A bare word that isn't a variable is a passage name, e.g. <<goto Library>>
365
+ if (/^[^"'`$_[(\s][^\s]*$/.test(source.trim())) {
366
+ try {
367
+ const e = this.parse(source);
368
+ if (e.k == "str")
369
+ return { name: e.v };
370
+ }
371
+ catch {
372
+ // Treated as a name
373
+ }
374
+ return { name: source.trim() };
375
+ }
376
+ const e = this.parse(source);
377
+ if (e.k == "str")
378
+ return { name: e.v };
379
+ return { expr: e };
380
+ }
381
+ }
382
+ // memorize(key, value) (#539): sets the key's persistent attribute. Adding to what's there, as
383
+ // memorize(key, Object.assign(recall(key, {}), { name: value })), sets the values inside it.
384
+ function memorizeStatements(args) {
385
+ const [name, value] = args;
386
+ if (value.k == "call" && value.fn == "__assign") {
387
+ const [target, added] = value.args;
388
+ if (target.k == "var" && target.name == name.v && added.k == "object") {
389
+ return added.entries.map(([key, v]) => {
390
+ const inside = targetName(memberOf({ k: "var", name: name.v }, { k: "str", v: key }));
391
+ if (inside === null)
392
+ throw new Unconvertible("Object.assign() with a name Squiffy can't use");
393
+ return { kind: "set", name: inside, value: v };
394
+ });
395
+ }
396
+ }
397
+ return [{ kind: "set", name: name.v, value }];
398
+ }
399
+ // A comparison, where x.indexOf(y) compared with -1 or 0 to see whether y is there is x contains y
400
+ // (#446). Anything else .indexOf() is for can't be converted: see print().
401
+ function indexOfCheck(left, op, right) {
402
+ if (left.k != "call" || left.fn != "__indexof")
403
+ return { k: "bin", op, l: left, r: right };
404
+ const n = right.k == "num" ? right.v : right.k == "neg" && right.e.k == "num" ? -right.e.v : null;
405
+ const contains = { k: "bin", op: "contains", l: left.args[0], r: left.args[1] };
406
+ if ((n == -1 && (op == "!=" || op == ">")) || (n == 0 && op == ">="))
407
+ return contains;
408
+ if ((n == -1 && (op == "=" || op == "<=")) || (n == 0 && op == "<"))
409
+ return { k: "not", e: contains };
410
+ return { k: "bin", op, l: left, r: right };
411
+ }
412
+ // Comments and helpers that show nothing, e.g. {{set}}
413
+ const silent = String.raw `\{\{!--[\s\S]*?--\}\}|\{\{(?:set|unset|inc|dec) [^{}]*\}\}`;
414
+ const spaceAfterSilent = new RegExp(String.raw `(?<=^|[ \t]|${silent})(${silent})[ \t]+`, "gm");
415
+ // Takes out the spaces after things that show nothing, at the start of a line or after another
416
+ // space. In SugarCube's HTML they make no difference, but in Squiffy's Markdown, a line that
417
+ // starts with four of them, once what's between them shows nothing, would be a code block.
418
+ function withoutSilentSpaces(body) {
419
+ for (;;) {
420
+ const tidied = body.replace(spaceAfterSilent, "$1");
421
+ if (tidied == body)
422
+ return body;
423
+ body = tidied;
424
+ }
425
+ }
426
+ // A <<do>>'s tags, from its tag "a b" argument
427
+ function doTags(args) {
428
+ const parts = splitMacroArgs(args);
429
+ const i = parts.indexOf("tag");
430
+ if (i == -1 || !parts[i + 1] || !/^["']/.test(parts[i + 1]))
431
+ return [];
432
+ return unescapeString(parts[i + 1]).split(/\s+/).filter(t => t);
433
+ }
434
+ // The attribute that a <<do>> with these tags is shown again when it changes
435
+ function redoAttribute(tags) {
436
+ if (!tags.length)
437
+ return "redo";
438
+ return "redo_" + [...tags].sort().join("_").replace(/\W/g, "_");
439
+ }
440
+ // The tags of every <<do>> in the story, so a <<redo>> anywhere knows what it shows again
441
+ function storyDoTags(story) {
442
+ return story.cached("sugarcube-do-tags", () => {
443
+ const sets = new Map();
444
+ for (const p of story.twine.passages) {
445
+ for (const m of p.text.matchAll(/<<\s*do\b((?:[^>]|>(?!>))*)>>/g)) {
446
+ const tags = doTags(m[1]);
447
+ sets.set(redoAttribute(tags), tags);
448
+ }
449
+ }
450
+ return [...sets.values()];
451
+ });
452
+ }
453
+ // Whether an expression is sure to be a number, so += can add it with inc
454
+ function isNumber(e) {
455
+ switch (e.k) {
456
+ case "num": return true;
457
+ case "neg": return isNumber(e.e);
458
+ case "loop": return e.kind == "index" || !!e.numbers;
459
+ case "bin": return ["-", "*", "/", "%"].includes(e.op) || (e.op == "+" && isNumber(e.l) && isNumber(e.r));
460
+ case "cond": return isNumber(e.then) && isNumber(e.otherwise);
461
+ case "call": return ["round", "floor", "ceil", "abs", "min", "max", "length", "visits", "lastvisited", "count"].includes(e.fn);
462
+ }
463
+ return false;
464
+ }
465
+ function clamp(value, min, max) {
466
+ return { k: "call", fn: "max", args: [min, { k: "call", fn: "min", args: [max, value] }] };
467
+ }
468
+ class ExpressionParser {
469
+ constructor(s, tokens) {
470
+ Object.defineProperty(this, "s", {
471
+ enumerable: true,
472
+ configurable: true,
473
+ writable: true,
474
+ value: s
475
+ });
476
+ Object.defineProperty(this, "tokens", {
477
+ enumerable: true,
478
+ configurable: true,
479
+ writable: true,
480
+ value: tokens
481
+ });
482
+ }
483
+ // Including test ? a : b (#446), which is right-associative
484
+ expression() {
485
+ const test = this.or();
486
+ if (!this.tokens.accept("?"))
487
+ return test;
488
+ const then = this.expression();
489
+ this.tokens.expect(":");
490
+ return { k: "cond", test, then, otherwise: this.expression() };
491
+ }
492
+ statement() {
493
+ const target = this.postfixValue();
494
+ if (target.v == "expr" && target.e.k == "loop")
495
+ throw new Unconvertible("changing a loop's variable inside the loop");
496
+ if (target.v == "expr" && target.e.k == "call" && target.e.fn == "__memorize")
497
+ return memorizeStatements(target.e.args);
498
+ if (target.v == "expr" && target.e.k == "call" && target.e.fn == "__forget") {
499
+ return [{ kind: "forget", names: target.e.args.map(a => a.v) }];
500
+ }
501
+ return [this.singleStatement(target, this.tokens.peek())];
502
+ }
503
+ // An object literal, or an ordinary expression
504
+ postfixOrObject() {
505
+ if (this.tokens.is("{"))
506
+ return this.primary();
507
+ return { v: "expr", e: this.expression() };
508
+ }
509
+ singleStatement(target, t) {
510
+ // An attribute, or a value inside one, such as hero.hp or inventory[i].name (#442)
511
+ const name = target.v == "expr" ? targetName(target.e) : null;
512
+ if (name !== null) {
513
+ if (t?.text == "++" || t?.text == "--") {
514
+ this.tokens.next();
515
+ return { kind: t.text == "++" ? "inc" : "dec", name, value: { k: "num", v: 1 } };
516
+ }
517
+ if (t && ["=", "+=", "-=", "*=", "/="].includes(t.text)) {
518
+ this.tokens.next();
519
+ const value = this.expression();
520
+ switch (t.text) {
521
+ case "+=":
522
+ if (value.k == "array")
523
+ return this.arrayChange("append", name, value);
524
+ // += adds text to text too, which inc can't
525
+ if (!isNumber(value))
526
+ return { kind: "set", name, value: { k: "bin", op: "+", l: target.e, r: value } };
527
+ return { kind: "inc", name, value };
528
+ case "-=": return { kind: "dec", name, value };
529
+ case "*=":
530
+ case "/=": return { kind: "set", name, value, op: t.text };
531
+ }
532
+ // $x to $x + 1
533
+ if (value.k == "bin" && (value.op == "+" || value.op == "-") && targetName(value.l) == name) {
534
+ if (value.r.k == "array")
535
+ return this.arrayChange(value.op == "+" ? "append" : "remove", name, value.r);
536
+ if (value.r.k == "num" || value.op == "-")
537
+ return { kind: value.op == "+" ? "inc" : "dec", name, value: value.r };
538
+ }
539
+ return { kind: "set", name, value };
540
+ }
541
+ throw new Unconvertible("a statement that isn't an assignment");
542
+ }
543
+ if (target.v == "expr" && target.e.k == "call" && target.e.fn == "__statement") {
544
+ const [kind, name, value] = target.e.args;
545
+ return { kind: kind.v, name: name.v, value };
546
+ }
547
+ if (target.v == "global")
548
+ throw new Unconvertible(`setting ${target.name}, which isn't a variable`);
549
+ throw new Unconvertible("a statement Squiffy can't convert");
550
+ }
551
+ arrayChange(kind, name, array) {
552
+ if (array.items.length != 1)
553
+ throw new Unconvertible("adding or removing more than one item at once");
554
+ return { kind, name, value: array.items[0] };
555
+ }
556
+ or() {
557
+ let left = this.and();
558
+ while (this.tokens.is("||")) {
559
+ this.tokens.next();
560
+ left = { k: "bin", op: "or", l: left, r: this.and() };
561
+ }
562
+ return left;
563
+ }
564
+ and() {
565
+ let left = this.equality();
566
+ while (this.tokens.is("&&")) {
567
+ this.tokens.next();
568
+ left = { k: "bin", op: "and", l: left, r: this.equality() };
569
+ }
570
+ return left;
571
+ }
572
+ equality() {
573
+ let left = this.relational();
574
+ for (;;) {
575
+ const t = this.tokens.peek()?.text;
576
+ if (t == "==" || t == "===") {
577
+ this.tokens.next();
578
+ left = indexOfCheck(left, "=", this.relational());
579
+ }
580
+ else if (t == "!=" || t == "!==") {
581
+ this.tokens.next();
582
+ left = indexOfCheck(left, "!=", this.relational());
583
+ }
584
+ else if (t == "=") {
585
+ throw new Unconvertible("an assignment (=) in a condition");
586
+ }
587
+ else {
588
+ return left;
589
+ }
590
+ }
591
+ }
592
+ relational() {
593
+ let left = this.additive();
594
+ for (;;) {
595
+ const t = this.tokens.peek()?.text;
596
+ if (t == ">" || t == "<" || t == ">=" || t == "<=") {
597
+ this.tokens.next();
598
+ left = indexOfCheck(left, t, this.additive());
599
+ }
600
+ else {
601
+ return left;
602
+ }
603
+ }
604
+ }
605
+ additive() {
606
+ let left = this.multiplicative();
607
+ while (this.tokens.is("+") || this.tokens.is("-")) {
608
+ const op = this.tokens.next().text;
609
+ left = { k: "bin", op, l: left, r: this.multiplicative() };
610
+ }
611
+ return left;
612
+ }
613
+ multiplicative() {
614
+ let left = this.unary();
615
+ while (this.tokens.is("*") || this.tokens.is("/") || this.tokens.is("%")) {
616
+ const op = this.tokens.next().text;
617
+ left = { k: "bin", op, l: left, r: this.unary() };
618
+ }
619
+ return left;
620
+ }
621
+ unary() {
622
+ const t = this.tokens.peek()?.text;
623
+ if (t == "!") {
624
+ this.tokens.next();
625
+ return { k: "not", e: this.unary() };
626
+ }
627
+ if (t == "-") {
628
+ this.tokens.next();
629
+ const e = this.unary();
630
+ return e.k == "num" ? { k: "num", v: -e.v } : { k: "neg", e };
631
+ }
632
+ if (t == "+") {
633
+ this.tokens.next();
634
+ return this.unary();
635
+ }
636
+ if (t == "def" || t == "ndef") {
637
+ this.tokens.next();
638
+ const e = this.unary();
639
+ return t == "def" ? { k: "bin", op: "!=", l: e, r: { k: "null" } } : { k: "bin", op: "=", l: e, r: { k: "null" } };
640
+ }
641
+ if (t == "typeof" || t == "new")
642
+ throw new Unconvertible(`"${t}"`);
643
+ return this.postfix();
644
+ }
645
+ postfix() {
646
+ return this.toExpr(this.postfixValue());
647
+ }
648
+ toExpr(v) {
649
+ if (v.v == "expr")
650
+ return v.e;
651
+ if (v.v == "object")
652
+ return { k: "object", entries: v.entries.map(([key, value]) => [key, this.toExpr(value)]) };
653
+ if (v.v == "member") {
654
+ // A list's or text's length (#446)
655
+ if (v.property == "length") {
656
+ const object = this.toExpr(v.object);
657
+ if (object.k == "call" && object.fn == "__keys") {
658
+ // Object.keys(x).length: the number of values in x, which {{length}} counts
659
+ const x = object.args[0];
660
+ return { k: "call", fn: "length", args: [x.k == "var" ? { k: "str", v: x.name } : x] };
661
+ }
662
+ return lengthOf(object);
663
+ }
664
+ throw new Unconvertible(`properties of variables (.${v.property})`);
665
+ }
666
+ throw new Unconvertible(`"${v.name}"`);
667
+ }
668
+ // The first argument of contains and length: the attribute's name, or an array
669
+ collection(v) {
670
+ if (v.v == "expr" && v.e.k == "var")
671
+ return { k: "str", v: v.e.name };
672
+ // A list inside an object, e.g. $hero.items
673
+ if (v.v == "expr" && (v.e.k == "array" || v.e.k == "member" || (v.e.k == "loop" && v.e.kind == "item")))
674
+ return v.e;
675
+ throw new Unconvertible("an array method on something other than a variable");
676
+ }
677
+ postfixValue() {
678
+ let value = this.primary();
679
+ for (;;) {
680
+ if (this.tokens.accept(".")) {
681
+ const property = this.tokens.next();
682
+ if (property.type != "ident")
683
+ throw new Unconvertible("an expression Squiffy can't read");
684
+ // A value inside an object: $player.hp is player.hp (#442)
685
+ if (value.v == "expr" && value.e.k != "array" && value.e.k != "call" && !this.tokens.is("(") && property.text != "length") {
686
+ value = { v: "expr", e: memberOf(value.e, { k: "str", v: property.text }) };
687
+ continue;
688
+ }
689
+ value = this.member(value, property.text);
690
+ }
691
+ else if (this.tokens.is("[")) {
692
+ this.tokens.next();
693
+ const index = this.expression();
694
+ this.tokens.expect("]");
695
+ if (value.v == "expr" && value.e.k == "var" && index.k == "loop" && index.kind == "index" && index.array == value.e.name) {
696
+ value = { v: "expr", e: { k: "loop", kind: "item", up: index.up } };
697
+ continue;
698
+ }
699
+ // A value inside an object or list, e.g. $inventory[_i] or $player["hp"] (#442)
700
+ if (value.v == "expr") {
701
+ value = { v: "expr", e: memberOf(value.e, index) };
702
+ continue;
703
+ }
704
+ throw new Unconvertible("array indexes and object properties ([...]) of something other than a value");
705
+ }
706
+ else if (this.tokens.is("(")) {
707
+ this.tokens.next();
708
+ const args = [];
709
+ if (!this.tokens.accept(")")) {
710
+ do
711
+ args.push(this.expression());
712
+ while (this.tokens.accept(","));
713
+ this.tokens.expect(")");
714
+ }
715
+ value = { v: "expr", e: this.call(value, args) };
716
+ }
717
+ else {
718
+ return value;
719
+ }
720
+ }
721
+ }
722
+ // State.variables.x is $x, and State.temporary.x is _x
723
+ member(object, property) {
724
+ if (object.v == "global") {
725
+ const path = `${object.name}.${property}`;
726
+ if (path == "State.variables" || path == "State.temporary" || path == "SugarCube.State")
727
+ return { v: "global", name: path };
728
+ if (object.name == "State.variables" || object.name == "variables")
729
+ return { v: "expr", e: { k: "var", name: this.s.attribute(property, false) } };
730
+ if (object.name == "State.temporary" || object.name == "temporary")
731
+ return { v: "expr", e: this.s.variable(property, true) };
732
+ // The player's settings (#452), which Squiffy reads the same way
733
+ if (object.name == "settings")
734
+ return { v: "expr", e: memberOf({ k: "var", name: "settings" }, { k: "str", v: property }) };
735
+ // setup.x, where passages set it: a property of the setup attribute
736
+ if (object.name == "setup" && this.s.ctx.story.setupValues.has(property)) {
737
+ return { v: "expr", e: memberOf({ k: "var", name: this.s.attribute("setup", false) }, { k: "str", v: property }) };
738
+ }
739
+ return { v: "global", name: path };
740
+ }
741
+ return { v: "member", object, property };
742
+ }
743
+ call(callee, args) {
744
+ const str = (e, what, expected = "a passage name") => {
745
+ if (e?.k == "str")
746
+ return e.v;
747
+ throw new Unconvertible(`${what} with something other than ${expected}`);
748
+ };
749
+ if (callee.v == "global") {
750
+ switch (callee.name) {
751
+ case "visited":
752
+ case "hasVisited": {
753
+ if (args.length == 0)
754
+ return { k: "call", fn: "visits", args: [{ k: "str", v: this.s.ctx.section }] };
755
+ if (args.length > 1)
756
+ throw new Unconvertible(`${callee.name}() with more than one passage`);
757
+ const section = this.s.ctx.story.sectionForUnknown(str(args[0], `${callee.name}()`));
758
+ return callee.name == "visited" ? { k: "call", fn: "visits", args: [{ k: "str", v: section }] } : { k: "call", fn: "seen", args: [{ k: "str", v: section }] };
759
+ }
760
+ // How many turns ago (#540)
761
+ case "lastVisited": {
762
+ if (args.length == 0)
763
+ return { k: "num", v: 0 };
764
+ if (args.length > 1)
765
+ throw new Unconvertible("lastVisited() with more than one passage");
766
+ const section = this.s.ctx.story.sectionForUnknown(str(args[0], "lastVisited()"));
767
+ return { k: "call", fn: "lastvisited", args: [{ k: "str", v: section }] };
768
+ }
769
+ case "turns":
770
+ return { k: "var", name: "turns" };
771
+ // Values that last across playthroughs (#539): squiffy.json's "persistent"
772
+ case "recall": {
773
+ if (args.length < 1 || args.length > 2)
774
+ throw new Unconvertible("recall() with no key");
775
+ const name = this.s.ctx.story.persistentAttribute(str(args[0], "recall()", "a key"));
776
+ const fallback = args[1];
777
+ // A value that's never been memorized is null, which is like nothing, false or an empty list or object
778
+ if (fallback && !(fallback.k == "null" || (fallback.k == "bool" && !fallback.v)
779
+ || (fallback.k == "object" && !fallback.entries.length) || (fallback.k == "array" && !fallback.items.length))) {
780
+ throw new Unconvertible("recall() with a default value");
781
+ }
782
+ return { k: "var", name };
783
+ }
784
+ case "memorize":
785
+ if (args.length != 2)
786
+ throw new Unconvertible("memorize() without a key and a value");
787
+ return { k: "call", fn: "__memorize", args: [{ k: "str", v: this.s.ctx.story.persistentAttribute(str(args[0], "memorize()", "a key")) }, args[1]] };
788
+ case "forget":
789
+ return { k: "call", fn: "__forget", args: args.map(a => ({ k: "str", v: this.s.ctx.story.persistentAttribute(str(a, "forget()", "a key")) })) };
790
+ case "Object.assign":
791
+ if (args.length != 2)
792
+ throw new Unconvertible("Object.assign()");
793
+ return { k: "call", fn: "__assign", args };
794
+ case "random":
795
+ if (args.length == 1)
796
+ return randomInteger({ k: "num", v: 0 }, args[0]);
797
+ return randomInteger(args[0], args[1]);
798
+ case "either":
799
+ return { k: "call", fn: "random", args: [{ k: "array", items: args }] };
800
+ case "passage":
801
+ return { k: "str", v: this.s.ctx.passage.name };
802
+ case "tags":
803
+ // Only as tags().includes("tag")
804
+ return { k: "call", fn: "__tags", args: [] };
805
+ // Numbers (#446)
806
+ case "Math.round":
807
+ case "Math.floor":
808
+ case "Math.ceil":
809
+ case "Math.abs":
810
+ if (args.length != 1)
811
+ throw new Unconvertible(`${callee.name}() with ${args.length ? "more than one value" : "no value"}`);
812
+ return { k: "call", fn: callee.name.substring(5), args };
813
+ case "Math.min":
814
+ case "Math.max":
815
+ if (!args.length)
816
+ throw new Unconvertible(`${callee.name}() with no values`);
817
+ return { k: "call", fn: callee.name.substring(5), args };
818
+ // SugarCube's Math.clamp(value, min, max)
819
+ case "Math.clamp":
820
+ if (args.length != 3)
821
+ throw new Unconvertible("Math.clamp() without a value, a minimum and a maximum");
822
+ return clamp(args[0], args[1], args[2]);
823
+ // Only to count an object's values, as Object.keys(x).length
824
+ case "Object.keys":
825
+ case "Object.values":
826
+ case "Object.entries":
827
+ case "Object.getOwnPropertyNames":
828
+ if (args.length != 1)
829
+ throw new Unconvertible(`${callee.name}()`);
830
+ return { k: "call", fn: "__keys", args };
831
+ case "Number":
832
+ case "String":
833
+ case "parseInt":
834
+ case "parseFloat":
835
+ if (args.length < 1)
836
+ throw new Unconvertible(`${callee.name}()`);
837
+ return args[0];
838
+ }
839
+ throw new Unconvertible(`${callee.name}()`);
840
+ }
841
+ if (callee.v == "member" && callee.object.v == "expr" && callee.object.e.k == "call" && callee.object.e.fn == "__tags") {
842
+ // tags().includes("x"): whether this is one of the passages tagged x
843
+ if ((callee.property == "includes" || callee.property == "contains") && args[0]?.k == "str") {
844
+ const tag = args[0].v;
845
+ const sections = this.s.ctx.story.twine.passages
846
+ .filter(p => p.tags.includes(tag))
847
+ .map(p => this.s.ctx.story.sectionFor(p.name))
848
+ .filter((s) => s !== undefined);
849
+ return { k: "call", fn: "at", args: [{ k: "array", items: sections.map(s => ({ k: "str", v: s })) }] };
850
+ }
851
+ throw new Unconvertible("tags()");
852
+ }
853
+ if (callee.v == "member") {
854
+ const collection = () => this.collection(callee.object);
855
+ const value = () => this.toExpr(callee.object);
856
+ const noArguments = () => {
857
+ if (args.length)
858
+ throw new Unconvertible(`.${callee.property}() with a value`);
859
+ };
860
+ switch (callee.property) {
861
+ // A list or text that has a value in it (#446)
862
+ case "includes":
863
+ case "contains":
864
+ if (args.length != 1)
865
+ throw new Unconvertible(`.${callee.property}() with more than one value`);
866
+ return { k: "bin", op: "contains", l: value(), r: args[0] };
867
+ // SugarCube's number.clamp(min, max)
868
+ case "clamp":
869
+ if (args.length != 2)
870
+ throw new Unconvertible(".clamp() without a minimum and a maximum");
871
+ return clamp(value(), args[0], args[1]);
872
+ // Only to check whether something is there, e.g. .indexOf(x) != -1: see indexOfCheck
873
+ case "indexOf":
874
+ if (args.length != 1)
875
+ throw new Unconvertible(`.${callee.property}() with more than one value`);
876
+ return { k: "call", fn: "__indexof", args: [value(), args[0]] };
877
+ // Text (#446)
878
+ case "toLowerCase":
879
+ case "toLocaleLowerCase":
880
+ noArguments();
881
+ return { k: "call", fn: "lower", args: [value()] };
882
+ case "toUpperCase":
883
+ case "toLocaleUpperCase":
884
+ noArguments();
885
+ return { k: "call", fn: "upper", args: [value()] };
886
+ case "toUpperFirst":
887
+ case "toLocaleUpperFirst":
888
+ noArguments();
889
+ return { k: "call", fn: "capitalise", args: [value()] };
890
+ case "random":
891
+ if (callee.object.v == "expr")
892
+ return { k: "call", fn: "random", args: [callee.object.e] };
893
+ break;
894
+ // Lists (#447). JavaScript's .join() puts a comma with no space between the items.
895
+ case "join":
896
+ if (args.length > 1)
897
+ throw new Unconvertible(".join() with more than one value");
898
+ return { k: "call", fn: "join", args: [value(), args[0] ?? { k: "str", v: "," }] };
899
+ case "sort":
900
+ case "shuffle":
901
+ // Squiffy's give back a new list, and leave the attribute as it was
902
+ if (args.length)
903
+ throw new Unconvertible(`.${callee.property}() with a function to compare the items`);
904
+ return { k: "call", fn: callee.property, args: [value()] };
905
+ case "slice":
906
+ if (args.length > 2)
907
+ throw new Unconvertible(".slice() with more than two values");
908
+ return { k: "call", fn: "slice", args: [value(), args[0] ?? { k: "num", v: 0 }, ...args.slice(1)] };
909
+ case "first":
910
+ case "last":
911
+ noArguments();
912
+ return { k: "call", fn: callee.property, args: [value()] };
913
+ case "count":
914
+ if (args.length != 1)
915
+ throw new Unconvertible(".count() with a position to start from");
916
+ return { k: "call", fn: "count", args: [value(), args[0]] };
917
+ case "push":
918
+ case "pushUnique":
919
+ case "delete": {
920
+ const target = collection();
921
+ if (target.k != "str" || args.length != 1)
922
+ throw new Unconvertible(`.${callee.property}() with more than one value`);
923
+ return { k: "call", fn: "__statement", args: [{ k: "str", v: callee.property == "delete" ? "remove" : "append" }, target, args[0]] };
924
+ }
925
+ }
926
+ throw new Unconvertible(`the .${callee.property}() method`);
927
+ }
928
+ throw new Unconvertible("calling something that isn't a function");
929
+ }
930
+ primary() {
931
+ const t = this.tokens.next();
932
+ switch (t.type) {
933
+ case "str": return { v: "expr", e: { k: "str", v: t.value } };
934
+ case "num": return { v: "expr", e: { k: "num", v: t.value } };
935
+ case "var": return { v: "expr", e: this.s.variable(t.value, false) };
936
+ case "temp": return { v: "expr", e: this.s.variable(t.value, true) };
937
+ case "ident":
938
+ switch (t.text) {
939
+ case "true": return { v: "expr", e: { k: "bool", v: true } };
940
+ case "false": return { v: "expr", e: { k: "bool", v: false } };
941
+ case "null":
942
+ case "undefined": return { v: "expr", e: { k: "null" } };
943
+ }
944
+ return { v: "global", name: t.text };
945
+ case "punct":
946
+ if (t.text == "(") {
947
+ const e = this.expression();
948
+ this.tokens.expect(")");
949
+ return { v: "expr", e };
950
+ }
951
+ if (t.text == "[") {
952
+ const items = [];
953
+ if (!this.tokens.accept("]")) {
954
+ do
955
+ items.push(this.expression());
956
+ while (this.tokens.accept(","));
957
+ this.tokens.expect("]");
958
+ }
959
+ return { v: "expr", e: { k: "array", items } };
960
+ }
961
+ if (t.text == "{") {
962
+ const entries = [];
963
+ if (!this.tokens.accept("}")) {
964
+ do {
965
+ if (this.tokens.is("}"))
966
+ break;
967
+ const key = this.tokens.next();
968
+ if (key.type != "ident" && key.type != "str" && key.type != "num")
969
+ throw new Unconvertible("a JavaScript object Squiffy can't read");
970
+ if (!/^[A-Za-z_]\w*$/.test(String(key.value ?? key.text)))
971
+ throw new Unconvertible("a JavaScript object with keys that aren't words");
972
+ this.tokens.expect(":");
973
+ entries.push([String(key.value ?? key.text), this.postfixOrObject()]);
974
+ } while (this.tokens.accept(","));
975
+ this.tokens.expect("}");
976
+ }
977
+ return { v: "object", entries };
978
+ }
979
+ break;
980
+ }
981
+ throw new Unconvertible(`an expression Squiffy can't read (at "${t.text}")`);
982
+ }
983
+ }
984
+ // SugarCube macro arguments: separated by spaces, each a string, number, $variable, [[link]],
985
+ // `expression` or bare word
986
+ function splitMacroArgs(args) {
987
+ const result = [];
988
+ let i = 0;
989
+ while (i < args.length) {
990
+ const c = args[i];
991
+ if (/\s/.test(c)) {
992
+ i++;
993
+ continue;
994
+ }
995
+ let end;
996
+ if (c == "\"" || c == "'" || c == "`") {
997
+ end = skipString(args, i);
998
+ if (end == -1)
999
+ end = args.length;
1000
+ }
1001
+ else if (args.startsWith("[[", i)) {
1002
+ end = args.indexOf("]]", i);
1003
+ end = end == -1 ? args.length : end + 2;
1004
+ }
1005
+ else {
1006
+ end = i;
1007
+ while (end < args.length && !/\s/.test(args[end]))
1008
+ end++;
1009
+ }
1010
+ result.push(args.substring(i, end));
1011
+ i = end;
1012
+ }
1013
+ return result;
1014
+ }
1015
+ class Writer {
1016
+ constructor(ctx) {
1017
+ Object.defineProperty(this, "ctx", {
1018
+ enumerable: true,
1019
+ configurable: true,
1020
+ writable: true,
1021
+ value: ctx
1022
+ });
1023
+ Object.defineProperty(this, "expr", {
1024
+ enumerable: true,
1025
+ configurable: true,
1026
+ writable: true,
1027
+ value: void 0
1028
+ });
1029
+ Object.defineProperty(this, "open", {
1030
+ enumerable: true,
1031
+ configurable: true,
1032
+ writable: true,
1033
+ value: new Set()
1034
+ });
1035
+ Object.defineProperty(this, "atLineStart", {
1036
+ enumerable: true,
1037
+ configurable: true,
1038
+ writable: true,
1039
+ value: true
1040
+ });
1041
+ // Widget name -> the section it's converted to
1042
+ Object.defineProperty(this, "widgets", {
1043
+ enumerable: true,
1044
+ configurable: true,
1045
+ writable: true,
1046
+ value: void 0
1047
+ });
1048
+ // The widgets whose calls wrap text (#450)
1049
+ Object.defineProperty(this, "containerWidgets", {
1050
+ enumerable: true,
1051
+ configurable: true,
1052
+ writable: true,
1053
+ value: void 0
1054
+ });
1055
+ // Element ids targeted by <<replace>> and friends, which become labels
1056
+ Object.defineProperty(this, "targets", {
1057
+ enumerable: true,
1058
+ configurable: true,
1059
+ writable: true,
1060
+ value: new Map()
1061
+ });
1062
+ this.expr = new SugarCubeExpressions(ctx);
1063
+ this.widgets = sugarCubeWidgets(ctx.story);
1064
+ this.containerWidgets = sugarCubeContainerWidgets(ctx.story);
1065
+ }
1066
+ // A widget passage: each <<widget>> in it, converted to a section
1067
+ widgetSections(nodes) {
1068
+ const result = [];
1069
+ for (const n of nodes) {
1070
+ if (n.t != "macro" || n.name != "widget")
1071
+ continue;
1072
+ const name = /^["']?([\w-]+)/.exec(n.args)?.[1]?.toLowerCase();
1073
+ const section = name ? this.widgets.get(name) : undefined;
1074
+ if (!section)
1075
+ continue;
1076
+ // An embedded section's directives don't run, so everything is a helper
1077
+ const state = { leading: false, directives: [], nobr: false };
1078
+ this.open.clear();
1079
+ this.atLineStart = true;
1080
+ this.expr.inContainerWidget = this.containerWidgets.has(name);
1081
+ let body;
1082
+ try {
1083
+ body = this.nodes(n.clauses?.[0]?.nodes ?? [], state);
1084
+ }
1085
+ finally {
1086
+ this.expr.inContainerWidget = false;
1087
+ }
1088
+ for (const tag of [...this.open].reverse())
1089
+ body += `</${tag}>`;
1090
+ result.push({ section, converted: { directives: [], body } });
1091
+ }
1092
+ return result;
1093
+ }
1094
+ // A call to a widget embeds the widget's section, with its arguments as the parameter args, a
1095
+ // list, as _args is in SugarCube. A container widget's call wraps text, which the widget shows
1096
+ // as _contents (#450).
1097
+ widgetCall(m, section, state) {
1098
+ const items = splitMacroArgs(m.args).map(a => {
1099
+ let value;
1100
+ try {
1101
+ value = /^[^"'`$_[(\-\d\s][^\s]*$/.test(a) && !["true", "false", "null"].includes(a) ? { k: "str", v: a } : this.expr.parse(a);
1102
+ }
1103
+ catch {
1104
+ value = { k: "str", v: a };
1105
+ }
1106
+ return value;
1107
+ });
1108
+ // With no arguments, an empty list, so that a widget that changes _args doesn't change
1109
+ // the story's attribute
1110
+ const params = items.length || sugarCubeWidgetsUsingArgs(this.ctx.story).has(m.name)
1111
+ ? ` ${this.expr.attribute("args", true)}=${print({ k: "array", items })}`
1112
+ : "";
1113
+ const name = print({ k: "str", v: section });
1114
+ if (m.clauses)
1115
+ return `{{#embed ${name}${params}}}${this.body(m, state)}{{/embed}}`;
1116
+ return `{{embed ${name}${params}}}`;
1117
+ }
1118
+ // Finds the ids that <<replace "#id">> and friends change, so they can be labels
1119
+ findTargets(source) {
1120
+ for (const m of source.matchAll(/<<(?:replace|append|prepend|remove)\s+["']#([\w-]+)["']/g)) {
1121
+ if (!this.targets.has(m[1]))
1122
+ this.targets.set(m[1], this.ctx.newLabel(m[1]));
1123
+ }
1124
+ let result = source;
1125
+ for (const [id, label] of this.targets) {
1126
+ const span = new RegExp(`<(span|div)\\b[^>]*\\bid=["']${id}["'][^>]*>([^<]*)</\\1>`, "g");
1127
+ result = result.replace(span, (_m, _tag, inner) => `\uE000label ${label}\uE001${inner}\uE000/label\uE001`);
1128
+ }
1129
+ return result;
1130
+ }
1131
+ passage(nodes, nobr) {
1132
+ const state = { leading: true, directives: [], nobr };
1133
+ nodes = topScripts(this.ctx, nodes, state.directives);
1134
+ let body = this.nodes(nodes, state);
1135
+ for (const tag of [...this.open].reverse())
1136
+ body += `</${tag}>`;
1137
+ body = body.replace(/\uE000label ([\w-]+)\uE001/g, "{{#label \"$1\"}}").replace(/\uE000\/label\uE001/g, "{{/label}}");
1138
+ return { directives: state.directives, body: withoutSilentSpaces(body) };
1139
+ }
1140
+ nodes(nodes, state) {
1141
+ let out = "";
1142
+ for (const node of nodes) {
1143
+ const written = this.node(node, state);
1144
+ if (node.t != "text" && written)
1145
+ this.atLineStart = false;
1146
+ out += written;
1147
+ }
1148
+ return out;
1149
+ }
1150
+ node(node, state) {
1151
+ switch (node.t) {
1152
+ case "text":
1153
+ if (node.s.trim())
1154
+ state.leading = false;
1155
+ return this.text(node.s, state);
1156
+ case "raw":
1157
+ return node.s;
1158
+ case "comment":
1159
+ return this.ctx.unconvertible(node.text, node.reason);
1160
+ case "html":
1161
+ return passageHtmlBlock(this.ctx, node, false).text;
1162
+ case "var":
1163
+ state.leading = false;
1164
+ try {
1165
+ return display(this.expr.parse(node.raw));
1166
+ }
1167
+ catch (e) {
1168
+ if (!(e instanceof Unconvertible))
1169
+ throw e;
1170
+ return this.ctx.unconvertible(node.raw, `This couldn't be converted: ${e.message}.`);
1171
+ }
1172
+ case "link":
1173
+ state.leading = false;
1174
+ return this.link(node);
1175
+ case "image": {
1176
+ state.leading = false;
1177
+ const alt = node.title ? ` alt="${escapeAttribute(node.title)}"` : "";
1178
+ if (/^data:|\.\w{2,4}$|^https?:/i.test(node.src) === false) {
1179
+ this.ctx.approximate(node.raw, "Images stored in the story (Twine.image passages) aren't converted. Put the image in a file next to the story.");
1180
+ }
1181
+ const img = `<img src="${escapeAttribute(node.src)}"${alt}>`;
1182
+ if (!node.link)
1183
+ return img;
1184
+ const target = this.ctx.story.sectionFor(node.link.trim());
1185
+ return target === undefined ? img : `{{section ${print({ k: "str", v: target })} text=${print({ k: "str", v: img })}}}`;
1186
+ }
1187
+ case "macro":
1188
+ return this.macro(node, state);
1189
+ }
1190
+ }
1191
+ link(node) {
1192
+ const text = this.inlineText(node.text);
1193
+ if (isUrl(node.target))
1194
+ return urlLink(text, node.target);
1195
+ let setters = [];
1196
+ if (node.setter !== undefined) {
1197
+ try {
1198
+ setters = this.setters(node.setter);
1199
+ }
1200
+ catch (e) {
1201
+ if (!(e instanceof Unconvertible))
1202
+ throw e;
1203
+ return this.ctx.unconvertible(node.raw, `This link's setter couldn't be converted: ${e.message}.`);
1204
+ }
1205
+ }
1206
+ if (/^[$_][A-Za-z]/.test(node.target) || /\(/.test(node.target) && !this.ctx.story.sectionFor(node.target)) {
1207
+ try {
1208
+ const target = this.expr.parse(node.target);
1209
+ return dynamicSectionLink(node.text, target, setters);
1210
+ }
1211
+ catch {
1212
+ // Treated as a passage name
1213
+ }
1214
+ }
1215
+ const target = this.ctx.story.sectionFor(node.target);
1216
+ if (target === undefined) {
1217
+ this.ctx.approximate(node.raw, `There's no passage called "${node.target}".`);
1218
+ return sectionLink(text, this.ctx.story.sectionForUnknown(node.target), setters);
1219
+ }
1220
+ return sectionLink(text, target, setters);
1221
+ }
1222
+ // Converts a link's setter ([[text|passage][$x to 1]]) to Squiffy setters
1223
+ setters(source, inLink = true) {
1224
+ return this.expr.statements(source).map(s => {
1225
+ switch (s.kind) {
1226
+ case "set": return setter(s.name, s.op ?? "=", s.value, inLink);
1227
+ case "inc": return setter(s.name, "+=", s.value, inLink);
1228
+ case "dec": return setter(s.name, "-=", s.value, inLink);
1229
+ case "forget": throw new Unconvertible("forget() in a link");
1230
+ default: throw new Unconvertible("changing an array in a link");
1231
+ }
1232
+ });
1233
+ }
1234
+ inlineText(text) {
1235
+ const nodes = new Parser(text, this.containerWidgets).parse(0).nodes;
1236
+ return this.nodes(nodes, { leading: false, directives: [], nobr: true }).replace(/\n/g, " ");
1237
+ }
1238
+ text(s, state) {
1239
+ let out = "";
1240
+ for (let i = 0; i < s.length;) {
1241
+ const rest = s.substring(i, i + 200);
1242
+ if (this.atLineStart) {
1243
+ this.atLineStart = false;
1244
+ const lineEnd = rest.indexOf("\n");
1245
+ const line = lineEnd == -1 ? rest : rest.substring(0, lineEnd);
1246
+ const heading = /^(!{1,6})\s*/.exec(line);
1247
+ if (heading) {
1248
+ out += "#".repeat(heading[1].length) + " ";
1249
+ i += heading[0].length;
1250
+ continue;
1251
+ }
1252
+ const bullet = /^([*#]+)\s+/.exec(line);
1253
+ if (bullet) {
1254
+ out += " ".repeat(bullet[1].length - 1) + (bullet[1].endsWith("#") ? "1. " : "* ");
1255
+ i += bullet[0].length;
1256
+ continue;
1257
+ }
1258
+ if (/^\s*-{4,}\s*$/.test(line)) {
1259
+ out += "<hr>";
1260
+ i += line.length;
1261
+ continue;
1262
+ }
1263
+ const number = /^(\s*\d+)\.(\s)/.exec(line);
1264
+ if (number) {
1265
+ // Not a Markdown list
1266
+ out += number[1] + "&#46;" + number[2];
1267
+ i += number[0].length;
1268
+ continue;
1269
+ }
1270
+ }
1271
+ const c = s[i];
1272
+ if (c == "\n" && state.nobr) {
1273
+ // SugarCube's nobr makes a run of line breaks one space
1274
+ while (i < s.length && /\s/.test(s[i]))
1275
+ i++;
1276
+ out += " ";
1277
+ continue;
1278
+ }
1279
+ if (c == "\n") {
1280
+ out += "\n";
1281
+ this.atLineStart = !state.nobr;
1282
+ i++;
1283
+ continue;
1284
+ }
1285
+ if (c == "\\" && s[i + 1] == "\n") {
1286
+ // Joins the line to the next
1287
+ i += 2;
1288
+ continue;
1289
+ }
1290
+ const style = /^@@([^;@]*);/.exec(rest);
1291
+ if (style) {
1292
+ const end = s.indexOf("@@", i + style[0].length);
1293
+ if (end != -1) {
1294
+ out += `<span${cssAttributes(style[1])}>`;
1295
+ // The text in it is converted with the rest, and @@ closes the span
1296
+ this.open.add("span@@");
1297
+ i += style[0].length;
1298
+ continue;
1299
+ }
1300
+ }
1301
+ if (rest.startsWith("@@") && this.open.has("span@@")) {
1302
+ this.open.delete("span@@");
1303
+ out += "</span>";
1304
+ i += 2;
1305
+ continue;
1306
+ }
1307
+ const toggle = this.toggle(s, i);
1308
+ if (toggle) {
1309
+ out += toggle.text;
1310
+ i += toggle.length;
1311
+ continue;
1312
+ }
1313
+ if (c == "<") {
1314
+ const tag = /^<\/?[A-Za-z][^<>]*>/.exec(rest);
1315
+ if (tag) {
1316
+ out += this.htmlTag(tag[0]);
1317
+ i += tag[0].length;
1318
+ continue;
1319
+ }
1320
+ }
1321
+ out += escapeProse(s, i);
1322
+ i++;
1323
+ }
1324
+ return out;
1325
+ }
1326
+ // An HTML tag, with SugarCube's data-passage links turned into Squiffy links
1327
+ htmlTag(tag) {
1328
+ tag = tag.replace(/\{\{/g, "&#123;{").replace(/\[/g, "&#91;").replace(/\]/g, "&#93;");
1329
+ // SugarCube's attribute directives, e.g. @class="_name", whose value is an expression
1330
+ return tag.replace(/(\s)@([\w-]+)=(?:"([^"]*)"|'([^']*)')/g, (whole, space, name, double, single) => {
1331
+ const source = (double ?? single ?? "").replace(/&#91;/g, "[").replace(/&#93;/g, "]").replace(/&#123;\{/g, "{{");
1332
+ try {
1333
+ return `${space}${name}="${display(this.expr.parse(source))}"`;
1334
+ }
1335
+ catch (e) {
1336
+ if (!(e instanceof Unconvertible))
1337
+ throw e;
1338
+ // Left in, it would stop the tag being HTML at all
1339
+ this.ctx.approximate(whole.trim(), `This attribute was left out, as its value couldn't be converted: ${e.message}.`);
1340
+ return "";
1341
+ }
1342
+ });
1343
+ }
1344
+ toggle(s, i) {
1345
+ const marks = [["''", "b"], ["//", "i"], ["__", "u"], ["==", "s"], ["^^", "sup"], ["~~", "sub"]];
1346
+ for (const [mark, tag] of marks) {
1347
+ if (!s.startsWith(mark, i))
1348
+ continue;
1349
+ if (mark == "//" && s[i - 1] == ":")
1350
+ return null;
1351
+ if (this.open.has(tag)) {
1352
+ this.open.delete(tag);
1353
+ return { text: `</${tag}>`, length: mark.length };
1354
+ }
1355
+ const end = s.indexOf(mark, i + mark.length);
1356
+ if (end == -1)
1357
+ return null;
1358
+ this.open.add(tag);
1359
+ return { text: `<${tag}>`, length: mark.length };
1360
+ }
1361
+ return null;
1362
+ }
1363
+ // ---- Macros ----
1364
+ // <<audio "tracks" actions>>
1365
+ audio(m, args) {
1366
+ const tracks = args[0] && /^["']/.test(args[0]) ? unescapeString(args[0]) : null;
1367
+ if (tracks === null)
1368
+ throw new Unconvertible("<<audio>> with tracks that aren't fixed");
1369
+ const action = { play: false, stop: false, loop: false };
1370
+ const num = (i) => {
1371
+ const raw = args[i] && /^["']/.test(args[i]) ? unescapeString(args[i]) : args[i];
1372
+ const n = Number(raw);
1373
+ if (raw === undefined || raw.trim() === "" || isNaN(n))
1374
+ throw new Unconvertible(`<<audio>> with "${args[i - 1]}" and a value that isn't a fixed number`);
1375
+ return n;
1376
+ };
1377
+ for (let i = 1; i < args.length; i++) {
1378
+ const word = args[i].toLowerCase();
1379
+ switch (word) {
1380
+ case "play":
1381
+ case "fadein":
1382
+ action.play = true;
1383
+ break;
1384
+ case "stop":
1385
+ case "fadeout":
1386
+ action.stop = true;
1387
+ break;
1388
+ case "loop":
1389
+ action.loop = true;
1390
+ break;
1391
+ case "unloop":
1392
+ break;
1393
+ case "volume":
1394
+ action.volume = num(++i);
1395
+ break;
1396
+ case "fadeoverto":
1397
+ case "fadeto": {
1398
+ if (word == "fadeoverto")
1399
+ action.fade = num(++i);
1400
+ const level = num(++i);
1401
+ if (level > 0)
1402
+ action.play = true;
1403
+ else
1404
+ action.stop = true;
1405
+ break;
1406
+ }
1407
+ case "pause":
1408
+ throw new Unconvertible("pausing a track");
1409
+ case "mute":
1410
+ case "unmute":
1411
+ throw new Unconvertible("muting a track");
1412
+ case "time":
1413
+ throw new Unconvertible("playing a track from part of the way through");
1414
+ case "goto":
1415
+ throw new Unconvertible("<<audio>> with goto");
1416
+ default:
1417
+ throw new Unconvertible(`<<audio>> with "${args[i]}"`);
1418
+ }
1419
+ }
1420
+ const audio = sugarCubeAudio(this.ctx.story);
1421
+ const ids = tracks.split(/\s+/).filter(t => t);
1422
+ const results = new Set();
1423
+ for (const id of ids) {
1424
+ if (id.startsWith(":")) {
1425
+ // A group: only stopping it can be converted. Looped tracks are music.
1426
+ if (!action.stop || !/^:(all|playing|looped)$/.test(id))
1427
+ throw new Unconvertible("audio groups");
1428
+ if (id != ":looped")
1429
+ results.add("{{stopsounds}}");
1430
+ results.add(`{{stopmusic${action.fade === undefined ? "" : ` fade=${action.fade}`}}}`);
1431
+ continue;
1432
+ }
1433
+ results.add(audioHelper(this.ctx, m.raw, audio, id, action));
1434
+ }
1435
+ return [...results].join("");
1436
+ }
1437
+ macro(m, state) {
1438
+ try {
1439
+ return this.macroOrThrow(m, state);
1440
+ }
1441
+ catch (e) {
1442
+ if (!(e instanceof Unconvertible))
1443
+ throw e;
1444
+ state.leading = false;
1445
+ return this.ctx.unconvertible(m.raw, `This couldn't be converted: ${e.message}.`);
1446
+ }
1447
+ }
1448
+ body(m, state, clause = 0) {
1449
+ return this.nodes(m.clauses?.[clause]?.nodes ?? [], { ...state, leading: false });
1450
+ }
1451
+ macroOrThrow(m, state) {
1452
+ const args = splitMacroArgs(m.args);
1453
+ switch (m.name) {
1454
+ case "set":
1455
+ return this.set(this.expr.statements(m.args), state);
1456
+ case "unset": {
1457
+ const statements = m.args.split(",").map(a => {
1458
+ const match = /^\s*([$_])([A-Za-z_]\w*)\s*$/.exec(a);
1459
+ if (!match)
1460
+ throw new Unconvertible("<<unset>> of something other than a variable");
1461
+ return { kind: "unset", name: this.expr.attribute(match[2], match[1] == "_") };
1462
+ });
1463
+ return this.set(statements, state);
1464
+ }
1465
+ case "run": {
1466
+ return this.set(this.expr.statements(m.args), state);
1467
+ }
1468
+ case "print":
1469
+ state.leading = false;
1470
+ return display(this.expr.parse(m.args));
1471
+ case "if": {
1472
+ state.leading = false;
1473
+ const clauses = m.clauses;
1474
+ let out = "";
1475
+ clauses.forEach((c, n) => {
1476
+ const cond = c.name == "else" ? null : this.expr.parse(c.args);
1477
+ out += n == 0 ? `{{#if ${print(cond)}}}` : cond ? `{{else if ${print(cond)}}}` : "{{else}}";
1478
+ out += this.nodes(c.nodes, { ...state, leading: false });
1479
+ });
1480
+ return out + "{{/if}}";
1481
+ }
1482
+ case "switch": {
1483
+ state.leading = false;
1484
+ const subject = this.expr.parse(m.args);
1485
+ let out = "";
1486
+ let first = true;
1487
+ for (const c of m.clauses.slice(1)) {
1488
+ let cond = null;
1489
+ if (c.name == "case") {
1490
+ const values = splitMacroArgs(c.args).map(a => this.expr.parse(a));
1491
+ cond = values.map((v) => ({ k: "bin", op: "=", l: subject, r: v }))
1492
+ .reduce((a, b) => ({ k: "bin", op: "or", l: a, r: b }));
1493
+ }
1494
+ out += first ? (cond ? `{{#if ${print(cond)}}}` : "{{#if true}}") : cond ? `{{else if ${print(cond)}}}` : "{{else}}";
1495
+ first = false;
1496
+ out += this.nodes(c.nodes, { ...state, leading: false });
1497
+ }
1498
+ return first ? "" : out + "{{/if}}";
1499
+ }
1500
+ case "include":
1501
+ case "display": {
1502
+ state.leading = false;
1503
+ const target = this.expr.passageName(args[0] ?? "");
1504
+ if ("name" in target)
1505
+ return `{{embed ${print({ k: "str", v: this.sectionName(target.name, m.raw) })}}}`;
1506
+ return `{{embed ${print(target.expr)}}}`;
1507
+ }
1508
+ case "goto":
1509
+ state.leading = false;
1510
+ return this.goto(args[0] ?? "", m.raw);
1511
+ case "link":
1512
+ case "button":
1513
+ case "click":
1514
+ state.leading = false;
1515
+ return this.linkMacro(m, args);
1516
+ case "linkreplace":
1517
+ case "linkappend":
1518
+ case "linkprepend": {
1519
+ state.leading = false;
1520
+ const text = this.linkText(args[0] ?? "");
1521
+ const content = this.body(m, state);
1522
+ const label = this.ctx.newLabel(text.plain);
1523
+ const replacement = m.name == "linkreplace" ? content : m.name == "linkappend" ? text.squiffy + content : content + text.squiffy;
1524
+ const passage = this.ctx.addPassage(text.plain, `{{#replace "${label}"}}${replacement}{{/replace}}`);
1525
+ return `{{#label "${label}"}}${passageLink(text.squiffy, passage)}{{/label}}`;
1526
+ }
1527
+ case "actions":
1528
+ case "choice": {
1529
+ state.leading = false;
1530
+ const links = args.map(a => {
1531
+ const target = this.expr.passageName(a);
1532
+ if (!("name" in target))
1533
+ throw new Unconvertible(`<<${m.name}>> with a passage that isn't fixed`);
1534
+ return sectionLink(escapeText(target.name), this.sectionName(target.name, m.raw));
1535
+ });
1536
+ return m.name == "actions" ? "\n" + links.map(l => `* ${l}`).join("\n") + "\n" : links.join(" ");
1537
+ }
1538
+ case "nobr":
1539
+ return this.nodes(m.clauses[0].nodes, { ...state, nobr: true });
1540
+ case "silently": {
1541
+ const content = this.nodes(m.clauses[0].nodes, state);
1542
+ // Only the helpers, which write nothing
1543
+ return (content.match(/\{\{(?:[^{}]|\{\{[^{}]*\}\})*\}\}/g) ?? []).join("");
1544
+ }
1545
+ case "do":
1546
+ return this.doMacro(m, state);
1547
+ case "redo":
1548
+ return this.redo(m);
1549
+ case "capture":
1550
+ case "done":
1551
+ if (m.name == "done")
1552
+ this.ctx.approximate(m.raw, "<<done>> has been converted to its contents, which are shown straight away.");
1553
+ return this.nodes(m.clauses[0].nodes, state);
1554
+ case "timed": {
1555
+ state.leading = false;
1556
+ // Each <<next>> waits after the one before, for its own delay, or, with none, the
1557
+ // delay before it. A delay can be worked out as the story runs (#451).
1558
+ let delay = { k: "num", v: 0 };
1559
+ // The time since the text was shown, while every delay is a number
1560
+ let total = 0;
1561
+ let out = "";
1562
+ m.clauses.forEach((c, i) => {
1563
+ const d = splitMacroArgs(c.args)[0];
1564
+ if (d)
1565
+ delay = this.expr.parse(d);
1566
+ total = total !== null && delay.k == "num" ? total + delay.v : null;
1567
+ const goto = this.gotoOnly(c.nodes);
1568
+ if (goto) {
1569
+ // {{goto}} waits from when the text is shown, so it needs the delays added up
1570
+ if (i > 0 && total === null)
1571
+ throw new Unconvertible("<<goto>> in a <<next>> after a delay that isn't fixed");
1572
+ out += goto.replace(/\}\}$/, ` after=${i == 0 ? delayValue(delay) : total}}}`);
1573
+ }
1574
+ else {
1575
+ // Animations play one after another, so each waits after the one before
1576
+ out += `{{#animate "fadeIn" start=${delayValue(delay)}}}${this.nodes(c.nodes, { ...state, leading: false })}{{/animate}}`;
1577
+ }
1578
+ });
1579
+ return out;
1580
+ }
1581
+ case "type": {
1582
+ state.leading = false;
1583
+ const speed = this.expr.parse(args[0] ?? "40ms");
1584
+ const interval = speed.k == "num" ? ` interval=${speed.v}` : "";
1585
+ return `{{#animate "typewriter"${interval}}}${this.body(m, state)}{{/animate}}`;
1586
+ }
1587
+ case "textbox":
1588
+ case "textarea":
1589
+ case "numberbox": {
1590
+ state.leading = false;
1591
+ const bound = this.receiver(args[0] ?? "");
1592
+ const defaultValue = args[1] ? this.expr.parse(args[1]) : null;
1593
+ // <<textbox>> and <<numberbox>> can go to a passage when Enter is pressed (#454)
1594
+ const passageArg = m.name == "textarea" ? undefined : args.slice(2).find(a => a != "autofocus");
1595
+ let goes = "";
1596
+ if (passageArg !== undefined) {
1597
+ const target = this.expr.passageName(passageArg);
1598
+ if (!("name" in target))
1599
+ throw new Unconvertible(`<<${m.name}>> going to a passage whose name isn't fixed`);
1600
+ goes = ` data-section="${escapeAttribute(this.sectionName(target.name, m.raw))}"`;
1601
+ }
1602
+ const value = defaultValue?.k == "str" || defaultValue?.k == "num" ? String(defaultValue.v) : null;
1603
+ const set = defaultValue ? `{{set "${bound}" ${print(defaultValue)}}}` : "";
1604
+ if (m.name == "textarea")
1605
+ return `${set}<textarea data-attribute="${bound}">${escapeText(escapeHtml(value ?? ""))}</textarea>`;
1606
+ const type = m.name == "numberbox" ? "number" : "text";
1607
+ return `${set}<input type="${type}" data-attribute="${bound}"${value === null ? "" : ` value="${escapeAttribute(value)}"`}${goes}>`;
1608
+ }
1609
+ case "checkbox": {
1610
+ state.leading = false;
1611
+ const bound = this.receiver(args[0] ?? "");
1612
+ this.ctx.approximate(m.raw, "Check how this checkbox works in Squiffy.");
1613
+ return `<input type="checkbox" data-attribute="${bound}">`;
1614
+ }
1615
+ case "radiobutton": {
1616
+ state.leading = false;
1617
+ const bound = this.receiver(args[0] ?? "");
1618
+ const value = this.expr.parse(args[1] ?? "");
1619
+ if (value.k != "str" && value.k != "num")
1620
+ throw new Unconvertible("<<radiobutton>> with a value that isn't fixed");
1621
+ this.ctx.approximate(m.raw, "Check how this radio button works in Squiffy.");
1622
+ return `<input type="radio" name="${bound}" data-attribute="${bound}" value="${escapeAttribute(String(value.v))}">`;
1623
+ }
1624
+ case "cycle":
1625
+ case "listbox": {
1626
+ state.leading = false;
1627
+ const bound = this.receiver(args[0] ?? "");
1628
+ const options = [];
1629
+ for (const c of m.clauses.slice(1)) {
1630
+ if (c.name == "optionsfrom")
1631
+ throw new Unconvertible("<<optionsfrom>>");
1632
+ const [label, value] = splitMacroArgs(c.args).map(a => this.expr.parse(a));
1633
+ if (label?.k != "str" && label?.k != "num")
1634
+ throw new Unconvertible("an option that isn't fixed text");
1635
+ const v = value ? value : label;
1636
+ if (v.k != "str" && v.k != "num")
1637
+ throw new Unconvertible("an option that isn't fixed text");
1638
+ options.push({ label: String(label.v), value: String(v.v) });
1639
+ }
1640
+ if (m.name == "listbox") {
1641
+ return `<select data-attribute="${bound}">${options.map(o => `<option value="${escapeAttribute(o.value)}">${escapeText(escapeHtml(o.label))}</option>`).join("")}</select>`;
1642
+ }
1643
+ if (options.some(o => o.label != o.value)) {
1644
+ this.ctx.approximate(m.raw, "Squiffy's {{rotate}} sets the attribute to the text shown, not the option's value.");
1645
+ }
1646
+ return `{{rotate ${print({ k: "array", items: options.map(o => ({ k: "str", v: o.label })) })} set="${bound}"}}`;
1647
+ }
1648
+ case "replace":
1649
+ case "append":
1650
+ case "prepend":
1651
+ case "remove": {
1652
+ state.leading = false;
1653
+ const target = /^["']#([\w-]+)["']$/.exec(args[0] ?? "");
1654
+ if (!target)
1655
+ throw new Unconvertible(`<<${m.name}>> on something other than an element with an id ("#id")`);
1656
+ const label = this.targets.get(target[1]);
1657
+ const content = m.name == "remove" ? "" : this.body(m, state);
1658
+ if (m.name == "append" || m.name == "prepend") {
1659
+ this.ctx.approximate(m.raw, `<<${m.name}>> has been converted to {{#replace}}, which replaces the text rather than adding to it.`);
1660
+ }
1661
+ return `{{#replace "${label}"}}${content}{{/replace}}`;
1662
+ }
1663
+ case "script":
1664
+ throw new Unconvertible("<<script>>, which runs SugarCube JavaScript");
1665
+ case "for": {
1666
+ state.leading = false;
1667
+ if (/<<\s*(?:break|continue)\s*>>/.test(m.raw))
1668
+ throw new Unconvertible("<<break>> and <<continue>>");
1669
+ const loop = this.forLoop(m.args);
1670
+ const numbers = loop.numbers || (loop.collection.k == "call" && loop.collection.fn == "range");
1671
+ const body = this.ctx.story.inLoop(loop.vars, loop.array, () => this.body(m, state), numbers);
1672
+ const collection = print(loop.collection);
1673
+ return `{{#each ${loop.collection.k == "cond" ? `(${collection})` : collection}}}${body}{{/each}}`;
1674
+ }
1675
+ case "widget":
1676
+ return "";
1677
+ case "back":
1678
+ case "return":
1679
+ // Left out on purpose (#445): a screen the player visits and leaves is a panel in Squiffy
1680
+ throw new Unconvertible(`<<${m.name}>>. For a screen like an inventory, use a panel. Squiffy has its own Back button`);
1681
+ case "audio":
1682
+ return leadingAudio(this.audio(m, args), state);
1683
+ case "cacheaudio":
1684
+ case "waitforaudio":
1685
+ // The tracks are found before the story's converted, and Squiffy loads every
1686
+ // sound file when the story starts
1687
+ return "";
1688
+ case "masteraudio":
1689
+ if (args.length == 1 && args[0].toLowerCase() == "stop")
1690
+ return leadingAudio(STOP_ALL_AUDIO, state);
1691
+ throw new Unconvertible("<<masteraudio>>, which changes all the story's sound at once, except to stop it");
1692
+ case "playlist":
1693
+ case "createplaylist":
1694
+ case "removeplaylist":
1695
+ case "track":
1696
+ throw new Unconvertible("playlists");
1697
+ case "createaudiogroup":
1698
+ case "removeaudiogroup":
1699
+ throw new Unconvertible("audio groups");
1700
+ case "addclass":
1701
+ case "removeclass":
1702
+ case "toggleclass": {
1703
+ // On the page (#449), which in Squiffy is the story's element. Classes on other
1704
+ // elements can't be converted.
1705
+ if (!/^["'](?:html|body|#story|#passages)["']$/i.test(args[0] ?? "")) {
1706
+ throw new Unconvertible(`<<${m.name}>> on something other than the page ("body")`);
1707
+ }
1708
+ if (args.length != 2)
1709
+ throw new Unconvertible(`<<${m.name}>> without one class to change`);
1710
+ state.leading = false;
1711
+ return `{{${m.name} ${print(this.expr.parse(args[1]))}}}`;
1712
+ }
1713
+ case "repeat": {
1714
+ // <<repeat 1s>>: its text is added again every second, until a <<stop>> (#451)
1715
+ state.leading = false;
1716
+ if (!args[0])
1717
+ throw new Unconvertible("<<repeat>> without a delay");
1718
+ const delay = delayValue(this.expr.parse(args[0]));
1719
+ return `{{#every ${delay} append=true}}${this.body(m, { ...state, leading: false })}{{/every}}`;
1720
+ }
1721
+ case "stop":
1722
+ return "{{stop}}";
1723
+ case "silent":
1724
+ return "";
1725
+ case "elseif":
1726
+ case "else":
1727
+ case "case":
1728
+ case "default":
1729
+ case "next":
1730
+ case "option":
1731
+ throw new Unconvertible(`<<${m.name}>> outside the macro it belongs to`);
1732
+ default:
1733
+ if (this.widgets.has(m.name)) {
1734
+ state.leading = false;
1735
+ return this.widgetCall(m, this.widgets.get(m.name), state);
1736
+ }
1737
+ if (!knownMacros.has(m.name))
1738
+ throw new Unconvertible(`the <<${m.name}>> macro, which isn't one of SugarCube's own: it's probably added by the story's JavaScript`);
1739
+ throw new Unconvertible(`the <<${m.name}>> macro, which Squiffy has no equivalent for`);
1740
+ }
1741
+ }
1742
+ // <<do>> (SugarCube 2.37): its contents, which <<redo>> shows again. They go in a section of
1743
+ // their own, which {{live}} shows, and shows again when the attribute for its tags changes.
1744
+ doMacro(m, state) {
1745
+ // A section of its own wouldn't have what's only there in this one, such as a loop's item
1746
+ if (this.ctx.story.inAnyLoop)
1747
+ return this.doInline(m, state, "it's in a loop");
1748
+ const directives = [];
1749
+ const body = this.nodes(m.clauses[0].nodes, { ...state, leading: false, directives });
1750
+ const reason = /\bargs\b(?!=)|\{\{content\}\}|\(content\)/.test(body) ? "it uses the widget's _args or _contents"
1751
+ : directives.length ? "it has something that has to go at the start of a section"
1752
+ : null;
1753
+ state.leading = false;
1754
+ if (reason) {
1755
+ state.directives.push(...directives);
1756
+ return this.doInline(m, state, reason, body);
1757
+ }
1758
+ // A panel is shown again whenever an attribute changes anyway
1759
+ if (this.ctx.kind == "panel")
1760
+ return body;
1761
+ const attribute = quote(redoAttribute(doTags(m.clauses[0].args)));
1762
+ // A passage of this section, so the links in it go to this section's passages. One shown
1763
+ // inside other sections (a footer, a widget, or StoryInit's text) is a section of its own.
1764
+ if (this.ctx.kind == "story" || this.ctx.kind == "header") {
1765
+ return `{{live ${attribute} passage=${quote(this.ctx.addPassage("do", body.trim()))}}}`;
1766
+ }
1767
+ const section = this.ctx.addSection(`${this.ctx.section || this.ctx.passage.name}: do`, { directives: [], body: body.trim() });
1768
+ return `{{live ${attribute} section=${quote(section)}}}`;
1769
+ }
1770
+ doInline(m, state, reason, body) {
1771
+ this.ctx.approximate(m.raw, `<<do>> has been converted to its contents, which <<redo>> doesn't show again, as ${reason}.`);
1772
+ return body ?? this.nodes(m.clauses[0].nodes, state);
1773
+ }
1774
+ // <<redo>>: shows the <<do>>s with any of its tags again, or with none, all of them
1775
+ redo(m) {
1776
+ const tags = splitMacroArgs(m.args).flatMap(a => /^["']/.test(a) ? unescapeString(a).split(/\s+/) : [a]).filter(t => t);
1777
+ if (tags.some(t => /[$_(]/.test(t)))
1778
+ throw new Unconvertible("<<redo>> with tags that aren't fixed");
1779
+ const attributes = new Set();
1780
+ for (const tagSet of storyDoTags(this.ctx.story)) {
1781
+ if (!tags.length || tagSet.some(t => tags.includes(t)))
1782
+ attributes.add(redoAttribute(tagSet));
1783
+ }
1784
+ return [...attributes].map(a => `{{inc ${quote(a)}}}`).join("");
1785
+ }
1786
+ // What a <<for>> goes through, as {{#each}} does, and the variables (with their $ or _) that
1787
+ // stand for its item and position. It can go through an array with range, or by position:
1788
+ // <<for _i to 0; _i lt $list.length; _i++>>. Either way, $list[_i] is the item.
1789
+ forLoop(args) {
1790
+ const range = /^\s*([$_][A-Za-z_]\w*)\s*(?:,\s*([$_][A-Za-z_]\w*)\s*)?\brange\b([\s\S]+)$/.exec(args);
1791
+ if (range) {
1792
+ const vars = new Map(range[2] ? [[range[1], "index"], [range[2], "item"]] : [[range[1], "item"]]);
1793
+ const collection = this.expr.parse(range[3]);
1794
+ // A number, <<for _i range 5>>, goes through 0 to 4, with the same number as the item
1795
+ // and its position. A calculation must be a number, but an attribute could be a list.
1796
+ if (collection.k == "num" || collection.k == "neg" || (collection.k == "bin" && "+-*/%".includes(collection.op))) {
1797
+ const zero = { k: "num", v: 0 };
1798
+ const last = collection.k == "num" ? { k: "num", v: collection.v - 1 } : { k: "bin", op: "-", l: collection, r: { k: "num", v: 1 } };
1799
+ const numbers = { k: "call", fn: "range", args: [zero, last] };
1800
+ // (range 0 -1) would count down, so there's nothing to go through unless it's above 0
1801
+ const counted = collection.k == "num"
1802
+ ? (collection.v > 0 ? numbers : { k: "array", items: [] })
1803
+ : { k: "cond", test: { k: "bin", op: ">", l: collection, r: zero }, then: numbers, otherwise: { k: "array", items: [] } };
1804
+ return { collection: counted, vars: new Map([...vars.keys()].map(v => [v, "item"])), numbers: true };
1805
+ }
1806
+ if (collection.k != "var" && collection.k != "array" && !(collection.k == "loop" && collection.kind == "item") && !isListCall(collection)) {
1807
+ throw new Unconvertible("<<for>> with range over something other than an array or a number");
1808
+ }
1809
+ // With a position as well, $list[_i] is the item too
1810
+ return { collection, vars, array: collection.k == "var" ? collection.name : undefined };
1811
+ }
1812
+ const counted = /^\s*_([A-Za-z_]\w*)\s*(?:to|=)\s*0\s*;\s*_\1\s*(?:lt|<)\s*([$_])([A-Za-z_]\w*)\.length\s*;\s*(?:_\1\s*\+\+|\+\+\s*_\1|_\1\s*\+=\s*1)\s*$/.exec(args);
1813
+ if (counted) {
1814
+ const array = this.expr.attribute(counted[3], counted[2] == "_");
1815
+ return { collection: { k: "var", name: array }, vars: new Map([["_" + counted[1], "index"]]), array };
1816
+ }
1817
+ // Counting, <<for _i to 1; _i lte 5; _i++>>, goes through (range 1 5), with _i as the item (#447)
1818
+ const counting = /^\s*_([A-Za-z_]\w*)\s*(?:to|=)\s*([^;]+);\s*_\1\s*(lte|lt|gte|gt|<=|>=|<|>)\s*([^;]+);\s*(_\1\s*\+\+|\+\+\s*_\1|_\1\s*\+=\s*1|_\1\s*--|--\s*_\1|_\1\s*-=\s*1)\s*$/.exec(args);
1819
+ if (counting) {
1820
+ const from = this.expr.parse(counting[2]);
1821
+ const bound = this.expr.parse(counting[4]);
1822
+ const up = counting[5].includes("+");
1823
+ const op = { "lt": "<", "lte": "<=", "gt": ">", "gte": ">=" }[counting[3]] ?? counting[3];
1824
+ if (up != op.startsWith("<"))
1825
+ throw new Unconvertible("a <<for>> loop that counts away from where it stops");
1826
+ // < 5 counting up stops at 4, and > 0 counting down at 1
1827
+ const to = op.length == 2 ? bound
1828
+ : bound.k == "num" ? { k: "num", v: bound.v + (up ? -1 : 1) }
1829
+ : { k: "bin", op: up ? "-" : "+", l: bound, r: { k: "num", v: 1 } };
1830
+ return { collection: { k: "call", fn: "range", args: [from, to] }, vars: new Map([["_" + counting[1], "item"]]) };
1831
+ }
1832
+ throw new Unconvertible("<<for>> loops, except ones that go through an array (with range), or count up or down by 1");
1833
+ }
1834
+ // The attribute a form macro like <<textbox "$name">> sets, or the value inside an object,
1835
+ // as in <<textbox "$hero.name">> (#454)
1836
+ receiver(arg) {
1837
+ const match = /^(["'])([$_][\s\S]*)\1$/.exec(arg);
1838
+ const e = match ? this.expr.parse(match[2]) : null;
1839
+ if (e?.k != "var" || isDynamicTarget(e.name)) {
1840
+ throw new Unconvertible("a form control that doesn't set a variable, or a value inside one with a fixed name");
1841
+ }
1842
+ return e.name;
1843
+ }
1844
+ linkText(arg) {
1845
+ if (arg.startsWith("[[")) {
1846
+ const node = parseLink(arg.slice(2, -2), arg);
1847
+ return { plain: node.text, squiffy: this.inlineText(node.text) };
1848
+ }
1849
+ // SugarCube reads a bare word that isn't a variable, a number or true, false, null,
1850
+ // undefined or NaN, or in setup or settings, as text: <<linkreplace Hint>>
1851
+ const bare = arg.trim();
1852
+ if (/^[^"'`$_[(\s\d-][^\s()]*$/.test(bare) && !/^(true|false|null|undefined|NaN|setup\..*|settings\..*)$/.test(bare)) {
1853
+ return { plain: bare, squiffy: this.inlineText(bare) };
1854
+ }
1855
+ const e = this.expr.parse(arg);
1856
+ if (e.k == "str")
1857
+ return { plain: e.v, squiffy: this.inlineText(e.v) };
1858
+ // Text worked out as the story runs, e.g. a loop's item: named after the expression
1859
+ return { plain: arg.replace(/[^\w\s]+/g, " ").trim() || "link", squiffy: display(e) };
1860
+ }
1861
+ sectionName(passage, raw) {
1862
+ const section = this.ctx.story.sectionFor(passage);
1863
+ if (section === undefined) {
1864
+ this.ctx.approximate(raw, `There's no passage called "${passage}".`);
1865
+ return this.ctx.story.sectionForUnknown(passage);
1866
+ }
1867
+ return section;
1868
+ }
1869
+ goto(arg, raw) {
1870
+ const target = this.expr.passageName(arg);
1871
+ if ("name" in target)
1872
+ return `{{goto ${print({ k: "str", v: this.sectionName(target.name, raw) })}}}`;
1873
+ return `{{goto ${print(target.expr)}}}`;
1874
+ }
1875
+ gotoOnly(nodes) {
1876
+ const significant = nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
1877
+ if (significant.length != 1)
1878
+ return null;
1879
+ const n = significant[0];
1880
+ if (n.t != "macro" || n.name != "goto")
1881
+ return null;
1882
+ return this.goto(splitMacroArgs(n.args)[0] ?? "", n.raw);
1883
+ }
1884
+ // <<link>>, <<button>>: the body runs when it's clicked, then the story goes to the passage
1885
+ // given, if there is one
1886
+ // "restart", "saves" or "settings", if a link's body is only <<run UI.restart()>>,
1887
+ // UI.saves() or UI.settings(), or the same in <<script>>
1888
+ uiAction(body) {
1889
+ if (body.length != 1 || body[0].t != "macro")
1890
+ return null;
1891
+ const m = body[0];
1892
+ const code = m.name == "run" ? m.args
1893
+ : m.name == "script" ? (m.clauses?.[0]?.nodes ?? []).map(n => n.t == "text" || n.t == "raw" ? n.s : "\0").join("")
1894
+ : null;
1895
+ const match = code === null ? null : /^\s*UI\.(restart|saves|settings)\(\s*\)\s*;?\s*$/.exec(code);
1896
+ return match ? match[1] : null;
1897
+ }
1898
+ linkMacro(m, args) {
1899
+ let text;
1900
+ let passage = null;
1901
+ let setters = [];
1902
+ let setterSource = null;
1903
+ let dynamicDestination = null;
1904
+ if (args[0]?.startsWith("[[")) {
1905
+ const link = /^\[\[(.*?)\](?:\[(.*)\])?\]$/.exec(args[0]);
1906
+ if (!link)
1907
+ throw new Unconvertible("a link Squiffy can't read");
1908
+ const node = parseLink(link[1], args[0]);
1909
+ text = { plain: node.text, squiffy: this.inlineText(node.text) };
1910
+ passage = node.target;
1911
+ if (link[2]) {
1912
+ setters = this.setters(link[2]);
1913
+ setterSource = link[2];
1914
+ }
1915
+ }
1916
+ else {
1917
+ text = this.linkText(args[0] ?? "");
1918
+ if (args[1]) {
1919
+ const target = this.expr.passageName(args[1]);
1920
+ if ("name" in target)
1921
+ passage = target.name;
1922
+ else
1923
+ dynamicDestination = target.expr;
1924
+ }
1925
+ }
1926
+ const body = m.clauses?.[0]?.nodes ?? [];
1927
+ const significant = body.filter(n => !(n.t == "text" && n.s.trim() == ""));
1928
+ // A trailing <<goto>> is where the link goes
1929
+ const last = significant[significant.length - 1];
1930
+ let gotoArg = null;
1931
+ if (last?.t == "macro" && last.name == "goto") {
1932
+ gotoArg = splitMacroArgs(last.args)[0] ?? "";
1933
+ significant.pop();
1934
+ }
1935
+ const destination = gotoArg !== null ? this.expr.passageName(gotoArg)
1936
+ : passage !== null ? { name: passage }
1937
+ : dynamicDestination ? { expr: dynamicDestination } : null;
1938
+ // A link that only runs UI.restart(), UI.saves() or UI.settings(): {{restart}}, {{saves}}
1939
+ // or {{settings}} (#452). Like
1940
+ // SugarCube's, {{restart}} asks the player first.
1941
+ const uiAction = destination ? null : this.uiAction(significant);
1942
+ if (uiAction)
1943
+ return `{{${uiAction} text=${quote(text.plain)}}}`;
1944
+ // Only <<set>>s: a link with setters
1945
+ const bodySetters = this.bodySetters(significant);
1946
+ if (destination && bodySetters) {
1947
+ const all = [...setters, ...bodySetters];
1948
+ if ("name" in destination)
1949
+ return sectionLink(text.squiffy, this.sectionName(destination.name, m.raw), all);
1950
+ return dynamicSectionLink(text.plain, destination.expr, all);
1951
+ }
1952
+ const state = { leading: true, directives: [], nobr: false };
1953
+ // In a loop, the body can use the loop's item, which the link sets an attribute to (#448)
1954
+ const { result: [content, directives], setters: loopSetters } = this.ctx.story.linkBody(() => {
1955
+ const content = this.nodes(body, state);
1956
+ return [content, [...(setterSource === null ? [] : this.setters(setterSource, false).map(s => `@set ${s}`)), ...state.directives]];
1957
+ });
1958
+ if (destination) {
1959
+ // Run the body in a section of its own, which then goes on to the passage
1960
+ const goto = gotoArg !== null ? "" : "\n" + ("name" in destination
1961
+ ? `{{goto ${print({ k: "str", v: this.sectionName(destination.name, m.raw) })}}}`
1962
+ : `{{goto ${print(destination.expr)}}}`);
1963
+ const section = this.ctx.addSection(`${this.ctx.section}: ${text.plain}`, { directives: [...directives], body: content + goto });
1964
+ return sectionLink(text.squiffy, section, loopSetters);
1965
+ }
1966
+ // Stays in this passage: a passage link, whose passage does what the body does
1967
+ const name = this.ctx.addPassage(text.plain, { directives: [...directives], body: content });
1968
+ return passageLink(text.squiffy, name, loopSetters);
1969
+ }
1970
+ // The setters for nodes that are only <<set>>s, or null
1971
+ bodySetters(nodes) {
1972
+ const result = [];
1973
+ for (const n of nodes) {
1974
+ if (n.t != "macro" || n.name != "set")
1975
+ return null;
1976
+ try {
1977
+ result.push(...this.setters(n.args));
1978
+ }
1979
+ catch (e) {
1980
+ if (e instanceof Unconvertible)
1981
+ return null;
1982
+ throw e;
1983
+ }
1984
+ }
1985
+ return result;
1986
+ }
1987
+ set(statements, state) {
1988
+ let out = "";
1989
+ for (const s of statements) {
1990
+ if (state.leading) {
1991
+ switch (s.kind) {
1992
+ case "set":
1993
+ state.directives.push(`@set ${setter(s.name, s.op ?? "=", s.value, false)}`);
1994
+ continue;
1995
+ case "inc":
1996
+ case "dec": {
1997
+ const amount = s.value.k == "num" && Number.isInteger(s.value.v) && s.value.v >= 0 ? s.value.v : null;
1998
+ state.directives.push(amount === null || isDynamicTarget(s.name)
1999
+ ? `@set ${setter(s.name, s.kind == "inc" ? "+=" : "-=", s.value, false)}`
2000
+ : `@${s.kind} ${s.name}${amount == 1 ? "" : " " + amount}`);
2001
+ continue;
2002
+ }
2003
+ case "unset":
2004
+ state.directives.push(`@unset ${s.name}`);
2005
+ continue;
2006
+ }
2007
+ }
2008
+ state.leading = false;
2009
+ if (s.kind == "forget") {
2010
+ out += `{{forget${s.names.map(n => " " + print({ k: "str", v: n })).join("")}}}`;
2011
+ continue;
2012
+ }
2013
+ if (isDynamicTarget(s.name))
2014
+ throw new Unconvertible("setting a value inside an object or list, by a variable's value, after the start of the passage");
2015
+ const name = print({ k: "str", v: s.name });
2016
+ switch (s.kind) {
2017
+ case "set":
2018
+ out += s.op
2019
+ ? `{{set ${name} ${print({ k: "bin", op: s.op == "*=" ? "*" : "/", l: { k: "var", name: s.name }, r: s.value })}}}`
2020
+ : `{{set ${name} ${print(s.value)}}}`;
2021
+ break;
2022
+ case "inc":
2023
+ case "dec":
2024
+ out += s.value.k == "num" && s.value.v == 1 ? `{{${s.kind} ${name}}}` : `{{${s.kind} ${name} ${print(s.value)}}}`;
2025
+ break;
2026
+ case "append":
2027
+ case "remove":
2028
+ out += `{{${s.kind} ${name} ${print(s.value)}}}`;
2029
+ break;
2030
+ case "unset":
2031
+ out += `{{unset ${name}}}`;
2032
+ break;
2033
+ }
2034
+ }
2035
+ return out;
2036
+ }
2037
+ }
2038
+ const knownMacros = new Set([
2039
+ "capture", "set", "unset", "run", "script", "include", "nobr", "print", "silently", "type", "if", "switch", "for",
2040
+ "break", "continue", "back", "return", "actions", "choice", "link", "button", "linkappend", "linkprepend",
2041
+ "linkreplace", "checkbox", "cycle", "listbox", "numberbox", "radiobutton", "textarea", "textbox", "addclass",
2042
+ "append", "copy", "prepend", "remove", "removeclass", "replace", "toggleclass", "audio", "cacheaudio",
2043
+ "createaudiogroup", "createplaylist", "masteraudio", "playlist", "removeaudiogroup", "removeplaylist",
2044
+ "waitforaudio", "done", "goto", "repeat", "stop", "timed", "widget", "display", "click", "do", "redo", "track",
2045
+ ]);
2046
+ // The story's tracks: the files <<cacheaudio>> gives them, and the ones <<audio>> sets to loop
2047
+ export function sugarCubeAudio(story) {
2048
+ return story.cached("sugarcube-audio", () => {
2049
+ const audio = { files: new Map(), looping: new Set() };
2050
+ const strings = (args) => splitMacroArgs(args).filter(a => /^["']/.test(a)).map(unescapeString);
2051
+ for (const p of story.twine.passages) {
2052
+ for (const m of p.text.matchAll(/<<\s*cacheaudio\s+([\s\S]*?)>>/g)) {
2053
+ const [track, ...sources] = strings(m[1]);
2054
+ // A source can say its format first: "mp3|music/theme.mp3"
2055
+ const file = pickSource(sources.map(s => s.replace(/^\w+\|/, "")));
2056
+ if (track && file && !audio.files.has(track))
2057
+ audio.files.set(track, file);
2058
+ }
2059
+ for (const m of p.text.matchAll(/<<\s*audio\s+([\s\S]*?)>>/g)) {
2060
+ const args = splitMacroArgs(m[1]);
2061
+ if (!args.slice(1).some(a => a.toLowerCase() == "loop") || !/^["']/.test(args[0] ?? ""))
2062
+ continue;
2063
+ for (const track of unescapeString(args[0]).split(/\s+/))
2064
+ if (track)
2065
+ audio.looping.add(track);
2066
+ }
2067
+ }
2068
+ // Tracks added in the story's JavaScript
2069
+ for (const m of story.twine.script.matchAll(/SimpleAudio\.tracks\.add\(\s*(["'])([^"']+)\1\s*,\s*(["'])([^"']+)\3/g)) {
2070
+ if (!audio.files.has(m[2]))
2071
+ audio.files.set(m[2], m[4].replace(/^\w+\|/, ""));
2072
+ }
2073
+ return audio;
2074
+ });
2075
+ }
2076
+ // The story's widgets, by name, with the section each is converted to
2077
+ export function sugarCubeWidgets(story) {
2078
+ return story.cached("sugarcube-widgets", () => {
2079
+ const result = new Map();
2080
+ for (const p of story.twine.passages) {
2081
+ if (!p.tags.includes("widget"))
2082
+ continue;
2083
+ for (const m of p.text.matchAll(/<<widget\s+["']?([\w-]+)/g)) {
2084
+ const name = m[1].toLowerCase();
2085
+ if (!result.has(name))
2086
+ result.set(name, story.uniqueSectionName(`widget ${name}`));
2087
+ }
2088
+ }
2089
+ return result;
2090
+ });
2091
+ }
2092
+ // The story's widgets that use _args (#450)
2093
+ function sugarCubeWidgetsUsingArgs(story) {
2094
+ return story.cached("sugarcube-widgets-using-args", () => {
2095
+ const result = new Set();
2096
+ for (const p of story.twine.passages) {
2097
+ if (!p.tags.includes("widget"))
2098
+ continue;
2099
+ for (const m of p.text.matchAll(/<<widget\s+["']?([\w-]+)["']?[^>]*>>([\s\S]*?)<<\/widget>>/g)) {
2100
+ if (/\b_args\b/.test(m[2]))
2101
+ result.add(m[1].toLowerCase());
2102
+ }
2103
+ }
2104
+ return result;
2105
+ });
2106
+ }
2107
+ // The story's container widgets (#450), <<widget "name" container>>, whose calls wrap text
2108
+ function sugarCubeContainerWidgets(story) {
2109
+ return story.cached("sugarcube-container-widgets", () => {
2110
+ const result = new Set();
2111
+ for (const p of story.twine.passages) {
2112
+ if (!p.tags.includes("widget"))
2113
+ continue;
2114
+ for (const m of p.text.matchAll(/<<widget\s+["']?([\w-]+)["']?([^>]*)>>/g)) {
2115
+ if (/\bcontainer\b/.test(m[2]))
2116
+ result.add(m[1].toLowerCase());
2117
+ }
2118
+ }
2119
+ return result;
2120
+ });
2121
+ }
2122
+ export function convertSugarCubeWidgets(text, ctx) {
2123
+ const writer = new Writer(ctx);
2124
+ const nodes = new Parser(writer.findTargets(text.replace(/\\\r?\n/g, "")), writer.containerWidgets).parse(0).nodes;
2125
+ return writer.widgetSections(nodes);
2126
+ }
2127
+ function cssAttributes(spec) {
2128
+ const classes = [];
2129
+ const styles = [];
2130
+ let id = "";
2131
+ for (const part of spec.split(/\s+/).filter(p => p)) {
2132
+ if (part.startsWith("."))
2133
+ classes.push(...part.substring(1).split(".").filter(c => c));
2134
+ else if (part.startsWith("#"))
2135
+ id = part.substring(1);
2136
+ else
2137
+ styles.push(part);
2138
+ }
2139
+ let attrs = "";
2140
+ if (id)
2141
+ attrs += ` id="${escapeAttribute(id)}"`;
2142
+ if (classes.length)
2143
+ attrs += ` class="${escapeAttribute(classes.join(" "))}"`;
2144
+ if (styles.length)
2145
+ attrs += ` style="${escapeAttribute(styles.join(" "))}"`;
2146
+ return attrs;
2147
+ }
2148
+ function escapeAttribute(s) {
2149
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/\[/g, "&#91;").replace(/\]/g, "&#93;").replace(/\{\{/g, "&#123;{");
2150
+ }
2151
+ // A character of SugarCube prose, which isn't Markdown: * and _ would be emphasis
2152
+ function escapeProse(s, i) {
2153
+ const c = s[i];
2154
+ if (c == "*")
2155
+ return "&#42;";
2156
+ if (c == "`")
2157
+ return "&#96;";
2158
+ if (c == "_" && !(/\w/.test(s[i - 1] ?? "") && /\w/.test(s[i + 1] ?? "")))
2159
+ return "&#95;";
2160
+ if (c == "{" && s[i + 1] == "{")
2161
+ return "&#123;";
2162
+ if (c == "}" && s[i + 1] == "}")
2163
+ return "&#125;";
2164
+ return escapeText(c);
2165
+ }
2166
+ export function convertSugarCubePassage(text, ctx) {
2167
+ const writer = new Writer(ctx);
2168
+ // A backslash at the end of a line joins it to the next
2169
+ const source = writer.findTargets(text.replace(/\\\r?\n/g, ""));
2170
+ const nodes = new Parser(source, writer.containerWidgets).parse(0).nodes;
2171
+ return writer.passage(nodes, ctx.passage.tags.includes("nobr"));
2172
+ }