squiffy-compiler 7.0.0-beta.4 → 7.0.0-beta.6

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 (43) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +3 -0
  3. package/dist/analyse.js +73 -12
  4. package/dist/compiler.d.ts +12 -2
  5. package/dist/compiler.js +6 -2
  6. package/dist/emit.d.ts +6 -0
  7. package/dist/emit.js +17 -1
  8. package/dist/language-service.js +36 -5
  9. package/dist/node.d.ts +8 -1
  10. package/dist/node.js +19 -5
  11. package/dist/parse.js +18 -2
  12. package/dist/project.d.ts +56 -0
  13. package/dist/project.js +159 -17
  14. package/dist/quest/aslx.d.ts +50 -0
  15. package/dist/quest/aslx.js +181 -0
  16. package/dist/quest/convert.d.ts +20 -0
  17. package/dist/quest/convert.js +475 -0
  18. package/dist/quest/script.d.ts +92 -0
  19. package/dist/quest/script.js +453 -0
  20. package/dist/quest/scripts.d.ts +24 -0
  21. package/dist/quest/scripts.js +501 -0
  22. package/dist/quest/text.d.ts +17 -0
  23. package/dist/quest/text.js +305 -0
  24. package/dist/setters.d.ts +6 -0
  25. package/dist/setters.js +43 -0
  26. package/dist/story-graph.d.ts +3 -1
  27. package/dist/story-graph.js +12 -3
  28. package/dist/syntax.d.ts +22 -2
  29. package/dist/text.d.ts +4 -0
  30. package/dist/text.js +28 -21
  31. package/dist/twine/convert.d.ts +82 -0
  32. package/dist/twine/convert.js +744 -0
  33. package/dist/twine/expression.d.ts +68 -0
  34. package/dist/twine/expression.js +215 -0
  35. package/dist/twine/harlowe.d.ts +18 -0
  36. package/dist/twine/harlowe.js +1912 -0
  37. package/dist/twine/story.d.ts +24 -0
  38. package/dist/twine/story.js +231 -0
  39. package/dist/twine/sugarcube.d.ts +34 -0
  40. package/dist/twine/sugarcube.js +1621 -0
  41. package/dist/v5.js +2 -1
  42. package/package.json +3 -2
  43. package/syntaxes/squiffy.tmLanguage.json +1 -1
@@ -0,0 +1,1621 @@
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 { display, print, randomInteger, skipString, Tokens, Unconvertible, unescapeString } from "./expression.js";
8
+ import { dynamicSectionLink, escapeText, isUrl, urlLink, passageLink, sectionLink, setter } from "./convert.js";
9
+ const containers = new Set([
10
+ "if", "for", "switch", "link", "button", "linkreplace", "linkappend", "linkprepend", "nobr", "silently", "capture",
11
+ "script", "timed", "repeat", "widget", "cycle", "listbox", "append", "prepend", "replace", "type", "done", "do",
12
+ "click", "createplaylist", "createaudiogroup",
13
+ ]);
14
+ const childMacros = {
15
+ if: ["elseif", "else"],
16
+ switch: ["case", "default"],
17
+ timed: ["next"],
18
+ cycle: ["option", "optionsfrom"],
19
+ listbox: ["option", "optionsfrom"],
20
+ repeat: [],
21
+ };
22
+ class Parser {
23
+ constructor(src) {
24
+ Object.defineProperty(this, "src", {
25
+ enumerable: true,
26
+ configurable: true,
27
+ writable: true,
28
+ value: src
29
+ });
30
+ }
31
+ // Parses until the end, or until the end of the container, or one of its child macros
32
+ parse(start, container) {
33
+ const src = this.src;
34
+ const nodes = [];
35
+ let text = "";
36
+ const flush = () => {
37
+ if (text)
38
+ nodes.push({ t: "text", s: text });
39
+ text = "";
40
+ };
41
+ let i = start;
42
+ while (i < src.length) {
43
+ const rest = src.substring(i, i + 300);
44
+ if (rest.startsWith("<<")) {
45
+ const macro = readMacro(src, i);
46
+ if (macro) {
47
+ const close = /^\/(\w+)$|^end\s*(\w+)$/.exec(macro.name);
48
+ if (close) {
49
+ const closing = close[1] ?? close[2];
50
+ if (container && closing == container) {
51
+ flush();
52
+ return { nodes, end: macro.end, stop: { name: closing, args: "", raw: macro.raw, close: true } };
53
+ }
54
+ // A stray closing tag: left out
55
+ flush();
56
+ i = macro.end;
57
+ continue;
58
+ }
59
+ const name = macro.name == "else" && /^\s*if\b/.test(macro.args) ? "elseif" : macro.name;
60
+ const args = name == "elseif" && macro.name == "else" ? macro.args.replace(/^\s*if\b/, "") : macro.args;
61
+ if (container && childMacros[container]?.includes(name)) {
62
+ flush();
63
+ return { nodes, end: macro.end, stop: { name, args, raw: macro.raw, close: false } };
64
+ }
65
+ flush();
66
+ if (containers.has(name)) {
67
+ const node = { t: "macro", name, args, raw: macro.raw, clauses: [] };
68
+ let clause = { name, args, raw: macro.raw, nodes: [] };
69
+ let j = macro.end;
70
+ for (;;) {
71
+ const body = this.parse(j, name);
72
+ clause.nodes = body.nodes;
73
+ node.clauses.push(clause);
74
+ j = body.end;
75
+ if (!body.stop || body.stop.close) {
76
+ node.raw = src.substring(i, j);
77
+ break;
78
+ }
79
+ clause = { name: body.stop.name, args: body.stop.args, raw: body.stop.raw, nodes: [] };
80
+ }
81
+ nodes.push(node);
82
+ i = j;
83
+ continue;
84
+ }
85
+ nodes.push({ t: "macro", name, args, raw: macro.raw });
86
+ i = macro.end;
87
+ continue;
88
+ }
89
+ }
90
+ if (rest.startsWith("/*") || rest.startsWith("/%")) {
91
+ const closer = rest.startsWith("/*") ? "*/" : "%/";
92
+ const end = src.indexOf(closer, i + 2);
93
+ flush();
94
+ i = end == -1 ? src.length : end + 2;
95
+ continue;
96
+ }
97
+ if (rest.startsWith("<!--")) {
98
+ const end = src.indexOf("-->", i + 4);
99
+ const stop = end == -1 ? src.length : end + 3;
100
+ flush();
101
+ nodes.push({ t: "raw", s: src.substring(i, stop).replace(/\n/g, " ") });
102
+ i = stop;
103
+ continue;
104
+ }
105
+ if (rest.startsWith("\"\"\"")) {
106
+ const end = src.indexOf("\"\"\"", i + 3);
107
+ if (end != -1) {
108
+ flush();
109
+ nodes.push({ t: "raw", s: escapeText(escapeHtml(src.substring(i + 3, end))) });
110
+ i = end + 3;
111
+ continue;
112
+ }
113
+ }
114
+ if (/^<nowiki>/i.test(rest)) {
115
+ const end = src.toLowerCase().indexOf("</nowiki>", i);
116
+ if (end != -1) {
117
+ flush();
118
+ nodes.push({ t: "raw", s: escapeText(src.substring(i + 8, end)) });
119
+ i = end + 9;
120
+ continue;
121
+ }
122
+ }
123
+ if (rest.startsWith("{{{")) {
124
+ const end = src.indexOf("}}}", i + 3);
125
+ if (end != -1) {
126
+ flush();
127
+ nodes.push({ t: "raw", s: `<code>${escapeText(escapeHtml(src.substring(i + 3, end)))}</code>` });
128
+ i = end + 3;
129
+ continue;
130
+ }
131
+ }
132
+ const scriptMatch = /^<(script|style)\b/i.exec(rest);
133
+ if (scriptMatch) {
134
+ const closeTag = `</${scriptMatch[1].toLowerCase()}>`;
135
+ const end = src.toLowerCase().indexOf(closeTag, i);
136
+ const stop = end == -1 ? src.length : end + closeTag.length;
137
+ flush();
138
+ nodes.push({ t: "comment", text: src.substring(i, stop), reason: `A <${scriptMatch[1]}> in a passage isn't run by Squiffy. Move it to the story's JavaScript or CSS file.` });
139
+ i = stop;
140
+ continue;
141
+ }
142
+ const image = /^\[[<>]?img\[(?:([^|\]]*)\|)?([^\]]*)\](?:\[([^\]]*)\])?\]/i.exec(rest);
143
+ if (image) {
144
+ flush();
145
+ nodes.push({ t: "image", raw: image[0], title: image[1], src: image[2], link: image[3] });
146
+ i += image[0].length;
147
+ continue;
148
+ }
149
+ const link = /^\[\[((?:[^\]]|\](?!\]|\[))*)\](?:\[((?:[^\]]|\](?!\]))*)\])?\]/.exec(rest);
150
+ if (link) {
151
+ flush();
152
+ nodes.push(parseLink(link[1], link[0], link[2]));
153
+ i += link[0].length;
154
+ continue;
155
+ }
156
+ const variable = /^(?:\$[A-Za-z_]|_[A-Za-z])\w*(?:\.[A-Za-z_$][\w$]*|\[(?:[^\]\n]+)\])*/.exec(rest);
157
+ if (variable && (rest[0] == "$" || !/\w/.test(src[i - 1] ?? "")) && !/\w/.test(src[i - 1] ?? "")) {
158
+ flush();
159
+ nodes.push({ t: "var", raw: variable[0] });
160
+ i += variable[0].length;
161
+ continue;
162
+ }
163
+ text += src[i];
164
+ i++;
165
+ }
166
+ flush();
167
+ return { nodes, end: i };
168
+ }
169
+ }
170
+ // Reads <<name args>> at start, or null if it isn't a macro
171
+ function readMacro(src, start) {
172
+ const head = /^<<(\/?[A-Za-z][\w-]*|=|-|end\s+\w+)/.exec(src.substring(start, start + 100));
173
+ if (!head)
174
+ return null;
175
+ let i = start + head[0].length;
176
+ while (i < src.length) {
177
+ const c = src[i];
178
+ if (c == "\"" || c == "'" || c == "`") {
179
+ const end = skipString(src, i);
180
+ if (end == -1)
181
+ return null;
182
+ i = end;
183
+ continue;
184
+ }
185
+ if (src.startsWith("[[", i)) {
186
+ const end = src.indexOf("]]", i);
187
+ if (end == -1)
188
+ return null;
189
+ i = end + 2;
190
+ continue;
191
+ }
192
+ if (src.startsWith("/*", i)) {
193
+ const end = src.indexOf("*/", i + 2);
194
+ if (end == -1)
195
+ return null;
196
+ i = end + 2;
197
+ continue;
198
+ }
199
+ if (src.startsWith(">>", i)) {
200
+ const name = head[1] == "=" || head[1] == "-" ? "print" : head[1].replace(/\s+/g, "");
201
+ return { name: name.toLowerCase(), args: src.substring(start + head[0].length, i).trim(), raw: src.substring(start, i + 2), end: i + 2 };
202
+ }
203
+ i++;
204
+ }
205
+ return null;
206
+ }
207
+ function parseLink(inner, raw, setter) {
208
+ let text;
209
+ let target;
210
+ const bar = inner.lastIndexOf("|");
211
+ const arrow = inner.lastIndexOf("->");
212
+ const back = inner.indexOf("<-");
213
+ if (bar != -1) {
214
+ text = inner.substring(0, bar);
215
+ target = inner.substring(bar + 1);
216
+ }
217
+ else if (arrow != -1) {
218
+ text = inner.substring(0, arrow);
219
+ target = inner.substring(arrow + 2);
220
+ }
221
+ else if (back != -1) {
222
+ target = inner.substring(0, back);
223
+ text = inner.substring(back + 2);
224
+ }
225
+ else {
226
+ text = target = inner;
227
+ }
228
+ return { t: "link", raw, text, target: target.trim(), ...(setter === undefined ? {} : { setter }) };
229
+ }
230
+ function escapeHtml(s) {
231
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
232
+ }
233
+ const symbols = [
234
+ "===", "!==", "**", "==", "!=", ">=", "<=", "&&", "||", "+=", "-=", "*=", "/=", "%=", "++", "--", "=>",
235
+ "+", "-", "*", "/", "%", ">", "<", "=", "!", "?", ":", "(", ")", "[", "]", "{", "}", ",", ".", ";", "&", "|",
236
+ ];
237
+ const wordOperators = {
238
+ to: "=", eq: "==", neq: "!=", is: "===", isnot: "!==", gt: ">", gte: ">=", lt: "<", lte: "<=",
239
+ and: "&&", or: "||", not: "!", def: "def", ndef: "ndef", typeof: "typeof", new: "new", instanceof: "instanceof",
240
+ };
241
+ function tokenize(s) {
242
+ const tokens = [];
243
+ let i = 0;
244
+ while (i < s.length) {
245
+ const c = s[i];
246
+ if (/\s/.test(c)) {
247
+ i++;
248
+ continue;
249
+ }
250
+ if (c == "\"" || c == "'") {
251
+ const end = skipString(s, i);
252
+ if (end == -1)
253
+ throw new Unconvertible("an expression with a string that isn't closed");
254
+ tokens.push({ type: "str", text: s.substring(i, end), value: unescapeString(s.substring(i, end)) });
255
+ i = end;
256
+ continue;
257
+ }
258
+ if (s.startsWith("/*", i)) {
259
+ const end = s.indexOf("*/", i + 2);
260
+ i = end == -1 ? s.length : end + 2;
261
+ continue;
262
+ }
263
+ if (c == "`")
264
+ throw new Unconvertible("a JavaScript template literal");
265
+ const num = /^(\d+(?:\.\d+)?|\.\d+)(ms|s)?(?![\w])/i.exec(s.substring(i));
266
+ if (num) {
267
+ let value = parseFloat(num[1]);
268
+ if (num[2]?.toLowerCase() == "s")
269
+ value *= 1000;
270
+ tokens.push({ type: "num", text: num[0], value });
271
+ i += num[0].length;
272
+ continue;
273
+ }
274
+ const variable = /^([$_])([A-Za-z_]\w*)/.exec(s.substring(i));
275
+ if (variable && (variable[1] == "$" || !/\w/.test(s[i - 1] ?? ""))) {
276
+ tokens.push({ type: variable[1] == "$" ? "var" : "temp", text: variable[0], value: variable[2] });
277
+ i += variable[0].length;
278
+ continue;
279
+ }
280
+ const word = /^[A-Za-z_$][\w$]*/.exec(s.substring(i));
281
+ if (word) {
282
+ const op = wordOperators[word[0]];
283
+ tokens.push(op ? { type: "op", text: op } : { type: "ident", text: word[0] });
284
+ i += word[0].length;
285
+ continue;
286
+ }
287
+ const symbol = symbols.find(o => s.startsWith(o, i));
288
+ if (symbol) {
289
+ // & and | on true and false work as && and ||, and are usually a typo for them
290
+ const text = symbol == "&" ? "&&" : symbol == "|" ? "||" : symbol;
291
+ tokens.push({ type: "(),[]{}.;:?".includes(symbol) ? "punct" : "op", text });
292
+ i += symbol.length;
293
+ continue;
294
+ }
295
+ throw new Unconvertible(`an expression Squiffy can't read ("${s.substring(i, i + 10)}")`);
296
+ }
297
+ return tokens;
298
+ }
299
+ export class SugarCubeExpressions {
300
+ constructor(ctx) {
301
+ Object.defineProperty(this, "ctx", {
302
+ enumerable: true,
303
+ configurable: true,
304
+ writable: true,
305
+ value: ctx
306
+ });
307
+ }
308
+ attribute(name, temp) {
309
+ return this.ctx.story.attribute(name, temp);
310
+ }
311
+ variable(name, temp) {
312
+ return this.ctx.story.variable(name, temp);
313
+ }
314
+ parse(source) {
315
+ const tokens = new Tokens(tokenize(source));
316
+ const e = new ExpressionParser(this, tokens).expression();
317
+ if (!tokens.done)
318
+ throw new Unconvertible(`an expression Squiffy can't read (at "${tokens.peek().text}")`);
319
+ return e;
320
+ }
321
+ // Statements, as in <<set>> and <<run>>: assignments and changes to arrays
322
+ statements(source) {
323
+ const tokens = new Tokens(tokenize(source));
324
+ const parser = new ExpressionParser(this, tokens);
325
+ const result = [];
326
+ while (!tokens.done) {
327
+ result.push(...parser.statement());
328
+ if (!tokens.accept(",") && !tokens.accept(";"))
329
+ break;
330
+ }
331
+ if (!tokens.done)
332
+ throw new Unconvertible(`a statement Squiffy can't read (at "${tokens.peek().text}")`);
333
+ return result;
334
+ }
335
+ // A value used as a passage name, for <<goto>>, <<include>> and links
336
+ passageName(source) {
337
+ const link = /^\[\[(.*)\]\]$/.exec(source.trim());
338
+ if (link) {
339
+ const node = parseLink(link[1], source);
340
+ return { name: node.target };
341
+ }
342
+ // A bare word that isn't a variable is a passage name, e.g. <<goto Library>>
343
+ if (/^[^"'`$_[(\s][^\s]*$/.test(source.trim())) {
344
+ try {
345
+ const e = this.parse(source);
346
+ if (e.k == "str")
347
+ return { name: e.v };
348
+ }
349
+ catch {
350
+ // Treated as a name
351
+ }
352
+ return { name: source.trim() };
353
+ }
354
+ const e = this.parse(source);
355
+ if (e.k == "str")
356
+ return { name: e.v };
357
+ return { expr: e };
358
+ }
359
+ }
360
+ class ExpressionParser {
361
+ constructor(s, tokens) {
362
+ Object.defineProperty(this, "s", {
363
+ enumerable: true,
364
+ configurable: true,
365
+ writable: true,
366
+ value: s
367
+ });
368
+ Object.defineProperty(this, "tokens", {
369
+ enumerable: true,
370
+ configurable: true,
371
+ writable: true,
372
+ value: tokens
373
+ });
374
+ }
375
+ expression() {
376
+ const e = this.or();
377
+ if (this.tokens.is("?"))
378
+ throw new Unconvertible("the ? : operator");
379
+ return e;
380
+ }
381
+ // Objects are flattened, so $player to { hp: 10 } sets player_hp
382
+ statement() {
383
+ const target = this.postfixValue();
384
+ if (target.v == "expr" && target.e.k == "loop")
385
+ throw new Unconvertible("changing a loop's variable inside the loop");
386
+ const t = this.tokens.peek();
387
+ if (target.v == "expr" && target.e.k == "var" && t?.text == "=") {
388
+ const start = this.tokens.pos;
389
+ this.tokens.next();
390
+ const value = this.postfixOrObject();
391
+ if (value.v == "object")
392
+ return this.flatten(target.e.name, value);
393
+ this.tokens.pos = start;
394
+ }
395
+ return [this.singleStatement(target, t)];
396
+ }
397
+ flatten(name, object) {
398
+ return object.entries.flatMap(([key, value]) => {
399
+ const attribute = `${name}_${key}`;
400
+ if (value.v == "object")
401
+ return this.flatten(attribute, value);
402
+ return [{ kind: "set", name: attribute, value: this.toExpr(value) }];
403
+ });
404
+ }
405
+ // An object literal, or an ordinary expression
406
+ postfixOrObject() {
407
+ if (this.tokens.is("{"))
408
+ return this.primary();
409
+ return { v: "expr", e: this.expression() };
410
+ }
411
+ singleStatement(target, t) {
412
+ if (target.v == "expr" && target.e.k == "var") {
413
+ const name = target.e.name;
414
+ if (t?.text == "++" || t?.text == "--") {
415
+ this.tokens.next();
416
+ return { kind: t.text == "++" ? "inc" : "dec", name, value: { k: "num", v: 1 } };
417
+ }
418
+ if (t && ["=", "+=", "-=", "*=", "/="].includes(t.text)) {
419
+ this.tokens.next();
420
+ const value = this.expression();
421
+ switch (t.text) {
422
+ case "+=":
423
+ if (value.k == "array")
424
+ return this.arrayChange("append", name, value);
425
+ return { kind: "inc", name, value };
426
+ case "-=": return { kind: "dec", name, value };
427
+ case "*=":
428
+ case "/=": return { kind: "set", name, value, op: t.text };
429
+ }
430
+ // $x to $x + 1
431
+ if (value.k == "bin" && (value.op == "+" || value.op == "-") && value.l.k == "var" && value.l.name == name) {
432
+ if (value.r.k == "array")
433
+ return this.arrayChange(value.op == "+" ? "append" : "remove", name, value.r);
434
+ if (value.r.k == "num" || value.op == "-")
435
+ return { kind: value.op == "+" ? "inc" : "dec", name, value: value.r };
436
+ }
437
+ return { kind: "set", name, value };
438
+ }
439
+ throw new Unconvertible("a statement that isn't an assignment");
440
+ }
441
+ if (target.v == "expr" && target.e.k == "call" && target.e.fn == "__statement") {
442
+ const [kind, name, value] = target.e.args;
443
+ return { kind: kind.v, name: name.v, value };
444
+ }
445
+ throw new Unconvertible("a statement Squiffy can't convert");
446
+ }
447
+ arrayChange(kind, name, array) {
448
+ if (array.items.length != 1)
449
+ throw new Unconvertible("adding or removing more than one item at once");
450
+ return { kind, name, value: array.items[0] };
451
+ }
452
+ or() {
453
+ let left = this.and();
454
+ while (this.tokens.is("||")) {
455
+ this.tokens.next();
456
+ left = { k: "bin", op: "or", l: left, r: this.and() };
457
+ }
458
+ return left;
459
+ }
460
+ and() {
461
+ let left = this.equality();
462
+ while (this.tokens.is("&&")) {
463
+ this.tokens.next();
464
+ left = { k: "bin", op: "and", l: left, r: this.equality() };
465
+ }
466
+ return left;
467
+ }
468
+ equality() {
469
+ let left = this.relational();
470
+ for (;;) {
471
+ const t = this.tokens.peek()?.text;
472
+ if (t == "==" || t == "===") {
473
+ this.tokens.next();
474
+ left = { k: "bin", op: "=", l: left, r: this.relational() };
475
+ }
476
+ else if (t == "!=" || t == "!==") {
477
+ this.tokens.next();
478
+ left = { k: "bin", op: "!=", l: left, r: this.relational() };
479
+ }
480
+ else if (t == "=") {
481
+ throw new Unconvertible("an assignment (=) in a condition");
482
+ }
483
+ else {
484
+ return left;
485
+ }
486
+ }
487
+ }
488
+ relational() {
489
+ let left = this.additive();
490
+ for (;;) {
491
+ const t = this.tokens.peek()?.text;
492
+ if (t == ">" || t == "<" || t == ">=" || t == "<=") {
493
+ this.tokens.next();
494
+ left = { k: "bin", op: t, l: left, r: this.additive() };
495
+ }
496
+ else {
497
+ return left;
498
+ }
499
+ }
500
+ }
501
+ additive() {
502
+ let left = this.multiplicative();
503
+ while (this.tokens.is("+") || this.tokens.is("-")) {
504
+ const op = this.tokens.next().text;
505
+ left = { k: "bin", op, l: left, r: this.multiplicative() };
506
+ }
507
+ return left;
508
+ }
509
+ multiplicative() {
510
+ let left = this.unary();
511
+ while (this.tokens.is("*") || this.tokens.is("/") || this.tokens.is("%")) {
512
+ const op = this.tokens.next().text;
513
+ left = { k: "bin", op, l: left, r: this.unary() };
514
+ }
515
+ return left;
516
+ }
517
+ unary() {
518
+ const t = this.tokens.peek()?.text;
519
+ if (t == "!") {
520
+ this.tokens.next();
521
+ return { k: "not", e: this.unary() };
522
+ }
523
+ if (t == "-") {
524
+ this.tokens.next();
525
+ const e = this.unary();
526
+ return e.k == "num" ? { k: "num", v: -e.v } : { k: "neg", e };
527
+ }
528
+ if (t == "+") {
529
+ this.tokens.next();
530
+ return this.unary();
531
+ }
532
+ if (t == "def" || t == "ndef") {
533
+ this.tokens.next();
534
+ const e = this.unary();
535
+ return t == "def" ? { k: "bin", op: "!=", l: e, r: { k: "null" } } : { k: "bin", op: "=", l: e, r: { k: "null" } };
536
+ }
537
+ if (t == "typeof" || t == "new")
538
+ throw new Unconvertible(`"${t}"`);
539
+ return this.postfix();
540
+ }
541
+ postfix() {
542
+ return this.toExpr(this.postfixValue());
543
+ }
544
+ toExpr(v) {
545
+ if (v.v == "expr")
546
+ return v.e;
547
+ if (v.v == "object")
548
+ throw new Unconvertible("a JavaScript object, other than one set to a variable");
549
+ if (v.v == "member") {
550
+ if (v.property == "length")
551
+ return { k: "call", fn: "length", args: [this.collection(v.object)] };
552
+ throw new Unconvertible(`properties of variables (.${v.property})`);
553
+ }
554
+ throw new Unconvertible(`"${v.name}"`);
555
+ }
556
+ // The first argument of contains and length: the attribute's name, or an array
557
+ collection(v) {
558
+ if (v.v == "expr" && v.e.k == "var")
559
+ return { k: "str", v: v.e.name };
560
+ if (v.v == "expr" && v.e.k == "array")
561
+ return v.e;
562
+ throw new Unconvertible("an array method on something other than a variable");
563
+ }
564
+ postfixValue() {
565
+ let value = this.primary();
566
+ for (;;) {
567
+ if (this.tokens.accept(".")) {
568
+ const property = this.tokens.next();
569
+ if (property.type != "ident")
570
+ throw new Unconvertible("an expression Squiffy can't read");
571
+ // An object's property, which is its own attribute: $player.hp is player_hp
572
+ if (value.v == "expr" && value.e.k == "var" && !this.tokens.is("(") && property.text != "length") {
573
+ value = { v: "expr", e: { k: "var", name: `${value.e.name}_${property.text}` } };
574
+ continue;
575
+ }
576
+ value = this.member(value, property.text);
577
+ }
578
+ else if (this.tokens.is("[")) {
579
+ this.tokens.next();
580
+ const index = this.expression();
581
+ this.tokens.expect("]");
582
+ // A widget's arguments, which a call to it puts in args_0, args_1 and so on
583
+ if (value.v == "expr" && value.e.k == "var" && index.k == "loop" && index.kind == "index" && index.array == value.e.name) {
584
+ value = { v: "expr", e: { k: "loop", kind: "item", up: index.up } };
585
+ continue;
586
+ }
587
+ if (value.v == "expr" && value.e.k == "var" && value.e.name == "args" && index.k == "num") {
588
+ value = { v: "expr", e: { k: "var", name: `args_${index.v}` } };
589
+ continue;
590
+ }
591
+ if (value.v == "expr" && value.e.k == "var" && index.k == "str" && /^[A-Za-z_]\w*$/.test(index.v)) {
592
+ value = { v: "expr", e: { k: "var", name: `${value.e.name}_${index.v}` } };
593
+ continue;
594
+ }
595
+ if (value.v == "expr" && (value.e.k == "var" || value.e.k == "array") && index.k == "num") {
596
+ value = { v: "expr", e: { k: "call", fn: "lookup", args: [value.e, index] } };
597
+ continue;
598
+ }
599
+ throw new Unconvertible("array indexes and object properties ([...])");
600
+ }
601
+ else if (this.tokens.is("(")) {
602
+ this.tokens.next();
603
+ const args = [];
604
+ if (!this.tokens.accept(")")) {
605
+ do
606
+ args.push(this.expression());
607
+ while (this.tokens.accept(","));
608
+ this.tokens.expect(")");
609
+ }
610
+ value = { v: "expr", e: this.call(value, args) };
611
+ }
612
+ else {
613
+ return value;
614
+ }
615
+ }
616
+ }
617
+ // State.variables.x is $x, and State.temporary.x is _x
618
+ member(object, property) {
619
+ if (object.v == "global") {
620
+ const path = `${object.name}.${property}`;
621
+ if (path == "State.variables" || path == "State.temporary" || path == "SugarCube.State")
622
+ return { v: "global", name: path };
623
+ if (object.name == "State.variables" || object.name == "variables")
624
+ return { v: "expr", e: { k: "var", name: this.s.attribute(property, false) } };
625
+ if (object.name == "State.temporary" || object.name == "temporary")
626
+ return { v: "expr", e: this.s.variable(property, true) };
627
+ return { v: "global", name: path };
628
+ }
629
+ return { v: "member", object, property };
630
+ }
631
+ call(callee, args) {
632
+ const str = (e, what) => {
633
+ if (e?.k == "str")
634
+ return e.v;
635
+ throw new Unconvertible(`${what} with something other than a passage name`);
636
+ };
637
+ if (callee.v == "global") {
638
+ switch (callee.name) {
639
+ case "visited":
640
+ case "hasVisited": {
641
+ if (args.length == 0)
642
+ return { k: "call", fn: "visits", args: [{ k: "str", v: this.s.ctx.section }] };
643
+ if (args.length > 1)
644
+ throw new Unconvertible(`${callee.name}() with more than one passage`);
645
+ const section = this.s.ctx.story.sectionForUnknown(str(args[0], `${callee.name}()`));
646
+ return callee.name == "visited" ? { k: "call", fn: "visits", args: [{ k: "str", v: section }] } : { k: "call", fn: "seen", args: [{ k: "str", v: section }] };
647
+ }
648
+ case "turns":
649
+ return { k: "var", name: "turns" };
650
+ case "random":
651
+ if (args.length == 1)
652
+ return randomInteger({ k: "num", v: 0 }, args[0]);
653
+ return randomInteger(args[0], args[1]);
654
+ case "either":
655
+ return { k: "call", fn: "random", args: [{ k: "array", items: args }] };
656
+ case "passage":
657
+ return { k: "str", v: this.s.ctx.passage.name };
658
+ case "tags":
659
+ // Only as tags().includes("tag")
660
+ return { k: "call", fn: "__tags", args: [] };
661
+ case "Number":
662
+ case "String":
663
+ case "parseInt":
664
+ case "parseFloat":
665
+ if (args.length < 1)
666
+ throw new Unconvertible(`${callee.name}()`);
667
+ return args[0];
668
+ }
669
+ throw new Unconvertible(`${callee.name}()`);
670
+ }
671
+ if (callee.v == "member" && callee.object.v == "expr" && callee.object.e.k == "call" && callee.object.e.fn == "__tags") {
672
+ // tags().includes("x"): whether this is one of the passages tagged x
673
+ if ((callee.property == "includes" || callee.property == "contains") && args[0]?.k == "str") {
674
+ const tag = args[0].v;
675
+ const sections = this.s.ctx.story.twine.passages
676
+ .filter(p => p.tags.includes(tag))
677
+ .map(p => this.s.ctx.story.sectionFor(p.name))
678
+ .filter((s) => s !== undefined);
679
+ return { k: "call", fn: "at", args: [{ k: "array", items: sections.map(s => ({ k: "str", v: s })) }] };
680
+ }
681
+ throw new Unconvertible("tags()");
682
+ }
683
+ if (callee.v == "member") {
684
+ const collection = () => this.collection(callee.object);
685
+ switch (callee.property) {
686
+ case "includes":
687
+ case "contains":
688
+ if (args.length != 1)
689
+ throw new Unconvertible(`.${callee.property}() with more than one value`);
690
+ return { k: "call", fn: "contains", args: [collection(), args[0]] };
691
+ case "random":
692
+ if (callee.object.v == "expr")
693
+ return { k: "call", fn: "random", args: [callee.object.e] };
694
+ break;
695
+ case "push":
696
+ case "pushUnique":
697
+ case "delete": {
698
+ const target = collection();
699
+ if (target.k != "str" || args.length != 1)
700
+ throw new Unconvertible(`.${callee.property}() with more than one value`);
701
+ return { k: "call", fn: "__statement", args: [{ k: "str", v: callee.property == "delete" ? "remove" : "append" }, target, args[0]] };
702
+ }
703
+ }
704
+ throw new Unconvertible(`the .${callee.property}() method`);
705
+ }
706
+ throw new Unconvertible("calling something that isn't a function");
707
+ }
708
+ primary() {
709
+ const t = this.tokens.next();
710
+ switch (t.type) {
711
+ case "str": return { v: "expr", e: { k: "str", v: t.value } };
712
+ case "num": return { v: "expr", e: { k: "num", v: t.value } };
713
+ case "var": return { v: "expr", e: this.s.variable(t.value, false) };
714
+ case "temp": return { v: "expr", e: this.s.variable(t.value, true) };
715
+ case "ident":
716
+ switch (t.text) {
717
+ case "true": return { v: "expr", e: { k: "bool", v: true } };
718
+ case "false": return { v: "expr", e: { k: "bool", v: false } };
719
+ case "null":
720
+ case "undefined": return { v: "expr", e: { k: "null" } };
721
+ }
722
+ return { v: "global", name: t.text };
723
+ case "punct":
724
+ if (t.text == "(") {
725
+ const e = this.expression();
726
+ this.tokens.expect(")");
727
+ return { v: "expr", e };
728
+ }
729
+ if (t.text == "[") {
730
+ const items = [];
731
+ if (!this.tokens.accept("]")) {
732
+ do
733
+ items.push(this.expression());
734
+ while (this.tokens.accept(","));
735
+ this.tokens.expect("]");
736
+ }
737
+ return { v: "expr", e: { k: "array", items } };
738
+ }
739
+ if (t.text == "{") {
740
+ const entries = [];
741
+ if (!this.tokens.accept("}")) {
742
+ do {
743
+ if (this.tokens.is("}"))
744
+ break;
745
+ const key = this.tokens.next();
746
+ if (key.type != "ident" && key.type != "str" && key.type != "num")
747
+ throw new Unconvertible("a JavaScript object Squiffy can't read");
748
+ if (!/^[A-Za-z_]\w*$/.test(String(key.value ?? key.text)))
749
+ throw new Unconvertible("a JavaScript object with keys that aren't words");
750
+ this.tokens.expect(":");
751
+ entries.push([String(key.value ?? key.text), this.postfixOrObject()]);
752
+ } while (this.tokens.accept(","));
753
+ this.tokens.expect("}");
754
+ }
755
+ return { v: "object", entries };
756
+ }
757
+ break;
758
+ }
759
+ throw new Unconvertible(`an expression Squiffy can't read (at "${t.text}")`);
760
+ }
761
+ }
762
+ // SugarCube macro arguments: separated by spaces, each a string, number, $variable, [[link]],
763
+ // `expression` or bare word
764
+ function splitMacroArgs(args) {
765
+ const result = [];
766
+ let i = 0;
767
+ while (i < args.length) {
768
+ const c = args[i];
769
+ if (/\s/.test(c)) {
770
+ i++;
771
+ continue;
772
+ }
773
+ let end;
774
+ if (c == "\"" || c == "'" || c == "`") {
775
+ end = skipString(args, i);
776
+ if (end == -1)
777
+ end = args.length;
778
+ }
779
+ else if (args.startsWith("[[", i)) {
780
+ end = args.indexOf("]]", i);
781
+ end = end == -1 ? args.length : end + 2;
782
+ }
783
+ else {
784
+ end = i;
785
+ while (end < args.length && !/\s/.test(args[end]))
786
+ end++;
787
+ }
788
+ result.push(args.substring(i, end));
789
+ i = end;
790
+ }
791
+ return result;
792
+ }
793
+ class Writer {
794
+ constructor(ctx) {
795
+ Object.defineProperty(this, "ctx", {
796
+ enumerable: true,
797
+ configurable: true,
798
+ writable: true,
799
+ value: ctx
800
+ });
801
+ Object.defineProperty(this, "expr", {
802
+ enumerable: true,
803
+ configurable: true,
804
+ writable: true,
805
+ value: void 0
806
+ });
807
+ Object.defineProperty(this, "open", {
808
+ enumerable: true,
809
+ configurable: true,
810
+ writable: true,
811
+ value: new Set()
812
+ });
813
+ Object.defineProperty(this, "atLineStart", {
814
+ enumerable: true,
815
+ configurable: true,
816
+ writable: true,
817
+ value: true
818
+ });
819
+ // Widget name -> the section it's converted to
820
+ Object.defineProperty(this, "widgets", {
821
+ enumerable: true,
822
+ configurable: true,
823
+ writable: true,
824
+ value: void 0
825
+ });
826
+ // Element ids targeted by <<replace>> and friends, which become labels
827
+ Object.defineProperty(this, "targets", {
828
+ enumerable: true,
829
+ configurable: true,
830
+ writable: true,
831
+ value: new Map()
832
+ });
833
+ this.expr = new SugarCubeExpressions(ctx);
834
+ this.widgets = sugarCubeWidgets(ctx.story);
835
+ }
836
+ // A widget passage: each <<widget>> in it, converted to a section
837
+ widgetSections(nodes) {
838
+ const result = [];
839
+ for (const n of nodes) {
840
+ if (n.t != "macro" || n.name != "widget")
841
+ continue;
842
+ const name = /^["']?([\w-]+)/.exec(n.args)?.[1]?.toLowerCase();
843
+ const section = name ? this.widgets.get(name) : undefined;
844
+ if (!section)
845
+ continue;
846
+ if (/\bcontainer\b/.test(n.args))
847
+ this.ctx.approximate(n.raw, "Container widgets (whose calls have text in them) can't be converted. Wherever the story uses one, it's been left as a comment.");
848
+ // An embedded section's directives don't run, so everything is a helper
849
+ const state = { leading: false, directives: [], nobr: false };
850
+ this.open.clear();
851
+ this.atLineStart = true;
852
+ let body = this.nodes(n.clauses?.[0]?.nodes ?? [], state);
853
+ for (const tag of [...this.open].reverse())
854
+ body += `</${tag}>`;
855
+ result.push({ section, converted: { directives: [], body } });
856
+ }
857
+ return result;
858
+ }
859
+ // A call to a widget: its arguments go in attributes _args_0, _args_1 and so on, then the
860
+ // widget's section is embedded
861
+ widgetCall(m, section) {
862
+ if (m.clauses)
863
+ throw new Unconvertible(`the <<${m.name}>> container widget`);
864
+ const sets = splitMacroArgs(m.args).map((a, n) => {
865
+ let value;
866
+ try {
867
+ value = /^[^"'`$_[(\-\d\s][^\s]*$/.test(a) && !["true", "false", "null"].includes(a) ? { k: "str", v: a } : this.expr.parse(a);
868
+ }
869
+ catch {
870
+ value = { k: "str", v: a };
871
+ }
872
+ return `{{set "args_${n}" ${print(value)}}}`;
873
+ });
874
+ return sets.join("") + `{{embed ${print({ k: "str", v: section })}}}`;
875
+ }
876
+ // Finds the ids that <<replace "#id">> and friends change, so they can be labels
877
+ findTargets(source) {
878
+ for (const m of source.matchAll(/<<(?:replace|append|prepend|remove)\s+["']#([\w-]+)["']/g)) {
879
+ if (!this.targets.has(m[1]))
880
+ this.targets.set(m[1], this.ctx.newLabel(m[1]));
881
+ }
882
+ let result = source;
883
+ for (const [id, label] of this.targets) {
884
+ const span = new RegExp(`<(span|div)\\b[^>]*\\bid=["']${id}["'][^>]*>([^<]*)</\\1>`, "g");
885
+ result = result.replace(span, (_m, _tag, inner) => `\uE000label ${label}\uE001${inner}\uE000/label\uE001`);
886
+ }
887
+ return result;
888
+ }
889
+ passage(nodes, nobr) {
890
+ const state = { leading: true, directives: [], nobr };
891
+ let body = this.nodes(nodes, state);
892
+ for (const tag of [...this.open].reverse())
893
+ body += `</${tag}>`;
894
+ body = body.replace(/\uE000label ([\w-]+)\uE001/g, "{{#label \"$1\"}}").replace(/\uE000\/label\uE001/g, "{{/label}}");
895
+ return { directives: state.directives, body };
896
+ }
897
+ nodes(nodes, state) {
898
+ let out = "";
899
+ for (const node of nodes) {
900
+ const written = this.node(node, state);
901
+ if (node.t != "text" && written)
902
+ this.atLineStart = false;
903
+ out += written;
904
+ }
905
+ return out;
906
+ }
907
+ node(node, state) {
908
+ switch (node.t) {
909
+ case "text":
910
+ if (node.s.trim())
911
+ state.leading = false;
912
+ return this.text(node.s, state);
913
+ case "raw":
914
+ return node.s;
915
+ case "comment":
916
+ return this.ctx.unconvertible(node.text, node.reason);
917
+ case "var":
918
+ state.leading = false;
919
+ try {
920
+ return display(this.expr.parse(node.raw));
921
+ }
922
+ catch (e) {
923
+ if (!(e instanceof Unconvertible))
924
+ throw e;
925
+ return this.ctx.unconvertible(node.raw, `This couldn't be converted: ${e.message}.`);
926
+ }
927
+ case "link":
928
+ state.leading = false;
929
+ return this.link(node);
930
+ case "image": {
931
+ state.leading = false;
932
+ const alt = node.title ? ` alt="${escapeAttribute(node.title)}"` : "";
933
+ if (/^data:|\.\w{2,4}$|^https?:/i.test(node.src) === false) {
934
+ 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.");
935
+ }
936
+ const img = `<img src="${escapeAttribute(node.src)}"${alt}>`;
937
+ if (!node.link)
938
+ return img;
939
+ const target = this.ctx.story.sectionFor(node.link.trim());
940
+ return target === undefined ? img : `{{section ${print({ k: "str", v: target })} text=${print({ k: "str", v: img })}}}`;
941
+ }
942
+ case "macro":
943
+ return this.macro(node, state);
944
+ }
945
+ }
946
+ link(node) {
947
+ const text = this.inlineText(node.text);
948
+ if (isUrl(node.target))
949
+ return urlLink(text, node.target);
950
+ let setters = [];
951
+ if (node.setter !== undefined) {
952
+ try {
953
+ setters = this.setters(node.setter);
954
+ }
955
+ catch (e) {
956
+ if (!(e instanceof Unconvertible))
957
+ throw e;
958
+ return this.ctx.unconvertible(node.raw, `This link's setter couldn't be converted: ${e.message}.`);
959
+ }
960
+ }
961
+ if (/^[$_][A-Za-z]/.test(node.target) || /\(/.test(node.target) && !this.ctx.story.sectionFor(node.target)) {
962
+ try {
963
+ const target = this.expr.parse(node.target);
964
+ return dynamicSectionLink(node.text, target, setters);
965
+ }
966
+ catch {
967
+ // Treated as a passage name
968
+ }
969
+ }
970
+ const target = this.ctx.story.sectionFor(node.target);
971
+ if (target === undefined) {
972
+ this.ctx.approximate(node.raw, `There's no passage called "${node.target}".`);
973
+ return sectionLink(text, this.ctx.story.sectionForUnknown(node.target), setters);
974
+ }
975
+ return sectionLink(text, target, setters);
976
+ }
977
+ // Converts a link's setter ([[text|passage][$x to 1]]) to Squiffy setters
978
+ setters(source, inLink = true) {
979
+ return this.expr.statements(source).map(s => {
980
+ switch (s.kind) {
981
+ case "set": return setter(s.name, s.op ?? "=", s.value, inLink);
982
+ case "inc": return setter(s.name, "+=", s.value, inLink);
983
+ case "dec": return setter(s.name, "-=", s.value, inLink);
984
+ default: throw new Unconvertible("changing an array in a link");
985
+ }
986
+ });
987
+ }
988
+ inlineText(text) {
989
+ const nodes = new Parser(text).parse(0).nodes;
990
+ return this.nodes(nodes, { leading: false, directives: [], nobr: true }).replace(/\n/g, " ");
991
+ }
992
+ text(s, state) {
993
+ let out = "";
994
+ for (let i = 0; i < s.length;) {
995
+ const rest = s.substring(i, i + 200);
996
+ if (this.atLineStart) {
997
+ this.atLineStart = false;
998
+ const lineEnd = rest.indexOf("\n");
999
+ const line = lineEnd == -1 ? rest : rest.substring(0, lineEnd);
1000
+ const heading = /^(!{1,6})\s*/.exec(line);
1001
+ if (heading) {
1002
+ out += "#".repeat(heading[1].length) + " ";
1003
+ i += heading[0].length;
1004
+ continue;
1005
+ }
1006
+ const bullet = /^([*#]+)\s+/.exec(line);
1007
+ if (bullet) {
1008
+ out += " ".repeat(bullet[1].length - 1) + (bullet[1].endsWith("#") ? "1. " : "* ");
1009
+ i += bullet[0].length;
1010
+ continue;
1011
+ }
1012
+ if (/^\s*-{4,}\s*$/.test(line)) {
1013
+ out += "<hr>";
1014
+ i += line.length;
1015
+ continue;
1016
+ }
1017
+ const number = /^(\s*\d+)\.(\s)/.exec(line);
1018
+ if (number) {
1019
+ // Not a Markdown list
1020
+ out += number[1] + "&#46;" + number[2];
1021
+ i += number[0].length;
1022
+ continue;
1023
+ }
1024
+ }
1025
+ const c = s[i];
1026
+ if (c == "\n") {
1027
+ out += state.nobr ? " " : "\n";
1028
+ this.atLineStart = !state.nobr;
1029
+ i++;
1030
+ continue;
1031
+ }
1032
+ if (c == "\\" && s[i + 1] == "\n") {
1033
+ // Joins the line to the next
1034
+ i += 2;
1035
+ continue;
1036
+ }
1037
+ const style = /^@@([^;@]*);/.exec(rest);
1038
+ if (style) {
1039
+ const end = s.indexOf("@@", i + style[0].length);
1040
+ if (end != -1) {
1041
+ out += `<span${cssAttributes(style[1])}>`;
1042
+ // The text in it is converted with the rest, and @@ closes the span
1043
+ this.open.add("span@@");
1044
+ i += style[0].length;
1045
+ continue;
1046
+ }
1047
+ }
1048
+ if (rest.startsWith("@@") && this.open.has("span@@")) {
1049
+ this.open.delete("span@@");
1050
+ out += "</span>";
1051
+ i += 2;
1052
+ continue;
1053
+ }
1054
+ const toggle = this.toggle(s, i);
1055
+ if (toggle) {
1056
+ out += toggle.text;
1057
+ i += toggle.length;
1058
+ continue;
1059
+ }
1060
+ if (c == "<") {
1061
+ const tag = /^<\/?[A-Za-z][^<>]*>/.exec(rest);
1062
+ if (tag) {
1063
+ out += this.htmlTag(tag[0]);
1064
+ i += tag[0].length;
1065
+ continue;
1066
+ }
1067
+ }
1068
+ out += escapeProse(s, i);
1069
+ i++;
1070
+ }
1071
+ return out;
1072
+ }
1073
+ // An HTML tag, with SugarCube's data-passage links turned into Squiffy links
1074
+ htmlTag(tag) {
1075
+ if (/\s@[\w-]+=/.test(tag)) {
1076
+ this.ctx.approximate(tag, "SugarCube's attribute directives (@attribute=\"...\") aren't converted.");
1077
+ }
1078
+ return tag.replace(/\{\{/g, "&#123;{").replace(/\[/g, "&#91;").replace(/\]/g, "&#93;");
1079
+ }
1080
+ toggle(s, i) {
1081
+ const marks = [["''", "b"], ["//", "i"], ["__", "u"], ["==", "s"], ["^^", "sup"], ["~~", "sub"]];
1082
+ for (const [mark, tag] of marks) {
1083
+ if (!s.startsWith(mark, i))
1084
+ continue;
1085
+ if (mark == "//" && s[i - 1] == ":")
1086
+ return null;
1087
+ if (this.open.has(tag)) {
1088
+ this.open.delete(tag);
1089
+ return { text: `</${tag}>`, length: mark.length };
1090
+ }
1091
+ const end = s.indexOf(mark, i + mark.length);
1092
+ if (end == -1)
1093
+ return null;
1094
+ this.open.add(tag);
1095
+ return { text: `<${tag}>`, length: mark.length };
1096
+ }
1097
+ return null;
1098
+ }
1099
+ // ---- Macros ----
1100
+ macro(m, state) {
1101
+ try {
1102
+ return this.macroOrThrow(m, state);
1103
+ }
1104
+ catch (e) {
1105
+ if (!(e instanceof Unconvertible))
1106
+ throw e;
1107
+ state.leading = false;
1108
+ return this.ctx.unconvertible(m.raw, `This couldn't be converted: ${e.message}.`);
1109
+ }
1110
+ }
1111
+ body(m, state, clause = 0) {
1112
+ return this.nodes(m.clauses?.[clause]?.nodes ?? [], { ...state, leading: false });
1113
+ }
1114
+ macroOrThrow(m, state) {
1115
+ const args = splitMacroArgs(m.args);
1116
+ switch (m.name) {
1117
+ case "set":
1118
+ return this.set(this.expr.statements(m.args), state);
1119
+ case "unset": {
1120
+ const statements = m.args.split(",").map(a => {
1121
+ const match = /^\s*([$_])([A-Za-z_]\w*)\s*$/.exec(a);
1122
+ if (!match)
1123
+ throw new Unconvertible("<<unset>> of something other than a variable");
1124
+ return { kind: "unset", name: this.expr.attribute(match[2], match[1] == "_") };
1125
+ });
1126
+ return this.set(statements, state);
1127
+ }
1128
+ case "run": {
1129
+ return this.set(this.expr.statements(m.args), state);
1130
+ }
1131
+ case "print":
1132
+ state.leading = false;
1133
+ return display(this.expr.parse(m.args));
1134
+ case "if": {
1135
+ state.leading = false;
1136
+ const clauses = m.clauses;
1137
+ let out = "";
1138
+ clauses.forEach((c, n) => {
1139
+ const cond = c.name == "else" ? null : this.expr.parse(c.args);
1140
+ out += n == 0 ? `{{#if ${print(cond)}}}` : cond ? `{{else if ${print(cond)}}}` : "{{else}}";
1141
+ out += this.nodes(c.nodes, { ...state, leading: false });
1142
+ });
1143
+ return out + "{{/if}}";
1144
+ }
1145
+ case "switch": {
1146
+ state.leading = false;
1147
+ const subject = this.expr.parse(m.args);
1148
+ let out = "";
1149
+ let first = true;
1150
+ for (const c of m.clauses.slice(1)) {
1151
+ let cond = null;
1152
+ if (c.name == "case") {
1153
+ const values = splitMacroArgs(c.args).map(a => this.expr.parse(a));
1154
+ cond = values.map((v) => ({ k: "bin", op: "=", l: subject, r: v }))
1155
+ .reduce((a, b) => ({ k: "bin", op: "or", l: a, r: b }));
1156
+ }
1157
+ out += first ? (cond ? `{{#if ${print(cond)}}}` : "{{#if true}}") : cond ? `{{else if ${print(cond)}}}` : "{{else}}";
1158
+ first = false;
1159
+ out += this.nodes(c.nodes, { ...state, leading: false });
1160
+ }
1161
+ return first ? "" : out + "{{/if}}";
1162
+ }
1163
+ case "include":
1164
+ case "display": {
1165
+ state.leading = false;
1166
+ const target = this.expr.passageName(args[0] ?? "");
1167
+ if ("name" in target)
1168
+ return `{{embed ${print({ k: "str", v: this.sectionName(target.name, m.raw) })}}}`;
1169
+ return `{{embed ${print(target.expr)}}}`;
1170
+ }
1171
+ case "goto":
1172
+ state.leading = false;
1173
+ return this.goto(args[0] ?? "", m.raw);
1174
+ case "link":
1175
+ case "button":
1176
+ case "click":
1177
+ state.leading = false;
1178
+ return this.linkMacro(m, args);
1179
+ case "linkreplace":
1180
+ case "linkappend":
1181
+ case "linkprepend": {
1182
+ state.leading = false;
1183
+ const text = this.linkText(args[0] ?? "");
1184
+ const content = this.body(m, state);
1185
+ const label = this.ctx.newLabel(text.plain);
1186
+ const replacement = m.name == "linkreplace" ? content : m.name == "linkappend" ? text.squiffy + content : content + text.squiffy;
1187
+ const passage = this.ctx.addPassage(text.plain, `{{#replace "${label}"}}${replacement}{{/replace}}`);
1188
+ return `{{#label "${label}"}}${passageLink(text.squiffy, passage)}{{/label}}`;
1189
+ }
1190
+ case "actions":
1191
+ case "choice": {
1192
+ state.leading = false;
1193
+ const links = args.map(a => {
1194
+ const target = this.expr.passageName(a);
1195
+ if (!("name" in target))
1196
+ throw new Unconvertible(`<<${m.name}>> with a passage that isn't fixed`);
1197
+ return sectionLink(escapeText(target.name), this.sectionName(target.name, m.raw));
1198
+ });
1199
+ return m.name == "actions" ? "\n" + links.map(l => `* ${l}`).join("\n") + "\n" : links.join(" ");
1200
+ }
1201
+ case "nobr":
1202
+ return this.nodes(m.clauses[0].nodes, { ...state, nobr: true });
1203
+ case "silently": {
1204
+ const content = this.nodes(m.clauses[0].nodes, state);
1205
+ // Only the helpers, which write nothing
1206
+ return (content.match(/\{\{(?:[^{}]|\{\{[^{}]*\}\})*\}\}/g) ?? []).join("");
1207
+ }
1208
+ case "capture":
1209
+ case "done":
1210
+ case "do":
1211
+ if (m.name == "done")
1212
+ this.ctx.approximate(m.raw, "<<done>> has been converted to its contents, which are shown straight away.");
1213
+ return this.nodes(m.clauses[0].nodes, state);
1214
+ case "timed": {
1215
+ state.leading = false;
1216
+ let delay = 0;
1217
+ let out = "";
1218
+ for (const c of m.clauses) {
1219
+ const d = splitMacroArgs(c.args)[0];
1220
+ const ms = d ? this.expr.parse(d) : { k: "num", v: 0 };
1221
+ if (ms.k != "num")
1222
+ throw new Unconvertible("<<timed>> with a delay that isn't fixed");
1223
+ delay += ms.v;
1224
+ const goto = this.gotoOnly(c.nodes);
1225
+ if (goto)
1226
+ out += goto.replace(/\}\}$/, ` after=${delay}}}`);
1227
+ else
1228
+ out += `{{#animate "fadeIn" start=${delay}}}${this.nodes(c.nodes, { ...state, leading: false })}{{/animate}}`;
1229
+ }
1230
+ return out;
1231
+ }
1232
+ case "type": {
1233
+ state.leading = false;
1234
+ const speed = this.expr.parse(args[0] ?? "40ms");
1235
+ const interval = speed.k == "num" ? ` interval=${speed.v}` : "";
1236
+ return `{{#animate "typewriter"${interval}}}${this.body(m, state)}{{/animate}}`;
1237
+ }
1238
+ case "textbox":
1239
+ case "textarea":
1240
+ case "numberbox": {
1241
+ state.leading = false;
1242
+ const bound = this.receiver(args[0] ?? "");
1243
+ const defaultValue = args[1] ? this.expr.parse(args[1]) : null;
1244
+ if (args.slice(2).some(a => a != "autofocus")) {
1245
+ this.ctx.approximate(m.raw, "Squiffy's text boxes don't go to a passage when Enter is pressed.");
1246
+ }
1247
+ const value = defaultValue?.k == "str" || defaultValue?.k == "num" ? String(defaultValue.v) : null;
1248
+ const set = defaultValue ? `{{set "${bound}" ${print(defaultValue)}}}` : "";
1249
+ if (m.name == "textarea")
1250
+ return `${set}<textarea data-attribute="${bound}">${escapeText(escapeHtml(value ?? ""))}</textarea>`;
1251
+ const type = m.name == "numberbox" ? "number" : "text";
1252
+ return `${set}<input type="${type}" data-attribute="${bound}"${value === null ? "" : ` value="${escapeAttribute(value)}"`}>`;
1253
+ }
1254
+ case "checkbox": {
1255
+ state.leading = false;
1256
+ const bound = this.receiver(args[0] ?? "");
1257
+ this.ctx.approximate(m.raw, "Check how this checkbox works in Squiffy.");
1258
+ return `<input type="checkbox" data-attribute="${bound}">`;
1259
+ }
1260
+ case "radiobutton": {
1261
+ state.leading = false;
1262
+ const bound = this.receiver(args[0] ?? "");
1263
+ const value = this.expr.parse(args[1] ?? "");
1264
+ if (value.k != "str" && value.k != "num")
1265
+ throw new Unconvertible("<<radiobutton>> with a value that isn't fixed");
1266
+ this.ctx.approximate(m.raw, "Check how this radio button works in Squiffy.");
1267
+ return `<input type="radio" name="${bound}" data-attribute="${bound}" value="${escapeAttribute(String(value.v))}">`;
1268
+ }
1269
+ case "cycle":
1270
+ case "listbox": {
1271
+ state.leading = false;
1272
+ const bound = this.receiver(args[0] ?? "");
1273
+ const options = [];
1274
+ for (const c of m.clauses.slice(1)) {
1275
+ if (c.name == "optionsfrom")
1276
+ throw new Unconvertible("<<optionsfrom>>");
1277
+ const [label, value] = splitMacroArgs(c.args).map(a => this.expr.parse(a));
1278
+ if (label?.k != "str" && label?.k != "num")
1279
+ throw new Unconvertible("an option that isn't fixed text");
1280
+ const v = value ? value : label;
1281
+ if (v.k != "str" && v.k != "num")
1282
+ throw new Unconvertible("an option that isn't fixed text");
1283
+ options.push({ label: String(label.v), value: String(v.v) });
1284
+ }
1285
+ if (m.name == "listbox") {
1286
+ return `<select data-attribute="${bound}">${options.map(o => `<option value="${escapeAttribute(o.value)}">${escapeText(escapeHtml(o.label))}</option>`).join("")}</select>`;
1287
+ }
1288
+ if (options.some(o => o.label != o.value)) {
1289
+ this.ctx.approximate(m.raw, "Squiffy's {{rotate}} sets the attribute to the text shown, not the option's value.");
1290
+ }
1291
+ return `{{rotate ${print({ k: "array", items: options.map(o => ({ k: "str", v: o.label })) })} set="${bound}"}}`;
1292
+ }
1293
+ case "replace":
1294
+ case "append":
1295
+ case "prepend":
1296
+ case "remove": {
1297
+ state.leading = false;
1298
+ const target = /^["']#([\w-]+)["']$/.exec(args[0] ?? "");
1299
+ if (!target)
1300
+ throw new Unconvertible(`<<${m.name}>> on something other than an element with an id ("#id")`);
1301
+ const label = this.targets.get(target[1]);
1302
+ const content = m.name == "remove" ? "" : this.body(m, state);
1303
+ if (m.name == "append" || m.name == "prepend") {
1304
+ this.ctx.approximate(m.raw, `<<${m.name}>> has been converted to {{#replace}}, which replaces the text rather than adding to it.`);
1305
+ }
1306
+ return `{{#replace "${label}"}}${content}{{/replace}}`;
1307
+ }
1308
+ case "script":
1309
+ throw new Unconvertible("<<script>>, which runs SugarCube JavaScript");
1310
+ case "for": {
1311
+ state.leading = false;
1312
+ if (/<<\s*(?:break|continue)\s*>>/.test(m.raw))
1313
+ throw new Unconvertible("<<break>> and <<continue>>");
1314
+ const loop = this.forLoop(m.args);
1315
+ const body = this.ctx.story.inLoop(loop.vars, loop.array, () => this.body(m, state));
1316
+ return `{{#each ${print(loop.collection)}}}${body}{{/each}}`;
1317
+ }
1318
+ case "widget":
1319
+ return "";
1320
+ case "back":
1321
+ case "return":
1322
+ throw new Unconvertible(`<<${m.name}>>. Squiffy has its own Back button`);
1323
+ case "audio":
1324
+ case "cacheaudio":
1325
+ case "playlist":
1326
+ case "masteraudio":
1327
+ case "waitforaudio":
1328
+ case "createplaylist":
1329
+ case "createaudiogroup":
1330
+ case "track":
1331
+ throw new Unconvertible("audio macros");
1332
+ case "addclass":
1333
+ case "removeclass":
1334
+ case "toggleclass":
1335
+ throw new Unconvertible("macros that change elements' classes");
1336
+ case "repeat":
1337
+ throw new Unconvertible("<<repeat>>, which runs again and again");
1338
+ case "stop":
1339
+ case "silent":
1340
+ return "";
1341
+ case "elseif":
1342
+ case "else":
1343
+ case "case":
1344
+ case "default":
1345
+ case "next":
1346
+ case "option":
1347
+ throw new Unconvertible(`<<${m.name}>> outside the macro it belongs to`);
1348
+ default:
1349
+ if (this.widgets.has(m.name)) {
1350
+ state.leading = false;
1351
+ return this.widgetCall(m, this.widgets.get(m.name));
1352
+ }
1353
+ if (!knownMacros.has(m.name))
1354
+ throw new Unconvertible(`the <<${m.name}>> macro, which isn't one of SugarCube's own: it's probably added by the story's JavaScript`);
1355
+ throw new Unconvertible(`the <<${m.name}>> macro, which Squiffy has no equivalent for`);
1356
+ }
1357
+ }
1358
+ // What a <<for>> goes through, as {{#each}} does, and the variables (with their $ or _) that
1359
+ // stand for its item and position. It can go through an array with range, or by position:
1360
+ // <<for _i to 0; _i lt $list.length; _i++>>. Either way, $list[_i] is the item.
1361
+ forLoop(args) {
1362
+ const range = /^\s*([$_][A-Za-z_]\w*)\s*(?:,\s*([$_][A-Za-z_]\w*)\s*)?\brange\b([\s\S]+)$/.exec(args);
1363
+ if (range) {
1364
+ const vars = new Map(range[2] ? [[range[1], "index"], [range[2], "item"]] : [[range[1], "item"]]);
1365
+ const collection = this.expr.parse(range[3]);
1366
+ if (collection.k != "var" && collection.k != "array" && !(collection.k == "loop" && collection.kind == "item")) {
1367
+ throw new Unconvertible("<<for>> with range over something other than an array");
1368
+ }
1369
+ // With a position as well, $list[_i] is the item too
1370
+ return { collection, vars, array: collection.k == "var" ? collection.name : undefined };
1371
+ }
1372
+ 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);
1373
+ if (counted) {
1374
+ const array = this.expr.attribute(counted[3], counted[2] == "_");
1375
+ return { collection: { k: "var", name: array }, vars: new Map([["_" + counted[1], "index"]]), array };
1376
+ }
1377
+ throw new Unconvertible("<<for>> loops, except ones that go through an array (with range, or from 0 to its length)");
1378
+ }
1379
+ // The attribute a form macro like <<textbox "$name">> sets
1380
+ receiver(arg) {
1381
+ const match = /^["']([$_])([A-Za-z_]\w*)["']$/.exec(arg);
1382
+ if (!match)
1383
+ throw new Unconvertible("a form control that doesn't set a plain variable");
1384
+ return this.expr.attribute(match[2], match[1] == "_");
1385
+ }
1386
+ linkText(arg) {
1387
+ if (arg.startsWith("[[")) {
1388
+ const node = parseLink(arg.slice(2, -2), arg);
1389
+ return { plain: node.text, squiffy: this.inlineText(node.text) };
1390
+ }
1391
+ const e = this.expr.parse(arg);
1392
+ if (e.k == "str")
1393
+ return { plain: e.v, squiffy: this.inlineText(e.v) };
1394
+ // Text worked out as the story runs, e.g. a loop's item: named after the expression
1395
+ return { plain: arg.replace(/[^\w\s]+/g, " ").trim() || "link", squiffy: display(e) };
1396
+ }
1397
+ sectionName(passage, raw) {
1398
+ const section = this.ctx.story.sectionFor(passage);
1399
+ if (section === undefined) {
1400
+ this.ctx.approximate(raw, `There's no passage called "${passage}".`);
1401
+ return this.ctx.story.sectionForUnknown(passage);
1402
+ }
1403
+ return section;
1404
+ }
1405
+ goto(arg, raw) {
1406
+ const target = this.expr.passageName(arg);
1407
+ if ("name" in target)
1408
+ return `{{goto ${print({ k: "str", v: this.sectionName(target.name, raw) })}}}`;
1409
+ return `{{goto ${print(target.expr)}}}`;
1410
+ }
1411
+ gotoOnly(nodes) {
1412
+ const significant = nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
1413
+ if (significant.length != 1)
1414
+ return null;
1415
+ const n = significant[0];
1416
+ if (n.t != "macro" || n.name != "goto")
1417
+ return null;
1418
+ return this.goto(splitMacroArgs(n.args)[0] ?? "", n.raw);
1419
+ }
1420
+ // <<link>>, <<button>>: the body runs when it's clicked, then the story goes to the passage
1421
+ // given, if there is one
1422
+ linkMacro(m, args) {
1423
+ let text;
1424
+ let passage = null;
1425
+ let setters = [];
1426
+ let setterSource = null;
1427
+ let dynamicDestination = null;
1428
+ if (args[0]?.startsWith("[[")) {
1429
+ const link = /^\[\[(.*?)\](?:\[(.*)\])?\]$/.exec(args[0]);
1430
+ if (!link)
1431
+ throw new Unconvertible("a link Squiffy can't read");
1432
+ const node = parseLink(link[1], args[0]);
1433
+ text = { plain: node.text, squiffy: this.inlineText(node.text) };
1434
+ passage = node.target;
1435
+ if (link[2]) {
1436
+ setters = this.setters(link[2]);
1437
+ setterSource = link[2];
1438
+ }
1439
+ }
1440
+ else {
1441
+ text = this.linkText(args[0] ?? "");
1442
+ if (args[1]) {
1443
+ const target = this.expr.passageName(args[1]);
1444
+ if ("name" in target)
1445
+ passage = target.name;
1446
+ else
1447
+ dynamicDestination = target.expr;
1448
+ }
1449
+ }
1450
+ const body = m.clauses?.[0]?.nodes ?? [];
1451
+ const significant = body.filter(n => !(n.t == "text" && n.s.trim() == ""));
1452
+ // A trailing <<goto>> is where the link goes
1453
+ const last = significant[significant.length - 1];
1454
+ let gotoArg = null;
1455
+ if (last?.t == "macro" && last.name == "goto") {
1456
+ gotoArg = splitMacroArgs(last.args)[0] ?? "";
1457
+ significant.pop();
1458
+ }
1459
+ const destination = gotoArg !== null ? this.expr.passageName(gotoArg)
1460
+ : passage !== null ? { name: passage }
1461
+ : dynamicDestination ? { expr: dynamicDestination } : null;
1462
+ // Only <<set>>s: a link with setters
1463
+ const bodySetters = this.bodySetters(significant);
1464
+ if (destination && bodySetters) {
1465
+ const all = [...setters, ...bodySetters];
1466
+ if ("name" in destination)
1467
+ return sectionLink(text.squiffy, this.sectionName(destination.name, m.raw), all);
1468
+ return dynamicSectionLink(text.plain, destination.expr, all);
1469
+ }
1470
+ const state = { leading: true, directives: [], nobr: false };
1471
+ const content = this.nodes(body, state);
1472
+ const directives = [...(setterSource === null ? [] : this.setters(setterSource, false).map(s => `@set ${s}`)), ...state.directives];
1473
+ if (destination) {
1474
+ // Run the body in a section of its own, which then goes on to the passage
1475
+ const goto = gotoArg !== null ? "" : "\n" + ("name" in destination
1476
+ ? `{{goto ${print({ k: "str", v: this.sectionName(destination.name, m.raw) })}}}`
1477
+ : `{{goto ${print(destination.expr)}}}`);
1478
+ const section = this.ctx.addSection(`${this.ctx.section}: ${text.plain}`, { directives, body: content + goto });
1479
+ return sectionLink(text.squiffy, section);
1480
+ }
1481
+ // Stays in this passage: a passage link, whose passage does what the body does
1482
+ const name = this.ctx.addPassage(text.plain, { directives, body: content });
1483
+ return passageLink(text.squiffy, name);
1484
+ }
1485
+ // The setters for nodes that are only <<set>>s, or null
1486
+ bodySetters(nodes) {
1487
+ const result = [];
1488
+ for (const n of nodes) {
1489
+ if (n.t != "macro" || n.name != "set")
1490
+ return null;
1491
+ try {
1492
+ result.push(...this.setters(n.args));
1493
+ }
1494
+ catch (e) {
1495
+ if (e instanceof Unconvertible)
1496
+ return null;
1497
+ throw e;
1498
+ }
1499
+ }
1500
+ return result;
1501
+ }
1502
+ set(statements, state) {
1503
+ let out = "";
1504
+ for (const s of statements) {
1505
+ if (state.leading) {
1506
+ switch (s.kind) {
1507
+ case "set":
1508
+ state.directives.push(`@set ${setter(s.name, s.op ?? "=", s.value, false)}`);
1509
+ continue;
1510
+ case "inc":
1511
+ case "dec": {
1512
+ const amount = s.value.k == "num" && Number.isInteger(s.value.v) && s.value.v >= 0 ? s.value.v : null;
1513
+ state.directives.push(amount === null
1514
+ ? `@set ${setter(s.name, s.kind == "inc" ? "+=" : "-=", s.value, false)}`
1515
+ : `@${s.kind} ${s.name}${amount == 1 ? "" : " " + amount}`);
1516
+ continue;
1517
+ }
1518
+ case "unset":
1519
+ state.directives.push(`@unset ${s.name}`);
1520
+ continue;
1521
+ }
1522
+ }
1523
+ state.leading = false;
1524
+ const name = print({ k: "str", v: s.name });
1525
+ switch (s.kind) {
1526
+ case "set":
1527
+ out += s.op
1528
+ ? `{{set ${name} ${print({ k: "bin", op: s.op == "*=" ? "*" : "/", l: { k: "var", name: s.name }, r: s.value })}}}`
1529
+ : `{{set ${name} ${print(s.value)}}}`;
1530
+ break;
1531
+ case "inc":
1532
+ case "dec":
1533
+ out += s.value.k == "num" && s.value.v == 1 ? `{{${s.kind} ${name}}}` : `{{${s.kind} ${name} ${print(s.value)}}}`;
1534
+ break;
1535
+ case "append":
1536
+ case "remove":
1537
+ out += `{{${s.kind} ${name} ${print(s.value)}}}`;
1538
+ break;
1539
+ case "unset":
1540
+ out += `{{unset ${name}}}`;
1541
+ break;
1542
+ }
1543
+ }
1544
+ return out;
1545
+ }
1546
+ }
1547
+ const knownMacros = new Set([
1548
+ "capture", "set", "unset", "run", "script", "include", "nobr", "print", "silently", "type", "if", "switch", "for",
1549
+ "break", "continue", "back", "return", "actions", "choice", "link", "button", "linkappend", "linkprepend",
1550
+ "linkreplace", "checkbox", "cycle", "listbox", "numberbox", "radiobutton", "textarea", "textbox", "addclass",
1551
+ "append", "copy", "prepend", "remove", "removeclass", "replace", "toggleclass", "audio", "cacheaudio",
1552
+ "createaudiogroup", "createplaylist", "masteraudio", "playlist", "removeaudiogroup", "removeplaylist",
1553
+ "waitforaudio", "done", "goto", "repeat", "stop", "timed", "widget", "display", "click", "do", "redo", "track",
1554
+ ]);
1555
+ // The story's widgets, by name, with the section each is converted to
1556
+ export function sugarCubeWidgets(story) {
1557
+ return story.cached("sugarcube-widgets", () => {
1558
+ const result = new Map();
1559
+ for (const p of story.twine.passages) {
1560
+ if (!p.tags.includes("widget"))
1561
+ continue;
1562
+ for (const m of p.text.matchAll(/<<widget\s+["']?([\w-]+)/g)) {
1563
+ const name = m[1].toLowerCase();
1564
+ if (!result.has(name))
1565
+ result.set(name, story.uniqueSectionName(`widget ${name}`));
1566
+ }
1567
+ }
1568
+ return result;
1569
+ });
1570
+ }
1571
+ export function convertSugarCubeWidgets(text, ctx) {
1572
+ const writer = new Writer(ctx);
1573
+ const nodes = new Parser(writer.findTargets(text.replace(/\\\r?\n/g, ""))).parse(0).nodes;
1574
+ return writer.widgetSections(nodes);
1575
+ }
1576
+ function cssAttributes(spec) {
1577
+ const classes = [];
1578
+ const styles = [];
1579
+ let id = "";
1580
+ for (const part of spec.split(/\s+/).filter(p => p)) {
1581
+ if (part.startsWith("."))
1582
+ classes.push(...part.substring(1).split(".").filter(c => c));
1583
+ else if (part.startsWith("#"))
1584
+ id = part.substring(1);
1585
+ else
1586
+ styles.push(part);
1587
+ }
1588
+ let attrs = "";
1589
+ if (id)
1590
+ attrs += ` id="${escapeAttribute(id)}"`;
1591
+ if (classes.length)
1592
+ attrs += ` class="${escapeAttribute(classes.join(" "))}"`;
1593
+ if (styles.length)
1594
+ attrs += ` style="${escapeAttribute(styles.join(" "))}"`;
1595
+ return attrs;
1596
+ }
1597
+ function escapeAttribute(s) {
1598
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/\[/g, "&#91;").replace(/\]/g, "&#93;").replace(/\{\{/g, "&#123;{");
1599
+ }
1600
+ // A character of SugarCube prose, which isn't Markdown: * and _ would be emphasis
1601
+ function escapeProse(s, i) {
1602
+ const c = s[i];
1603
+ if (c == "*")
1604
+ return "&#42;";
1605
+ if (c == "`")
1606
+ return "&#96;";
1607
+ if (c == "_" && !(/\w/.test(s[i - 1] ?? "") && /\w/.test(s[i + 1] ?? "")))
1608
+ return "&#95;";
1609
+ if (c == "{" && s[i + 1] == "{")
1610
+ return "&#123;";
1611
+ if (c == "}" && s[i + 1] == "}")
1612
+ return "&#125;";
1613
+ return escapeText(c);
1614
+ }
1615
+ export function convertSugarCubePassage(text, ctx) {
1616
+ const writer = new Writer(ctx);
1617
+ // A backslash at the end of a line joins it to the next
1618
+ const source = writer.findTargets(text.replace(/\\\r?\n/g, ""));
1619
+ const nodes = new Parser(source).parse(0).nodes;
1620
+ return writer.passage(nodes, ctx.passage.tags.includes("nobr"));
1621
+ }