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,180 @@
1
+ // Finds Handlebars syntax errors in a section's or passage's text, which the runtime would
2
+ // otherwise only report when the text is shown ("Template error: Parse error on line 6...").
3
+ //
4
+ // The text is parsed the way the runtime's text processor compiles it: after the compiler has
5
+ // turned links into helpers, and after rewriteInfixExpressions. (The runtime also adds a __body=
6
+ // to each {{#every}} first, but that's only ever a string parameter, so it can't make a
7
+ // difference to whether the text parses.)
8
+ import Handlebars from "handlebars";
9
+ import { findTagEnd, InfixRewriteError, mapRewrittenPosition, rewriteInfixExpressions } from "./infix-expressions.js";
10
+ const lexer = Handlebars.Parser.lexer;
11
+ export function findTemplateError(text) {
12
+ if (!text.includes("{{"))
13
+ return null;
14
+ const edits = [];
15
+ let rewritten;
16
+ try {
17
+ rewritten = rewriteInfixExpressions(text, edits);
18
+ }
19
+ catch (e) {
20
+ // An expression it can't read, e.g. {{set "gold" gold +}}
21
+ if (!(e instanceof InfixRewriteError))
22
+ throw e;
23
+ const end = e.end + (text.startsWith("~}}", e.end) ? 3 : 2);
24
+ return { start: e.start, end, message: `${describeTag(text.slice(e.start, end))} isn't valid: ${e.message}` };
25
+ }
26
+ try {
27
+ Handlebars.parse(rewritten);
28
+ return null;
29
+ }
30
+ catch (e) {
31
+ const error = e;
32
+ const lineStarts = [0];
33
+ for (let i = 0; i < rewritten.length; i++) {
34
+ if (rewritten[i] == "\n")
35
+ lineStarts.push(i + 1);
36
+ }
37
+ const offset = (line, column) => mapRewrittenPosition(edits, Math.min((lineStarts[line - 1] ?? rewritten.length) + column, rewritten.length));
38
+ if (error.lineNumber !== undefined) {
39
+ return handlebarsError(text, error.message, offset(error.lineNumber, error.column ?? 0));
40
+ }
41
+ const loc = lexer.yylloc;
42
+ const pos = loc ? offset(loc.first_line, loc.first_column) : 0;
43
+ return parseError(text, error.message, pos);
44
+ }
45
+ }
46
+ // "unless doesn't match if - 1:3", or "Invalid path: a/this - 1:31"
47
+ function handlebarsError(text, message, pos) {
48
+ message = message.replace(/ - \d+:\d+$/, "");
49
+ const tag = tagAt(text, pos) ?? { start: pos, end: pos };
50
+ const tagText = describeTag(text.slice(tag.start, tag.end));
51
+ const mismatch = /^(.+) doesn't match (.+)$/.exec(message);
52
+ if (mismatch) {
53
+ return { ...tag, message: `${tagText} is closed by {{/${mismatch[2]}}}, but it needs a {{/${mismatch[1]}}}` };
54
+ }
55
+ return { ...tag, message: `${tagText} isn't valid Handlebars: ${message}` };
56
+ }
57
+ function parseError(text, message, pos) {
58
+ // The last line says what the parser expected, e.g. "Expecting 'ID', 'STRING', ..., got 'INVALID'"
59
+ const got = /got '([^']+)'\s*$/.exec(message)?.[1];
60
+ if (got == "EOF") {
61
+ const open = unclosedBlock(text);
62
+ if (open) {
63
+ return { ...open, message: `${describeTag(text.slice(open.start, open.end))} has no {{/${open.name}}} to close it` };
64
+ }
65
+ }
66
+ const tag = tagAt(text, pos);
67
+ if (!tag) {
68
+ const end = Math.min(pos + 1, text.length);
69
+ return { start: Math.min(pos, end), end, message: "this text isn't valid Handlebars" + (got ? ` (it found ${got == "EOF" ? "the end of the text" : `'${got}'`} where it didn't expect it)` : "") };
70
+ }
71
+ const tagText = text.slice(tag.start, tag.end);
72
+ return { ...tag, message: `${describeTag(tagText)} isn't valid Handlebars${hint(tagText)}` };
73
+ }
74
+ // Suggests {{= ...}} for what looks like an expression in a plain {{...}}, e.g. {{round + 1}}
75
+ function hint(tagText) {
76
+ const inner = tagText.replace(/^\{\{\{?~?\s*/, "").replace(/\s*~?\}?\}\}$/, "");
77
+ if (/^[#/=!>^&]|^else\b/.test(inner))
78
+ return "";
79
+ if (!/\s(?:[-+*/%<>?]|[=!<>]=|&&|\|\||and|or|contains)\s/.test(` ${inner} `))
80
+ return "";
81
+ return `. To show the result of an expression, start it with "=": {{= ${inner}}}`;
82
+ }
83
+ // The {{...}} tag that pos is in, if any
84
+ function tagAt(text, pos) {
85
+ let start = text.lastIndexOf("{{", pos);
86
+ if (start == -1)
87
+ return null;
88
+ if (text[start - 1] == "{")
89
+ start--;
90
+ const bodyStart = text.startsWith("{{{", start) ? start + 3 : start + 2;
91
+ const close = findTagEnd(text, bodyStart);
92
+ if (close == -1) {
93
+ const lineEnd = text.indexOf("\n", start);
94
+ return { start, end: lineEnd == -1 ? text.length : lineEnd };
95
+ }
96
+ let end = close + (text.startsWith("~}}", close) ? 3 : 2);
97
+ if (text[end] == "}" && bodyStart == start + 3)
98
+ end++;
99
+ if (pos >= end && pos > start)
100
+ return null;
101
+ return { start, end };
102
+ }
103
+ // The innermost {{#block}} with no {{/block}} after it
104
+ function unclosedBlock(text) {
105
+ const tags = /(\\*)\{\{~?\s*([#/])\s*([^\s}~]+)/g;
106
+ const open = [];
107
+ let match;
108
+ while ((match = tags.exec(text)) !== null) {
109
+ if (match[1].length % 2 == 1)
110
+ continue;
111
+ const start = match.index + match[1].length;
112
+ if (match[2] == "#") {
113
+ const close = findTagEnd(text, start + 2);
114
+ const end = close == -1 ? text.length : close + (text.startsWith("~}}", close) ? 3 : 2);
115
+ open.push({ start, end, name: match[3].replace(/^>/, "") });
116
+ }
117
+ else {
118
+ const index = open.map(o => o.name).lastIndexOf(match[3]);
119
+ if (index != -1)
120
+ open.length = index;
121
+ }
122
+ }
123
+ return open.pop() ?? null;
124
+ }
125
+ function describeTag(tagText) {
126
+ const oneLine = tagText.replace(/\s*\n\s*/g, " ");
127
+ return oneLine.length > 60 ? oneLine.substring(0, 57) + "..." : oneLine;
128
+ }
129
+ // Helpers whose blocks show their text with the same names as the text around them. In any other
130
+ // block, such as {{#each}} or one of the story's own helpers, a name can refer to something else.
131
+ const SAME_CONTEXT_BLOCKS = new Set(["if", "unless", "every", "once", "firsttime", "embed", "style", "label", "replace", "animate"]);
132
+ // The names used in a section's or passage's text, which it reads the way findTemplateError does.
133
+ // Text with a syntax error has none.
134
+ export function findTemplateNames(text) {
135
+ const result = { bare: [], embedParameters: new Set() };
136
+ if (!text.includes("{{"))
137
+ return result;
138
+ const edits = [];
139
+ let ast;
140
+ let rewritten;
141
+ try {
142
+ rewritten = rewriteInfixExpressions(text, edits);
143
+ ast = Handlebars.parse(rewritten);
144
+ }
145
+ catch {
146
+ return result;
147
+ }
148
+ const lineStarts = [0];
149
+ for (let i = 0; i < rewritten.length; i++) {
150
+ if (rewritten[i] == "\n")
151
+ lineStarts.push(i + 1);
152
+ }
153
+ const offset = (pos) => mapRewrittenPosition(edits, Math.min((lineStarts[pos.line - 1] ?? rewritten.length) + pos.column, rewritten.length));
154
+ const visit = (node, sameContext) => {
155
+ if (!node)
156
+ return;
157
+ if (node.path?.type == "PathExpression" && node.path.original == "embed") {
158
+ for (const pair of node.hash?.pairs ?? [])
159
+ result.embedParameters.add(pair.key);
160
+ }
161
+ if (node.type == "MustacheStatement" && sameContext && node.loc) {
162
+ const path = node.path;
163
+ if (path.type == "PathExpression" && !path.data && path.depth == 0 && !/^this\b/.test(path.original)
164
+ && path.parts.length && !node.params?.length && !node.hash?.pairs.length) {
165
+ result.bare.push({ start: offset(node.loc.start), end: offset(node.loc.end), name: path.original, root: path.parts[0] });
166
+ }
167
+ }
168
+ for (const child of [...node.params ?? [], ...(node.hash?.pairs ?? []).map(p => p.value)])
169
+ visit(child, sameContext);
170
+ if (node.type == "BlockStatement") {
171
+ const same = sameContext && node.path?.type == "PathExpression" && SAME_CONTEXT_BLOCKS.has(node.path.original);
172
+ visit(node.program, same);
173
+ visit(node.inverse, same);
174
+ }
175
+ for (const child of node.body ?? [])
176
+ visit(child, sameContext);
177
+ };
178
+ visit(ast, true);
179
+ return result;
180
+ }
package/dist/text.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ export interface TextLink {
2
+ linkType: "section" | "passage";
3
+ form: "named" | "unnamed" | "next" | "input";
4
+ text?: string;
5
+ target: string;
6
+ start: number;
7
+ end: number;
8
+ targetStart: number;
9
+ targetEnd: number;
10
+ }
11
+ export interface TextEmbed {
12
+ name: string;
13
+ start: number;
14
+ end: number;
15
+ nameStart: number;
16
+ nameEnd: number;
17
+ }
18
+ export type TextGoto = TextEmbed;
19
+ export type TextDeactivate = TextEmbed;
20
+ export interface NoNextSection {
21
+ display: string;
22
+ start: number;
23
+ end: number;
24
+ }
25
+ export interface TransformResult {
26
+ output: string;
27
+ links: TextLink[];
28
+ embeds: TextEmbed[];
29
+ gotos: TextGoto[];
30
+ deactivates: TextDeactivate[];
31
+ noNextSection: NoNextSection[];
32
+ mapStart: (pos: number) => number;
33
+ mapEnd: (pos: number) => number;
34
+ }
35
+ export declare const balancedTarget: string;
36
+ export declare function transformText(text: string, getNextSectionName: () => string | null, expressions?: boolean): TransformResult;
37
+ export interface SourceLine {
38
+ line: number;
39
+ length: number;
40
+ }
41
+ export declare function positionMapper(lines: SourceLine[], lineLengths: number[]): (offset: number) => {
42
+ line: number;
43
+ character: number;
44
+ };
package/dist/text.js ADDED
@@ -0,0 +1,348 @@
1
+ // Converts the links in a section's or passage's text into Handlebars helpers, and records
2
+ // where each link and embed was in the original text.
3
+ //
4
+ // The conversion is a series of regex replacements, each running on the output of the one
5
+ // before, and the exact order matters (for example, [[a]](b) has to be converted before [a](b)
6
+ // would match inside it). So rather than parse links some other way, this runs exactly those
7
+ // replacements, and keeps a map from each position in the current string back to the original
8
+ // text, so that what each regex matched can be traced to where it was written.
9
+ class MappedString {
10
+ constructor(original) {
11
+ Object.defineProperty(this, "original", {
12
+ enumerable: true,
13
+ configurable: true,
14
+ writable: true,
15
+ value: original
16
+ });
17
+ Object.defineProperty(this, "value", {
18
+ enumerable: true,
19
+ configurable: true,
20
+ writable: true,
21
+ value: void 0
22
+ });
23
+ Object.defineProperty(this, "segments", {
24
+ enumerable: true,
25
+ configurable: true,
26
+ writable: true,
27
+ value: void 0
28
+ });
29
+ this.value = original;
30
+ this.segments = original.length
31
+ ? [{ start: 0, end: original.length, origStart: 0, origEnd: original.length, copied: true }]
32
+ : [];
33
+ }
34
+ // Like String.replace with a global regex, except the callback gets the match's offset.
35
+ replace(regex, replacer) {
36
+ const replacements = [];
37
+ this.value = this.value.replace(regex, (...args) => {
38
+ // The callback's arguments are the match, the groups, the offset and the whole string.
39
+ // None of these regexes have named groups, so there's no groups object after those.
40
+ const offset = args[args.length - 2];
41
+ const match = args.slice(0, args.length - 2);
42
+ const text = replacer(match, offset);
43
+ replacements.push({ start: offset, end: offset + match[0].length, text });
44
+ return text;
45
+ });
46
+ if (replacements.length) {
47
+ this.applyToSegments(replacements);
48
+ }
49
+ }
50
+ applyToSegments(replacements) {
51
+ const segments = [];
52
+ let newPos = 0;
53
+ const copyRange = (from, to) => {
54
+ for (const s of this.segments) {
55
+ const start = Math.max(s.start, from);
56
+ const end = Math.min(s.end, to);
57
+ if (start >= end)
58
+ continue;
59
+ const length = end - start;
60
+ segments.push(s.copied
61
+ ? { start: newPos, end: newPos + length, origStart: s.origStart + start - s.start, origEnd: s.origStart + end - s.start, copied: true }
62
+ : { start: newPos, end: newPos + length, origStart: s.origStart, origEnd: s.origEnd, copied: false });
63
+ newPos += length;
64
+ }
65
+ };
66
+ let oldPos = 0;
67
+ for (const r of replacements) {
68
+ copyRange(oldPos, r.start);
69
+ const origStart = this.mapStart(r.start);
70
+ const origEnd = this.mapEnd(r.end);
71
+ if (r.text.length) {
72
+ segments.push({
73
+ start: newPos,
74
+ end: newPos + r.text.length,
75
+ origStart,
76
+ origEnd,
77
+ copied: r.text === this.original.substring(origStart, origEnd),
78
+ });
79
+ newPos += r.text.length;
80
+ }
81
+ oldPos = r.end;
82
+ }
83
+ copyRange(oldPos, Infinity);
84
+ this.segments = segments;
85
+ }
86
+ // Maps the start of a range in the current string to the original string.
87
+ mapStart(pos) {
88
+ const s = this.find(seg => seg.end > pos);
89
+ if (!s)
90
+ return this.original.length;
91
+ if (pos < s.start)
92
+ return s.origStart;
93
+ return s.copied ? s.origStart + pos - s.start : s.origStart;
94
+ }
95
+ // Maps the (exclusive) end of a range in the current string to the original string.
96
+ mapEnd(pos) {
97
+ const s = this.find(seg => seg.end >= pos);
98
+ if (!s)
99
+ return this.original.length;
100
+ if (pos <= s.start)
101
+ return s.origStart;
102
+ return s.copied ? s.origStart + pos - s.start : s.origEnd;
103
+ }
104
+ // Binary search for the first segment matching a predicate that's monotonic in segment order.
105
+ find(predicate) {
106
+ let low = 0;
107
+ let high = this.segments.length;
108
+ while (low < high) {
109
+ const mid = (low + high) >> 1;
110
+ if (predicate(this.segments[mid]))
111
+ high = mid;
112
+ else
113
+ low = mid + 1;
114
+ }
115
+ return this.segments[low];
116
+ }
117
+ }
118
+ // The target is everything before the first comma, and the setters everything after it. With
119
+ // expressions, they're kept as written, since a setter can contain commas in quotes, and the
120
+ // runtime splits them. Without, a space is added after each comma, as Squiffy 6 did.
121
+ function extractLinkFunctions(link, expressions) {
122
+ if (!expressions) {
123
+ const fragments = link.split(",");
124
+ return {
125
+ target: fragments[0].trim(),
126
+ setters: fragments.slice(1).join(", ")
127
+ };
128
+ }
129
+ const comma = link.indexOf(",");
130
+ return {
131
+ target: (comma == -1 ? link : link.substring(0, comma)).trim(),
132
+ setters: comma == -1 ? "" : link.substring(comma + 1),
133
+ };
134
+ }
135
+ function getAdditionalLinkParameters(link, expressions) {
136
+ const functions = extractLinkFunctions(link, expressions);
137
+ let additionalParameters = "";
138
+ if (functions.setters.trim().length > 0) {
139
+ additionalParameters += ` set="${escapeForHandlebarsString(functions.setters)}"`;
140
+ }
141
+ return {
142
+ target: functions.target,
143
+ additionalParameters
144
+ };
145
+ }
146
+ // Text with balanced brackets, nested up to three deep, as few characters as possible
147
+ const noBrackets = "[^()]";
148
+ const nested = (inner) => `\\((?:${noBrackets}|${inner})*\\)`;
149
+ export const balancedTarget = `(?:${noBrackets}|${nested(nested(nested(noBrackets)))})*?`;
150
+ function escapeForHandlebarsString(s) {
151
+ return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
152
+ }
153
+ // getNextSectionName returns the section after this one, for [[text>]] links, or null if
154
+ // there isn't one.
155
+ // expressions: whether link setters take expressions (see AnalyseSettings.expressions)
156
+ export function transformText(text, getNextSectionName, expressions = false) {
157
+ const input = new MappedString(text);
158
+ const links = [];
159
+ const embeds = [];
160
+ const noNextSection = [];
161
+ // Records a link, given the offset of its match and of its target group in the current string.
162
+ const addLink = (link, matchStart, matchLength, targetStart, targetLength) => {
163
+ links.push({
164
+ ...link,
165
+ start: input.mapStart(matchStart),
166
+ end: input.mapEnd(matchStart + matchLength),
167
+ targetStart: input.mapStart(targetStart),
168
+ targetEnd: input.mapEnd(targetStart + targetLength),
169
+ });
170
+ };
171
+ // Handlebars expressions can contain square brackets that aren't links, such as
172
+ // {{someArray.[1]}} or {{someHelper "[x]"}}, so swap each one for a placeholder while
173
+ // converting links. Text between block helpers like {{#if x}}...{{/if}} is still converted. A
174
+ // comment ends at --}}, and can have }} and links in it before that.
175
+ const mustaches = [];
176
+ input.replace(/\{\{!--[\s\S]*?--\}\}|\{\{\{[\s\S]*?\}\}\}|\{\{[\s\S]*?\}\}/g, ([match]) => {
177
+ mustaches.push(match);
178
+ return `${mustaches.length - 1}`;
179
+ });
180
+ const restore = (s) => s.replace(/(\d+)/g, (_match, i) => mustaches[Number(i)]);
181
+ // A link once it's converted, kept out of the way of the patterns for later kinds of link, which
182
+ // would otherwise find links in its setters, such as the [1] in [[Go]](next, party[1].hp += 2)
183
+ const converted = (helper) => {
184
+ mustaches.push(helper);
185
+ return `${mustaches.length - 1}`;
186
+ };
187
+ // A link's target, inside its (...). With expressions, a setter can have brackets in it, e.g.
188
+ // [[Buy]](shop, gold -= (price - 1) * 2), so the target can contain balanced brackets, up to
189
+ // three deep. Without, it ends at the first ")", as in Squiffy 6.
190
+ const target = expressions ? balancedTarget : "(?:.*?)";
191
+ // nextSectionLinkRegex matches [[text>]] - a link to the next section. Followed by a (target),
192
+ // it's a named link whose text ends with >, such as [[<i>Go in</i>]](cave).
193
+ const nextSectionLinkRegex = /\[\[([^\]]*?)>\]\](?!\()/g;
194
+ input.replace(nextSectionLinkRegex, ([match, rawText], offset) => {
195
+ const text = restore(rawText);
196
+ const nextSectionName = getNextSectionName();
197
+ if (!nextSectionName) {
198
+ noNextSection.push({ display: `[[${text}>]]`, start: input.mapStart(offset), end: input.mapEnd(offset + match.length) });
199
+ return `[[${text}]]`; // fallback
200
+ }
201
+ addLink({ linkType: "section", form: "next", text, target: "" }, offset, match.length, offset + 2 + rawText.length, 0);
202
+ return converted(`{{section "${escapeForHandlebarsString(nextSectionName)}" text="${escapeForHandlebarsString(text)}"}}`);
203
+ });
204
+ // namedNextSectionLinkRegex matches [[text]](>) or [[text]](>, setter=value)
205
+ // - a named link where target starts with >
206
+ const namedNextSectionLinkRegex = new RegExp(`\\[\\[([^\\]]*?)\\]\\]\\(>(${target})\\)`, "g");
207
+ input.replace(namedNextSectionLinkRegex, ([match, rawText, rawRest], offset) => {
208
+ const text = restore(rawText);
209
+ const rest = restore(rawRest);
210
+ const nextSectionName = getNextSectionName();
211
+ if (!nextSectionName) {
212
+ noNextSection.push({ display: `[[${text}]](>)`, start: input.mapStart(offset), end: input.mapEnd(offset + match.length) });
213
+ return `[[${text}]]`; // fallback
214
+ }
215
+ addLink({ linkType: "section", form: "next", text, target: rest }, offset, match.length, offset + 2 + rawText.length + 4, rawRest.length);
216
+ // rest could be empty or ", setter=value"
217
+ const parsedName = getAdditionalLinkParameters(nextSectionName + rest, expressions);
218
+ return converted(`{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`);
219
+ });
220
+ // namedSectionLinkRegex matches:
221
+ // open [[
222
+ // any text - the link text
223
+ // closing ]]
224
+ // open bracket
225
+ // any text - the name of the section
226
+ // closing bracket
227
+ const namedSectionLinkRegex = new RegExp(`\\[\\[([^\\]]*?)\\]\\]\\((${target})\\)`, "g");
228
+ input.replace(namedSectionLinkRegex, ([match, rawText, rawName], offset) => {
229
+ const text = restore(rawText);
230
+ const name = restore(rawName);
231
+ addLink({ linkType: "section", form: "named", text, target: name }, offset, match.length, offset + 2 + rawText.length + 3, rawName.length);
232
+ const parsedName = getAdditionalLinkParameters(name, expressions);
233
+ return converted(`{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`);
234
+ });
235
+ // namedPassageLinkRegex matches:
236
+ // not preceded by ! (to avoid matching image links like ![alt](src))
237
+ // open [
238
+ // any text - the link text
239
+ // closing ]
240
+ // open bracket, but not http(s):// after it
241
+ // any text - the name of the passage
242
+ // closing bracket
243
+ const namedPassageLinkRegex = new RegExp(`(?<!!)\\[([^\\]]*?)\\]\\(((?!https?:\\/\\/)${target})\\)`, "g");
244
+ input.replace(namedPassageLinkRegex, ([match, rawText, rawName], offset) => {
245
+ const text = restore(rawText);
246
+ const name = restore(rawName);
247
+ addLink({ linkType: "passage", form: "named", text, target: name }, offset, match.length, offset + 1 + rawText.length + 2, rawName.length);
248
+ const parsedName = getAdditionalLinkParameters(name, expressions);
249
+ return converted(`{{passage "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`);
250
+ });
251
+ // unnamedSectionLinkRegex matches:
252
+ // open [[
253
+ // any text - the link text
254
+ // closing ]]
255
+ const unnamedSectionLinkRegex = /\[\[(.*?)\]\]/g;
256
+ input.replace(unnamedSectionLinkRegex, ([match, rawName], offset) => {
257
+ const name = restore(rawName);
258
+ addLink({ linkType: "section", form: "unnamed", target: name }, offset, match.length, offset + 2, rawName.length);
259
+ return converted(`{{section "${escapeForHandlebarsString(name)}"}}`);
260
+ });
261
+ // unnamedPassageLinkRegex matches:
262
+ // not preceded by ! (to avoid matching image links like ![alt])
263
+ // open [
264
+ // any text - the link text
265
+ // closing ]
266
+ // no bracket after
267
+ const unnamedPassageLinkRegex = /(?<!!)\[(.*?)\]([^(]|$)/g;
268
+ input.replace(unnamedPassageLinkRegex, ([match, rawName, suffix], offset) => {
269
+ const name = restore(rawName);
270
+ addLink({ linkType: "passage", form: "unnamed", target: name }, offset, match.length - suffix.length, offset + 1, rawName.length);
271
+ return converted(`{{passage "${escapeForHandlebarsString(name)}"}}`) + suffix;
272
+ });
273
+ input.replace(/(\d+)/g, ([, i]) => mustaches[Number(i)]);
274
+ // Matches {{embed "name"}} or {{goto 'name'}} with a literal name. An embed can also be a
275
+ // block, {{#embed "name"}}...{{/embed}}, which wraps text (#450).
276
+ const findNamed = (helper, block = false) => {
277
+ const result = [];
278
+ const regex = new RegExp(`\\{\\{~?\\s*${block ? "#?" : ""}${helper}\\s+(["'])(.*?)\\1`, "g");
279
+ let match;
280
+ while ((match = regex.exec(input.value))) {
281
+ const start = match.index;
282
+ const end = start + match[0].length;
283
+ const nameEnd = end - 1;
284
+ const nameStart = nameEnd - match[2].length;
285
+ result.push({
286
+ name: match[2],
287
+ start: input.mapStart(start),
288
+ end: input.mapEnd(end),
289
+ nameStart: input.mapStart(nameStart),
290
+ nameEnd: input.mapEnd(nameEnd),
291
+ });
292
+ }
293
+ return result;
294
+ };
295
+ embeds.push(...findNamed("embed", true));
296
+ // A text box that goes to a section or passage when Enter is pressed (#454), as in
297
+ // <input data-attribute="name" data-section="next">. It's left as it is, and only recorded.
298
+ const inputTag = /<input\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi;
299
+ const targetAttribute = /\sdata-(section|passage)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i;
300
+ let tag;
301
+ while ((tag = inputTag.exec(input.value))) {
302
+ const attribute = targetAttribute.exec(tag[0]);
303
+ if (!attribute)
304
+ continue;
305
+ const name = attribute[2] ?? attribute[3] ?? attribute[4];
306
+ const start = tag.index;
307
+ const nameEnd = start + attribute.index + attribute[0].length - (attribute[4] === undefined ? 1 : 0);
308
+ const nameStart = nameEnd - name.length;
309
+ links.push({
310
+ linkType: attribute[1].toLowerCase() == "section" ? "section" : "passage",
311
+ form: "input",
312
+ target: name,
313
+ start: input.mapStart(start),
314
+ end: input.mapEnd(start + tag[0].length),
315
+ targetStart: input.mapStart(nameStart),
316
+ targetEnd: input.mapEnd(nameEnd),
317
+ });
318
+ }
319
+ return {
320
+ output: input.value, links, embeds, gotos: findNamed("goto"), deactivates: findNamed("deactivate"), noNextSection,
321
+ mapStart: pos => input.mapStart(pos),
322
+ mapEnd: pos => input.mapEnd(pos),
323
+ };
324
+ }
325
+ // Returns a function that converts an offset into lines.join("\n") to a position in the source file.
326
+ export function positionMapper(lines, lineLengths) {
327
+ const starts = [];
328
+ let pos = 0;
329
+ for (const length of lineLengths) {
330
+ starts.push(pos);
331
+ pos += length + 1;
332
+ }
333
+ return (offset) => {
334
+ let low = 0;
335
+ let high = starts.length - 1;
336
+ while (low < high) {
337
+ const mid = (low + high + 1) >> 1;
338
+ if (starts[mid] <= offset)
339
+ low = mid;
340
+ else
341
+ high = mid - 1;
342
+ }
343
+ const source = lines[low];
344
+ if (!source)
345
+ return { line: 0, character: 0 };
346
+ return { line: source.line, character: Math.min(offset - starts[low], source.length) };
347
+ };
348
+ }
@@ -0,0 +1,21 @@
1
+ import type { PassageContext } from "./convert.js";
2
+ export interface StoryAudio {
3
+ files: Map<string, string>;
4
+ looping: Set<string>;
5
+ }
6
+ export declare function trackFile(audio: StoryAudio, track: string): string;
7
+ export declare function pickSource(sources: string[]): string | undefined;
8
+ export interface AudioAction {
9
+ play: boolean;
10
+ stop: boolean;
11
+ loop: boolean;
12
+ fade?: number;
13
+ volume?: number;
14
+ }
15
+ export declare function audioHelper(ctx: PassageContext, raw: string, audio: StoryAudio, track: string, action: AudioAction): string;
16
+ export declare const STOP_ALL_AUDIO = "{{stopsounds}}{{stopmusic}}";
17
+ export declare function audioDirective(helper: string): string | null;
18
+ export declare function leadingAudio(out: string, state: {
19
+ leading: boolean;
20
+ directives: string[];
21
+ }): string;
@@ -0,0 +1,80 @@
1
+ // Converts Twine's sound to Squiffy's music and sound helpers (#444). Squiffy has two kinds of
2
+ // sound: music, which loops and carries on from one section to the next until it's changed, and
3
+ // sounds, which play once. A Twine track that's set to loop anywhere in the story is music, and
4
+ // any other is a sound.
5
+ import { quote, Unconvertible } from "./expression.js";
6
+ // The file a track plays: the one the story gives it, or the track name itself if that looks
7
+ // like a file, such as "rain.mp3"
8
+ export function trackFile(audio, track) {
9
+ const file = audio.files.get(track);
10
+ if (file !== undefined)
11
+ return file;
12
+ if (/\.\w{2,4}$/.test(track))
13
+ return track;
14
+ throw new Unconvertible(`a track ("${track}") that the story doesn't give a file for`);
15
+ }
16
+ // The best of a track's sources: MP3 plays in every browser
17
+ export function pickSource(sources) {
18
+ return sources.find(s => /\.mp3(\?|#|$)/i.test(s)) ?? sources[0];
19
+ }
20
+ // What a track does, as Squiffy: {{music}}, {{stopmusic}}, {{sound}}, {{stopsounds}}, or nothing
21
+ export function audioHelper(ctx, raw, audio, track, action) {
22
+ const looping = action.loop || audio.looping.has(track);
23
+ const fade = action.fade === undefined ? "" : ` fade=${action.fade}`;
24
+ if (action.stop) {
25
+ if (looping)
26
+ return `{{stopmusic${fade}}}`;
27
+ // Squiffy stops every sound playing once, which is the same thing if there's only one
28
+ const sounds = new Set([...audio.files.keys()].filter(t => !audio.looping.has(t)));
29
+ sounds.add(track);
30
+ if (sounds.size > 1) {
31
+ ctx.story.note("audio-stop-sound", raw, "Squiffy stops every sound that's playing once, not just one track, so these stop the others too");
32
+ }
33
+ return "{{stopsounds}}";
34
+ }
35
+ if (!action.play)
36
+ return "";
37
+ const file = quote(trackFile(audio, track));
38
+ if (looping) {
39
+ if (action.volume !== undefined && action.volume != 1) {
40
+ ctx.story.note("audio-music-volume", raw, "Squiffy plays music at full volume, so the music's volume has been left out");
41
+ }
42
+ return `{{music ${file}${fade}}}`;
43
+ }
44
+ const volume = action.volume !== undefined && action.volume != 1 ? ` volume=${Math.max(0, Math.min(1, action.volume))}` : "";
45
+ return `{{sound ${file}${volume}}}`;
46
+ }
47
+ // Stops every sound and the music, as <<masteraudio stop>> and (masteraudio: "stopall") do
48
+ export const STOP_ALL_AUDIO = "{{stopsounds}}{{stopmusic}}";
49
+ // A helper that can be a directive, @music or @sound, for the start of a passage, or null
50
+ export function audioDirective(helper) {
51
+ if (helper == "{{stopmusic}}")
52
+ return "@music stop";
53
+ if (helper == "{{stopsounds}}")
54
+ return "@sound stop";
55
+ const m = /^\{\{(music|sound) "([^"&{}]+)"\}\}$/.exec(helper);
56
+ if (!m || m[2].trim() != m[2] || m[2] == "stop")
57
+ return null;
58
+ return `@${m[1]} ${m[2]}`;
59
+ }
60
+ // Audio helpers as directives where they can be, at the start of a passage
61
+ export function leadingAudio(out, state) {
62
+ if (!state.leading)
63
+ return out;
64
+ const helpers = out.match(/\{\{[^{}]*\}\}/g) ?? [];
65
+ const directives = helpers.map(audioDirective);
66
+ if (helpers.join("") != out || directives.some(d => d === null)) {
67
+ state.leading = false;
68
+ return out;
69
+ }
70
+ for (const directive of directives) {
71
+ // Only the last @music counts, as in Harlowe stopping one track and playing another
72
+ if (directive.startsWith("@music ")) {
73
+ const earlier = state.directives.findIndex(d => d.startsWith("@music "));
74
+ if (earlier != -1)
75
+ state.directives.splice(earlier, 1);
76
+ }
77
+ state.directives.push(directive);
78
+ }
79
+ return "";
80
+ }