squiffy-compiler 7.0.0-beta.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 (61) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +20 -1
  3. package/dist/analyse.js +457 -26
  4. package/dist/compiler.d.ts +20 -0
  5. package/dist/compiler.js +9 -1
  6. package/dist/css-urls.d.ts +4 -0
  7. package/dist/css-urls.js +59 -0
  8. package/dist/emit.d.ts +28 -0
  9. package/dist/emit.js +79 -1
  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 +14 -1
  17. package/dist/language-service.js +266 -52
  18. package/dist/node.d.ts +23 -0
  19. package/dist/node.js +122 -0
  20. package/dist/parse.d.ts +5 -0
  21. package/dist/parse.js +62 -4
  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 +56 -4
  41. package/dist/templates.d.ts +17 -0
  42. package/dist/templates.js +180 -0
  43. package/dist/text.d.ts +9 -2
  44. package/dist/text.js +99 -39
  45. package/dist/twine/audio.d.ts +21 -0
  46. package/dist/twine/audio.js +80 -0
  47. package/dist/twine/convert.d.ts +131 -0
  48. package/dist/twine/convert.js +1057 -0
  49. package/dist/twine/expression.d.ts +88 -0
  50. package/dist/twine/expression.js +318 -0
  51. package/dist/twine/harlowe.d.ts +27 -0
  52. package/dist/twine/harlowe.js +2341 -0
  53. package/dist/twine/settings.d.ts +9 -0
  54. package/dist/twine/settings.js +322 -0
  55. package/dist/twine/story.d.ts +24 -0
  56. package/dist/twine/story.js +231 -0
  57. package/dist/twine/sugarcube.d.ts +40 -0
  58. package/dist/twine/sugarcube.js +2172 -0
  59. package/dist/v5.js +2 -1
  60. package/package.json +23 -5
  61. package/syntaxes/squiffy.tmLanguage.json +1003 -0
package/dist/analyse.js CHANGED
@@ -1,6 +1,12 @@
1
1
  import { parse } from "./parse.js";
2
2
  import { positionMapper, transformText } from "./text.js";
3
+ import { isScriptPath, isSquiffyPath, isStylesheetPath, PROJECT_FILENAME } from "./project.js";
3
4
  import { findV5Syntax } from "./v5.js";
5
+ import { findTemplateError, findTemplateNames } from "./templates.js";
6
+ import { BUILT_IN_HELPERS } from "./helpers.js";
7
+ import { ignoredDiagnostics } from "./ignore.js";
8
+ import { sectionLabels } from "./section-labels.js";
9
+ import { attributesSetIn, BUILT_IN_ATTRIBUTES, findAtAttributes, findBuiltInAttributeSets, findUnquotedText } from "./setters.js";
4
10
  // Caches the syntax tree of each file by filename, reparsing a file only when its text changes.
5
11
  export class ParseCache {
6
12
  constructor() {
@@ -107,6 +113,67 @@ class TextContainer {
107
113
  writable: true,
108
114
  value: []
109
115
  });
116
+ // @music (#444): the file to play, or null for @music stop. Undefined leaves it as it is.
117
+ Object.defineProperty(this, "music", {
118
+ enumerable: true,
119
+ configurable: true,
120
+ writable: true,
121
+ value: void 0
122
+ });
123
+ // @sound: the files to play once, in order, with "stop" for @sound stop
124
+ Object.defineProperty(this, "sounds", {
125
+ enumerable: true,
126
+ configurable: true,
127
+ writable: true,
128
+ value: []
129
+ });
130
+ // @class (#449): classes on the story's element while the section is the current one
131
+ Object.defineProperty(this, "classes", {
132
+ enumerable: true,
133
+ configurable: true,
134
+ writable: true,
135
+ value: []
136
+ });
137
+ // @tag (#527): tags the story can list sections and passages by
138
+ Object.defineProperty(this, "tags", {
139
+ enumerable: true,
140
+ configurable: true,
141
+ writable: true,
142
+ value: []
143
+ });
144
+ // @transition (#489): how it appears, and how long that takes in milliseconds
145
+ Object.defineProperty(this, "transition", {
146
+ enumerable: true,
147
+ configurable: true,
148
+ writable: true,
149
+ value: void 0
150
+ });
151
+ Object.defineProperty(this, "transitionTime", {
152
+ enumerable: true,
153
+ configurable: true,
154
+ writable: true,
155
+ value: void 0
156
+ });
157
+ // @leave: how the old text goes when this clears the screen, and how long that takes
158
+ Object.defineProperty(this, "leave", {
159
+ enumerable: true,
160
+ configurable: true,
161
+ writable: true,
162
+ value: void 0
163
+ });
164
+ Object.defineProperty(this, "leaveTime", {
165
+ enumerable: true,
166
+ configurable: true,
167
+ writable: true,
168
+ value: void 0
169
+ });
170
+ // Where @leave is, to say if there's nothing for it to do
171
+ Object.defineProperty(this, "leaveNode", {
172
+ enumerable: true,
173
+ configurable: true,
174
+ writable: true,
175
+ value: void 0
176
+ });
110
177
  // The text after links have been converted
111
178
  Object.defineProperty(this, "output", {
112
179
  enumerable: true,
@@ -181,42 +248,114 @@ export class Passage extends TextContainer {
181
248
  writable: true,
182
249
  value: node
183
250
  });
251
+ // @repeat: its links stay clickable (#104)
252
+ Object.defineProperty(this, "repeat", {
253
+ enumerable: true,
254
+ configurable: true,
255
+ writable: true,
256
+ value: false
257
+ });
184
258
  }
185
259
  }
186
260
  export const analysisInternals = new WeakMap();
187
261
  const lineRange = (node) => node.range;
262
+ // A @transition time (#489), such as "1s", "0.5s" or "400ms", in milliseconds
263
+ function parseTransitionTime(time) {
264
+ const match = /^(\d+(?:\.\d+)?|\.\d+)(s|ms)$/.exec(time);
265
+ if (!match)
266
+ return undefined;
267
+ return Math.round(parseFloat(match[1]) * (match[2] == "s" ? 1000 : 1));
268
+ }
188
269
  // Resolves @imports, builds the story's sections and passages, and reports diagnostics.
189
270
  export async function analyse(settings) {
190
271
  const story = new Story();
191
272
  const cache = settings.parseCache ?? new ParseCache();
192
273
  const files = [];
274
+ // Each file's text, in the same order as files
275
+ const texts = [];
193
276
  const diagnostics = [];
194
277
  const legacyErrors = [];
195
278
  const legacyWarnings = [];
196
279
  let autoSectionCount = 0;
197
- const report = (severity, code, filename, range, message, legacyLine) => {
198
- diagnostics.push({ file: filename ?? "", range, severity, code, message });
280
+ // The story starts at the main file's first section by default, even if an @import
281
+ // above it has already added sections from other files.
282
+ let mainFirstSection;
283
+ // Each warning's line in legacyWarnings, so that a warning a squiffy-ignore comment turns off can be removed from both
284
+ const legacyWarningOf = new Map();
285
+ const report = (severity, code, filename, range, message, legacyLine, subject) => {
286
+ const diagnostic = { file: filename ?? "", range, severity, code, message, ...(subject === undefined ? {} : { subject }) };
287
+ diagnostics.push(diagnostic);
288
+ if (severity == "hint")
289
+ return;
199
290
  const legacy = `${severity.toUpperCase()}: ${filename} line ${legacyLine}: ${message}`;
200
291
  (severity == "error" ? legacyErrors : legacyWarnings).push(legacy);
292
+ if (severity == "warning")
293
+ legacyWarningOf.set(diagnostic, legacy);
294
+ };
295
+ const storyFiles = settings.storyFiles && new Set(settings.storyFiles);
296
+ // The .squiffy files processed so far, so a story file the main file has already @imported
297
+ // isn't processed again
298
+ const processed = new Set();
299
+ // Files read by @ui, which in folder mode aren't added to the page as scripts too
300
+ const uiFiles = new Set();
301
+ // The .css and .js files added to the page so far, named as getMatchingFilenames names them
302
+ const stylesheetFiles = [];
303
+ const scriptFiles = [];
304
+ // Adds a stylesheet or script to the page. An @import adds it every time, as in Squiffy 6, but
305
+ // folder mode only adds one that isn't there already.
306
+ const addPageFile = (filename, externalFiles, imported) => {
307
+ const [names, local] = isStylesheetPath(filename)
308
+ ? [stylesheetFiles, story.stylesheets]
309
+ : [scriptFiles, story.scripts];
310
+ if (names.includes(filename) && !imported)
311
+ return;
312
+ if (!names.includes(filename))
313
+ names.push(filename);
314
+ local.push(externalFiles.getLocalFilename(filename));
201
315
  };
202
316
  async function processFile(text, filename, isFirst) {
203
317
  const file = cache.parse(text, filename);
204
318
  files.push(file);
319
+ texts.push(text);
320
+ processed.add(filename);
205
321
  const lines = text.replace(/\r/g, "").split("\n");
206
322
  warnAboutV5Syntax(text, lines, filename);
323
+ if (settings.expressions) {
324
+ for (const found of findAtAttributes(file)) {
325
+ const name = found.text.substring(1);
326
+ report("warning", "squiffy/at-attribute", filename, found.range, `Use ${name} rather than ${found.text}: in a story with a ${PROJECT_FILENAME}, setters name attributes without "@".`, found.range.start.line + 1);
327
+ }
328
+ }
207
329
  let section = null;
208
330
  let passage = null;
209
331
  let inUiBlock = false;
332
+ // Where an earlier section or passage was defined, for a duplicate's warning
333
+ const earlierLocation = (earlierFilename, line) => earlierFilename == filename || !earlierFilename ? `line ${line}` : `${earlierFilename} line ${line}`;
334
+ const addSection = (name, line, node) => {
335
+ if (isFirst && !mainFirstSection)
336
+ mainFirstSection = name;
337
+ const earlier = hasOwn(story.sections, name) ? story.sections[name] : undefined;
338
+ // The compiler's own names (_default, _continue1, ...) only clash with a section the
339
+ // author named the same way. The main file's preamble can add "_default" more than
340
+ // once, each replacing the last, but that's not a clash the author can see.
341
+ if (earlier && node && !(node.kind == "preamble" && earlier.node?.kind == "preamble")) {
342
+ // A --- in the preamble starts a section that has no node of its own
343
+ const range = node.nameRange ?? node.header?.range
344
+ ?? { start: { line: line - 1, character: 0 }, end: { line: line - 1, character: lines[line - 1]?.length ?? 0 } };
345
+ report("warning", "squiffy/duplicate-section", filename, range, `There's already a section called [[${name}]], at ${earlierLocation(earlier.filename, earlier.line)}. This one replaces it.`, range.start.line + 1);
346
+ }
347
+ return story.addSection(name, filename, line, node);
348
+ };
210
349
  const ensureSectionExists = (line) => {
211
350
  if (!section && isFirst) {
212
- return story.addSection("_default", filename, line, file.preamble);
351
+ return addSection("_default", line, file.preamble);
213
352
  }
214
353
  return section;
215
354
  };
216
355
  const addAutoSection = (node, line) => {
217
356
  autoSectionCount++;
218
357
  const autoSectionName = `_continue${autoSectionCount}`;
219
- section = story.addSection(autoSectionName, filename, line, node);
358
+ section = addSection(autoSectionName, line, node);
220
359
  passage = null;
221
360
  return autoSectionName;
222
361
  };
@@ -230,7 +369,7 @@ export async function analyse(settings) {
230
369
  const lineCount = header.range.start.line + 1;
231
370
  switch (header.type) {
232
371
  case "section-header":
233
- section = story.addSection(header.name, filename, lineCount, node);
372
+ section = addSection(header.name, lineCount, node);
234
373
  passage = null;
235
374
  return true;
236
375
  case "continue": {
@@ -262,6 +401,10 @@ export async function analyse(settings) {
262
401
  report("error", "squiffy/passage-without-section", filename, node.nameRange, `Can't add passage "${node.name}" as no section has been created.`, lineCount);
263
402
  return false;
264
403
  }
404
+ if (hasOwn(section.passages, node.name)) {
405
+ const earlier = section.passages[node.name];
406
+ report("warning", "squiffy/duplicate-passage", filename, node.nameRange, `There's already a passage called [${node.name}] in section '${section.name}', at ${earlierLocation(section.filename, earlier.line)}. This one replaces it.`, lineCount);
407
+ }
265
408
  passage = section.addPassage(node.name, lineCount, node);
266
409
  return true;
267
410
  };
@@ -275,6 +418,13 @@ export async function analyse(settings) {
275
418
  return true;
276
419
  case "ui-file":
277
420
  if (settings.externalFiles) {
421
+ // In folder mode, the file isn't also added to the page as a script, so it
422
+ // doesn't run twice. Its name is looked up before it's read, as reading it
423
+ // can leave it out of getMatchingFilenames.
424
+ if (storyFiles) {
425
+ for (const match of await settings.externalFiles.getMatchingFilenames(node.path))
426
+ uiFiles.add(match);
427
+ }
278
428
  story.uiJs.push(await settings.externalFiles.getContent(node.path));
279
429
  }
280
430
  else {
@@ -292,32 +442,115 @@ export async function analyse(settings) {
292
442
  passage.clear = true;
293
443
  }
294
444
  return true;
295
- case "title":
296
- story.title = node.value;
445
+ case "repeat":
446
+ if (!passage) {
447
+ report("warning", "squiffy/repeat-not-in-passage", filename, lineRange(node), "@repeat only works in a passage, so this was ignored.", lineCount);
448
+ }
449
+ else {
450
+ passage.repeat = true;
451
+ }
297
452
  return true;
453
+ case "end":
454
+ // Only for the language service's dead end check
455
+ if (!passage) {
456
+ section = ensureSectionExists(lineCount);
457
+ if (!section)
458
+ return sectionRequired(node);
459
+ }
460
+ return true;
461
+ case "title":
298
462
  case "start":
299
- story.start = node.value;
463
+ // In folder mode, a file that isn't the main file could otherwise quietly
464
+ // change the story's title or where it starts
465
+ if (storyFiles && !isFirst) {
466
+ report("warning", "squiffy/not-in-main-file", filename, lineRange(node), `@${node.type} only works in the story's main file, so this was ignored.`, lineCount);
467
+ }
468
+ else if (node.type == "title") {
469
+ story.title = node.value;
470
+ }
471
+ else {
472
+ story.start = node.value;
473
+ }
300
474
  return true;
301
- case "import":
475
+ case "import": {
302
476
  if (!settings.externalFiles) {
303
477
  warnExternalFilesUnavailable(`@import ${node.pattern}`, node, filename);
304
478
  return true;
305
479
  }
306
- for (const importFilename of await settings.externalFiles.getMatchingFilenames(node.pattern)) {
307
- if (importFilename.endsWith(".squiffy")) {
480
+ const matches = await settings.externalFiles.getMatchingFilenames(node.pattern);
481
+ if (storyFiles && matches.length && matches.every(m => storyFiles.has(m))) {
482
+ report("hint", "squiffy/redundant-import", filename, lineRange(node), `${matches.length == 1 ? "This file is" : "These files are"} already part of the story, as ${PROJECT_FILENAME} includes every .squiffy, .css and .js file in the folder, so this @import isn't needed.`, lineCount);
483
+ }
484
+ for (const importFilename of matches) {
485
+ if (isSquiffyPath(importFilename)) {
308
486
  const content = await settings.externalFiles.getContent(importFilename);
309
487
  const success = await processFile(content, importFilename, false);
310
488
  if (!success && !settings.recover)
311
489
  return false;
312
490
  }
313
- else if (importFilename.endsWith(".js")) {
314
- story.scripts.push(settings.externalFiles.getLocalFilename(importFilename));
491
+ else if (isStylesheetPath(importFilename) || isScriptPath(importFilename)) {
492
+ addPageFile(importFilename, settings.externalFiles, true);
315
493
  }
316
- else if (importFilename.endsWith(".css")) {
317
- story.stylesheets.push(settings.externalFiles.getLocalFilename(importFilename));
494
+ }
495
+ return true;
496
+ }
497
+ case "sound": {
498
+ const target = passage ?? (section = ensureSectionExists(lineCount));
499
+ if (!target)
500
+ return sectionRequired(node);
501
+ const value = node.value.trim();
502
+ if (node.directive == "sound")
503
+ target.sounds.push(value);
504
+ else
505
+ target.music = value == "stop" ? null : value;
506
+ return true;
507
+ }
508
+ case "class": {
509
+ const target = passage ?? (section = ensureSectionExists(lineCount));
510
+ if (!target)
511
+ return sectionRequired(node);
512
+ for (const name of node.value.split(/\s+/)) {
513
+ if (name && !target.classes.includes(name))
514
+ target.classes.push(name);
515
+ }
516
+ return true;
517
+ }
518
+ case "tag": {
519
+ const target = passage ?? (section = ensureSectionExists(lineCount));
520
+ if (!target)
521
+ return sectionRequired(node);
522
+ for (const name of node.value.split(/\s+/)) {
523
+ if (name && !target.tags.includes(name))
524
+ target.tags.push(name);
525
+ }
526
+ return true;
527
+ }
528
+ case "transition": {
529
+ const target = passage ?? (section = ensureSectionExists(lineCount));
530
+ if (!target)
531
+ return sectionRequired(node);
532
+ if (!/^[A-Za-z][\w-]*$/.test(node.value)) {
533
+ report("warning", "squiffy/transition", filename, node.valueRange, `"${node.value}" can't be the name of a transition, so this was ignored. A name is letters, numbers, - and _, starting with a letter.`, lineCount);
534
+ return true;
535
+ }
536
+ let time;
537
+ if (node.time !== undefined) {
538
+ time = parseTransitionTime(node.time);
539
+ if (time === undefined) {
540
+ report("warning", "squiffy/transition", filename, lineRange(node), `"${node.time}" isn't a time, such as 1s or 400ms, so the transition takes its usual time.`, lineCount);
318
541
  }
319
542
  }
543
+ if (node.directive == "leave") {
544
+ target.leave = node.value;
545
+ target.leaveTime = time;
546
+ target.leaveNode = { filename, range: lineRange(node) };
547
+ }
548
+ else {
549
+ target.transition = node.value;
550
+ target.transitionTime = time;
551
+ }
320
552
  return true;
553
+ }
321
554
  case "attribute": {
322
555
  section = ensureSectionExists(lineCount);
323
556
  let attribute;
@@ -405,6 +638,65 @@ export async function analyse(settings) {
405
638
  function warnExternalFilesUnavailable(line, node, filename) {
406
639
  report("warning", "squiffy/external-files-unavailable", filename, lineRange(node), `"${line}" was ignored, as other files can't be loaded here`, node.range.start.line + 1);
407
640
  }
641
+ // Text in a setter without quotes, as in Squiffy 6 (#373). A single word is only reported if no
642
+ // attribute of that name is set anywhere in the story, so this needs every file first.
643
+ function warnAboutUnquotedText() {
644
+ const set = new Set();
645
+ files.forEach((file, i) => attributesSetIn(file, texts[i]).forEach(name => set.add(name)));
646
+ for (const file of files) {
647
+ for (const found of findUnquotedText(file, name => set.has(name))) {
648
+ const quoted = found.quoted ?? `"${found.text}"`;
649
+ const message = found.kind == "word"
650
+ ? `${found.text} isn't set anywhere in the story, so this sets ${found.attribute} to nothing. For the text ${quoted}, use quotes.`
651
+ : `Text in a setter goes in quotes in a story with a ${PROJECT_FILENAME}: ${quoted}.`;
652
+ report("warning", "squiffy/unquoted-text", file.filename, found.range, message, found.range.start.line + 1);
653
+ }
654
+ }
655
+ }
656
+ // {{name}} on its own shows the attribute called name if there's no helper called that, and
657
+ // an attribute that hasn't been set shows nothing, so a mistyped or missing helper, or a
658
+ // mistyped attribute, would otherwise fail without a word (#526). An attribute counts as set
659
+ // if the story might set it anywhere: see attributesSetIn, which takes anything in quotes,
660
+ // and the story's JavaScript is read the same way, which covers squiffy.set("name", ...) and
661
+ // registerHelper("name", ...).
662
+ async function warnAboutUnknownNames() {
663
+ const known = new Set([...BUILT_IN_HELPERS, ...BUILT_IN_ATTRIBUTES.keys(), ...embedParameters]);
664
+ const addKnown = (name) => {
665
+ known.add(name);
666
+ known.add(name.split(".")[0]);
667
+ };
668
+ // Squiffy's own attributes, such as _section, start with "_"
669
+ const isUnknown = (bare) => !known.has(bare.root) && !bare.root.startsWith("_");
670
+ if (!bareNames.some(isUnknown))
671
+ return;
672
+ files.forEach((file, i) => attributesSetIn(file, texts[i]).forEach(addKnown));
673
+ if (!bareNames.some(isUnknown))
674
+ return;
675
+ const scripts = [...story.uiJs];
676
+ if (settings.externalFiles) {
677
+ for (const filename of scriptFiles) {
678
+ try {
679
+ scripts.push(await settings.externalFiles.getContent(filename));
680
+ }
681
+ catch {
682
+ // A script that can't be read can't be checked
683
+ }
684
+ }
685
+ }
686
+ for (const script of scripts) {
687
+ for (const match of script.matchAll(/"([^"\\\n]*)"|'([^'\\\n]*)'|`([^`\\]*)`/g)) {
688
+ addKnown((match[1] ?? match[2] ?? match[3]).trim());
689
+ }
690
+ }
691
+ const suggestions = [...known].filter(name => /^[A-Za-z_]\w*$/.test(name) && !name.startsWith("_"));
692
+ for (const bare of bareNames) {
693
+ if (!isUnknown(bare))
694
+ continue;
695
+ const close = closestName(bare.root, suggestions);
696
+ const suggestion = close ? ` Did you mean {{${bare.name.replace(bare.root, close)}}}?` : "";
697
+ report("warning", "squiffy/unknown-name", bare.filename, bare.range, `${bare.where}, {{${bare.name}}} isn't a helper, and nothing in the story sets an attribute called ${bare.root}, so it shows nothing.${suggestion}`, bare.range.start.line + 1, bare.root);
698
+ }
699
+ }
408
700
  function warnAboutV5Syntax(text, lines, filename) {
409
701
  const truncate = (s) => s.length > 60 ? s.substring(0, 57) + "..." : s;
410
702
  for (const match of findV5Syntax(text)) {
@@ -428,61 +720,162 @@ export async function analyse(settings) {
428
720
  // Set once the sections are all known, before checking links
429
721
  let sectionNames = [];
430
722
  let sectionIndexes = new Map();
723
+ // What warnings call sections without names of their own, e.g. 'the "+++Continue..." after "cave"'
724
+ let labels = new Map();
725
+ // {{name}} on its own in the story's text, and the names of the values passed to embeds, for
726
+ // warnAboutUnknownNames, which needs every section's text first
727
+ const bareNames = [];
728
+ const embedParameters = new Set();
431
729
  function checkText(container, section, passage) {
432
730
  const getNextSectionName = () => {
433
731
  return sectionNames[(sectionIndexes.get(section.name) ?? -1) + 1] || null;
434
732
  };
435
- const result = transformText(container.text.join("\n"), getNextSectionName);
733
+ const result = transformText(container.text.join("\n"), getNextSectionName, settings.expressions);
436
734
  container.output = result.output;
437
735
  const toPosition = positionMapper(container.textSources, container.text.map(t => t.length));
438
736
  const toRange = (start, end) => ({ start: toPosition(start), end: toPosition(end) });
439
- const where = passage
440
- ? `In section '${section.name}', passage '${passage.name}'`
441
- : `In section '${section.name}'`;
737
+ const label = labels.get(section.name);
738
+ const inSection = label && section.node?.kind != "named" ? `In ${label}` : `In section '${section.name}'`;
739
+ const where = passage ? `${inSection}, passage '${passage.name}'` : inSection;
442
740
  const legacyLine = passage ? passage.line : section.line;
443
741
  const warn = (code, start, end, message, line = legacyLine) => {
444
742
  report("warning", code, section.filename, toRange(start, end), message, line);
445
743
  };
744
+ // Handlebars syntax errors, which would stop the text being shown at all
745
+ const templateError = findTemplateError(result.output);
746
+ if (templateError) {
747
+ const range = toRange(result.mapStart(templateError.start), result.mapEnd(templateError.end));
748
+ report("error", "squiffy/template-syntax", section.filename, range, `${where}, ${templateError.message}`, range.start.line + 1);
749
+ }
750
+ else {
751
+ const names = findTemplateNames(result.output);
752
+ names.embedParameters.forEach(name => embedParameters.add(name));
753
+ for (const bare of names.bare) {
754
+ const range = toRange(result.mapStart(bare.start), result.mapEnd(bare.end));
755
+ bareNames.push({ ...bare, filename: section.filename, range, where });
756
+ }
757
+ }
446
758
  for (const missing of result.noNextSection) {
447
- warn("squiffy/no-next-section", missing.start, missing.end, `In section '${section.name}', there is a ${missing.display} link but no following section exists`, section.line);
759
+ warn("squiffy/no-next-section", missing.start, missing.end, `${inSection}, there is a ${missing.display} link but no following section exists`, section.line);
448
760
  }
761
+ // Like the runtime, a passage link can go to one of the master section's passages
762
+ const masterPassages = story.sections[""]?.passages ?? {};
449
763
  for (const link of result.links) {
450
764
  if (link.form == "next")
451
765
  continue;
452
- if (link.linkType == "section") {
766
+ if (link.form == "input") {
767
+ const exists = link.linkType == "section"
768
+ ? hasOwn(story.sections, link.target)
769
+ : hasOwn(section.passages, link.target) || hasOwn(masterPassages, link.target);
770
+ if (!exists) {
771
+ warn(link.linkType == "section" ? "squiffy/unknown-section-link" : "squiffy/unknown-passage-link", link.start, link.end, `${where} there is a text box that goes to a ${link.linkType} called "${link.target}" when Enter is pressed, which doesn't exist`);
772
+ }
773
+ }
774
+ else if (link.linkType == "section") {
453
775
  if (!linkDestinationExists(link.target, story.sections)) {
454
776
  warn("squiffy/unknown-section-link", link.start, link.end, `${where} there is a link to a section called [[${link.target}]], which doesn't exist`);
455
777
  }
456
778
  }
457
- else if (!linkDestinationExists(link.target, section.passages)) {
779
+ else if (!linkDestinationExists(link.target, section.passages) && !linkDestinationExists(link.target, masterPassages)) {
458
780
  warn("squiffy/unknown-passage-link", link.start, link.end, `${where} there is a link to a passage called [${link.target}], which doesn't exist`);
459
781
  }
460
782
  }
461
783
  // Like the runtime's embed helper, a name can refer to a passage in the
462
- // current section or to any section.
784
+ // current section or the master section, or to any section.
463
785
  for (const embed of result.embeds) {
464
- if (!(embed.name in section.passages) && !(embed.name in story.sections)) {
786
+ if (!(embed.name in section.passages) && !(embed.name in story.sections) && !hasOwn(masterPassages, embed.name)) {
465
787
  warn("squiffy/unknown-embed", embed.start, embed.end, `${where} there is an embed of {{embed "${embed.name}"}}, but no section or passage with that name exists`);
466
788
  }
467
789
  }
790
+ // {{goto}} only goes to sections
791
+ for (const goto of result.gotos) {
792
+ if (!goto.name || !(goto.name in story.sections)) {
793
+ const passage = goto.name in section.passages ? ` ({{goto}} can't go to a passage: use {{embed "${goto.name}"}} to show it here)` : "";
794
+ warn("squiffy/unknown-goto", goto.start, goto.end, `${where} there is a {{goto "${goto.name}"}}, but no section with that name exists${passage}`);
795
+ }
796
+ }
797
+ // {{deactivate}} disables links to a passage in this section, or in the master section
798
+ for (const deactivate of result.deactivates) {
799
+ if (!(deactivate.name in section.passages) && !(deactivate.name in masterPassages)) {
800
+ warn("squiffy/unknown-deactivate", deactivate.start, deactivate.end, `${where} there is a {{deactivate "${deactivate.name}"}}, but no passage with that name exists in this section`);
801
+ }
802
+ }
468
803
  }
469
804
  // With recover, processFile carries on after errors, so check for them too
470
- const success = await processFile(settings.script, settings.scriptBaseFilename, true) && !legacyErrors.length;
805
+ let success = await processFile(settings.script, settings.scriptBaseFilename, true);
806
+ // In folder mode, the rest of the story's files, in order
807
+ for (const storyFile of settings.storyFiles ?? []) {
808
+ if (!success && !settings.recover)
809
+ break;
810
+ if (processed.has(storyFile))
811
+ continue;
812
+ if (!settings.externalFiles) {
813
+ report("warning", "squiffy/external-files-unavailable", settings.scriptBaseFilename, { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } }, "The story's other files were ignored, as other files can't be loaded here", 1);
814
+ break;
815
+ }
816
+ if (!isSquiffyPath(storyFile)) {
817
+ if (!uiFiles.has(storyFile))
818
+ addPageFile(storyFile, settings.externalFiles, false);
819
+ continue;
820
+ }
821
+ const content = await settings.externalFiles.getContent(storyFile);
822
+ success = await processFile(content, storyFile, false) && success;
823
+ }
824
+ success && (success = !legacyErrors.length);
471
825
  if (success || settings.recover) {
472
826
  if (!Object.keys(story.sections).length) {
473
827
  story.addSection("_default", settings.scriptBaseFilename, 0, undefined);
474
828
  }
475
829
  if (!story.start) {
476
- story.start = Object.keys(story.sections)[0];
830
+ story.start = mainFirstSection ?? Object.keys(story.sections)[0];
477
831
  }
478
832
  sectionNames = Object.keys(story.sections);
479
833
  sectionIndexes = new Map(sectionNames.map((name, i) => [name, i]));
834
+ const nodeNames = new Map(Object.values(story.sections).flatMap(section => section.node ? [[section.node, section.name]] : []));
835
+ labels = sectionLabels(files, node => nodeNames.get(node));
480
836
  for (const section of Object.values(story.sections)) {
481
837
  checkText(section, section, null);
482
838
  for (const passage of Object.values(section.passages)) {
483
839
  checkText(passage, section, passage);
484
840
  }
485
841
  }
842
+ success && (success = !legacyErrors.length);
843
+ await warnAboutUnknownNames();
844
+ }
845
+ if (settings.expressions) {
846
+ warnAboutUnquotedText();
847
+ }
848
+ // A story setting an attribute that Squiffy sets itself, such as turns (#377)
849
+ files.forEach((file, i) => {
850
+ for (const found of findBuiltInAttributeSets(file, texts[i])) {
851
+ report("warning", "squiffy/built-in-attribute", file.filename, found.range, `Squiffy sets ${found.name} itself: it's ${BUILT_IN_ATTRIBUTES.get(found.name)}. Use a different name for your own attribute.`, found.range.start.line + 1);
852
+ }
853
+ });
854
+ // @leave only does something when the screen is cleared: by the section or passage it's in, or by
855
+ // one that it's for, as the master section's @leave is for every section
856
+ // With @clear, or {{clear}} in its text (#524), which may only clear it some of the time
857
+ const clearsItself = (t) => !!t && (t.clear || t.text.some(line => /\{\{~?\s*clear\s*~?\}\}/.test(line)));
858
+ const master = story.sections[""];
859
+ const clears = (s) => clearsItself(s) || Object.values(s.passages).some(clearsItself);
860
+ const anyClear = Object.values(story.sections).some(clears);
861
+ const checkLeave = (target, used) => {
862
+ if (!target.leaveNode || target.leave == "none" || used)
863
+ return;
864
+ report("warning", "squiffy/transition", target.leaveNode.filename, target.leaveNode.range, "@leave is for when the screen is cleared, but nothing it's for has @clear or {{clear}}, so it does nothing.", target.leaveNode.range.start.line + 1);
865
+ };
866
+ for (const section of Object.values(story.sections)) {
867
+ const masterPassageClears = clearsItself(section.passages[""]) || clearsItself(master?.passages[""]);
868
+ checkLeave(section, section === master ? anyClear : clears(section) || clearsItself(master) || (master ? Object.values(master.passages).some(clearsItself) : false));
869
+ for (const passage of Object.values(section.passages)) {
870
+ checkLeave(passage, clearsItself(passage) || masterPassageClears || (passage.name == "" && clears(section)));
871
+ }
872
+ }
873
+ // Warnings turned off by {{!-- squiffy-ignore --}} comments
874
+ const ignored = ignoredDiagnostics(files, diagnostics);
875
+ if (ignored.size) {
876
+ diagnostics.splice(0, diagnostics.length, ...diagnostics.filter(d => !ignored.has(d)));
877
+ const ignoredLines = new Set([...ignored].map(d => legacyWarningOf.get(d)));
878
+ legacyWarnings.splice(0, legacyWarnings.length, ...legacyWarnings.filter(w => !ignoredLines.has(w)));
486
879
  }
487
880
  const analysis = {
488
881
  success,
@@ -494,10 +887,48 @@ export async function analyse(settings) {
494
887
  ...(section.node ? { node: section.node } : {}),
495
888
  passages: Object.values(section.passages).map(passage => ({ name: passage.name, node: passage.node })),
496
889
  })),
890
+ start: story.start,
891
+ expressions: settings.expressions ?? false,
892
+ stylesheets: stylesheetFiles,
893
+ scripts: scriptFiles,
497
894
  };
498
895
  analysisInternals.set(analysis, { story, legacyErrors, legacyWarnings });
499
896
  return analysis;
500
897
  }
898
+ // The name most like name, for a typo: one letter out for a short name, or two for a longer one.
899
+ // A name of one or two letters is too short to guess at.
900
+ function closestName(name, names) {
901
+ if (name.length < 3)
902
+ return undefined;
903
+ const limit = name.length <= 5 ? 1 : 2;
904
+ let best;
905
+ let bestDistance = limit + 1;
906
+ for (const candidate of names) {
907
+ if (candidate == name || Math.abs(candidate.length - name.length) > limit)
908
+ continue;
909
+ const distance = editDistance(name.toLowerCase(), candidate.toLowerCase());
910
+ if (distance < bestDistance) {
911
+ best = candidate;
912
+ bestDistance = distance;
913
+ }
914
+ }
915
+ return best;
916
+ }
917
+ // Letters added, removed or changed, and two swapped, to turn a into b
918
+ function editDistance(a, b) {
919
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
920
+ for (let j = 1; j <= b.length; j++)
921
+ d[0][j] = j;
922
+ for (let i = 1; i <= a.length; i++) {
923
+ for (let j = 1; j <= b.length; j++) {
924
+ const cost = a[i - 1] == b[j - 1] ? 0 : 1;
925
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
926
+ if (i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1])
927
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
928
+ }
929
+ }
930
+ return d[a.length][b.length];
931
+ }
501
932
  function linkDestinationExists(link, keys) {
502
933
  // Link destination data may look like:
503
934
  // passageName