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
@@ -0,0 +1,504 @@
1
+ // Converts a Quest gamebook, from Quest 5 or Quest Viva, into a Squiffy story: each page becomes a section, and its options
2
+ // become links. Like the Twine converter, this is a pure function with no I/O: the CLI and the
3
+ // editor read the game (from a .aslx file, or the game.aslx in a .quest file) and write the files
4
+ // it returns. Anything that can't be converted is kept as a comment in the story and listed as a
5
+ // problem, so the author can deal with it by hand.
6
+ import { formatProjectFile } from "../project.js";
7
+ import { finishText, reservedAttributes, sanitiseName, sectionLink, urlLink } from "../twine/convert.js";
8
+ import { attributeRef, print, quote } from "../twine/expression.js";
9
+ import { parseQuestGame, QuestParseError } from "./aslx.js";
10
+ import { ScriptParser } from "./script.js";
11
+ import { convertScript, linkChanges } from "./scripts.js";
12
+ import { convertQuestText, escapeLineStarts } from "./text.js";
13
+ export function convertQuestGamebook(source, options = {}) {
14
+ const game = parseQuestGame(source);
15
+ if (!game.gamebook) {
16
+ throw new QuestParseError("This is a Quest text adventure, not a gamebook. Only gamebooks can be converted to Squiffy.");
17
+ }
18
+ return convertGame(game, options);
19
+ }
20
+ // A Quest object's attribute, as text, or "" if it isn't text
21
+ function stringAttribute(o, name) {
22
+ const value = o.attributes.get(name);
23
+ return value?.type == "string" ? value.value : "";
24
+ }
25
+ // Whether a script calls a function or command, such as "play sound", anywhere in it
26
+ function calls(statements, fn) {
27
+ return statements.some(s => {
28
+ switch (s.k) {
29
+ case "call": return s.fn == fn || calls(s.callback ?? [], fn);
30
+ case "if": return s.branches.some(b => calls(b.body, fn)) || calls(s.otherwise ?? [], fn);
31
+ case "firsttime": return calls(s.body, fn) || calls(s.otherwise ?? [], fn);
32
+ case "switch": return s.cases.some(c => calls(c.body, fn)) || calls(s.otherwise ?? [], fn);
33
+ default: return false;
34
+ }
35
+ });
36
+ }
37
+ function booleanValue(value) {
38
+ return value?.type == "boolean" ? value.value : undefined;
39
+ }
40
+ // A comment in the story, for Quest code that couldn't be converted. Handlebars comments can't
41
+ // contain --}}, and line breaks would let the compiler read a line of it as something else.
42
+ function comment(text) {
43
+ const clean = text.replace(/--\}\}/g, "-- }}").replace(/\s*\n\s*/g, " ").trim();
44
+ return `{{!-- Quest: ${clean} --}}`;
45
+ }
46
+ function oneLine(text) {
47
+ const line = text.replace(/\s+/g, " ").trim();
48
+ return line.length > 120 ? line.substring(0, 117) + "..." : line;
49
+ }
50
+ function convertGame(game, options) {
51
+ const name = options.name ?? "story";
52
+ const problems = [];
53
+ const problemKeys = new Set();
54
+ const addProblem = (problem) => {
55
+ const key = `${problem.page}\u0000${problem.text}\u0000${problem.reason}`;
56
+ if (problemKeys.has(key))
57
+ return;
58
+ problemKeys.add(key);
59
+ problems.push(problem);
60
+ };
61
+ const assets = new Set();
62
+ const gameSetting = (setting) => game.game.attributes.get(setting) ?? game.gameDefaults.get(setting);
63
+ // Link pages go to a web page, rather than being pages of the story
64
+ const isLinkPage = (p) => p.inherits.includes("link");
65
+ const pagesByName = new Map(game.pages.map(p => [p.name, p]));
66
+ const storyPages = game.pages.filter(p => !isLinkPage(p));
67
+ // Pages keep their names where they can: a name that's the same as another once it's been
68
+ // tidied up gets a number
69
+ const sectionNames = new Map();
70
+ const usedNames = new Set();
71
+ const wanted = storyPages.map(p => sanitiseName(p.name) || "Untitled");
72
+ storyPages.forEach((p, n) => {
73
+ if (!usedNames.has(wanted[n].toLowerCase())) {
74
+ sectionNames.set(p.name, wanted[n]);
75
+ usedNames.add(wanted[n].toLowerCase());
76
+ }
77
+ });
78
+ storyPages.forEach((p, n) => {
79
+ if (sectionNames.has(p.name))
80
+ return;
81
+ let candidate = wanted[n];
82
+ for (let i = 2; usedNames.has(candidate.toLowerCase()); i++)
83
+ candidate = `${wanted[n]} ${i}`;
84
+ sectionNames.set(p.name, candidate);
85
+ usedNames.add(candidate.toLowerCase());
86
+ });
87
+ const target = (page) => {
88
+ const p = pagesByName.get(page);
89
+ if (!p)
90
+ return undefined;
91
+ if (isLinkPage(p))
92
+ return { url: stringAttribute(p, "address") };
93
+ return { section: sectionNames.get(p.name) };
94
+ };
95
+ // Quest keeps flags and counters as attributes of the game. Most can keep their names.
96
+ const attribute = (questName) => {
97
+ const trimmed = questName.trim();
98
+ return reservedAttributes.has(trimmed) ? trimmed + "_" : trimmed;
99
+ };
100
+ const startPage = (game.start && sectionNames.has(game.start) ? game.start : undefined) ?? storyPages[0]?.name;
101
+ const title = game.game.name.replace(/\s+/g, " ").trim();
102
+ const showTitle = booleanValue(gameSetting("showtitle")) ?? true;
103
+ const clearLastPage = booleanValue(gameSetting("clearlastpage")) ?? false;
104
+ // The game's scripts are read first, as they can add links to other pages, which those pages
105
+ // need to show
106
+ const objectNames = new Set([...game.pages.map(p => p.name), "game", "player"]);
107
+ const isPage = (name) => pagesByName.has(name);
108
+ const pageScripts = new Map();
109
+ const scriptOnlyPages = new Set();
110
+ for (const page of storyPages) {
111
+ const runScript = booleanValue(page.attributes.get("runscript")) || page.inherits.includes("scripttext");
112
+ const scriptOnly = booleanValue(page.attributes.get("runscriptonly")) || page.inherits.includes("script");
113
+ if (scriptOnly)
114
+ scriptOnlyPages.add(page.name);
115
+ const script = page.attributes.get("script");
116
+ if ((runScript || scriptOnly) && script?.type == "script" && script.value.trim()) {
117
+ pageScripts.set(page.name, ScriptParser.parse(script.value, objectNames));
118
+ }
119
+ }
120
+ const roomEnterValue = game.game.attributes.get("roomenter");
121
+ const roomEnter = roomEnterValue?.type == "script" && roomEnterValue.value.trim() ? ScriptParser.parse(roomEnterValue.value, objectNames) : undefined;
122
+ const dynamicLinks = new Map();
123
+ const addedLinks = new Map();
124
+ const usedLinkAttributes = new Set();
125
+ const initialOptions = (p) => {
126
+ const value = p?.attributes.get("options");
127
+ return value?.type == "stringdictionary" ? value.value : [];
128
+ };
129
+ const dynamicLink = (source, destination) => {
130
+ const key = `${source}\u0000${destination}`;
131
+ let link = dynamicLinks.get(key);
132
+ if (!link) {
133
+ const base = `link_${sectionNames.get(source) ?? source}_${sectionNames.get(destination) ?? destination}`.replace(/[^\p{L}\p{N}_]+/gu, "_");
134
+ let name = base;
135
+ for (let n = 2; usedLinkAttributes.has(name.toLowerCase()); n++)
136
+ name = `${base}_${n}`;
137
+ usedLinkAttributes.add(name.toLowerCase());
138
+ const initial = initialOptions(pagesByName.get(source)).find(([d]) => d == destination)?.[1];
139
+ link = { attribute: name, texts: initial === undefined ? [] : [initial], initial };
140
+ dynamicLinks.set(key, link);
141
+ if (initial === undefined)
142
+ addedLinks.set(source, [...addedLinks.get(source) ?? [], destination]);
143
+ }
144
+ return link;
145
+ };
146
+ for (const [page, statements] of [...pageScripts, ["", roomEnter ?? []]]) {
147
+ for (const change of linkChanges(statements, page || undefined, isPage)) {
148
+ const link = dynamicLink(change.source, change.destination);
149
+ if (change.text !== undefined && !link.texts.includes(change.text))
150
+ link.texts.push(change.text);
151
+ }
152
+ }
153
+ // With more than one text, the attribute is which one, counting from 1
154
+ const linkValue = (link, text) => link.texts.length > 1 ? { k: "num", v: link.texts.indexOf(text) + 1 } : { k: "bool", v: true };
155
+ let firstTimes = 0;
156
+ let styled = false;
157
+ const scriptContext = (ctx, page) => ({
158
+ ...ctx,
159
+ page,
160
+ isPage,
161
+ linkAttribute: (source, destination) => dynamicLink(source, destination).attribute,
162
+ linkValue: (source, destination, text) => linkValue(dynamicLink(source, destination), text),
163
+ newFirstTime: () => `firsttime_${++firstTimes}`,
164
+ noteStyle: () => { styled = true; },
165
+ });
166
+ // Quest stops every sound when the player goes to another page, unless the last page with a
167
+ // sound was set to continue playing it (game.continuesound). That's done at the start of each
168
+ // page, or in the master section if the script that runs on every page plays a sound, as
169
+ // Quest stops sounds before running it.
170
+ const pageSound = (p) => scriptOnlyPages.has(p.name) ? "" : stringAttribute(p, "sound").trim();
171
+ const playsSound = storyPages.some(p => pageSound(p))
172
+ || [...pageScripts.values(), roomEnter ?? []].some(statements => calls(statements, "play sound"));
173
+ const continuesSound = storyPages.some(p => pageSound(p) && booleanValue(p.attributes.get("continuesound")));
174
+ const continueAttribute = attribute("continuesound");
175
+ const stopSounds = !playsSound ? { directives: [], lines: [] }
176
+ : continuesSound ? { directives: [], lines: [`{{#unless ${attributeRef(continueAttribute)}}}{{stopsounds}}{{stopmusic}}{{/unless}}`] }
177
+ : { directives: ["@sound stop", "@music stop"], lines: [] };
178
+ const stopInMaster = !!roomEnter && calls(roomEnter, "play sound");
179
+ const sections = [];
180
+ for (const page of storyPages) {
181
+ const section = sectionNames.get(page.name);
182
+ const passages = [];
183
+ const ctx = {
184
+ section,
185
+ target,
186
+ attribute,
187
+ unconvertible(text, reason) {
188
+ addProblem({ page: page.name, text: oneLine(text), reason });
189
+ return comment(text);
190
+ },
191
+ approximate(text, reason) {
192
+ addProblem({ page: page.name, text: oneLine(text), reason });
193
+ },
194
+ addPassage(hint, content) {
195
+ const base = sanitiseName(hint.replace(/<[^>]*>|\{[^{}]*\}/g, "")).replace(/:/g, "").substring(0, 40).trim() || "more";
196
+ let passage = base;
197
+ for (let n = 2; passages.some(p => p.startsWith(`[${passage}]:\n`)) || passage == section; n++)
198
+ passage = `${base} ${n}`;
199
+ passages.push(`[${passage}]:\n${finishText(escapeLineStarts(content))}`);
200
+ return passage;
201
+ },
202
+ asset(file) {
203
+ if (file && !/^(https?:)?\/\//i.test(file))
204
+ assets.add(file);
205
+ },
206
+ };
207
+ const lines = stopInMaster ? [] : [...stopSounds.lines];
208
+ const directives = stopInMaster ? [] : [...stopSounds.directives];
209
+ if (page.name == startPage) {
210
+ const initial = [...dynamicLinks.values()].filter(l => l.initial !== undefined);
211
+ const parts = [];
212
+ if (showTitle && title) {
213
+ const subtitle = stringAttribute(game.game, "subtitle").trim();
214
+ const author = stringAttribute(game.game, "author").trim();
215
+ const heading = [`<h1>${convertQuestText(title, ctx, "inline")}</h1>`];
216
+ if (subtitle)
217
+ heading.push(`<p>${convertQuestText(subtitle, ctx, "inline")}</p>`);
218
+ if (author)
219
+ heading.push(`<p>${convertQuestText(author, ctx, "inline")}</p>`);
220
+ parts.push(`<div class="quest-title" style="text-align: center">${heading.join("")}</div>`);
221
+ }
222
+ // Quest shows the title once, when the game starts, and many gamebooks go back to
223
+ // their first page to play again
224
+ if (initial.length || parts.length) {
225
+ lines.push(`{{#if (visits ${quote(section)}) = 1}}`, ...initial.map(l => `{{set ${quote(l.attribute)} ${print(linkValue(l, l.initial))}}}`), ...parts, "{{/if}}");
226
+ }
227
+ }
228
+ const scriptOnly = scriptOnlyPages.has(page.name);
229
+ const option = (destination, text) => {
230
+ const linkText = convertQuestText(text || destination, ctx, "inline");
231
+ const to = target(destination);
232
+ if (!to) {
233
+ addProblem({ page: page.name, text: oneLine(text || destination), reason: `This option goes to a page called "${destination}", which isn't in the game. Quest shows it as a broken link, so it isn't a link here.` });
234
+ return `${linkText} (broken link)`;
235
+ }
236
+ return "url" in to ? urlLink(linkText, to.url) : sectionLink(linkText, to.section);
237
+ };
238
+ const dynamic = (destination, link) => link.texts.flatMap((text, i) => [
239
+ `{{#if ${link.texts.length > 1 ? `${attributeRef(link.attribute)} = ${i + 1}` : attributeRef(link.attribute)}}}`,
240
+ option(destination, text),
241
+ "{{/if}}",
242
+ ]);
243
+ // The page's links, made when they're first needed, so problems are listed in the order of
244
+ // the page. A page that only runs its script shows no links.
245
+ let optionLines;
246
+ const pageLinks = () => {
247
+ if (optionLines)
248
+ return optionLines;
249
+ optionLines = [];
250
+ if (scriptOnly)
251
+ return optionLines;
252
+ for (const [destination, text] of initialOptions(page)) {
253
+ const link = dynamicLinks.get(`${page.name}\u0000${destination}`);
254
+ optionLines.push(...(link ? dynamic(destination, link) : [option(destination, text)]));
255
+ }
256
+ for (const destination of addedLinks.get(page.name) ?? []) {
257
+ optionLines.push(...dynamic(destination, dynamicLinks.get(`${page.name}\u0000${destination}`)));
258
+ }
259
+ return optionLines;
260
+ };
261
+ const statements = pageScripts.get(page.name);
262
+ let moves = false;
263
+ // Sections for what happens after the player types something (GetInput), which go after
264
+ // this one
265
+ const continued = [];
266
+ const continueSection = (content) => {
267
+ let name = `${section} continued`;
268
+ for (let n = 2; usedNames.has(name.toLowerCase()); n++)
269
+ name = `${section} continued ${n}`;
270
+ usedNames.add(name.toLowerCase());
271
+ const links = pageLinks();
272
+ const text = [content, ...(links.length ? ["", ...links] : [])].join("\n");
273
+ const leavesHere = /\[\[|<a href|\{\{goto/.test(text);
274
+ continued.push(`[[${name}]]:\n${[...(leavesHere ? [] : ["@end"]), finishText(escapeLineStarts(text))].filter(l => l).join("\n")}`);
275
+ return name;
276
+ };
277
+ if (statements) {
278
+ const script = convertScript(statements, { ...scriptContext(ctx, page.name), continueSection });
279
+ directives.push(...script.directives);
280
+ lines.push(...script.lines);
281
+ moves = script.lines.some(l => l.includes("{{goto"));
282
+ }
283
+ if (!scriptOnly) {
284
+ const picture = stringAttribute(page, "picture").trim();
285
+ if (picture) {
286
+ ctx.asset(picture);
287
+ lines.push(`<img class="quest-picture" src="${escapeAttribute(picture)}" alt="">`, "");
288
+ }
289
+ const youtube = youTubeId(stringAttribute(page, "youtube"));
290
+ if (youtube) {
291
+ lines.push(`<iframe class="quest-youtube" width="560" height="315" src="https://www.youtube.com/embed/${encodeURIComponent(youtube)}" allowfullscreen></iframe>`, "");
292
+ }
293
+ const sound = pageSound(page);
294
+ if (sound) {
295
+ ctx.asset(sound);
296
+ if (continuesSound) {
297
+ // After the sounds are stopped at the start of the page, which is in its text
298
+ const continues = booleanValue(page.attributes.get("continuesound")) ?? false;
299
+ lines.push(`{{sound ${quote(sound)}}}{{set ${quote(continueAttribute)} ${continues}}}`);
300
+ }
301
+ else {
302
+ directives.push(`@sound ${sound}`);
303
+ }
304
+ }
305
+ lines.push(convertQuestText(stringAttribute(page, "description"), ctx, "block"));
306
+ const links = pageLinks();
307
+ if (links.length)
308
+ lines.push("", ...links);
309
+ if (moves) {
310
+ addProblem({
311
+ page: page.name, text: page.name,
312
+ reason: "This page's script can go to another page. In Quest, the rest of the page wasn't shown then, but here its text and links are shown first.",
313
+ });
314
+ }
315
+ }
316
+ // A page with no links, and no script that goes somewhere, is one of the endings
317
+ const leaves = (l) => l.includes("[[") || l.includes("<a href") || l.includes("{{goto");
318
+ if (!lines.some(leaves) && !passages.some(leaves))
319
+ directives.push("@end");
320
+ const body = finishText(escapeLineStarts(lines.join("\n")));
321
+ sections.push([`[[${section}]]:\n${[...directives, body].filter(l => l).join("\n")}`.trimEnd(), ...passages, ...continued].join("\n\n"));
322
+ }
323
+ for (const p of game.pages.filter(isLinkPage)) {
324
+ if (!stringAttribute(p, "address").trim()) {
325
+ addProblem({ page: p.name, text: p.name, reason: "This link page has no web address." });
326
+ }
327
+ }
328
+ // The master section runs with every section, as the game's roomenter script runs on every page
329
+ const master = [];
330
+ if (clearLastPage)
331
+ master.push("@clear");
332
+ if (stopInMaster)
333
+ master.push(...stopSounds.directives, ...stopSounds.lines);
334
+ if (roomEnter) {
335
+ const ctx = {
336
+ section: "",
337
+ target,
338
+ attribute,
339
+ unconvertible(text, reason) {
340
+ addProblem({ text: oneLine(text), reason: `${reason} It's in the script that runs on every page, in the master section, [[]].` });
341
+ return comment(text);
342
+ },
343
+ approximate(text, reason) {
344
+ addProblem({ text: oneLine(text), reason });
345
+ },
346
+ asset(file) {
347
+ if (file && !/^(https?:)?\/\//i.test(file))
348
+ assets.add(file);
349
+ },
350
+ };
351
+ const script = convertScript(roomEnter, scriptContext(ctx));
352
+ master.push(...script.directives);
353
+ const body = finishText(escapeLineStarts(script.lines.join("\n")));
354
+ if (body)
355
+ master.push(body);
356
+ }
357
+ if (styled && clearLastPage) {
358
+ addProblem({ text: "SetBackgroundColour", reason: "The game clears the screen before each page, so a script's changes to how it looks, such as its colours or font, only last until the next page. To keep one, set it in story.css." });
359
+ }
360
+ for (const [setting, value] of game.game.attributes) {
361
+ if (value.type == "script" && setting != "roomenter" && value.value.trim()) {
362
+ addProblem({ text: setting, reason: `The game's "${setting}" script can't be converted yet: ${oneLine(value.value)}` });
363
+ }
364
+ }
365
+ for (const file of game.javascript) {
366
+ addProblem({ text: file, reason: "The game's JavaScript was written for Quest, so it isn't part of the story." });
367
+ }
368
+ const files = {};
369
+ const exclude = [];
370
+ if (options.files) {
371
+ const available = new Set(options.files.map(f => f.toLowerCase()));
372
+ for (const asset of assets) {
373
+ if (!available.has(asset.toLowerCase())) {
374
+ addProblem({ text: asset, reason: "The game uses this file, but it wasn't found with the game." });
375
+ }
376
+ }
377
+ // Quest's own scripts and styles would break Squiffy's page
378
+ exclude.push(...options.files.filter(f => /\.(js|css)$/i.test(f)));
379
+ }
380
+ const css = stylesheet(game, gameSetting);
381
+ if (css)
382
+ files[`${name}.css`] = css;
383
+ const header = [];
384
+ if (title)
385
+ header.push(`@title ${title}`);
386
+ const startSection = startPage === undefined ? undefined : sectionNames.get(startPage);
387
+ if (startSection !== undefined)
388
+ header.push(`@start ${startSection}`);
389
+ const script = [
390
+ header.join("\n"),
391
+ master.length ? `[[]]:\n${master.join("\n")}` : "",
392
+ ...sections,
393
+ ].filter(s => s.length).join("\n\n") + "\n";
394
+ files[`${name}.squiffy`] = script;
395
+ files["squiffy.json"] = formatProjectFile({ main: `${name}.squiffy`, exclude });
396
+ return {
397
+ title,
398
+ format: `${productName(game.aslVersion)} gamebook`,
399
+ files,
400
+ main: `${name}.squiffy`,
401
+ pages: storyPages.length,
402
+ assets: [...assets],
403
+ problems,
404
+ };
405
+ }
406
+ // The version of Quest a game was saved by, from its ASL version: Quest 5 (e.g. "550" is 5.5), or
407
+ // from version 6, Quest Viva
408
+ function productName(aslVersion) {
409
+ const version = /^(\d)(\d)\d$/.exec(aslVersion);
410
+ if (!version)
411
+ return "Quest";
412
+ return `${Number(version[1]) >= 6 ? "Quest Viva" : "Quest"} ${version[1]}.${version[2]}`;
413
+ }
414
+ function escapeAttribute(s) {
415
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/\[/g, "&#91;").replace(/\]/g, "&#93;");
416
+ }
417
+ // A YouTube video's id, from what the author typed: the id, or the video's address
418
+ function youTubeId(text) {
419
+ const t = text.trim();
420
+ const match = /(?:youtu\.be\/|[?&]v=|\/embed\/|\/shorts\/)([\w-]{6,})/.exec(t);
421
+ return match ? match[1] : t;
422
+ }
423
+ // The game's colours, fonts and page width, as a stylesheet. Only the ones the author chose are
424
+ // included: the rest follow Squiffy's defaults, which have light and dark versions.
425
+ function stylesheet(game, setting) {
426
+ const own = (name) => {
427
+ const value = game.game.attributes.get(name);
428
+ if (value?.type == "string")
429
+ return value.value.trim();
430
+ if (value?.type == "number")
431
+ return String(value.value);
432
+ return "";
433
+ };
434
+ const variables = [];
435
+ const imports = [];
436
+ const background = own("defaultbackground");
437
+ const foreground = own("defaultforeground");
438
+ const link = own("defaultlinkforeground");
439
+ if (background || foreground || link) {
440
+ // Quest shows a game with its own colours in light mode
441
+ variables.push("color-scheme: light;");
442
+ if (background)
443
+ variables.push(`--squiffy-background: ${cssValue(background)};`);
444
+ if (foreground)
445
+ variables.push(`--squiffy-text: ${cssValue(foreground)};`);
446
+ if (link)
447
+ variables.push(`--squiffy-link: ${cssValue(link)};`, `--squiffy-link-hover: ${cssValue(link)};`);
448
+ }
449
+ const webFont = own("defaultwebfont");
450
+ const font = own("defaultfont");
451
+ if (webFont) {
452
+ imports.push(`@import url("https://fonts.googleapis.com/css2?family=${encodeURIComponent(webFont).replace(/%20/g, "+")}&display=swap");`);
453
+ }
454
+ if (webFont || font) {
455
+ const families = [webFont ? `"${webFont.replace(/["\\]/g, "")}"` : "", cssValue(font)].filter(f => f);
456
+ variables.push(`--squiffy-font-family: ${families.join(", ")};`);
457
+ }
458
+ const size = own("defaultfontsize");
459
+ if (size && Number(size) > 0)
460
+ variables.push(`--squiffy-font-size: ${Number(size)}pt;`);
461
+ const width = own("customwidth");
462
+ const setWidth = setting("setcustomwidth");
463
+ if (width && Number(width) > 0 && (setWidth?.type != "boolean" || setWidth.value)) {
464
+ variables.push(`--squiffy-max-width: ${Number(width)}px;`);
465
+ }
466
+ if (!variables.length)
467
+ return undefined;
468
+ return [
469
+ "/* The game's colours, fonts and page width in Quest. See https://squiffystory.com/styling/ */",
470
+ ...imports,
471
+ "",
472
+ ":root {",
473
+ ...variables.map(v => " " + v),
474
+ "}",
475
+ "",
476
+ ].join("\n");
477
+ }
478
+ // A CSS value from the game, with nothing in it that could end the rule
479
+ function cssValue(value) {
480
+ return value.replace(/[;{}<>]/g, "").trim();
481
+ }
482
+ // The problems as a text file, to keep with the converted story: the ones about the whole story,
483
+ // then each page's, in the order of the game
484
+ export function formatQuestProblems(result, sourceName) {
485
+ const lines = [
486
+ `Converted ${sourceName ?? "a Quest gamebook"} (${result.format}) to Squiffy: ${result.pages} page${result.pages == 1 ? "" : "s"}.`,
487
+ "",
488
+ ];
489
+ if (result.problems.length == 0) {
490
+ lines.push("Everything was converted.");
491
+ return lines.join("\n") + "\n";
492
+ }
493
+ lines.push(`${result.problems.length} thing${result.problems.length == 1 ? "" : "s"} couldn't be converted exactly. Where something couldn't be converted at all, the story has the`, "Quest code in a comment, {{!-- Quest: ... --}}, so you can search for \"Quest:\" to find them.", "");
494
+ const sorted = [...result.problems.filter(p => p.page === undefined), ...result.problems.filter(p => p.page !== undefined)];
495
+ let page = "\u0000";
496
+ for (const p of sorted) {
497
+ if (p.page !== page) {
498
+ page = p.page;
499
+ lines.push(page === undefined ? "The whole story:" : `${page}:`);
500
+ }
501
+ lines.push(` ${p.text}`, ` ${p.reason}`);
502
+ }
503
+ return lines.join("\n") + "\n";
504
+ }
@@ -0,0 +1,92 @@
1
+ export type QExpr = {
2
+ k: "num";
3
+ v: number;
4
+ } | {
5
+ k: "str";
6
+ v: string;
7
+ } | {
8
+ k: "bool";
9
+ v: boolean;
10
+ } | {
11
+ k: "null";
12
+ } | {
13
+ k: "path";
14
+ parts: string[];
15
+ } | {
16
+ k: "call";
17
+ fn: string;
18
+ args: QExpr[];
19
+ } | {
20
+ k: "bin";
21
+ op: string;
22
+ l: QExpr;
23
+ r: QExpr;
24
+ } | {
25
+ k: "not";
26
+ e: QExpr;
27
+ } | {
28
+ k: "neg";
29
+ e: QExpr;
30
+ };
31
+ export type QStmt = {
32
+ src: string;
33
+ } & ({
34
+ k: "if";
35
+ branches: {
36
+ cond: QExpr;
37
+ body: QStmt[];
38
+ }[];
39
+ otherwise?: QStmt[];
40
+ } | {
41
+ k: "firsttime";
42
+ body: QStmt[];
43
+ otherwise?: QStmt[];
44
+ } | {
45
+ k: "switch";
46
+ value: QExpr;
47
+ cases: {
48
+ values: QExpr[];
49
+ body: QStmt[];
50
+ }[];
51
+ otherwise?: QStmt[];
52
+ } | {
53
+ k: "call";
54
+ fn: string;
55
+ args: QExpr[];
56
+ callback?: QStmt[];
57
+ } | {
58
+ k: "assign";
59
+ target: QExpr;
60
+ value: QExpr;
61
+ } | {
62
+ k: "raw";
63
+ });
64
+ export declare class ScriptParser {
65
+ private readonly source;
66
+ private readonly names;
67
+ private tokens;
68
+ private pos;
69
+ constructor(source: string, names: Set<string>);
70
+ static parse(source: string, names: Set<string>): QStmt[];
71
+ private peek;
72
+ private is;
73
+ private expect;
74
+ private skipNewlines;
75
+ private statements;
76
+ private block;
77
+ private statement;
78
+ private endOfStatement;
79
+ private skipRawStatement;
80
+ private sourceFrom;
81
+ private statementOrThrow;
82
+ private condition;
83
+ private arguments;
84
+ private expressionList;
85
+ expression(): QExpr;
86
+ private static readonly levels;
87
+ private binary;
88
+ private unary;
89
+ private primary;
90
+ private objectName;
91
+ private path;
92
+ }