squiffy-compiler 6.0.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 (62) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +96 -0
  3. package/dist/analyse.js +951 -0
  4. package/dist/compiler.d.ts +32 -40
  5. package/dist/compiler.js +26 -691
  6. package/dist/css-urls.d.ts +4 -0
  7. package/dist/css-urls.js +59 -0
  8. package/dist/emit.d.ts +71 -0
  9. package/dist/emit.js +192 -0
  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 +90 -0
  17. package/dist/language-service.js +883 -0
  18. package/dist/node.d.ts +23 -0
  19. package/dist/node.js +122 -0
  20. package/dist/parse.d.ts +22 -0
  21. package/dist/parse.js +316 -0
  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 +198 -0
  41. package/dist/syntax.js +8 -0
  42. package/dist/templates.d.ts +17 -0
  43. package/dist/templates.js +180 -0
  44. package/dist/text.d.ts +44 -0
  45. package/dist/text.js +348 -0
  46. package/dist/twine/audio.d.ts +21 -0
  47. package/dist/twine/audio.js +80 -0
  48. package/dist/twine/convert.d.ts +131 -0
  49. package/dist/twine/convert.js +1057 -0
  50. package/dist/twine/expression.d.ts +88 -0
  51. package/dist/twine/expression.js +318 -0
  52. package/dist/twine/harlowe.d.ts +27 -0
  53. package/dist/twine/harlowe.js +2341 -0
  54. package/dist/twine/settings.d.ts +9 -0
  55. package/dist/twine/settings.js +322 -0
  56. package/dist/twine/story.d.ts +24 -0
  57. package/dist/twine/story.js +231 -0
  58. package/dist/twine/sugarcube.d.ts +40 -0
  59. package/dist/twine/sugarcube.js +2172 -0
  60. package/dist/v5.js +2 -1
  61. package/package.json +35 -6
  62. package/syntaxes/squiffy.tmLanguage.json +1003 -0
@@ -0,0 +1,488 @@
1
+ // The squiffy.json project file, which makes a folder of .squiffy files one story:
2
+ //
3
+ // { "version": 1, "main": "story.squiffy", "exclude": ["drafts/**"] }
4
+ //
5
+ // Without it, a story is its main file plus whatever that @imports. With it, the story is every
6
+ // .squiffy, .css and .js file in the folder and its subfolders, except those `exclude` matches:
7
+ // the main file first, then the rest in path order. These are the rules the CLI, the Vite plugin,
8
+ // the language service and the editor all share. They're pure functions, so each can supply its own file list.
9
+ export const PROJECT_FILENAME = "squiffy.json";
10
+ // The newest project file format this version of Squiffy understands. It counts the file
11
+ // format, not the Squiffy release, and only goes up when the meaning of a project changes.
12
+ export const PROJECT_FILE_VERSION = 1;
13
+ // Where the project file's JSON schema is published
14
+ export const PROJECT_SCHEMA_URL = "https://squiffystory.com/schema/squiffy.json";
15
+ export const PLAYER_SETTING_TYPES = ["toggle", "list", "range"];
16
+ // The icons a panel's button can have. The runtime has the same list (PANEL_ICONS).
17
+ export const PANEL_ICONS = ["bag", "person", "map", "help", "info", "list", "book", "star", "heart"];
18
+ // The published page's text in English, which squiffy.json's "strings" can replace
19
+ export const PAGE_STRINGS = {
20
+ back: "Back",
21
+ restart: "Restart",
22
+ restartConfirm: "Are you sure you want to restart?",
23
+ switchToDark: "Switch to dark mode",
24
+ switchToLight: "Switch to light mode",
25
+ // The mute button, for a story with music or sounds
26
+ mute: "Mute",
27
+ unmute: "Unmute",
28
+ // The Saved games dialog, opened by the Save button. [name] and [time] are filled in.
29
+ saves: "Saved games",
30
+ saveName: "Name (optional)",
31
+ save: "Save",
32
+ noSaves: "No saved games yet.",
33
+ savedGame: "Saved game",
34
+ savedToday: "Today, [time]",
35
+ savedYesterday: "Yesterday, [time]",
36
+ load: "Load",
37
+ loadConfirm: "Load \"[name]\"? You'll lose anything you've done since you last saved.",
38
+ saveOptions: "Options for [name]",
39
+ overwrite: "Overwrite",
40
+ overwriteConfirm: "Overwrite \"[name]\"?",
41
+ rename: "Rename",
42
+ newName: "New name",
43
+ saveToFile: "Save to file",
44
+ loadFromFile: "Load from file",
45
+ delete: "Delete",
46
+ deleteConfirm: "Delete \"[name]\"? This can't be undone.",
47
+ cancel: "Cancel",
48
+ close: "Close",
49
+ wrongStory: "This saved game is for a different story.",
50
+ notASave: "This file isn't a saved game.",
51
+ cantSave: "The game couldn't be saved. Try Save to file instead.",
52
+ // The Settings dialog, for a story with "settings"
53
+ settings: "Settings",
54
+ resetSettings: "Reset to defaults",
55
+ };
56
+ // Parses and checks a squiffy.json. An error is a sentence to show the author as is.
57
+ export function parseProjectFile(text) {
58
+ const fail = (error) => ({ success: false, error });
59
+ let json;
60
+ try {
61
+ json = JSON.parse(text);
62
+ }
63
+ catch (e) {
64
+ return fail(`${PROJECT_FILENAME} isn't valid JSON: ${e instanceof Error ? e.message : String(e)}`);
65
+ }
66
+ if (!json || typeof json != "object" || Array.isArray(json)) {
67
+ return fail(`${PROJECT_FILENAME} should contain an object, such as { "version": 1, "main": "story.squiffy" }.`);
68
+ }
69
+ const data = json;
70
+ const version = data.version;
71
+ if (version === undefined) {
72
+ return fail(`${PROJECT_FILENAME} needs a "version", which should be ${PROJECT_FILE_VERSION}.`);
73
+ }
74
+ if (typeof version != "number" || !Number.isInteger(version) || version < 1) {
75
+ return fail(`${PROJECT_FILENAME}'s "version" should be a whole number, such as ${PROJECT_FILE_VERSION}.`);
76
+ }
77
+ if (version > PROJECT_FILE_VERSION) {
78
+ return fail(`This story's ${PROJECT_FILENAME} is version ${version}, which needs a newer version of Squiffy.`);
79
+ }
80
+ const main = data.main;
81
+ if (main === undefined) {
82
+ return fail(`${PROJECT_FILENAME} needs a "main" file, such as "main": "story.squiffy".`);
83
+ }
84
+ if (typeof main != "string" || !main.trim()) {
85
+ return fail(`${PROJECT_FILENAME}'s "main" should be the name of a .squiffy file, such as "story.squiffy".`);
86
+ }
87
+ const mainPath = normalisePath(main);
88
+ if (mainPath === null) {
89
+ return fail(`${PROJECT_FILENAME}'s "main" should be a path inside the project's folder, not "${main}".`);
90
+ }
91
+ if (!mainPath.endsWith(".squiffy")) {
92
+ return fail(`${PROJECT_FILENAME}'s "main" should be a .squiffy file, not "${main}".`);
93
+ }
94
+ const exclude = data.exclude ?? [];
95
+ if (!Array.isArray(exclude) || exclude.some(pattern => typeof pattern != "string")) {
96
+ return fail(`${PROJECT_FILENAME}'s "exclude" should be a list of file patterns, such as ["drafts/**"].`);
97
+ }
98
+ const id = data.id;
99
+ if (id !== undefined && (typeof id != "string" || !id.trim())) {
100
+ return fail(`${PROJECT_FILENAME}'s "id" should be text that identifies the story, such as "${EXAMPLE_ID}".`);
101
+ }
102
+ const backButton = data.backButton;
103
+ if (backButton !== undefined && typeof backButton != "boolean") {
104
+ return fail(`${PROJECT_FILENAME}'s "backButton" should be true or false.`);
105
+ }
106
+ const saveButton = data.saveButton;
107
+ if (saveButton !== undefined && typeof saveButton != "boolean") {
108
+ return fail(`${PROJECT_FILENAME}'s "saveButton" should be true or false.`);
109
+ }
110
+ const strings = data.strings;
111
+ if (strings !== undefined && (!isObject(strings) || Object.values(strings).some(value => typeof value != "string"))) {
112
+ return fail(`${PROJECT_FILENAME}'s "strings" should be an object of text, such as { "restart": "Recommencer" }.`);
113
+ }
114
+ const panels = parsePanels(data.panels);
115
+ if (typeof panels == "string")
116
+ return fail(panels);
117
+ const settings = parseSettings(data.settings);
118
+ if (typeof settings == "string")
119
+ return fail(settings);
120
+ const persistent = parsePersistent(data.persistent);
121
+ if (typeof persistent == "string")
122
+ return fail(persistent);
123
+ const map = parseMapPositions(data.map);
124
+ return {
125
+ success: true,
126
+ project: {
127
+ version, main: mainPath, exclude: exclude,
128
+ ...(id !== undefined ? { id: id.trim() } : {}),
129
+ ...(map ? { map } : {}),
130
+ ...(backButton !== undefined ? { backButton } : {}),
131
+ ...(saveButton !== undefined ? { saveButton } : {}),
132
+ ...(strings !== undefined ? { strings: pickPageStrings(strings) } : {}),
133
+ ...(panels !== undefined ? { panels } : {}),
134
+ ...(settings !== undefined ? { settings } : {}),
135
+ ...(persistent !== undefined ? { persistent } : {}),
136
+ },
137
+ };
138
+ }
139
+ // The page strings Squiffy knows about. Others are left out, so a story written for a newer Squiffy,
140
+ // with strings this one doesn't have, still builds.
141
+ function pickPageStrings(strings) {
142
+ return Object.fromEntries(Object.entries(strings).filter(([name]) => Object.prototype.hasOwnProperty.call(PAGE_STRINGS, name)));
143
+ }
144
+ // squiffy.json's "panels", or an error to show the author
145
+ function parsePanels(value) {
146
+ if (value === undefined)
147
+ return undefined;
148
+ const example = "{ \"passage\": \"inventory\", \"label\": \"Inventory\" }";
149
+ if (!Array.isArray(value))
150
+ return `${PROJECT_FILENAME}'s "panels" should be a list, such as [${example}].`;
151
+ const panels = [];
152
+ for (const [i, item] of value.entries()) {
153
+ const which = `${PROJECT_FILENAME}'s panel ${i + 1}`;
154
+ if (!isObject(item))
155
+ return `${which} should be an object, such as ${example}.`;
156
+ if (typeof item.passage != "string" || !item.passage.trim()) {
157
+ return `${which} needs a "passage": the name of a passage in the master section [[]].`;
158
+ }
159
+ if (typeof item.label != "string" || !item.label.trim()) {
160
+ return `${which} needs a "label", for its button, such as "Inventory".`;
161
+ }
162
+ if (item.position !== undefined && item.position !== "side" && item.position !== "button") {
163
+ return `${which}'s "position" should be "side" or "button".`;
164
+ }
165
+ if (item.icon !== undefined && !PANEL_ICONS.includes(item.icon)) {
166
+ return `${which}'s "icon" should be one of ${PANEL_ICONS.map(icon => `"${icon}"`).join(", ")}.`;
167
+ }
168
+ panels.push({
169
+ passage: item.passage.trim(),
170
+ label: item.label.trim(),
171
+ ...(item.position !== undefined ? { position: item.position } : {}),
172
+ ...(item.icon !== undefined ? { icon: item.icon } : {}),
173
+ });
174
+ }
175
+ return panels;
176
+ }
177
+ // squiffy.json's "persistent", or an error to show the author
178
+ function parsePersistent(value) {
179
+ if (value === undefined)
180
+ return undefined;
181
+ const example = "[\"endings\", \"found_pebbles\"]";
182
+ if (!Array.isArray(value))
183
+ return `${PROJECT_FILENAME}'s "persistent" should be a list of attribute names, such as ${example}.`;
184
+ const names = [];
185
+ for (const item of value) {
186
+ const name = typeof item == "string" ? item.trim() : "";
187
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name)) {
188
+ return `${PROJECT_FILENAME}'s "persistent" should be a list of attribute names, of letters, digits and underscores, such as ${example}.`;
189
+ }
190
+ if (name == "settings")
191
+ return `${PROJECT_FILENAME}'s "persistent" can't have "settings", which is the player's settings.`;
192
+ if (!names.includes(name))
193
+ names.push(name);
194
+ }
195
+ return names;
196
+ }
197
+ // squiffy.json's "settings", or an error to show the author
198
+ function parseSettings(value) {
199
+ if (value === undefined)
200
+ return undefined;
201
+ const example = "{ \"name\": \"warnings\", \"type\": \"toggle\", \"label\": \"Content warnings\" }";
202
+ if (!Array.isArray(value))
203
+ return `${PROJECT_FILENAME}'s "settings" should be a list, such as [${example}].`;
204
+ const settings = [];
205
+ const names = new Set();
206
+ for (const [i, item] of value.entries()) {
207
+ const which = `${PROJECT_FILENAME}'s setting ${i + 1}`;
208
+ if (!isObject(item))
209
+ return `${which} should be an object, such as ${example}.`;
210
+ const name = typeof item.name == "string" ? item.name.trim() : "";
211
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
212
+ return `${which} needs a "name" of letters, digits and underscores, such as "warnings", which the story reads as settings.warnings.`;
213
+ }
214
+ if (names.has(name))
215
+ return `${PROJECT_FILENAME} has more than one setting called "${name}".`;
216
+ names.add(name);
217
+ const label = typeof item.label == "string" && item.label.trim() ? item.label.trim() : name;
218
+ if (item.description !== undefined && typeof item.description != "string") {
219
+ return `${which}'s "description" should be text.`;
220
+ }
221
+ const base = {
222
+ name, label,
223
+ ...(typeof item.description == "string" && item.description.trim() ? { description: item.description.trim() } : {}),
224
+ };
225
+ const type = item.type ?? "toggle";
226
+ if (type == "toggle") {
227
+ if (item.default !== undefined && typeof item.default != "boolean") {
228
+ return `${which}'s "default" should be true or false.`;
229
+ }
230
+ settings.push({ ...base, type: "toggle", ...(item.default !== undefined ? { default: item.default } : {}) });
231
+ }
232
+ else if (type == "list") {
233
+ const options = Array.isArray(item.options) ? item.options.map(parseSettingOption) : null;
234
+ if (!options || !options.length || options.some(option => !option)) {
235
+ return `${which} needs "options" for the player to choose from, such as ["Small", "Medium", "Large"], or objects with a "value" and a "label".`;
236
+ }
237
+ const values = options.map(option => option.value);
238
+ if (new Set(values).size != values.length)
239
+ return `${which} has the same option more than once.`;
240
+ if (item.default !== undefined && !values.includes(item.default)) {
241
+ return `${which}'s "default" should be one of its options' values.`;
242
+ }
243
+ settings.push({
244
+ ...base, type: "list", options: options,
245
+ ...(item.default !== undefined ? { default: item.default } : {}),
246
+ });
247
+ }
248
+ else if (type == "range") {
249
+ const isNumber = (n) => typeof n == "number" && Number.isFinite(n);
250
+ if (!isNumber(item.min) || !isNumber(item.max) || item.min > item.max) {
251
+ return `${which} needs a "min" and a "max", such as "min": 1, "max": 5.`;
252
+ }
253
+ if (item.step !== undefined && (!isNumber(item.step) || item.step <= 0)) {
254
+ return `${which}'s "step" should be a number above 0.`;
255
+ }
256
+ if (item.default !== undefined && (!isNumber(item.default) || item.default < item.min || item.default > item.max)) {
257
+ return `${which}'s "default" should be a number from its "min" to its "max".`;
258
+ }
259
+ settings.push({
260
+ ...base, type: "range", min: item.min, max: item.max,
261
+ ...(item.step !== undefined ? { step: item.step } : {}),
262
+ ...(item.default !== undefined ? { default: item.default } : {}),
263
+ });
264
+ }
265
+ else {
266
+ return `${which}'s "type" should be ${PLAYER_SETTING_TYPES.map(t => `"${t}"`).join(", ")}.`;
267
+ }
268
+ }
269
+ return settings;
270
+ }
271
+ // A list setting's option: text, which is both its value and its label, or { value, label }
272
+ function parseSettingOption(option) {
273
+ if (typeof option == "string" && option.trim())
274
+ return { value: option.trim(), label: option.trim() };
275
+ if (typeof option == "number" || typeof option == "boolean")
276
+ return { value: String(option), label: String(option) };
277
+ if (!isObject(option) || typeof option.value != "string" || !option.value.trim())
278
+ return null;
279
+ const label = typeof option.label == "string" && option.label.trim() ? option.label.trim() : option.value.trim();
280
+ return { value: option.value.trim(), label };
281
+ }
282
+ const EXAMPLE_ID = "0b7c6d9e-3f1a-4e2b-9c5d-8a7f6e5d4c3b";
283
+ const isPosition = (value) => Array.isArray(value) && value.length == 2 && value.every(n => typeof n == "number" && Number.isFinite(n));
284
+ const isObject = (value) => !!value && typeof value == "object" && !Array.isArray(value);
285
+ // The story map's positions. Only the editor uses them, so anything that isn't a position is
286
+ // left out rather than stopping the story from building.
287
+ function parseMapPositions(value) {
288
+ if (!isObject(value))
289
+ return undefined;
290
+ const sections = {};
291
+ const passages = {};
292
+ if (isObject(value.sections)) {
293
+ for (const [name, position] of Object.entries(value.sections)) {
294
+ if (isPosition(position))
295
+ sections[name] = position;
296
+ }
297
+ }
298
+ if (isObject(value.passages)) {
299
+ for (const [section, byName] of Object.entries(value.passages)) {
300
+ if (!isObject(byName))
301
+ continue;
302
+ for (const [name, position] of Object.entries(byName)) {
303
+ if (isPosition(position))
304
+ (passages[section] ?? (passages[section] = {}))[name] = position;
305
+ }
306
+ }
307
+ }
308
+ return { sections, passages };
309
+ }
310
+ // A project path with "/" separators and no "." segments, or null if it goes outside the folder
311
+ // or is absolute.
312
+ function normalisePath(path) {
313
+ const slashes = path.replace(/\\/g, "/");
314
+ if (slashes.startsWith("/") || /^[a-zA-Z]:/.test(slashes))
315
+ return null;
316
+ const parts = [];
317
+ for (const part of slashes.split("/")) {
318
+ if (part == "" || part == ".")
319
+ continue;
320
+ if (part == "..")
321
+ return null;
322
+ parts.push(part);
323
+ }
324
+ return parts.length ? parts.join("/") : null;
325
+ }
326
+ // "*" and "?" match within one path segment; "**" matches across segments.
327
+ export function globToRegExp(pattern) {
328
+ let out = "";
329
+ for (let i = 0; i < pattern.length; i++) {
330
+ const c = pattern[i];
331
+ if (c == "*") {
332
+ if (pattern[i + 1] == "*") {
333
+ i++;
334
+ if (pattern[i + 1] == "/") {
335
+ i++;
336
+ out += "(?:.*/)?";
337
+ }
338
+ else {
339
+ out += ".*";
340
+ }
341
+ }
342
+ else {
343
+ out += "[^/]*";
344
+ }
345
+ }
346
+ else if (c == "?") {
347
+ out += "[^/]";
348
+ }
349
+ else {
350
+ out += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
351
+ }
352
+ }
353
+ return new RegExp(`^${out}$`);
354
+ }
355
+ // Whether `exclude` leaves a file out of the story: a pattern matches it or one of its folders.
356
+ export function isExcluded(path, exclude) {
357
+ const parts = path.split("/");
358
+ return exclude.some(pattern => {
359
+ const normalised = normalisePath(pattern.trim());
360
+ if (normalised === null)
361
+ return false;
362
+ const regex = globToRegExp(normalised);
363
+ for (let i = 1; i <= parts.length; i++) {
364
+ if (regex.test(parts.slice(0, i).join("/")))
365
+ return true;
366
+ }
367
+ return false;
368
+ });
369
+ }
370
+ // Folders whose files are never part of a story, whatever `exclude` says: node_modules, and
371
+ // folders whose names start with "." (.git, .vscode and the like).
372
+ export function isAlwaysSkipped(path) {
373
+ const folders = path.split("/").slice(0, -1);
374
+ return folders.some(folder => folder == "node_modules" || folder.startsWith("."));
375
+ }
376
+ // The folder, next to squiffy.json, that the CLI builds a project's published files into. Its
377
+ // files are never part of the story.
378
+ export const BUILD_FOLDER = "build";
379
+ // The files that Squiffy 6, and Squiffy 7 without a squiffy.json, write next to the main file
380
+ // when publishing a story, with its index.html. With an index.html beside them, they're taken to
381
+ // be an old build, and aren't part of the story unless it @imports them.
382
+ const OLD_BUILD_FILES = ["story.js", "style.css", "squiffy.runtime.js", "squiffy.runtime.global.js"];
383
+ // The kinds of file that are part of a story
384
+ export const isSquiffyPath = (path) => path.endsWith(".squiffy");
385
+ export const isStylesheetPath = (path) => path.endsWith(".css");
386
+ export const isScriptPath = (path) => path.endsWith(".js");
387
+ export const isStoryFilePath = (path) => isSquiffyPath(path) || isStylesheetPath(path) || isScriptPath(path);
388
+ // Sorts paths by code point, so the order is the same everywhere, whatever the locale.
389
+ export const comparePaths = (a, b) => a < b ? -1 : a > b ? 1 : 0;
390
+ // Which of a project's files make up the story: its .squiffy files, stylesheets and scripts.
391
+ // `paths` are relative to the project file's folder, with "/" separators, as from a recursive
392
+ // listing of the folder; files of other kinds are ignored. Pass `skip` to leave out more files
393
+ // or folders, such as a build's output folder.
394
+ export function getStoryFiles(project, paths, skip = []) {
395
+ const included = [];
396
+ const stylesheets = [];
397
+ const scripts = [];
398
+ const excluded = [];
399
+ const all = new Set(paths);
400
+ const skipped = [BUILD_FOLDER, ...skip].map(folder => normalisePath(folder)).filter(folder => folder !== null);
401
+ const mainSlash = project.main.lastIndexOf("/");
402
+ const mainFolder = mainSlash < 0 ? "" : project.main.substring(0, mainSlash + 1);
403
+ const oldBuild = all.has(mainFolder + "index.html") ? new Set(OLD_BUILD_FILES.map(file => mainFolder + file)) : new Set();
404
+ for (const path of all) {
405
+ if (!isStoryFilePath(path) || path == project.main || isAlwaysSkipped(path) || oldBuild.has(path))
406
+ continue;
407
+ if (skipped.some(folder => path == folder || path.startsWith(folder + "/")))
408
+ continue;
409
+ if (isExcluded(path, project.exclude))
410
+ excluded.push(path);
411
+ else if (isSquiffyPath(path))
412
+ included.push(path);
413
+ else if (isStylesheetPath(path))
414
+ stylesheets.push(path);
415
+ else
416
+ scripts.push(path);
417
+ }
418
+ return {
419
+ main: project.main,
420
+ included: included.sort(comparePaths),
421
+ stylesheets: stylesheets.sort(comparePaths),
422
+ scripts: scripts.sort(comparePaths),
423
+ excluded: excluded.sort(comparePaths),
424
+ };
425
+ }
426
+ // The story's files after the main file, in the order the compiler takes them (see
427
+ // AnalyseSettings.storyFiles): its .squiffy files, then its stylesheets, then its scripts.
428
+ export const storyFileList = (story) => [...story.included, ...story.stylesheets, ...story.scripts];
429
+ // The text of a new project file. It's given a new random id, unless one is passed in.
430
+ export function formatProjectFile(project) {
431
+ const json = {
432
+ $schema: PROJECT_SCHEMA_URL,
433
+ version: PROJECT_FILE_VERSION,
434
+ id: project.id ?? crypto.randomUUID(),
435
+ main: project.main,
436
+ };
437
+ if (project.exclude?.length)
438
+ json.exclude = project.exclude;
439
+ if (project.panels?.length)
440
+ json.panels = project.panels;
441
+ if (project.settings?.length)
442
+ json.settings = project.settings;
443
+ if (project.persistent?.length)
444
+ json.persistent = project.persistent;
445
+ const text = JSON.stringify(json, null, 2) + "\n";
446
+ return project.map ? updateProjectFile(text, { map: project.map }) : text;
447
+ }
448
+ // Changes a project file's text, keeping any other properties it has. Returns undefined if the
449
+ // text isn't a JSON object. A `map` with no positions removes it.
450
+ export function updateProjectFile(text, changes) {
451
+ let json;
452
+ try {
453
+ json = JSON.parse(text);
454
+ }
455
+ catch {
456
+ return undefined;
457
+ }
458
+ if (!json || typeof json != "object" || Array.isArray(json))
459
+ return undefined;
460
+ const data = { ...json };
461
+ if (changes.main !== undefined)
462
+ data.main = changes.main;
463
+ if (changes.exclude !== undefined) {
464
+ if (changes.exclude.length)
465
+ data.exclude = changes.exclude;
466
+ else
467
+ delete data.exclude;
468
+ }
469
+ if (changes.map !== undefined) {
470
+ const { sections, passages } = changes.map;
471
+ const used = Object.fromEntries(Object.entries(passages).filter(([, byName]) => Object.keys(byName).length));
472
+ // Anything else that's in "map" stays, but empty lists of positions don't
473
+ const map = { ...(isObject(data.map) ? data.map : {}) };
474
+ delete map.sections;
475
+ delete map.passages;
476
+ if (Object.keys(sections).length)
477
+ map.sections = sections;
478
+ if (Object.keys(used).length)
479
+ map.passages = used;
480
+ if (Object.keys(map).length)
481
+ data.map = map;
482
+ else
483
+ delete data.map;
484
+ }
485
+ const indent = /^\{\s*\n([ \t]+)/.exec(text)?.[1] ?? 2;
486
+ // Each position on one line, rather than an x and a y on lines of their own
487
+ return JSON.stringify(data, null, indent).replace(/\[\s+(-?[\d.e+-]+),\s+(-?[\d.e+-]+)\s+\]/g, "[$1, $2]") + "\n";
488
+ }
@@ -0,0 +1,51 @@
1
+ export declare class QuestParseError extends Error {
2
+ }
3
+ export interface XmlElement {
4
+ name: string;
5
+ attrs: Record<string, string>;
6
+ children: XmlElement[];
7
+ text: string;
8
+ }
9
+ export declare function parseXml(source: string): XmlElement;
10
+ export type QuestValue = {
11
+ type: "string";
12
+ value: string;
13
+ } | {
14
+ type: "boolean";
15
+ value: boolean;
16
+ } | {
17
+ type: "number";
18
+ value: number;
19
+ } | {
20
+ type: "script";
21
+ value: string;
22
+ } | {
23
+ type: "stringdictionary";
24
+ value: [string, string][];
25
+ } | {
26
+ type: "stringlist";
27
+ value: string[];
28
+ } | {
29
+ type: "other";
30
+ typeName: string;
31
+ value: string;
32
+ };
33
+ export declare function readValue(element: XmlElement): QuestValue;
34
+ export interface QuestObject {
35
+ name: string;
36
+ inherits: string[];
37
+ attributes: Map<string, QuestValue>;
38
+ children: QuestObject[];
39
+ }
40
+ export interface QuestGame {
41
+ aslVersion: string;
42
+ gamebook: boolean;
43
+ game: QuestObject;
44
+ gameDefaults: Map<string, QuestValue>;
45
+ pages: QuestObject[];
46
+ start?: string;
47
+ player?: QuestObject;
48
+ javascript: string[];
49
+ }
50
+ export declare function parseQuestGame(source: string): QuestGame;
51
+ export declare function isQuestSource(source: string): boolean;