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

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 (47) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +6 -0
  3. package/dist/analyse.js +101 -11
  4. package/dist/compiler.d.ts +9 -2
  5. package/dist/compiler.js +5 -2
  6. package/dist/css-urls.d.ts +4 -0
  7. package/dist/css-urls.js +59 -0
  8. package/dist/emit.d.ts +13 -0
  9. package/dist/emit.js +45 -1
  10. package/dist/language-service.d.ts +1 -0
  11. package/dist/language-service.js +39 -13
  12. package/dist/node.d.ts +7 -1
  13. package/dist/node.js +16 -5
  14. package/dist/parse.d.ts +3 -0
  15. package/dist/parse.js +25 -2
  16. package/dist/project.d.ts +56 -0
  17. package/dist/project.js +148 -15
  18. package/dist/quest/aslx.d.ts +50 -0
  19. package/dist/quest/aslx.js +181 -0
  20. package/dist/quest/convert.d.ts +20 -0
  21. package/dist/quest/convert.js +504 -0
  22. package/dist/quest/script.d.ts +92 -0
  23. package/dist/quest/script.js +453 -0
  24. package/dist/quest/scripts.d.ts +24 -0
  25. package/dist/quest/scripts.js +505 -0
  26. package/dist/quest/text.d.ts +17 -0
  27. package/dist/quest/text.js +305 -0
  28. package/dist/setters.d.ts +4 -0
  29. package/dist/setters.js +10 -5
  30. package/dist/story-graph.d.ts +2 -1
  31. package/dist/story-graph.js +2 -0
  32. package/dist/syntax.d.ts +27 -2
  33. package/dist/text.d.ts +2 -0
  34. package/dist/text.js +24 -15
  35. package/dist/twine/audio.d.ts +21 -0
  36. package/dist/twine/audio.js +80 -0
  37. package/dist/twine/convert.d.ts +15 -1
  38. package/dist/twine/convert.js +217 -21
  39. package/dist/twine/expression.d.ts +26 -1
  40. package/dist/twine/expression.js +111 -6
  41. package/dist/twine/harlowe.d.ts +10 -0
  42. package/dist/twine/harlowe.js +417 -58
  43. package/dist/twine/sugarcube.d.ts +4 -0
  44. package/dist/twine/sugarcube.js +388 -86
  45. package/dist/v5.js +2 -1
  46. package/package.json +3 -2
  47. package/syntaxes/squiffy.tmLanguage.json +9 -4
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- ## Local development
1
+ # squiffy-compiler
2
2
 
3
- `npm run dev -- examples/helloworld/helloworld.squiffy`
3
+ Compiles Squiffy story files into JavaScript. See [the main README](../README.md) and the [docs](https://squiffystory.com).
4
+
5
+ ## Tests
6
+
7
+ ```bash
8
+ npm test
9
+ ```
10
+
11
+ `test/fixtures/` has a small story for each feature. `compiler.test.ts` compiles each of them, and the complete stories in `../examples`, and compares the output with its snapshots. The fixtures have no `squiffy.json`, so they use Squiffy 6's rules for setters. `warnings/` has stories that should produce warnings.
package/dist/analyse.d.ts CHANGED
@@ -35,6 +35,8 @@ export interface Analysis {
35
35
  sections: SectionSymbol[];
36
36
  start: string;
37
37
  expressions: boolean;
38
+ stylesheets: string[];
39
+ scripts: string[];
38
40
  }
39
41
  export declare class Story {
40
42
  sections: Record<string, Section>;
@@ -53,6 +55,9 @@ declare class TextContainer {
53
55
  js: string[];
54
56
  clear: boolean;
55
57
  attributes: string[];
58
+ music?: string | null;
59
+ sounds: string[];
60
+ classes: string[];
56
61
  output: string;
57
62
  addText(text: string, source: SourceLine): void;
58
63
  }
@@ -69,6 +74,7 @@ export declare class Passage extends TextContainer {
69
74
  name: string;
70
75
  line: number;
71
76
  node: PassageNode;
77
+ repeat: boolean;
72
78
  constructor(name: string, line: number, node: PassageNode);
73
79
  }
74
80
  export interface AnalysisInternals {
package/dist/analyse.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { parse } from "./parse.js";
2
2
  import { positionMapper, transformText } from "./text.js";
3
- import { PROJECT_FILENAME } from "./project.js";
3
+ import { isScriptPath, isSquiffyPath, isStylesheetPath, PROJECT_FILENAME } from "./project.js";
4
4
  import { findV5Syntax } from "./v5.js";
5
5
  import { attributesSetIn, BUILT_IN_ATTRIBUTES, findAtAttributes, findBuiltInAttributeSets, findUnquotedText } from "./setters.js";
6
6
  // Caches the syntax tree of each file by filename, reparsing a file only when its text changes.
@@ -109,6 +109,27 @@ class TextContainer {
109
109
  writable: true,
110
110
  value: []
111
111
  });
112
+ // @music (#444): the file to play, or null for @music stop. Undefined leaves it as it is.
113
+ Object.defineProperty(this, "music", {
114
+ enumerable: true,
115
+ configurable: true,
116
+ writable: true,
117
+ value: void 0
118
+ });
119
+ // @sound: the files to play once, in order, with "stop" for @sound stop
120
+ Object.defineProperty(this, "sounds", {
121
+ enumerable: true,
122
+ configurable: true,
123
+ writable: true,
124
+ value: []
125
+ });
126
+ // @class (#449): classes on the story's element while the section is the current one
127
+ Object.defineProperty(this, "classes", {
128
+ enumerable: true,
129
+ configurable: true,
130
+ writable: true,
131
+ value: []
132
+ });
112
133
  // The text after links have been converted
113
134
  Object.defineProperty(this, "output", {
114
135
  enumerable: true,
@@ -183,6 +204,13 @@ export class Passage extends TextContainer {
183
204
  writable: true,
184
205
  value: node
185
206
  });
207
+ // @repeat: its links stay clickable (#104)
208
+ Object.defineProperty(this, "repeat", {
209
+ enumerable: true,
210
+ configurable: true,
211
+ writable: true,
212
+ value: false
213
+ });
186
214
  }
187
215
  }
188
216
  export const analysisInternals = new WeakMap();
@@ -212,6 +240,23 @@ export async function analyse(settings) {
212
240
  // The .squiffy files processed so far, so a story file the main file has already @imported
213
241
  // isn't processed again
214
242
  const processed = new Set();
243
+ // Files read by @ui, which in folder mode aren't added to the page as scripts too
244
+ const uiFiles = new Set();
245
+ // The .css and .js files added to the page so far, named as getMatchingFilenames names them
246
+ const stylesheetFiles = [];
247
+ const scriptFiles = [];
248
+ // Adds a stylesheet or script to the page. An @import adds it every time, as in Squiffy 6, but
249
+ // folder mode only adds one that isn't there already.
250
+ const addPageFile = (filename, externalFiles, imported) => {
251
+ const [names, local] = isStylesheetPath(filename)
252
+ ? [stylesheetFiles, story.stylesheets]
253
+ : [scriptFiles, story.scripts];
254
+ if (names.includes(filename) && !imported)
255
+ return;
256
+ if (!names.includes(filename))
257
+ names.push(filename);
258
+ local.push(externalFiles.getLocalFilename(filename));
259
+ };
215
260
  async function processFile(text, filename, isFirst) {
216
261
  const file = cache.parse(text, filename);
217
262
  files.push(file);
@@ -317,6 +362,13 @@ export async function analyse(settings) {
317
362
  return true;
318
363
  case "ui-file":
319
364
  if (settings.externalFiles) {
365
+ // In folder mode, the file isn't also added to the page as a script, so it
366
+ // doesn't run twice. Its name is looked up before it's read, as reading it
367
+ // can leave it out of getMatchingFilenames.
368
+ if (storyFiles) {
369
+ for (const match of await settings.externalFiles.getMatchingFilenames(node.path))
370
+ uiFiles.add(match);
371
+ }
320
372
  story.uiJs.push(await settings.externalFiles.getContent(node.path));
321
373
  }
322
374
  else {
@@ -334,6 +386,14 @@ export async function analyse(settings) {
334
386
  passage.clear = true;
335
387
  }
336
388
  return true;
389
+ case "repeat":
390
+ if (!passage) {
391
+ report("warning", "squiffy/repeat-not-in-passage", filename, lineRange(node), "@repeat only works in a passage, so this was ignored.", lineCount);
392
+ }
393
+ else {
394
+ passage.repeat = true;
395
+ }
396
+ return true;
337
397
  case "end":
338
398
  // Only for the language service's dead end check
339
399
  if (!passage) {
@@ -362,27 +422,43 @@ export async function analyse(settings) {
362
422
  return true;
363
423
  }
364
424
  const matches = await settings.externalFiles.getMatchingFilenames(node.pattern);
365
- const squiffyMatches = matches.filter(m => m.endsWith(".squiffy"));
366
- if (storyFiles && squiffyMatches.length && squiffyMatches.length == matches.length
367
- && squiffyMatches.every(m => storyFiles.has(m))) {
368
- report("hint", "squiffy/redundant-import", filename, lineRange(node), `${squiffyMatches.length == 1 ? "This file is" : "These files are"} already part of the story, as ${PROJECT_FILENAME} includes every .squiffy file in the folder, so this @import isn't needed.`, lineCount);
425
+ if (storyFiles && matches.length && matches.every(m => storyFiles.has(m))) {
426
+ 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);
369
427
  }
370
428
  for (const importFilename of matches) {
371
- if (importFilename.endsWith(".squiffy")) {
429
+ if (isSquiffyPath(importFilename)) {
372
430
  const content = await settings.externalFiles.getContent(importFilename);
373
431
  const success = await processFile(content, importFilename, false);
374
432
  if (!success && !settings.recover)
375
433
  return false;
376
434
  }
377
- else if (importFilename.endsWith(".js")) {
378
- story.scripts.push(settings.externalFiles.getLocalFilename(importFilename));
379
- }
380
- else if (importFilename.endsWith(".css")) {
381
- story.stylesheets.push(settings.externalFiles.getLocalFilename(importFilename));
435
+ else if (isStylesheetPath(importFilename) || isScriptPath(importFilename)) {
436
+ addPageFile(importFilename, settings.externalFiles, true);
382
437
  }
383
438
  }
384
439
  return true;
385
440
  }
441
+ case "sound": {
442
+ const target = passage ?? (section = ensureSectionExists(lineCount));
443
+ if (!target)
444
+ return sectionRequired(node);
445
+ const value = node.value.trim();
446
+ if (node.directive == "sound")
447
+ target.sounds.push(value);
448
+ else
449
+ target.music = value == "stop" ? null : value;
450
+ return true;
451
+ }
452
+ case "class": {
453
+ const target = passage ?? (section = ensureSectionExists(lineCount));
454
+ if (!target)
455
+ return sectionRequired(node);
456
+ for (const name of node.value.split(/\s+/)) {
457
+ if (name && !target.classes.includes(name))
458
+ target.classes.push(name);
459
+ }
460
+ return true;
461
+ }
386
462
  case "attribute": {
387
463
  section = ensureSectionExists(lineCount);
388
464
  let attribute;
@@ -552,6 +628,13 @@ export async function analyse(settings) {
552
628
  warn("squiffy/unknown-goto", goto.start, goto.end, `${where} there is a {{goto "${goto.name}"}}, but no section with that name exists${passage}`);
553
629
  }
554
630
  }
631
+ // {{deactivate}} disables links to a passage in this section, or in the master section
632
+ const masterPassages = story.sections[""]?.passages ?? {};
633
+ for (const deactivate of result.deactivates) {
634
+ if (!(deactivate.name in section.passages) && !(deactivate.name in masterPassages)) {
635
+ 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`);
636
+ }
637
+ }
555
638
  }
556
639
  // With recover, processFile carries on after errors, so check for them too
557
640
  let success = await processFile(settings.script, settings.scriptBaseFilename, true);
@@ -565,6 +648,11 @@ export async function analyse(settings) {
565
648
  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);
566
649
  break;
567
650
  }
651
+ if (!isSquiffyPath(storyFile)) {
652
+ if (!uiFiles.has(storyFile))
653
+ addPageFile(storyFile, settings.externalFiles, false);
654
+ continue;
655
+ }
568
656
  const content = await settings.externalFiles.getContent(storyFile);
569
657
  success = await processFile(content, storyFile, false) && success;
570
658
  }
@@ -606,6 +694,8 @@ export async function analyse(settings) {
606
694
  })),
607
695
  start: story.start,
608
696
  expressions: settings.expressions ?? false,
697
+ stylesheets: stylesheetFiles,
698
+ scripts: scriptFiles,
609
699
  };
610
700
  analysisInternals.set(analysis, { story, legacyErrors, legacyWarnings });
611
701
  return analysis;
@@ -1,6 +1,7 @@
1
1
  import { ExternalFiles, ParseCache } from "./analyse.js";
2
2
  import { CompileSuccess } from "./emit.js";
3
3
  import type { Diagnostic } from "./syntax.js";
4
+ import type { Panel } from "./project.js";
4
5
  export { findV5Syntax, convertV5Syntax } from "./v5.js";
5
6
  export type { V5SyntaxMatch, V5ConversionProblem, V5ConversionResult } from "./v5.js";
6
7
  export { convertSetters, convertSetter } from "./setters.js";
@@ -8,6 +9,9 @@ export { convertTwine, convertTwineStory, formatTwineProblems } from "./twine/co
8
9
  export type { TwineConversionResult, TwineConversionProblem, TwineConversionOptions } from "./twine/convert.js";
9
10
  export { parseTwine, isTwineSource, TwineParseError } from "./twine/story.js";
10
11
  export type { TwineStory, TwinePassage } from "./twine/story.js";
12
+ export { convertQuestGamebook, formatQuestProblems } from "./quest/convert.js";
13
+ export type { QuestConversionResult, QuestConversionProblem, QuestConversionOptions } from "./quest/convert.js";
14
+ export { isQuestSource, QuestParseError } from "./quest/aslx.js";
11
15
  export type { SetterConversion, SetterConversionProblem, SetterConversionResult } from "./setters.js";
12
16
  export { parse } from "./parse.js";
13
17
  export { analyse, ParseCache } from "./analyse.js";
@@ -15,8 +19,9 @@ export type { AnalyseSettings, Analysis, ExternalFiles, SectionSymbol, PassageSy
15
19
  export { emit } from "./emit.js";
16
20
  export type { EmitSettings, Output, UiInfo, CompileSuccess } from "./emit.js";
17
21
  export { formatDiagnostic } from "./syntax.js";
18
- export { PROJECT_FILENAME, PROJECT_FILE_VERSION, PROJECT_SCHEMA_URL, parseProjectFile, getStoryFiles, isExcluded, isAlwaysSkipped, formatProjectFile, updateProjectFile, } from "./project.js";
19
- export type { MapPositions, ProjectFile, ParsedProjectFile, StoryFiles } from "./project.js";
22
+ export { findCssUrls, isRelativeUrl, resolveCssUrl, rewriteCssUrls } from "./css-urls.js";
23
+ export { PROJECT_FILENAME, PROJECT_FILE_VERSION, PROJECT_SCHEMA_URL, parseProjectFile, getStoryFiles, isExcluded, isAlwaysSkipped, formatProjectFile, updateProjectFile, PAGE_STRINGS, PANEL_ICONS, storyFileList, BUILD_FOLDER, } from "./project.js";
24
+ export type { MapPositions, PageStringName, PageStrings, Panel, PanelIcon, ProjectFile, ParsedProjectFile, StoryFiles } from "./project.js";
20
25
  export type * from "./syntax.js";
21
26
  interface CompilerSettings {
22
27
  scriptBaseFilename?: string;
@@ -27,6 +32,8 @@ interface CompilerSettings {
27
32
  parseCache?: ParseCache;
28
33
  storyFiles?: string[];
29
34
  expressions?: boolean;
35
+ projectId?: string;
36
+ panels?: Panel[];
30
37
  }
31
38
  export interface CompileError {
32
39
  success: false;
package/dist/compiler.js CHANGED
@@ -4,6 +4,8 @@ export { findV5Syntax, convertV5Syntax } from "./v5.js";
4
4
  export { convertSetters, convertSetter } from "./setters.js";
5
5
  export { convertTwine, convertTwineStory, formatTwineProblems } from "./twine/convert.js";
6
6
  export { parseTwine, isTwineSource, TwineParseError } from "./twine/story.js";
7
+ export { convertQuestGamebook, formatQuestProblems } from "./quest/convert.js";
8
+ export { isQuestSource, QuestParseError } from "./quest/aslx.js";
7
9
  // The compiler works in three stages, which can also be used separately:
8
10
  // - parse() turns one file into a syntax tree, with a source range on every node
9
11
  // - analyse() resolves @imports, builds the story's sections and passages, and reports diagnostics
@@ -12,7 +14,8 @@ export { parse } from "./parse.js";
12
14
  export { analyse, ParseCache } from "./analyse.js";
13
15
  export { emit } from "./emit.js";
14
16
  export { formatDiagnostic } from "./syntax.js";
15
- export { PROJECT_FILENAME, PROJECT_FILE_VERSION, PROJECT_SCHEMA_URL, parseProjectFile, getStoryFiles, isExcluded, isAlwaysSkipped, formatProjectFile, updateProjectFile, } from "./project.js";
17
+ export { findCssUrls, isRelativeUrl, resolveCssUrl, rewriteCssUrls } from "./css-urls.js";
18
+ export { PROJECT_FILENAME, PROJECT_FILE_VERSION, PROJECT_SCHEMA_URL, parseProjectFile, getStoryFiles, isExcluded, isAlwaysSkipped, formatProjectFile, updateProjectFile, PAGE_STRINGS, PANEL_ICONS, storyFileList, BUILD_FOLDER, } from "./project.js";
16
19
  export async function compile(settings) {
17
20
  const analysis = await analyse(settings);
18
21
  const { legacyErrors, legacyWarnings } = analysisInternals.get(analysis);
@@ -28,5 +31,5 @@ export async function compile(settings) {
28
31
  diagnostics: analysis.diagnostics,
29
32
  };
30
33
  }
31
- return emit(analysis, { globalJs: settings.globalJs });
34
+ return emit(analysis, { globalJs: settings.globalJs, projectId: settings.projectId, panels: settings.panels });
32
35
  }
@@ -0,0 +1,4 @@
1
+ export declare function isRelativeUrl(url: string): boolean;
2
+ export declare function rewriteCssUrls(css: string, replace: (url: string) => string | undefined): string;
3
+ export declare function findCssUrls(css: string): string[];
4
+ export declare function resolveCssUrl(sheetPath: string, url: string): string | null;
@@ -0,0 +1,59 @@
1
+ // The url()s in a story's own stylesheets, such as a font's files or a background image. A
2
+ // stylesheet refers to them by their path from its own folder, as a web page's CSS does. That
3
+ // works as it is in a published story, whose stylesheets are separate files, but a one-file
4
+ // export or the editor's preview has to swap each for something it can load.
5
+ const URL_PATTERN = /url\(\s*(?:"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)'|([^)"'\s]*))\s*\)/gi;
6
+ // A url() that's a path to a file beside the stylesheet, rather than a web address, a data: URI,
7
+ // an absolute path or a reference to an SVG element like "#gradient"
8
+ export function isRelativeUrl(url) {
9
+ return url != "" && !/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(url);
10
+ }
11
+ // Replaces each relative url() in css with what replace returns for it, or leaves it as it is if
12
+ // replace returns undefined
13
+ export function rewriteCssUrls(css, replace) {
14
+ return css.replace(URL_PATTERN, (match, double, single, bare) => {
15
+ const url = (double ?? single ?? bare ?? "").trim();
16
+ if (!isRelativeUrl(url))
17
+ return match;
18
+ const replacement = replace(url);
19
+ return replacement === undefined ? match : `url("${replacement.replace(/["\\\n]/g, c => c == "\n" ? "\\a " : `\\${c}`)}")`;
20
+ });
21
+ }
22
+ // The relative url()s in css
23
+ export function findCssUrls(css) {
24
+ const urls = [];
25
+ rewriteCssUrls(css, url => {
26
+ urls.push(url);
27
+ return undefined;
28
+ });
29
+ return urls;
30
+ }
31
+ // The path, from the story's folder, of a url() in the stylesheet at sheetPath (also from the
32
+ // story's folder), e.g. "fonts/literata/latin-400-normal.woff2" for "latin-400-normal.woff2" in
33
+ // "fonts/literata/literata.css". Null if it's outside the story's folder. A query or #fragment,
34
+ // such as the "?#iefix" some older @font-face rules have, isn't part of the path.
35
+ export function resolveCssUrl(sheetPath, url) {
36
+ let path = url.replace(/[?#].*$/, "");
37
+ try {
38
+ path = decodeURI(path);
39
+ }
40
+ catch {
41
+ // Not valid percent-encoding: use it as it is
42
+ }
43
+ const sheet = sheetPath.replace(/\\/g, "/").split("/");
44
+ sheet.pop();
45
+ const parts = sheet.filter(part => part != "" && part != ".");
46
+ for (const part of path.replace(/\\/g, "/").split("/")) {
47
+ if (part == "" || part == ".")
48
+ continue;
49
+ if (part == "..") {
50
+ if (!parts.length || parts[parts.length - 1] == "..")
51
+ return null;
52
+ parts.pop();
53
+ }
54
+ else {
55
+ parts.push(part);
56
+ }
57
+ }
58
+ return parts.length ? parts.join("/") : null;
59
+ }
package/dist/emit.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Analysis } from "./analyse.js";
2
2
  import type { Diagnostic } from "./syntax.js";
3
+ import type { Panel } from "./project.js";
3
4
  export interface Output {
4
5
  story: OutputStory;
5
6
  js: string[][];
@@ -7,13 +8,19 @@ export interface Output {
7
8
  interface OutputStory {
8
9
  start: string;
9
10
  id: string | null;
11
+ projectId?: string;
10
12
  uiJsIndex?: number;
11
13
  expressions?: boolean;
14
+ panels?: Panel[];
12
15
  sections: Record<string, OutputSection>;
16
+ audio?: string[];
13
17
  }
14
18
  interface OutputSection {
15
19
  text?: string;
16
20
  clear?: boolean;
21
+ music?: string | null;
22
+ sounds?: string[];
23
+ classes?: string[];
17
24
  attributes?: string[];
18
25
  jsIndex?: number;
19
26
  passages?: Record<string, OutputPassage>;
@@ -22,6 +29,10 @@ interface OutputSection {
22
29
  interface OutputPassage {
23
30
  text?: string;
24
31
  clear?: boolean;
32
+ music?: string | null;
33
+ sounds?: string[];
34
+ classes?: string[];
35
+ repeat?: boolean;
25
36
  attributes?: string[];
26
37
  jsIndex?: number;
27
38
  }
@@ -32,6 +43,8 @@ export interface UiInfo {
32
43
  }
33
44
  export interface EmitSettings {
34
45
  globalJs?: boolean;
46
+ projectId?: string;
47
+ panels?: Panel[];
35
48
  }
36
49
  export interface CompileSuccess {
37
50
  success: true;
package/dist/emit.js CHANGED
@@ -1,6 +1,21 @@
1
1
  import pkg from "../package.json" with { type: "json" };
2
2
  import { analysisInternals } from "./analyse.js";
3
3
  const version = pkg.version;
4
+ // {{music "file"}} or {{sound "file"}}
5
+ const SOUND_HELPER = /\{\{\s*(?:music|sound)\s+(["'])([^"'{}]+)\1/g;
6
+ // @music and @sound (#444), and the files they and the text name, for OutputStory.audio
7
+ function addSounds(output, from, audio) {
8
+ if (from.music !== undefined)
9
+ output.music = from.music;
10
+ if (from.sounds.length)
11
+ output.sounds = from.sounds;
12
+ if (from.music)
13
+ audio.add(from.music);
14
+ from.sounds.forEach(file => { if (file != "stop")
15
+ audio.add(file); });
16
+ for (const match of from.output.matchAll(SOUND_HELPER))
17
+ audio.add(match[2]);
18
+ }
4
19
  // Produces the story data and JavaScript for an analysis that succeeded.
5
20
  export function emit(analysis, settings = {}) {
6
21
  const internals = analysisInternals.get(analysis);
@@ -22,10 +37,17 @@ export function emit(analysis, settings = {}) {
22
37
  if (analysis.expressions) {
23
38
  output.story.expressions = true;
24
39
  }
40
+ if (settings.projectId) {
41
+ output.story.projectId = settings.projectId;
42
+ }
43
+ if (settings.panels?.length) {
44
+ output.story.panels = settings.panels;
45
+ }
25
46
  if (story.uiJs.length > 0) {
26
47
  output.js.push(story.uiJs);
27
48
  output.story.uiJsIndex = output.js.length - 1;
28
49
  }
50
+ const audio = new Set();
29
51
  for (const sectionName of Object.keys(story.sections)) {
30
52
  const section = story.sections[sectionName];
31
53
  const outputSection = {};
@@ -34,6 +56,9 @@ export function emit(analysis, settings = {}) {
34
56
  outputSection.clear = true;
35
57
  }
36
58
  outputSection.text = section.output;
59
+ addSounds(outputSection, section, audio);
60
+ if (section.classes.length)
61
+ outputSection.classes = section.classes;
37
62
  if (section.attributes.length > 0) {
38
63
  outputSection.attributes = section.attributes;
39
64
  }
@@ -44,7 +69,8 @@ export function emit(analysis, settings = {}) {
44
69
  if ("@last" in section.passages) {
45
70
  let passageCount = 0;
46
71
  for (const passageName of Object.keys(section.passages)) {
47
- if (passageName.length > 0 && passageName?.substring(0, 1) !== "@") {
72
+ // A passage with @repeat doesn't count, as clicking it doesn't use it up
73
+ if (passageName.length > 0 && passageName?.substring(0, 1) !== "@" && !section.passages[passageName].repeat) {
48
74
  passageCount++;
49
75
  }
50
76
  }
@@ -60,7 +86,13 @@ export function emit(analysis, settings = {}) {
60
86
  if (passage.clear) {
61
87
  outputPassage.clear = true;
62
88
  }
89
+ if (passage.repeat) {
90
+ outputPassage.repeat = true;
91
+ }
63
92
  outputPassage.text = passage.output;
93
+ addSounds(outputPassage, passage, audio);
94
+ if (passage.classes.length)
95
+ outputPassage.classes = passage.classes;
64
96
  if (passage.attributes.length > 0) {
65
97
  outputPassage.attributes = passage.attributes;
66
98
  }
@@ -70,6 +102,9 @@ export function emit(analysis, settings = {}) {
70
102
  }
71
103
  }
72
104
  }
105
+ if (audio.size) {
106
+ output.story.audio = [...audio];
107
+ }
73
108
  const getJs = async (excludeHeader) => {
74
109
  const outputJs = [];
75
110
  if (!excludeHeader) {
@@ -83,12 +118,21 @@ export function emit(analysis, settings = {}) {
83
118
  outputJs.push("export const story = {};");
84
119
  }
85
120
  outputJs.push(`story.id = ${JSON.stringify(output.story.id, null, 4)};`);
121
+ if (output.story.projectId) {
122
+ outputJs.push(`story.projectId = ${JSON.stringify(output.story.projectId)};`);
123
+ }
86
124
  if (output.story.uiJsIndex !== undefined) {
87
125
  outputJs.push(`story.uiJsIndex = ${output.story.uiJsIndex};`);
88
126
  }
89
127
  if (output.story.expressions) {
90
128
  outputJs.push("story.expressions = true;");
91
129
  }
130
+ if (output.story.panels) {
131
+ outputJs.push(`story.panels = ${JSON.stringify(output.story.panels, null, 4)};`);
132
+ }
133
+ if (output.story.audio) {
134
+ outputJs.push(`story.audio = ${JSON.stringify(output.story.audio, null, 4)};`);
135
+ }
92
136
  outputJs.push(`story.start = ${JSON.stringify(output.story.start, null, 4)};`);
93
137
  outputJs.push(`story.sections = ${JSON.stringify(output.story.sections, null, 4)};`);
94
138
  outputJs.push("story.js = [");
@@ -75,6 +75,7 @@ export interface LanguageService {
75
75
  getProjectInfo(): Promise<ProjectInfo>;
76
76
  getAnalysis(): Promise<Analysis>;
77
77
  getDiagnostics(path: string): Promise<Diagnostic[]>;
78
+ getAllDiagnostics(): Promise<Diagnostic[]>;
78
79
  getDocumentSymbols(path: string): Promise<DocumentSymbol[]>;
79
80
  getDefinition(path: string, position: Position): Promise<Location | undefined>;
80
81
  getReferences(path: string, position: Position, includeDeclaration?: boolean): Promise<Location[]>;
@@ -6,12 +6,12 @@
6
6
  //
7
7
  // Positions and ranges are zero-based { line, character }, following LSP conventions.
8
8
  import { analyse, ParseCache } from "./analyse.js";
9
- import { getStoryFiles, globToRegExp, parseProjectFile, PROJECT_FILENAME } from "./project.js";
9
+ import { getStoryFiles, globToRegExp, parseProjectFile, PROJECT_FILENAME, storyFileList } from "./project.js";
10
10
  import { convertV5Syntax, findV5Syntax } from "./v5.js";
11
- import { findUnquotedText } from "./setters.js";
11
+ import { findUnquotedText, splitWithOffsets } from "./setters.js";
12
12
  import { buildStoryGraph, storyGraphDiagnostics } from "./story-graph.js";
13
13
  const sameSymbol = (a, b) => a.kind == b.kind && a.name == b.name && (a.kind == "section" || a.section == b.section);
14
- const usageRange = (usage) => (usage.link ?? usage.embed ?? usage.goto).range;
14
+ const usageRange = (usage) => (usage.link ?? usage.embed ?? usage.goto ?? usage.deactivate).range;
15
15
  // Directives, for completion, with what they do
16
16
  const DIRECTIVES = [
17
17
  ["title", "Sets the story's title"],
@@ -22,7 +22,11 @@ const DIRECTIVES = [
22
22
  ["inc", "Adds to an attribute"],
23
23
  ["dec", "Subtracts from an attribute"],
24
24
  ["clear", "Clears the screen"],
25
+ ["repeat", "Lets the player click this passage's links again"],
25
26
  ["end", "Marks this section as an ending"],
27
+ ["music", "Plays music until it's changed, or stops it with @music stop"],
28
+ ["sound", "Plays a sound once, or stops the sounds playing with @sound stop"],
29
+ ["class", "Puts classes on the story while this section is shown, for its stylesheet"],
26
30
  ["ui", "JavaScript for the story's user interface"],
27
31
  ];
28
32
  const contains = (range, pos) => comparePositions(range.start, pos) <= 0 && comparePositions(pos, range.end) <= 0;
@@ -40,8 +44,9 @@ function resolveName(target, has) {
40
44
  }
41
45
  // The name a broken link was trying to reach
42
46
  const intendedName = (target) => target.trim().split(",")[0].trim();
47
+ // The attribute a setter sets, e.g. gold in gold += 1, or hero.hp in hero.hp = 10 (#442)
43
48
  function attributeName(expression) {
44
- return expression.replace(/^\s*not\s+/, "").split(/[-+]?=/)[0].trim();
49
+ return /^\s*(?:not\s+)?(\w+(?:\.\w+)*)/.exec(expression)?.[1] ?? "";
45
50
  }
46
51
  function resolvePath(baseDir, relative) {
47
52
  const parts = baseDir ? baseDir.split("/") : [];
@@ -156,7 +161,7 @@ export function createLanguageService(options) {
156
161
  return { ...fallback, error: parsed.error };
157
162
  const project = parsed.project;
158
163
  const story = getStoryFiles(project, paths);
159
- return { projectFile: project, mainFile: project.main, storyFiles: story.included, excludedFiles: story.excluded };
164
+ return { projectFile: project, mainFile: project.main, storyFiles: storyFileList(story), excludedFiles: story.excluded };
160
165
  }
161
166
  async function buildIndex() {
162
167
  const texts = new Map();
@@ -216,6 +221,14 @@ export function createLanguageService(options) {
216
221
  if (section.node)
217
222
  index.nodeNames.set(section.node, section.name);
218
223
  }
224
+ // An attribute, and for a value inside an object, the object too: hero.hp adds hero
225
+ const addAttribute = (name) => {
226
+ const parts = name.split(".");
227
+ for (let i = 1; i <= parts.length; i++) {
228
+ if (parts[i - 1])
229
+ index.attributes.add(parts.slice(0, i).join("."));
230
+ }
231
+ };
219
232
  for (const [path, file] of index.files) {
220
233
  for (const node of [file.preamble, ...file.sections]) {
221
234
  if (node.type == "snippet") {
@@ -225,11 +238,10 @@ export function createLanguageService(options) {
225
238
  for (const container of [node, ...node.passages]) {
226
239
  for (const link of container.links) {
227
240
  index.usages.push({ file: path, container, sectionNode: node, link });
228
- const setters = link.target.split(",").slice(1);
241
+ const comma = link.target.indexOf(",");
242
+ const setters = comma == -1 ? [] : splitWithOffsets(link.target.substring(comma + 1)).map(part => part.text);
229
243
  for (const setter of setters) {
230
- const name = attributeName(setter);
231
- if (name)
232
- index.attributes.add(name);
244
+ addAttribute(attributeName(setter));
233
245
  }
234
246
  }
235
247
  for (const embed of container.embeds) {
@@ -238,11 +250,12 @@ export function createLanguageService(options) {
238
250
  for (const goto of container.gotos) {
239
251
  index.usages.push({ file: path, container, sectionNode: node, goto });
240
252
  }
253
+ for (const deactivate of container.deactivates) {
254
+ index.usages.push({ file: path, container, sectionNode: node, deactivate });
255
+ }
241
256
  for (const statement of container.body) {
242
257
  if (statement.type == "attribute") {
243
- const name = attributeName(statement.value);
244
- if (name)
245
- index.attributes.add(name);
258
+ addAttribute(attributeName(statement.value));
246
259
  }
247
260
  else if (statement.type == "js") {
248
261
  for (const match of statement.code.matchAll(/\bset\(\s*["']([^"']+)["']/g)) {
@@ -312,6 +325,11 @@ export function createLanguageService(options) {
312
325
  const name = usage.goto.name;
313
326
  return name && index.sections.has(name) ? { kind: "section", name } : undefined;
314
327
  }
328
+ if (usage.deactivate) {
329
+ const name = usage.deactivate.name;
330
+ const passages = passagesOf(index, usage.sectionNode);
331
+ return sectionName !== undefined && passages?.has(name) ? { kind: "passage", section: sectionName, name } : undefined;
332
+ }
315
333
  const link = usage.link;
316
334
  if (link.linkType == "section") {
317
335
  if (link.form == "next") {
@@ -385,6 +403,8 @@ export function createLanguageService(options) {
385
403
  return usage.embed.nameRange;
386
404
  if (usage.goto)
387
405
  return usage.goto.nameRange;
406
+ if (usage.deactivate)
407
+ return usage.deactivate.nameRange;
388
408
  const link = usage.link;
389
409
  if (link.form == "next")
390
410
  return undefined;
@@ -461,6 +481,9 @@ export function createLanguageService(options) {
461
481
  const index = await getIndex();
462
482
  return allDiagnostics(index).filter(d => d.file == path);
463
483
  },
484
+ async getAllDiagnostics() {
485
+ return allDiagnostics(await getIndex());
486
+ },
464
487
  async getDocumentSymbols(path) {
465
488
  const index = await getIndex();
466
489
  const tree = await getFile(index, path);
@@ -579,7 +602,7 @@ export function createLanguageService(options) {
579
602
  .map(name => ({ label: name, kind: "passage", range: replace(typed) }));
580
603
  };
581
604
  let match;
582
- if ((match = /\{\{~?\s*embed\s+["']([^"']*)$/.exec(prefix))) {
605
+ if ((match = /\{\{~?\s*#?embed\s+["']([^"']*)$/.exec(prefix))) {
583
606
  return [...passageItems(match[1]), ...sectionItems(match[1])];
584
607
  }
585
608
  // {{seen "name"}}, (visits "name") etc., which take a section or passage (#377)
@@ -589,6 +612,9 @@ export function createLanguageService(options) {
589
612
  if ((match = /\{\{~?\s*goto\s+["']([^"']*)$/.exec(prefix))) {
590
613
  return sectionItems(match[1]);
591
614
  }
615
+ if ((match = /\{\{~?\s*deactivate\s+["']([^"']*)$/.exec(prefix))) {
616
+ return passageItems(match[1]);
617
+ }
592
618
  if ((match = /\[\[[^\]]*\]\]\(([^),]*)$/.exec(prefix))) {
593
619
  return sectionItems(match[1]);
594
620
  }