squiffy-compiler 7.0.0-beta.3 → 7.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/text.js CHANGED
@@ -115,30 +115,45 @@ class MappedString {
115
115
  return this.segments[low];
116
116
  }
117
117
  }
118
- function extractLinkFunctions(link) {
119
- const fragments = link.split(",");
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(",");
120
130
  return {
121
- target: fragments[0].trim(),
122
- setters: fragments.slice(1).join(", ")
131
+ target: (comma == -1 ? link : link.substring(0, comma)).trim(),
132
+ setters: comma == -1 ? "" : link.substring(comma + 1),
123
133
  };
124
134
  }
125
- function getAdditionalLinkParameters(link) {
126
- const functions = extractLinkFunctions(link);
135
+ function getAdditionalLinkParameters(link, expressions) {
136
+ const functions = extractLinkFunctions(link, expressions);
127
137
  let additionalParameters = "";
128
- if (functions.setters.length > 0) {
129
- additionalParameters += ` set="${functions.setters}"`;
138
+ if (functions.setters.trim().length > 0) {
139
+ additionalParameters += ` set="${escapeForHandlebarsString(functions.setters)}"`;
130
140
  }
131
141
  return {
132
142
  target: functions.target,
133
143
  additionalParameters
134
144
  };
135
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)))})*?`;
136
150
  function escapeForHandlebarsString(s) {
137
151
  return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
138
152
  }
139
153
  // getNextSectionName returns the section after this one, for [[text>]] links, or null if
140
154
  // there isn't one.
141
- export function transformText(text, getNextSectionName) {
155
+ // expressions: whether link setters take expressions (see AnalyseSettings.expressions)
156
+ export function transformText(text, getNextSectionName, expressions = false) {
142
157
  const input = new MappedString(text);
143
158
  const links = [];
144
159
  const embeds = [];
@@ -162,6 +177,10 @@ export function transformText(text, getNextSectionName) {
162
177
  return `${mustaches.length - 1}`;
163
178
  });
164
179
  const restore = (s) => s.replace(/(\d+)/g, (_match, i) => mustaches[Number(i)]);
180
+ // A link's target, inside its (...). With expressions, a setter can have brackets in it, e.g.
181
+ // [[Buy]](shop, gold -= (price - 1) * 2), so the target can contain balanced brackets, up to
182
+ // three deep. Without, it ends at the first ")", as in Squiffy 6.
183
+ const target = expressions ? balancedTarget : "(?:.*?)";
165
184
  // nextSectionLinkRegex matches [[text>]] - a link to the next section
166
185
  const nextSectionLinkRegex = /\[\[([^\]]*?)>\]\]/g;
167
186
  input.replace(nextSectionLinkRegex, ([match, rawText], offset) => {
@@ -176,7 +195,7 @@ export function transformText(text, getNextSectionName) {
176
195
  });
177
196
  // namedNextSectionLinkRegex matches [[text]](>) or [[text]](>, setter=value)
178
197
  // - a named link where target starts with >
179
- const namedNextSectionLinkRegex = /\[\[([^\]]*?)\]\]\(>(.*?)\)/g;
198
+ const namedNextSectionLinkRegex = new RegExp(`\\[\\[([^\\]]*?)\\]\\]\\(>(${target})\\)`, "g");
180
199
  input.replace(namedNextSectionLinkRegex, ([match, rawText, rawRest], offset) => {
181
200
  const text = restore(rawText);
182
201
  const rest = restore(rawRest);
@@ -187,7 +206,7 @@ export function transformText(text, getNextSectionName) {
187
206
  }
188
207
  addLink({ linkType: "section", form: "next", text, target: rest }, offset, match.length, offset + 2 + rawText.length + 4, rawRest.length);
189
208
  // rest could be empty or ", setter=value"
190
- const parsedName = getAdditionalLinkParameters(nextSectionName + rest);
209
+ const parsedName = getAdditionalLinkParameters(nextSectionName + rest, expressions);
191
210
  return `{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`;
192
211
  });
193
212
  // namedSectionLinkRegex matches:
@@ -197,12 +216,12 @@ export function transformText(text, getNextSectionName) {
197
216
  // open bracket
198
217
  // any text - the name of the section
199
218
  // closing bracket
200
- const namedSectionLinkRegex = /\[\[([^\]]*?)\]\]\((.*?)\)/g;
219
+ const namedSectionLinkRegex = new RegExp(`\\[\\[([^\\]]*?)\\]\\]\\((${target})\\)`, "g");
201
220
  input.replace(namedSectionLinkRegex, ([match, rawText, rawName], offset) => {
202
221
  const text = restore(rawText);
203
222
  const name = restore(rawName);
204
223
  addLink({ linkType: "section", form: "named", text, target: name }, offset, match.length, offset + 2 + rawText.length + 3, rawName.length);
205
- const parsedName = getAdditionalLinkParameters(name);
224
+ const parsedName = getAdditionalLinkParameters(name, expressions);
206
225
  return `{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`;
207
226
  });
208
227
  // namedPassageLinkRegex matches:
@@ -213,12 +232,12 @@ export function transformText(text, getNextSectionName) {
213
232
  // open bracket, but not http(s):// after it
214
233
  // any text - the name of the passage
215
234
  // closing bracket
216
- const namedPassageLinkRegex = /(?<!!)\[([^\]]*?)\]\(((?!https?:\/\/).*?)\)/g;
235
+ const namedPassageLinkRegex = new RegExp(`(?<!!)\\[([^\\]]*?)\\]\\(((?!https?:\\/\\/)${target})\\)`, "g");
217
236
  input.replace(namedPassageLinkRegex, ([match, rawText, rawName], offset) => {
218
237
  const text = restore(rawText);
219
238
  const name = restore(rawName);
220
239
  addLink({ linkType: "passage", form: "named", text, target: name }, offset, match.length, offset + 1 + rawText.length + 2, rawName.length);
221
- const parsedName = getAdditionalLinkParameters(name);
240
+ const parsedName = getAdditionalLinkParameters(name, expressions);
222
241
  return `{{passage "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`;
223
242
  });
224
243
  // unnamedSectionLinkRegex matches:
@@ -244,23 +263,28 @@ export function transformText(text, getNextSectionName) {
244
263
  return `{{passage "${escapeForHandlebarsString(name)}"}}${suffix}`;
245
264
  });
246
265
  input.replace(/(\d+)/g, ([, i]) => mustaches[Number(i)]);
247
- // embedRegex matches {{embed "name"}} or {{embed 'name'}} with a literal name.
248
- const embedRegex = /\{\{~?\s*embed\s+(["'])(.*?)\1/g;
249
- let match;
250
- while ((match = embedRegex.exec(input.value))) {
251
- const start = match.index;
252
- const end = start + match[0].length;
253
- const nameEnd = end - 1;
254
- const nameStart = nameEnd - match[2].length;
255
- embeds.push({
256
- name: match[2],
257
- start: input.mapStart(start),
258
- end: input.mapEnd(end),
259
- nameStart: input.mapStart(nameStart),
260
- nameEnd: input.mapEnd(nameEnd),
261
- });
262
- }
263
- return { output: input.value, links, embeds, noNextSection };
266
+ // Matches {{embed "name"}} or {{goto 'name'}} with a literal name.
267
+ const findNamed = (helper) => {
268
+ const result = [];
269
+ const regex = new RegExp(`\\{\\{~?\\s*${helper}\\s+(["'])(.*?)\\1`, "g");
270
+ let match;
271
+ while ((match = regex.exec(input.value))) {
272
+ const start = match.index;
273
+ const end = start + match[0].length;
274
+ const nameEnd = end - 1;
275
+ const nameStart = nameEnd - match[2].length;
276
+ result.push({
277
+ name: match[2],
278
+ start: input.mapStart(start),
279
+ end: input.mapEnd(end),
280
+ nameStart: input.mapStart(nameStart),
281
+ nameEnd: input.mapEnd(nameEnd),
282
+ });
283
+ }
284
+ return result;
285
+ };
286
+ embeds.push(...findNamed("embed"));
287
+ return { output: input.value, links, embeds, gotos: findNamed("goto"), noNextSection };
264
288
  }
265
289
  // Returns a function that converts an offset into lines.join("\n") to a position in the source file.
266
290
  export function positionMapper(lines, lineLengths) {
@@ -0,0 +1,75 @@
1
+ import type { Expr } from "./expression.js";
2
+ import type { TwinePassage, TwineStory } from "./story.js";
3
+ export interface TwineConversionProblem {
4
+ passage?: string;
5
+ text: string;
6
+ reason: string;
7
+ }
8
+ export interface TwineConversionResult {
9
+ title: string;
10
+ format: string;
11
+ files: Record<string, string>;
12
+ main: string;
13
+ passages: number;
14
+ problems: TwineConversionProblem[];
15
+ }
16
+ export interface TwineConversionOptions {
17
+ name?: string;
18
+ }
19
+ export interface PassageContext {
20
+ readonly story: StoryContext;
21
+ readonly passage: TwinePassage;
22
+ readonly section: string;
23
+ unconvertible(text: string, reason: string): string;
24
+ approximate(text: string, reason: string): void;
25
+ addPassage(nameHint: string, content: ConvertedPassage | string): string;
26
+ reservePassage(nameHint: string): {
27
+ name: string;
28
+ fill: (content: ConvertedPassage | string) => void;
29
+ };
30
+ addSection(nameHint: string, content: ConvertedPassage | string): string;
31
+ newLabel(hint: string): string;
32
+ }
33
+ export interface ConvertedPassage {
34
+ directives: string[];
35
+ body: string;
36
+ }
37
+ export declare class StoryContext {
38
+ readonly twine: TwineStory;
39
+ readonly problems: TwineConversionProblem[];
40
+ private readonly sectionNames;
41
+ private readonly usedSectionNames;
42
+ private readonly usedLabels;
43
+ readonly extraSections: string[];
44
+ private readonly permanentVars;
45
+ readonly passagesByName: Map<string, TwinePassage>;
46
+ constructor(twine: TwineStory, passages: TwinePassage[]);
47
+ private readonly problemKeys;
48
+ addProblem(problem: TwineConversionProblem): void;
49
+ notePermanentVar(name: string): void;
50
+ sectionFor(passageName: string): string | undefined;
51
+ private trimmed?;
52
+ private trimmedNames;
53
+ private readonly cache;
54
+ cached<T>(key: string, make: () => T): T;
55
+ private readonly notes;
56
+ note(key: string, text: string, reason: string): void;
57
+ noteProblems(): TwineConversionProblem[];
58
+ sectionForUnknown(passageName: string): string;
59
+ uniqueSectionName(hint: string): string;
60
+ newLabel(hint: string): string;
61
+ attribute(name: string, temporary: boolean): string;
62
+ }
63
+ export declare function sanitiseName(name: string): string;
64
+ export declare function escapeText(text: string): string;
65
+ export declare function sectionLink(text: string | null, target: string, setters?: string[]): string;
66
+ export declare function isUrl(target: string): boolean;
67
+ export declare function urlLink(text: string, url: string): string;
68
+ export declare function dynamicSectionLink(text: string, target: Expr, setters?: string[]): string;
69
+ export declare function passageLink(text: string, target: string): string;
70
+ export declare function setter(name: string, op: "=" | "+=" | "-=" | "*=" | "/=", value: Expr, inLink: boolean): string;
71
+ export declare function comment(text: string): string;
72
+ export declare function formatTwineProblems(result: TwineConversionResult, sourceName?: string): string;
73
+ export declare function convertTwine(source: string, options?: TwineConversionOptions): TwineConversionResult;
74
+ export declare function convertTwineStory(twine: TwineStory, options?: TwineConversionOptions): TwineConversionResult;
75
+ export declare function finishText(text: string): string;