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

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.
@@ -1,20 +1,22 @@
1
1
  // The whole story as a directed graph: its sections and passages, and the links between them,
2
2
  // with which can be reached from the start and which sections are dead ends. The language
3
3
  // service builds it from its index (see getStoryGraph), for the story map and for the
4
- // "unreachable section" and "dead end" diagnostics.
4
+ // "unreachable section" and "dead end" diagnostics, and the "sound on the first screen" one.
5
+ import { capitalise, sectionDetail, sectionLabels } from "./section-labels.js";
5
6
  export const sectionId = (name) => `section:${name}`;
6
7
  export const passageId = (section, name) => `passage:${section}/${name}`;
7
8
  const NAVIGATION = new Set(["section-link", "goto", "script"]);
8
9
  const collapsed = (position) => ({ start: position, end: position });
9
10
  const comparePositions = (a, b) => a.line - b.line || a.character - b.character;
10
- // The parts of a container's text inside {{#if}} or {{#unless}} blocks
11
+ // The parts of a container's text inside {{#if}} or {{#unless}} blocks, or {{#every}} (#451),
12
+ // whose text is shown later, if the player is still there
11
13
  function conditionalRanges(container) {
12
14
  const ranges = [];
13
15
  const open = [];
14
16
  for (const statement of container.body) {
15
17
  if (statement.type != "text")
16
18
  continue;
17
- for (const match of statement.text.matchAll(/\{\{~?\s*([#/])(if|unless)\b/g)) {
19
+ for (const match of statement.text.matchAll(/\{\{~?\s*([#/])(if|unless|every)\b/g)) {
18
20
  const position = { line: statement.range.start.line, character: match.index };
19
21
  if (match[1] == "#") {
20
22
  open.push(position);
@@ -31,16 +33,6 @@ function conditionalRanges(container) {
31
33
  ranges.push({ start, end: container.range.end });
32
34
  return ranges;
33
35
  }
34
- // What the outline calls a section without a name of its own
35
- function sectionDetail(node) {
36
- if (node.kind == "preamble")
37
- return "(Start)";
38
- if (node.header?.type == "continue")
39
- return `+++${node.header.text}`;
40
- if (node.header?.type == "separator")
41
- return "---";
42
- return undefined;
43
- }
44
36
  // The end of a section's or passage's own text, leaving out blank lines and its passages
45
37
  function contentEnd(container) {
46
38
  const ownEnd = container.type == "section" && container.passages.length
@@ -141,6 +133,11 @@ export function buildStoryGraph(source) {
141
133
  }
142
134
  }
143
135
  }
136
+ for (const [name, label] of sectionLabels(source.files.values(), node => source.nodeNames.get(node))) {
137
+ const node = nodeById.get(sectionId(name));
138
+ if (node)
139
+ node.label = label;
140
+ }
144
141
  // The link a +++ line adds to the section before it
145
142
  for (const [file, tree] of source.files) {
146
143
  const all = [tree.preamble, ...tree.sections];
@@ -197,7 +194,7 @@ export function buildStoryGraph(source) {
197
194
  if (dynamic)
198
195
  unknown.add(from);
199
196
  const resolvedName = target?.name;
200
- const setters = link.form != "next" && link.target.trim() == resolvedName
197
+ const setters = link.form == "input" || (link.form != "next" && link.target.trim() == resolvedName)
201
198
  ? []
202
199
  : link.target.split(",").slice(1).map(s => s.trim()).filter(Boolean);
203
200
  const text = link.text ?? link.target.trim().split(",")[0].trim();
@@ -351,7 +348,7 @@ export function storyGraphDiagnostics(graph) {
351
348
  range: node.location.range,
352
349
  severity: "warning",
353
350
  code: "squiffy/unreachable-section",
354
- message: `The section "${node.name}" can't be reached from the start of the story, as nothing the player can reach links to it.`,
351
+ message: `${capitalise(node.label ?? `the section "${node.name}"`)} can't be reached from the start of the story, as nothing the player can reach links to it.`,
355
352
  });
356
353
  }
357
354
  else if (node.deadEnd) {
@@ -360,9 +357,57 @@ export function storyGraphDiagnostics(graph) {
360
357
  range: node.location.range,
361
358
  severity: "warning",
362
359
  code: "squiffy/dead-end",
363
- message: `The section "${node.name}" has no way out, as it has no links to another section. If it's one of the story's endings, add @end to say so.`,
360
+ message: `${capitalise(node.label ?? `the section "${node.name}"`)} has no way out, as it has no links to another section. If it's one of the story's endings, add @end to say so.`,
364
361
  });
365
362
  }
366
363
  }
367
364
  return diagnostics;
368
365
  }
366
+ // {{music "file"}} or {{sound "file"}}, as emit.ts finds them
367
+ const SOUND_HELPER = /\{\{~?\s*(music|sound)\s+(["'])([^"'{}]+)\2/g;
368
+ // Sound on the story's first screen: browsers don't let a page play sound until the player has
369
+ // clicked something, so music there waits for their first click, and a sound played once there
370
+ // isn't heard at all. That's the start section's own @music, @sound, {{music}} and {{sound}},
371
+ // and the master section's @music and @sound, which play with every section, the first too.
372
+ // (Its passages, and the start section's, are shown by a click, so they're fine.)
373
+ export function firstScreenSoundDiagnostics(source) {
374
+ const diagnostics = [];
375
+ const report = (file, range, kind, value, master) => {
376
+ const where = master ? "The master section plays this with every section, including the story's first screen, but browsers" : "Browsers";
377
+ const what = kind == "music"
378
+ ? `so "${value}" won't start until the player's first click`
379
+ : `so "${value}" won't be heard on the story's first screen`;
380
+ diagnostics.push({
381
+ file,
382
+ range,
383
+ severity: "warning",
384
+ code: "squiffy/sound-on-first-screen",
385
+ message: `${where} don't play sound until the player has clicked something, ${what}. Begin the story with a title screen and a link such as "Begin", and play it in the section that link goes to.`,
386
+ });
387
+ };
388
+ const check = (name, master) => {
389
+ const section = source.sections.get(name);
390
+ if (!section?.node)
391
+ return;
392
+ for (const statement of section.node.body) {
393
+ if (statement.type == "sound") {
394
+ if (statement.value != "stop")
395
+ report(section.file, statement.range, statement.directive, statement.value, master);
396
+ }
397
+ else if (statement.type == "text" && !master) {
398
+ for (const match of statement.text.matchAll(SOUND_HELPER)) {
399
+ const before = statement.text.substring(0, match.index);
400
+ const lines = before.split("\n");
401
+ const line = statement.range.start.line + lines.length - 1;
402
+ const character = (lines.length == 1 ? statement.range.start.character : 0) + lines[lines.length - 1].length;
403
+ const range = { start: { line, character }, end: { line, character: character + match[0].length } };
404
+ report(section.file, range, match[1], match[3], false);
405
+ }
406
+ }
407
+ }
408
+ };
409
+ if (source.start != "")
410
+ check(source.start, false);
411
+ check("", true);
412
+ return diagnostics;
413
+ }
package/dist/syntax.d.ts CHANGED
@@ -7,7 +7,7 @@ export interface Range {
7
7
  end: Position;
8
8
  }
9
9
  export type DiagnosticSeverity = "error" | "warning" | "hint";
10
- export type DiagnosticCode = "squiffy/passage-without-section" | "squiffy/text-in-ui-block" | "squiffy/content-before-section" | "squiffy/v5-syntax" | "squiffy/at-attribute" | "squiffy/unquoted-text" | "squiffy/built-in-attribute" | "squiffy/external-files-unavailable" | "squiffy/no-next-section" | "squiffy/unknown-embed" | "squiffy/unknown-goto" | "squiffy/unknown-deactivate" | "squiffy/unknown-section-link" | "squiffy/unknown-passage-link" | "squiffy/duplicate-section" | "squiffy/duplicate-passage" | "squiffy/not-in-main-file" | "squiffy/repeat-not-in-passage" | "squiffy/redundant-import" | "squiffy/project-file" | "squiffy/unreachable-section" | "squiffy/dead-end";
10
+ export type DiagnosticCode = "squiffy/passage-without-section" | "squiffy/text-in-ui-block" | "squiffy/content-before-section" | "squiffy/v5-syntax" | "squiffy/at-attribute" | "squiffy/unquoted-text" | "squiffy/built-in-attribute" | "squiffy/external-files-unavailable" | "squiffy/no-next-section" | "squiffy/unknown-embed" | "squiffy/unknown-goto" | "squiffy/unknown-deactivate" | "squiffy/unknown-section-link" | "squiffy/unknown-passage-link" | "squiffy/duplicate-section" | "squiffy/duplicate-passage" | "squiffy/not-in-main-file" | "squiffy/repeat-not-in-passage" | "squiffy/transition" | "squiffy/redundant-import" | "squiffy/project-file" | "squiffy/unreachable-section" | "squiffy/dead-end" | "squiffy/sound-on-first-screen" | "squiffy/template-syntax";
11
11
  export interface Diagnostic {
12
12
  file: string;
13
13
  range: Range;
@@ -134,6 +134,14 @@ export interface ClassNode {
134
134
  valueRange: Range;
135
135
  range: Range;
136
136
  }
137
+ export interface TransitionNode {
138
+ type: "transition";
139
+ directive: "transition" | "leave";
140
+ value: string;
141
+ valueRange: Range;
142
+ time?: string;
143
+ range: Range;
144
+ }
137
145
  export interface AttributeNode {
138
146
  type: "attribute";
139
147
  directive: "set" | "unset" | "inc" | "dec";
@@ -153,11 +161,11 @@ export interface TextNode {
153
161
  text: string;
154
162
  range: Range;
155
163
  }
156
- export type StatementNode = SeparatorNode | TitleNode | StartNode | ImportNode | UiBlockStartNode | UiFileNode | ClearNode | RepeatNode | EndNode | AttributeNode | SoundNode | ClassNode | JsNode | TextNode;
164
+ export type StatementNode = SeparatorNode | TitleNode | StartNode | ImportNode | UiBlockStartNode | UiFileNode | ClearNode | RepeatNode | EndNode | AttributeNode | SoundNode | ClassNode | TransitionNode | JsNode | TextNode;
157
165
  export interface LinkNode {
158
166
  type: "link";
159
167
  linkType: "section" | "passage";
160
- form: "named" | "unnamed" | "next";
168
+ form: "named" | "unnamed" | "next" | "input";
161
169
  text?: string;
162
170
  target: string;
163
171
  range: Range;
@@ -0,0 +1,6 @@
1
+ export interface TemplateError {
2
+ start: number;
3
+ end: number;
4
+ message: string;
5
+ }
6
+ export declare function findTemplateError(text: string): TemplateError | null;
@@ -0,0 +1,128 @@
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
+ }
package/dist/text.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export interface TextLink {
2
2
  linkType: "section" | "passage";
3
- form: "named" | "unnamed" | "next";
3
+ form: "named" | "unnamed" | "next" | "input";
4
4
  text?: string;
5
5
  target: string;
6
6
  start: number;
@@ -29,6 +29,8 @@ export interface TransformResult {
29
29
  gotos: TextGoto[];
30
30
  deactivates: TextDeactivate[];
31
31
  noNextSection: NoNextSection[];
32
+ mapStart: (pos: number) => number;
33
+ mapEnd: (pos: number) => number;
32
34
  }
33
35
  export declare const balancedTarget: string;
34
36
  export declare function transformText(text: string, getNextSectionName: () => string | null, expressions?: boolean): TransformResult;
package/dist/text.js CHANGED
@@ -293,7 +293,34 @@ export function transformText(text, getNextSectionName, expressions = false) {
293
293
  return result;
294
294
  };
295
295
  embeds.push(...findNamed("embed", true));
296
- return { output: input.value, links, embeds, gotos: findNamed("goto"), deactivates: findNamed("deactivate"), noNextSection };
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
+ };
297
324
  }
298
325
  // Returns a function that converts an offset into lines.join("\n") to a position in the source file.
299
326
  export function positionMapper(lines, lineLengths) {
@@ -45,6 +45,14 @@ export declare class StoryContext {
45
45
  readonly extraSections: string[];
46
46
  private readonly permanentVars;
47
47
  readonly passagesByName: Map<string, TwinePassage>;
48
+ readonly passageStyles: {
49
+ passage: string;
50
+ css: string;
51
+ }[];
52
+ readonly passageScripts: {
53
+ passage: string;
54
+ js: string;
55
+ }[];
48
56
  constructor(twine: TwineStory, passages: TwinePassage[]);
49
57
  private readonly problemKeys;
50
58
  addProblem(problem: TwineConversionProblem): void;
@@ -73,6 +81,7 @@ export declare class StoryContext {
73
81
  }
74
82
  export declare function sanitiseName(name: string): string;
75
83
  export declare function escapeText(text: string): string;
84
+ export declare function escapeLinkBrackets(text: string): string;
76
85
  export declare function sectionLink(text: string | null, target: string, setters?: string[]): string;
77
86
  export declare function isUrl(target: string): boolean;
78
87
  export declare function urlLink(text: string, url: string): string;
@@ -85,5 +94,31 @@ export declare function convertTwine(source: string, options?: TwineConversionOp
85
94
  export declare function convertTwineStory(twine: TwineStory, options?: TwineConversionOptions): TwineConversionResult;
86
95
  export declare function tagClasses(tags: string[]): string[];
87
96
  export declare function convertTagSelectors(css: string): string;
97
+ export interface HtmlBlock {
98
+ t: "html";
99
+ tag: "script" | "style";
100
+ raw: string;
101
+ attributes: string;
102
+ content: string;
103
+ }
104
+ export declare function readHtmlBlock(src: string, i: number): {
105
+ block: HtmlBlock;
106
+ end: number;
107
+ } | undefined;
108
+ export declare function passageHtmlBlock(ctx: PassageContext, block: HtmlBlock, top: boolean): {
109
+ text: string;
110
+ directive?: string;
111
+ };
112
+ export declare function topScripts<N extends {
113
+ t: string;
114
+ }>(ctx: PassageContext, nodes: (N | HtmlBlock)[], directives: string[]): (N | HtmlBlock | {
115
+ t: "raw";
116
+ s: string;
117
+ })[];
118
+ export declare function convertTwineSelectors(css: string): {
119
+ css: string;
120
+ translated: string[];
121
+ untranslated: string[];
122
+ };
88
123
  export declare function usesOuterLoop(text: string): boolean;
89
124
  export declare function finishText(text: string): string;