@rohal12/twee-ts 1.1.1

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,2212 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ CONFIG_FILENAME: () => CONFIG_FILENAME,
24
+ TweeLexer: () => TweeLexer,
25
+ TweeTsError: () => TweeTsError,
26
+ applyTagAliases: () => applyTagAliases,
27
+ compile: () => compile,
28
+ compileToFile: () => compileToFile,
29
+ discoverCachedFormats: () => discoverCachedFormats,
30
+ discoverFormats: () => discoverFormats,
31
+ fetchAndCacheFormat: () => fetchAndCacheFormat,
32
+ fetchDirectFormat: () => fetchDirectFormat,
33
+ generateIFID: () => generateIFID,
34
+ getCacheDir: () => getCacheDir,
35
+ getFormatSearchDirs: () => getFormatSearchDirs,
36
+ loadConfig: () => loadConfig,
37
+ loadConfigFile: () => loadConfigFile,
38
+ parseFormatJSON: () => parseFormatJSON,
39
+ parseSemver: () => parseSemver,
40
+ parseTwee: () => parseTwee,
41
+ resolveRemoteFormat: () => resolveRemoteFormat,
42
+ scaffoldConfig: () => scaffoldConfig,
43
+ semverCompare: () => semverCompare,
44
+ storyInspect: () => storyInspect,
45
+ tweeLexer: () => tweeLexer,
46
+ validateConfig: () => validateConfig,
47
+ validateIFID: () => validateIFID,
48
+ watch: () => watch
49
+ });
50
+ module.exports = __toCommonJS(src_exports);
51
+
52
+ // src/compiler.ts
53
+ var import_node_fs7 = require("fs");
54
+
55
+ // src/ifid.ts
56
+ var import_node_crypto = require("crypto");
57
+ function generateIFID() {
58
+ return (0, import_node_crypto.randomUUID)().toUpperCase();
59
+ }
60
+ function validateIFID(ifid) {
61
+ let uuid = ifid;
62
+ switch (ifid.length) {
63
+ case 36:
64
+ break;
65
+ case 45: {
66
+ if (ifid.slice(0, 7).toUpperCase() !== "UUID://" || ifid.slice(43) !== "//") {
67
+ return "invalid IFID UUID://...// format";
68
+ }
69
+ uuid = ifid.slice(7, 43);
70
+ break;
71
+ }
72
+ default:
73
+ return `invalid IFID length: ${ifid.length}`;
74
+ }
75
+ for (let i = 0; i < uuid.length; i++) {
76
+ const ch = uuid[i];
77
+ switch (i) {
78
+ case 8:
79
+ case 13:
80
+ case 18:
81
+ case 23:
82
+ if (ch !== "-") {
83
+ return `invalid IFID character '${ch}' at position ${i + 1}`;
84
+ }
85
+ break;
86
+ case 14:
87
+ if (ch < "1" || ch > "5") {
88
+ return `invalid version '${ch}' at position ${i + 1}`;
89
+ }
90
+ break;
91
+ case 19:
92
+ if (!["8", "9", "a", "A", "b", "B"].includes(ch)) {
93
+ return `invalid variant '${ch}' at position ${i + 1}`;
94
+ }
95
+ break;
96
+ default:
97
+ if (!/^[0-9a-fA-F]$/.test(ch)) {
98
+ return `invalid IFID hex value '${ch}' at position ${i + 1}`;
99
+ }
100
+ break;
101
+ }
102
+ }
103
+ return null;
104
+ }
105
+
106
+ // src/escape.ts
107
+ function attrEscape(s) {
108
+ if (s.length === 0) return s;
109
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
110
+ }
111
+ function htmlEscape(s) {
112
+ if (s.length === 0) return s;
113
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
114
+ }
115
+ function tiddlerEscape(s) {
116
+ if (s.length === 0) return s;
117
+ return s.replace(/\\/g, "\\s").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/\t/g, "\\t").replace(/\n/g, "\\n");
118
+ }
119
+ function tweeEscape(s) {
120
+ if (s.length === 0) return s;
121
+ return s.replace(/[\\[\]{}]/g, (ch) => "\\" + ch);
122
+ }
123
+ function tweeUnescape(s) {
124
+ if (s.length === 0) return s;
125
+ let result = "";
126
+ for (let i = 0; i < s.length; i++) {
127
+ if (s[i] === "\\") {
128
+ i++;
129
+ if (i >= s.length) break;
130
+ }
131
+ result += s[i];
132
+ }
133
+ return result;
134
+ }
135
+
136
+ // src/passage.ts
137
+ var INFO_PASSAGE_NAMES = /* @__PURE__ */ new Set([
138
+ "StoryAuthor",
139
+ "StoryInit",
140
+ "StoryMenu",
141
+ "StorySubtitle",
142
+ "StoryTitle",
143
+ "PassageReady",
144
+ "PassageDone",
145
+ "PassageHeader",
146
+ "PassageFooter",
147
+ "StoryBanner",
148
+ "StoryCaption",
149
+ "MenuOptions",
150
+ "MenuShare",
151
+ "MenuStory",
152
+ "StoryInterface",
153
+ "StoryShare",
154
+ "StorySettings",
155
+ "StoryData",
156
+ "StoryIncludes"
157
+ ]);
158
+ var INFO_TAGS = ["annotation", "script", "stylesheet", "widget"];
159
+ function hasTag(p, tag) {
160
+ return p.tags.includes(tag);
161
+ }
162
+ function hasAnyTag(p, ...tags) {
163
+ return p.tags.some((t) => tags.includes(t));
164
+ }
165
+ function hasTagStartingWith(p, prefix) {
166
+ return p.tags.some((t) => t.startsWith(prefix));
167
+ }
168
+ function hasInfoTags(p) {
169
+ return hasAnyTag(p, ...INFO_TAGS) || hasTagStartingWith(p, "Twine.");
170
+ }
171
+ function hasInfoName(p) {
172
+ return INFO_PASSAGE_NAMES.has(p.name);
173
+ }
174
+ function isInfoPassage(p) {
175
+ return hasInfoName(p) || hasInfoTags(p);
176
+ }
177
+ function isStoryPassage(p) {
178
+ return !hasInfoName(p) && !hasInfoTags(p);
179
+ }
180
+ function hasMetadataPosition(p) {
181
+ return p.metadata != null && p.metadata.position != null && p.metadata.position !== "";
182
+ }
183
+ function hasMetadataSize(p) {
184
+ return p.metadata != null && p.metadata.size != null && p.metadata.size !== "";
185
+ }
186
+ function hasAnyMetadata(p) {
187
+ return hasMetadataPosition(p) || hasMetadataSize(p);
188
+ }
189
+ function marshalMetadata(meta) {
190
+ const obj = {};
191
+ if (meta.position) obj.position = meta.position;
192
+ if (meta.size) obj.size = meta.size;
193
+ return JSON.stringify(obj);
194
+ }
195
+ function passageToTwee(p, outMode) {
196
+ let output;
197
+ if (outMode === "twee3") {
198
+ output = ":: " + tweeEscape(p.name);
199
+ if (p.tags.length > 0) {
200
+ output += " [" + tweeEscape(p.tags.join(" ")) + "]";
201
+ }
202
+ if (hasAnyMetadata(p) && p.metadata) {
203
+ output += " " + marshalMetadata(p.metadata);
204
+ }
205
+ } else {
206
+ output = ":: " + p.name;
207
+ if (p.tags.length > 0) {
208
+ output += " [" + p.tags.join(" ") + "]";
209
+ }
210
+ }
211
+ output += "\n";
212
+ if (p.text.length > 0) {
213
+ output += p.text + "\n";
214
+ }
215
+ output += "\n\n";
216
+ return output;
217
+ }
218
+ function passageToPassagedata(p, pid) {
219
+ let position;
220
+ let size;
221
+ if (hasMetadataPosition(p)) {
222
+ position = p.metadata.position;
223
+ } else {
224
+ const x = pid % 10;
225
+ let y = Math.floor(pid / 10);
226
+ const xp = x === 0 ? 10 : x;
227
+ const yp = x === 0 ? y : y + 1;
228
+ position = `${xp * 125 - 25},${yp * 125 - 25}`;
229
+ }
230
+ if (hasMetadataSize(p)) {
231
+ size = p.metadata.size;
232
+ } else {
233
+ size = "100,100";
234
+ }
235
+ return `<tw-passagedata pid="${pid}" name=${quote(attrEscape(p.name))} tags=${quote(attrEscape(p.tags.join(" ")))} position=${quote(attrEscape(position))} size=${quote(attrEscape(size))}>${htmlEscape(p.text)}</tw-passagedata>`;
236
+ }
237
+ function passageToTiddler(p, pid) {
238
+ let position;
239
+ if (hasMetadataPosition(p)) {
240
+ position = p.metadata.position;
241
+ } else {
242
+ const x = pid % 10;
243
+ let y = Math.floor(pid / 10);
244
+ const xp = x === 0 ? 10 : x;
245
+ const yp = x === 0 ? y : y + 1;
246
+ position = `${xp * 140 - 130},${yp * 140 - 130}`;
247
+ }
248
+ return `<div tiddler=${quote(attrEscape(p.name))} tags=${quote(attrEscape(p.tags.join(" ")))} twine-position=${quote(attrEscape(position))}>${tiddlerEscape(p.text)}</div>`;
249
+ }
250
+ function countWords(p) {
251
+ let text = p.text;
252
+ text = text.replace(/\n/g, "");
253
+ text = text.replace(/(?:\/%.+?%\/|\/\*.+?\*\/|<!--.+?-->)/gs, "");
254
+ const normalized = text.normalize("NFKD");
255
+ const count = [...normalized].length;
256
+ if (count === 0) return 0;
257
+ const words = Math.floor(count / 5);
258
+ return count % 5 > 0 ? words + 1 : words;
259
+ }
260
+ function applyTagAliases(passages, aliases) {
261
+ const entries = Object.entries(aliases);
262
+ if (entries.length === 0) return;
263
+ for (const p of passages) {
264
+ const original = [...p.tags];
265
+ for (const [alias, canonical] of entries) {
266
+ if (original.includes(alias) && !p.tags.includes(canonical)) {
267
+ p.tags.push(canonical);
268
+ }
269
+ }
270
+ }
271
+ }
272
+ function quote(s) {
273
+ return `"${s}"`;
274
+ }
275
+
276
+ // src/story.ts
277
+ function createStory() {
278
+ return {
279
+ name: "",
280
+ ifid: "",
281
+ passages: [],
282
+ legacyIFID: "",
283
+ twine1: { settings: /* @__PURE__ */ new Map() },
284
+ twine2: {
285
+ format: "",
286
+ formatVersion: "",
287
+ options: /* @__PURE__ */ new Map(),
288
+ start: "",
289
+ tagColors: /* @__PURE__ */ new Map(),
290
+ zoom: 1
291
+ }
292
+ };
293
+ }
294
+ function storyHas(story, name) {
295
+ return story.passages.some((p) => p.name === name);
296
+ }
297
+ function storyIndex(story, name) {
298
+ return story.passages.findIndex((p) => p.name === name);
299
+ }
300
+ function storyAppend(story, p, diagnostics) {
301
+ const i = storyIndex(story, p.name);
302
+ if (i === -1) {
303
+ story.passages.push(p);
304
+ } else {
305
+ diagnostics.push({
306
+ level: "warning",
307
+ message: `Replacing existing passage "${p.name}" with duplicate.`
308
+ });
309
+ story.passages[i] = p;
310
+ }
311
+ }
312
+ function storyPrepend(story, p, diagnostics) {
313
+ const i = storyIndex(story, p.name);
314
+ if (i === -1) {
315
+ story.passages.unshift(p);
316
+ } else {
317
+ diagnostics.push({
318
+ level: "warning",
319
+ message: `Replacing existing passage "${p.name}" with duplicate.`
320
+ });
321
+ story.passages[i] = p;
322
+ }
323
+ }
324
+ function marshalStoryData(story) {
325
+ const data = {};
326
+ if (story.ifid) data.ifid = story.ifid;
327
+ if (story.twine2.format) data.format = story.twine2.format;
328
+ if (story.twine2.formatVersion) data["format-version"] = story.twine2.formatVersion;
329
+ const options = [];
330
+ for (const [opt, val] of story.twine2.options) {
331
+ if (val) options.push(opt);
332
+ }
333
+ if (options.length > 0) data.options = options;
334
+ if (story.twine2.start) data.start = story.twine2.start;
335
+ if (story.twine2.tagColors.size > 0) {
336
+ data["tag-colors"] = Object.fromEntries(story.twine2.tagColors);
337
+ }
338
+ if (story.twine2.zoom !== 1) data.zoom = story.twine2.zoom;
339
+ return JSON.stringify(data, null, " ");
340
+ }
341
+ function unmarshalStoryData(story, json) {
342
+ let data;
343
+ try {
344
+ data = JSON.parse(json);
345
+ } catch (e) {
346
+ return `Cannot unmarshal "StoryData"; ${e instanceof Error ? e.message : String(e)}`;
347
+ }
348
+ if (data.ifid) story.ifid = data.ifid.toUpperCase();
349
+ if (data.format) story.twine2.format = data.format;
350
+ if (data["format-version"]) story.twine2.formatVersion = data["format-version"];
351
+ if (data.options) {
352
+ for (const opt of data.options) {
353
+ story.twine2.options.set(opt, true);
354
+ }
355
+ }
356
+ if (data.start) story.twine2.start = data.start;
357
+ if (data["tag-colors"]) {
358
+ for (const [tag, color] of Object.entries(data["tag-colors"])) {
359
+ story.twine2.tagColors.set(tag, color);
360
+ }
361
+ }
362
+ if (data.zoom != null && data.zoom !== 0) story.twine2.zoom = data.zoom;
363
+ return null;
364
+ }
365
+ function unmarshalStorySettings(story, text, diagnostics) {
366
+ const obsolete = [];
367
+ for (const rawLine of text.split("\n")) {
368
+ const line = rawLine.trim();
369
+ if (line.length === 0) continue;
370
+ const colonIdx = line.indexOf(":");
371
+ if (colonIdx === -1) {
372
+ diagnostics.push({
373
+ level: "warning",
374
+ message: `Malformed "StorySettings" entry; skipping "${line}".`
375
+ });
376
+ continue;
377
+ }
378
+ const key = line.slice(0, colonIdx).trim().toLowerCase();
379
+ const val = line.slice(colonIdx + 1).trim().toLowerCase();
380
+ switch (key) {
381
+ case "ifid": {
382
+ const err = validateIFID(val);
383
+ if (err === null) {
384
+ story.legacyIFID = val.toUpperCase();
385
+ }
386
+ obsolete.push('"ifid"');
387
+ continue;
388
+ }
389
+ case "zoom":
390
+ obsolete.push('"zoom"');
391
+ continue;
392
+ }
393
+ story.twine1.settings.set(key, val);
394
+ }
395
+ if (obsolete.length > 0) {
396
+ const entries = obsolete.length === 1 ? "entry" : "entries";
397
+ const pronoun = obsolete.length === 1 ? "it" : "them";
398
+ diagnostics.push({
399
+ level: "warning",
400
+ message: `Detected obsolete "StorySettings" ${entries}: ${obsolete.join(", ")}. Please remove ${pronoun} from the "StorySettings" special passage.`
401
+ });
402
+ }
403
+ }
404
+ function storyAdd(story, p, diagnostics) {
405
+ switch (p.name) {
406
+ case "StoryIncludes":
407
+ diagnostics.push({
408
+ level: "warning",
409
+ message: 'Ignoring "StoryIncludes" compiler special passage; twee-ts allows you to specify project files and/or directories to recursively search.'
410
+ });
411
+ break;
412
+ case "StoryData": {
413
+ const err = unmarshalStoryData(story, p.text);
414
+ if (err === null) {
415
+ if (story.ifid.length > 0) {
416
+ const vErr = validateIFID(story.ifid);
417
+ if (vErr !== null) {
418
+ diagnostics.push({
419
+ level: "error",
420
+ message: `Cannot validate IFID; ${vErr}.`
421
+ });
422
+ }
423
+ }
424
+ p.text = marshalStoryData(story);
425
+ } else {
426
+ diagnostics.push({
427
+ level: "error",
428
+ message: `Cannot unmarshal "StoryData" compiler special passage; ${err}.`
429
+ });
430
+ }
431
+ break;
432
+ }
433
+ case "StorySettings":
434
+ unmarshalStorySettings(story, p.text, diagnostics);
435
+ break;
436
+ case "StoryTitle":
437
+ p.text = p.text.trim();
438
+ story.name = p.text;
439
+ break;
440
+ }
441
+ storyAppend(story, p, diagnostics);
442
+ }
443
+ function getStoryStats(story) {
444
+ let storyPassages = 0;
445
+ let words = 0;
446
+ for (const p of story.passages) {
447
+ if (isStoryPassage(p)) {
448
+ storyPassages++;
449
+ words += countWords(p);
450
+ }
451
+ }
452
+ return { passages: story.passages.length, storyPassages, words };
453
+ }
454
+
455
+ // src/filesystem.ts
456
+ var import_node_fs = require("fs");
457
+ var import_node_path2 = require("path");
458
+
459
+ // src/media-types.ts
460
+ var import_node_path = require("path");
461
+ var MEDIA_TYPE_MAP = {
462
+ // Audio
463
+ aac: "audio/aac",
464
+ flac: "audio/flac",
465
+ ogg: "audio/ogg",
466
+ wav: "audio/wav",
467
+ mp3: "audio/mpeg",
468
+ m4a: "audio/mp4",
469
+ oga: "audio/ogg",
470
+ opus: "audio/ogg",
471
+ wave: "audio/wav",
472
+ weba: "audio/webm",
473
+ // Fonts
474
+ otf: "font/otf",
475
+ ttf: "font/ttf",
476
+ woff: "font/woff",
477
+ woff2: "font/woff2",
478
+ // Images
479
+ gif: "image/gif",
480
+ jpeg: "image/jpeg",
481
+ jpg: "image/jpeg",
482
+ png: "image/png",
483
+ svg: "image/svg+xml",
484
+ tif: "image/tiff",
485
+ tiff: "image/tiff",
486
+ webp: "image/webp",
487
+ // Metadata
488
+ vtt: "text/vtt",
489
+ // Video
490
+ mp4: "video/mp4",
491
+ ogv: "video/ogg",
492
+ webm: "video/webm"
493
+ };
494
+ function mediaTypeFromExt(ext) {
495
+ return MEDIA_TYPE_MAP[ext] ?? "";
496
+ }
497
+ function mediaTypeFromFilename(filename) {
498
+ return mediaTypeFromExt(normalizedFileExt(filename));
499
+ }
500
+ function normalizedFileExt(filename) {
501
+ const ext = (0, import_node_path.extname)(filename);
502
+ if (!ext) return "";
503
+ return ext.slice(1).toLowerCase();
504
+ }
505
+ function slugify(original) {
506
+ return original.replace(/[\x00-\x20!-/:-@[-^`{-\x9f]+/g, "_");
507
+ }
508
+ function isKnownFileType(filename) {
509
+ const ext = normalizedFileExt(filename);
510
+ return KNOWN_EXTENSIONS.has(ext);
511
+ }
512
+ var KNOWN_EXTENSIONS = /* @__PURE__ */ new Set([
513
+ "tw",
514
+ "twee",
515
+ "tw2",
516
+ "twee2",
517
+ "htm",
518
+ "html",
519
+ "css",
520
+ "js",
521
+ "otf",
522
+ "ttf",
523
+ "woff",
524
+ "woff2",
525
+ "gif",
526
+ "jpeg",
527
+ "jpg",
528
+ "png",
529
+ "svg",
530
+ "tif",
531
+ "tiff",
532
+ "webp",
533
+ "aac",
534
+ "flac",
535
+ "m4a",
536
+ "mp3",
537
+ "oga",
538
+ "ogg",
539
+ "opus",
540
+ "wav",
541
+ "wave",
542
+ "weba",
543
+ "mp4",
544
+ "ogv",
545
+ "webm",
546
+ "vtt"
547
+ ]);
548
+ function fontFormatHint(ext) {
549
+ switch (ext) {
550
+ case "ttf":
551
+ return "truetype";
552
+ case "otf":
553
+ return "opentype";
554
+ default:
555
+ return ext;
556
+ }
557
+ }
558
+
559
+ // src/filesystem.ts
560
+ function getFilenames(pathnames, outFilename) {
561
+ const filenames = [];
562
+ const absOutFile = outFilename ? (0, import_node_path2.resolve)(outFilename) : "";
563
+ function walk(pathname) {
564
+ let stat;
565
+ try {
566
+ stat = (0, import_node_fs.statSync)(pathname);
567
+ } catch {
568
+ return;
569
+ }
570
+ if (stat.isFile()) {
571
+ const abs = (0, import_node_path2.resolve)(pathname);
572
+ if (abs === absOutFile) return;
573
+ const rel = (0, import_node_path2.relative)(process.cwd(), abs);
574
+ filenames.push(rel || abs);
575
+ } else if (stat.isDirectory()) {
576
+ let entries;
577
+ try {
578
+ entries = (0, import_node_fs.readdirSync)(pathname);
579
+ } catch {
580
+ return;
581
+ }
582
+ for (const entry of entries) {
583
+ walk((0, import_node_path2.join)(pathname, entry));
584
+ }
585
+ }
586
+ }
587
+ for (const pathname of pathnames) {
588
+ walk(pathname);
589
+ }
590
+ return filenames;
591
+ }
592
+ function watchFilesystem(pathnames, outFilename, callback) {
593
+ const absOutFile = (0, import_node_path2.resolve)(outFilename);
594
+ const watchers = [];
595
+ let buildTimer = null;
596
+ const BUILD_DEBOUNCE = 500;
597
+ function scheduleBuild() {
598
+ if (buildTimer) clearTimeout(buildTimer);
599
+ buildTimer = setTimeout(() => {
600
+ buildTimer = null;
601
+ callback();
602
+ }, BUILD_DEBOUNCE);
603
+ }
604
+ for (const pathname of pathnames) {
605
+ try {
606
+ const watcher = (0, import_node_fs.watch)(pathname, { recursive: true }, (_event, filename) => {
607
+ if (!filename) return;
608
+ const abs = (0, import_node_path2.resolve)(pathname, filename);
609
+ if (abs === absOutFile) return;
610
+ if (isKnownFileType(filename)) {
611
+ scheduleBuild();
612
+ }
613
+ });
614
+ watchers.push(watcher);
615
+ } catch {
616
+ }
617
+ }
618
+ callback();
619
+ return {
620
+ close() {
621
+ if (buildTimer) clearTimeout(buildTimer);
622
+ for (const w of watchers) w.close();
623
+ }
624
+ };
625
+ }
626
+
627
+ // src/formats.ts
628
+ var import_node_fs2 = require("fs");
629
+ var import_node_path3 = require("path");
630
+ var import_node_os = require("os");
631
+ function parseFormatJSON(source, formatId) {
632
+ const first = source.indexOf("{");
633
+ const last = source.lastIndexOf("}");
634
+ if (first === -1 || last === -1) return null;
635
+ let chunk = source.slice(first, last + 1);
636
+ try {
637
+ return JSON.parse(chunk);
638
+ } catch {
639
+ if (formatId.toLowerCase().startsWith("harlowe")) {
640
+ const setupIdx = chunk.lastIndexOf(',"setup": function');
641
+ if (setupIdx !== -1) {
642
+ chunk = chunk.slice(0, setupIdx) + "}";
643
+ try {
644
+ return JSON.parse(chunk);
645
+ } catch {
646
+ }
647
+ }
648
+ }
649
+ return null;
650
+ }
651
+ }
652
+ function readUTF8(filename) {
653
+ let content = (0, import_node_fs2.readFileSync)(filename, "utf-8");
654
+ if (content.charCodeAt(0) === 65279) content = content.slice(1);
655
+ content = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
656
+ return content;
657
+ }
658
+ function discoverFormats(searchDirs) {
659
+ const formats = /* @__PURE__ */ new Map();
660
+ const baseFilenames = ["format.js", "header.html"];
661
+ for (const searchDir of searchDirs) {
662
+ try {
663
+ const stat = (0, import_node_fs2.statSync)(searchDir);
664
+ if (!stat.isDirectory()) continue;
665
+ } catch {
666
+ continue;
667
+ }
668
+ let entries;
669
+ try {
670
+ entries = (0, import_node_fs2.readdirSync)(searchDir);
671
+ } catch {
672
+ continue;
673
+ }
674
+ for (const entry of entries) {
675
+ const formatDir = (0, import_node_path3.join)(searchDir, entry);
676
+ try {
677
+ if (!(0, import_node_fs2.statSync)(formatDir).isDirectory()) continue;
678
+ } catch {
679
+ continue;
680
+ }
681
+ for (const baseFilename of baseFilenames) {
682
+ const formatFilename = (0, import_node_path3.join)(formatDir, baseFilename);
683
+ try {
684
+ const stat = (0, import_node_fs2.statSync)(formatFilename);
685
+ if (!stat.isFile()) continue;
686
+ } catch {
687
+ continue;
688
+ }
689
+ const isTwine2 = baseFilename === "format.js";
690
+ const format = {
691
+ id: entry,
692
+ filename: formatFilename,
693
+ isTwine2,
694
+ name: "",
695
+ version: "",
696
+ proofing: false
697
+ };
698
+ if (isTwine2) {
699
+ try {
700
+ const source = readUTF8(formatFilename);
701
+ const data = parseFormatJSON(source, entry);
702
+ if (!data) continue;
703
+ format.name = data.name;
704
+ format.version = data.version;
705
+ format.proofing = data.proofing ?? false;
706
+ } catch {
707
+ continue;
708
+ }
709
+ }
710
+ formats.set(entry, format);
711
+ break;
712
+ }
713
+ }
714
+ }
715
+ return formats;
716
+ }
717
+ function getFormatSearchDirs(extraPaths = [], useTweegoPath = true) {
718
+ const subdirNames = ["storyformats", ".storyformats", "story-formats", "storyFormats", "targets"];
719
+ const basePaths = /* @__PURE__ */ new Set();
720
+ try {
721
+ basePaths.add((0, import_node_os.homedir)());
722
+ } catch {
723
+ }
724
+ basePaths.add(process.cwd());
725
+ const dirs = [];
726
+ for (const base of basePaths) {
727
+ for (const sub of subdirNames) {
728
+ const dir = (0, import_node_path3.join)(base, sub);
729
+ try {
730
+ if ((0, import_node_fs2.statSync)(dir).isDirectory()) {
731
+ dirs.push(dir);
732
+ }
733
+ } catch {
734
+ }
735
+ }
736
+ }
737
+ dirs.push(...extraPaths);
738
+ if (useTweegoPath) {
739
+ const tweegoPath = process.env.TWEEGO_PATH;
740
+ if (tweegoPath) {
741
+ dirs.push(...tweegoPath.split(process.platform === "win32" ? ";" : ":"));
742
+ }
743
+ }
744
+ return dirs;
745
+ }
746
+ function parseSemver(v) {
747
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
748
+ if (!m) return null;
749
+ return [Number(m[1]), Number(m[2]), Number(m[3])];
750
+ }
751
+ function semverCompare(a, b) {
752
+ for (let i = 0; i < 3; i++) {
753
+ if (a[i] !== b[i]) return a[i] - b[i];
754
+ }
755
+ return 0;
756
+ }
757
+ function getFormatIdByNameAndVersion(formats, name, version) {
758
+ const wanted = parseSemver(version);
759
+ let bestVersion = null;
760
+ let bestId;
761
+ for (const [id, f] of formats) {
762
+ if (!f.isTwine2 || f.name !== name) continue;
763
+ const have = parseSemver(f.version);
764
+ if (!have) continue;
765
+ if (wanted === null || have[0] === wanted[0] && semverCompare(have, wanted) >= 0) {
766
+ if (!bestVersion || semverCompare(have, bestVersion) > 0) {
767
+ bestVersion = have;
768
+ bestId = id;
769
+ }
770
+ }
771
+ }
772
+ return bestId;
773
+ }
774
+ function readFormatSource(format) {
775
+ const source = readUTF8(format.filename);
776
+ if (format.isTwine2) {
777
+ const data = parseFormatJSON(source, format.id);
778
+ if (!data) throw new Error(`Cannot parse format ${format.id} JSON`);
779
+ return data.source;
780
+ }
781
+ return source;
782
+ }
783
+
784
+ // src/loader.ts
785
+ var import_node_fs3 = require("fs");
786
+ var import_node_path4 = require("path");
787
+
788
+ // src/lexer.ts
789
+ var EOF = -1;
790
+ var HEADER_DELIM = "::";
791
+ var NEWLINE_HEADER_DELIM = "\n::";
792
+ var LexerContext = class {
793
+ input;
794
+ line = 1;
795
+ start = 0;
796
+ pos = 0;
797
+ items = [];
798
+ constructor(input) {
799
+ this.input = input;
800
+ }
801
+ next() {
802
+ if (this.pos >= this.input.length) return EOF;
803
+ const ch = this.input.charCodeAt(this.pos);
804
+ this.pos++;
805
+ if (ch === 10) this.line++;
806
+ return ch;
807
+ }
808
+ peek() {
809
+ if (this.pos >= this.input.length) return EOF;
810
+ return this.input.charCodeAt(this.pos);
811
+ }
812
+ backup() {
813
+ if (this.pos > this.start) {
814
+ this.pos--;
815
+ if (this.input.charCodeAt(this.pos) === 10) this.line--;
816
+ } else {
817
+ throw new Error("backup would leave pos < start");
818
+ }
819
+ }
820
+ emit(type) {
821
+ const val = this.input.slice(this.start, this.pos);
822
+ this.items.push({ type, line: this.line, pos: this.start, val });
823
+ if (type === 6 /* Content */) {
824
+ for (let i = this.start; i < this.pos; i++) {
825
+ if (this.input.charCodeAt(i) === 10) this.line++;
826
+ }
827
+ }
828
+ this.start = this.pos;
829
+ }
830
+ ignore() {
831
+ for (let i = this.start; i < this.pos; i++) {
832
+ if (this.input.charCodeAt(i) === 10) this.line++;
833
+ }
834
+ this.start = this.pos;
835
+ }
836
+ acceptRun(valid) {
837
+ let ch;
838
+ for (ch = this.next(); ch !== EOF && valid.includes(String.fromCharCode(ch)); ch = this.next()) {
839
+ }
840
+ if (ch !== EOF) this.backup();
841
+ }
842
+ errorf(message) {
843
+ this.items.push({
844
+ type: 0 /* Error */,
845
+ line: this.line,
846
+ pos: this.start,
847
+ val: message
848
+ });
849
+ return null;
850
+ }
851
+ /** Drain all pending items and return them. */
852
+ drainItems() {
853
+ const result = this.items;
854
+ this.items = [];
855
+ return result;
856
+ }
857
+ };
858
+ function acceptQuoted(ctx, quote2) {
859
+ for (; ; ) {
860
+ const ch = ctx.next();
861
+ switch (ch) {
862
+ case 92: {
863
+ const r = ctx.next();
864
+ if (r !== 10 && r !== EOF) break;
865
+ }
866
+ // falls through
867
+ case 10:
868
+ case EOF:
869
+ return "unterminated quoted string";
870
+ default:
871
+ if (ch === quote2) return null;
872
+ break;
873
+ }
874
+ }
875
+ }
876
+ function lexProlog(ctx) {
877
+ if (ctx.input.startsWith(HEADER_DELIM, ctx.pos)) {
878
+ return lexHeaderDelim;
879
+ }
880
+ const i = ctx.input.indexOf(NEWLINE_HEADER_DELIM, ctx.pos);
881
+ if (i > -1) {
882
+ ctx.pos = i + 1;
883
+ ctx.ignore();
884
+ return lexHeaderDelim;
885
+ }
886
+ ctx.emit(1 /* EOF */);
887
+ return null;
888
+ }
889
+ function lexContent(ctx) {
890
+ if (ctx.input.startsWith(HEADER_DELIM, ctx.pos)) {
891
+ return lexHeaderDelim;
892
+ }
893
+ const i = ctx.input.indexOf(NEWLINE_HEADER_DELIM, ctx.pos);
894
+ if (i > -1) {
895
+ ctx.pos = i + 1;
896
+ ctx.emit(6 /* Content */);
897
+ return lexHeaderDelim;
898
+ }
899
+ ctx.pos = ctx.input.length;
900
+ if (ctx.pos > ctx.start) {
901
+ ctx.emit(6 /* Content */);
902
+ }
903
+ ctx.emit(1 /* EOF */);
904
+ return null;
905
+ }
906
+ function lexHeaderDelim(ctx) {
907
+ ctx.pos += HEADER_DELIM.length;
908
+ ctx.emit(2 /* Header */);
909
+ return lexName;
910
+ }
911
+ function lexName(ctx) {
912
+ let r;
913
+ outer: for (; ; ) {
914
+ r = ctx.next();
915
+ switch (r) {
916
+ case 92: {
917
+ const next = ctx.next();
918
+ if (next !== 10 && next !== EOF) break;
919
+ r = next;
920
+ }
921
+ // falls through
922
+ case 91:
923
+ // [
924
+ case 93:
925
+ // ]
926
+ case 123:
927
+ // {
928
+ case 125:
929
+ // }
930
+ case 10:
931
+ // \n
932
+ case EOF:
933
+ if (r !== EOF) ctx.backup();
934
+ break outer;
935
+ }
936
+ }
937
+ ctx.emit(3 /* Name */);
938
+ switch (r) {
939
+ case 91:
940
+ return lexTags;
941
+ // [
942
+ case 93:
943
+ return ctx.errorf(`unexpected right square bracket ']'`);
944
+ case 123:
945
+ return lexMetadata;
946
+ // {
947
+ case 125:
948
+ return ctx.errorf(`unexpected right curly brace '}'`);
949
+ case 10:
950
+ ctx.pos++;
951
+ ctx.ignore();
952
+ return lexContent;
953
+ }
954
+ ctx.emit(1 /* EOF */);
955
+ return null;
956
+ }
957
+ function lexNextOptionalBlock(ctx) {
958
+ ctx.acceptRun(" ");
959
+ ctx.ignore();
960
+ const r = ctx.peek();
961
+ switch (r) {
962
+ case 91:
963
+ return lexTags;
964
+ // [
965
+ case 93:
966
+ return ctx.errorf(`unexpected right square bracket ']'`);
967
+ case 123:
968
+ return lexMetadata;
969
+ // {
970
+ case 125:
971
+ return ctx.errorf(`unexpected right curly brace '}'`);
972
+ case 10:
973
+ ctx.pos++;
974
+ ctx.ignore();
975
+ return lexContent;
976
+ case EOF:
977
+ ctx.emit(1 /* EOF */);
978
+ return null;
979
+ }
980
+ return ctx.errorf(`illegal character '${String.fromCharCode(r)}' amid the optional blocks`);
981
+ }
982
+ function lexTags(ctx) {
983
+ ctx.pos++;
984
+ for (; ; ) {
985
+ const r = ctx.next();
986
+ switch (r) {
987
+ case 92: {
988
+ const next = ctx.next();
989
+ if (next !== 10 && next !== EOF) break;
990
+ }
991
+ // falls through
992
+ case 10:
993
+ case EOF:
994
+ if (r === 10) ctx.backup();
995
+ return ctx.errorf("unterminated tag block");
996
+ case 93:
997
+ if (ctx.pos > ctx.start) ctx.emit(4 /* Tags */);
998
+ return lexNextOptionalBlock;
999
+ case 91:
1000
+ return ctx.errorf(`unexpected left square bracket '['`);
1001
+ case 123:
1002
+ return ctx.errorf(`unexpected left curly brace '{'`);
1003
+ case 125:
1004
+ return ctx.errorf(`unexpected right curly brace '}'`);
1005
+ }
1006
+ }
1007
+ }
1008
+ function lexMetadata(ctx) {
1009
+ ctx.pos++;
1010
+ let depth = 1;
1011
+ for (; ; ) {
1012
+ const r = ctx.next();
1013
+ switch (r) {
1014
+ case 34: {
1015
+ const err = acceptQuoted(ctx, 34);
1016
+ if (err) return ctx.errorf(err);
1017
+ break;
1018
+ }
1019
+ case 10:
1020
+ ctx.backup();
1021
+ // falls through
1022
+ case EOF:
1023
+ return ctx.errorf("unterminated metadata block");
1024
+ case 123:
1025
+ depth++;
1026
+ break;
1027
+ case 125:
1028
+ depth--;
1029
+ if (depth === 0) {
1030
+ if (ctx.pos > ctx.start) ctx.emit(5 /* Metadata */);
1031
+ return lexNextOptionalBlock;
1032
+ }
1033
+ break;
1034
+ }
1035
+ }
1036
+ }
1037
+ function* tweeLexer(input) {
1038
+ const ctx = new LexerContext(input);
1039
+ let state = lexProlog;
1040
+ while (state !== null) {
1041
+ state = state(ctx);
1042
+ const items = ctx.drainItems();
1043
+ for (const item of items) {
1044
+ yield item;
1045
+ }
1046
+ }
1047
+ const remaining = ctx.drainItems();
1048
+ for (const item of remaining) {
1049
+ yield item;
1050
+ }
1051
+ }
1052
+ var TweeLexer = class {
1053
+ gen;
1054
+ constructor(input) {
1055
+ this.gen = tweeLexer(input);
1056
+ }
1057
+ nextItem() {
1058
+ const result = this.gen.next();
1059
+ if (result.done) {
1060
+ return { item: { type: 1 /* EOF */, line: 0, pos: 0, val: "" }, done: true };
1061
+ }
1062
+ return { item: result.value, done: false };
1063
+ }
1064
+ *[Symbol.iterator]() {
1065
+ yield* this.gen;
1066
+ }
1067
+ };
1068
+
1069
+ // src/twee2-compat.ts
1070
+ var twee2DetectRe = /^:: *[^[]*?(?: *\[.*?\])? *<(.*?)> *$/m;
1071
+ var twee2HeaderRe = /^(:: *[^[]*?)( *\[.*?\])?(?: *<(.*?)>)? *$/gm;
1072
+ var twee2BadPosRe = /^(::.*?) *\{"position":" *"\}$/gm;
1073
+ function hasTwee2Syntax(s) {
1074
+ return twee2DetectRe.test(s);
1075
+ }
1076
+ function twee2ToV3(s) {
1077
+ if (!hasTwee2Syntax(s)) return s;
1078
+ s = s.replace(twee2HeaderRe, (_, p1, p2, p3) => {
1079
+ const tags = p2 ?? "";
1080
+ const pos = p3 ?? "";
1081
+ return `${p1}${tags} {"position":"${pos}"}`;
1082
+ });
1083
+ s = s.replace(twee2BadPosRe, "$1");
1084
+ return s;
1085
+ }
1086
+
1087
+ // src/parser.ts
1088
+ function parseTwee(source, options = {}) {
1089
+ const { filename = "<inline>", trim = true, twee2Compat = false } = options;
1090
+ const diagnostics = [];
1091
+ if (twee2Compat) {
1092
+ source = twee2ToV3(source);
1093
+ }
1094
+ const passages = [];
1095
+ let current = null;
1096
+ let pCount = 0;
1097
+ let lastType = 1 /* EOF */;
1098
+ for (const item of tweeLexer(source)) {
1099
+ switch (item.type) {
1100
+ case 0 /* Error */:
1101
+ diagnostics.push({
1102
+ level: "error",
1103
+ message: `line ${item.line}: Malformed twee source; ${item.val}.`,
1104
+ file: filename,
1105
+ line: item.line
1106
+ });
1107
+ return { passages, diagnostics };
1108
+ case 1 /* EOF */:
1109
+ if (pCount > 0 && current) {
1110
+ passages.push(current);
1111
+ }
1112
+ return { passages, diagnostics };
1113
+ case 2 /* Header */:
1114
+ pCount++;
1115
+ if (pCount > 1 && current) {
1116
+ passages.push(current);
1117
+ }
1118
+ current = { name: "", tags: [], text: "" };
1119
+ break;
1120
+ case 3 /* Name */: {
1121
+ if (!current) break;
1122
+ const name = tweeUnescape(item.val).trim();
1123
+ if (name.length === 0) {
1124
+ diagnostics.push({
1125
+ level: "error",
1126
+ message: `line ${item.line}: Malformed twee source; passage with no name.`,
1127
+ file: filename,
1128
+ line: item.line
1129
+ });
1130
+ return { passages, diagnostics };
1131
+ }
1132
+ current.name = name;
1133
+ break;
1134
+ }
1135
+ case 4 /* Tags */: {
1136
+ if (!current) break;
1137
+ if (lastType !== 3 /* Name */) {
1138
+ diagnostics.push({
1139
+ level: "error",
1140
+ message: `line ${item.line}: Malformed twee source; optional tags block must immediately follow the passage name.`,
1141
+ file: filename,
1142
+ line: item.line
1143
+ });
1144
+ return { passages, diagnostics };
1145
+ }
1146
+ const inner = item.val.slice(1, -1);
1147
+ current.tags = tweeUnescape(inner).split(/\s+/).filter(Boolean);
1148
+ break;
1149
+ }
1150
+ case 5 /* Metadata */: {
1151
+ if (!current) break;
1152
+ if (lastType !== 3 /* Name */ && lastType !== 4 /* Tags */) {
1153
+ diagnostics.push({
1154
+ level: "error",
1155
+ message: `line ${item.line}: Malformed twee source; optional metadata block must immediately follow the passage name or tags block.`,
1156
+ file: filename,
1157
+ line: item.line
1158
+ });
1159
+ return { passages, diagnostics };
1160
+ }
1161
+ try {
1162
+ const parsed = JSON.parse(item.val);
1163
+ const meta = {};
1164
+ if (typeof parsed.position === "string") meta.position = parsed.position;
1165
+ if (typeof parsed.size === "string") meta.size = parsed.size;
1166
+ current.metadata = meta;
1167
+ } catch (e) {
1168
+ diagnostics.push({
1169
+ level: "warning",
1170
+ message: `load ${filename}: line ${item.line}: Malformed twee source; could not decode metadata (reason: ${e instanceof Error ? e.message : String(e)}).`,
1171
+ file: filename,
1172
+ line: item.line
1173
+ });
1174
+ }
1175
+ break;
1176
+ }
1177
+ case 6 /* Content */: {
1178
+ if (!current) break;
1179
+ current.text = trim ? item.val.trim() : item.val;
1180
+ break;
1181
+ }
1182
+ }
1183
+ lastType = item.type;
1184
+ }
1185
+ if (pCount > 0 && current) {
1186
+ passages.push(current);
1187
+ }
1188
+ return { passages, diagnostics };
1189
+ }
1190
+
1191
+ // src/loader.ts
1192
+ function readUTF82(filename) {
1193
+ let content = (0, import_node_fs3.readFileSync)(filename, "utf-8");
1194
+ if (content.charCodeAt(0) === 65279) content = content.slice(1);
1195
+ content = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1196
+ return content;
1197
+ }
1198
+ function readBase64(filename) {
1199
+ return (0, import_node_fs3.readFileSync)(filename).toString("base64");
1200
+ }
1201
+ function loadSources(story, filenames, opts, diagnostics, processedFiles) {
1202
+ for (const filename of filenames) {
1203
+ if (processedFiles.has(filename)) {
1204
+ diagnostics.push({ level: "warning", message: `load ${filename}: Skipping duplicate.` });
1205
+ continue;
1206
+ }
1207
+ const ext = normalizedFileExt(filename);
1208
+ try {
1209
+ switch (ext) {
1210
+ case "tw":
1211
+ case "twee":
1212
+ loadTwee(story, filename, opts, diagnostics);
1213
+ break;
1214
+ case "tw2":
1215
+ case "twee2":
1216
+ loadTwee(story, filename, { ...opts, twee2Compat: true }, diagnostics);
1217
+ break;
1218
+ case "css":
1219
+ loadTagged(story, "stylesheet", filename, diagnostics);
1220
+ break;
1221
+ case "js":
1222
+ loadTagged(story, "script", filename, diagnostics);
1223
+ break;
1224
+ case "otf":
1225
+ case "ttf":
1226
+ case "woff":
1227
+ case "woff2":
1228
+ loadFont(story, filename, diagnostics);
1229
+ break;
1230
+ case "gif":
1231
+ case "jpeg":
1232
+ case "jpg":
1233
+ case "png":
1234
+ case "svg":
1235
+ case "tif":
1236
+ case "tiff":
1237
+ case "webp":
1238
+ loadMedia(story, "Twine.image", filename, diagnostics);
1239
+ break;
1240
+ case "aac":
1241
+ case "flac":
1242
+ case "m4a":
1243
+ case "mp3":
1244
+ case "oga":
1245
+ case "ogg":
1246
+ case "opus":
1247
+ case "wav":
1248
+ case "wave":
1249
+ case "weba":
1250
+ loadMedia(story, "Twine.audio", filename, diagnostics);
1251
+ break;
1252
+ case "mp4":
1253
+ case "ogv":
1254
+ case "webm":
1255
+ loadMedia(story, "Twine.video", filename, diagnostics);
1256
+ break;
1257
+ case "vtt":
1258
+ loadMedia(story, "Twine.vtt", filename, diagnostics);
1259
+ break;
1260
+ default:
1261
+ continue;
1262
+ }
1263
+ } catch (e) {
1264
+ diagnostics.push({
1265
+ level: "error",
1266
+ message: `load ${filename}: ${e instanceof Error ? e.message : String(e)}`,
1267
+ file: filename
1268
+ });
1269
+ continue;
1270
+ }
1271
+ processedFiles.add(filename);
1272
+ }
1273
+ if (story.name !== "" && !story.passages.some((p) => p.name === "StoryTitle")) {
1274
+ storyPrepend(story, { name: "StoryTitle", tags: [], text: story.name }, diagnostics);
1275
+ }
1276
+ }
1277
+ function loadInlineSources(story, sources, opts, diagnostics) {
1278
+ for (const source of sources) {
1279
+ if (typeof source === "string") {
1280
+ continue;
1281
+ }
1282
+ const content = typeof source.content === "string" ? source.content : source.content.toString("utf-8");
1283
+ const ext = normalizedFileExt(source.filename);
1284
+ if (ext === "tw" || ext === "twee" || ext === "tw2" || ext === "twee2" || !ext) {
1285
+ const twee2 = ext === "tw2" || ext === "twee2" || opts.twee2Compat;
1286
+ const result = parseTwee(content, {
1287
+ filename: source.filename,
1288
+ trim: opts.trim ?? true,
1289
+ twee2Compat: twee2
1290
+ });
1291
+ diagnostics.push(...result.diagnostics);
1292
+ for (const p of result.passages) {
1293
+ storyAdd(story, p, diagnostics);
1294
+ }
1295
+ }
1296
+ }
1297
+ }
1298
+ function loadTwee(story, filename, opts, diagnostics) {
1299
+ const source = readUTF82(filename);
1300
+ const result = parseTwee(source, {
1301
+ filename,
1302
+ trim: opts.trim ?? true,
1303
+ twee2Compat: opts.twee2Compat ?? false
1304
+ });
1305
+ diagnostics.push(...result.diagnostics);
1306
+ for (const p of result.passages) {
1307
+ storyAdd(story, p, diagnostics);
1308
+ }
1309
+ }
1310
+ function loadTagged(story, tag, filename, diagnostics) {
1311
+ const source = readUTF82(filename);
1312
+ storyAdd(story, { name: (0, import_node_path4.basename)(filename), tags: [tag], text: source }, diagnostics);
1313
+ }
1314
+ function loadMedia(story, tag, filename, diagnostics) {
1315
+ const source = readBase64(filename);
1316
+ const name = (0, import_node_path4.basename)(filename).split(".")[0];
1317
+ storyAdd(story, {
1318
+ name,
1319
+ tags: [tag],
1320
+ text: `data:${mediaTypeFromFilename(filename)};base64,${source}`
1321
+ }, diagnostics);
1322
+ }
1323
+ function loadFont(story, filename, diagnostics) {
1324
+ const source = readBase64(filename);
1325
+ const name = (0, import_node_path4.basename)(filename);
1326
+ const family = name.split(".")[0];
1327
+ const ext = normalizedFileExt(filename);
1328
+ const mediaType = mediaTypeFromExt(ext);
1329
+ const hint = fontFormatHint(ext);
1330
+ storyAdd(story, {
1331
+ name,
1332
+ tags: ["stylesheet"],
1333
+ text: `@font-face {
1334
+ font-family: "${family}";
1335
+ src: url("data:${mediaType};base64,${source}") format("${hint}");
1336
+ }`
1337
+ }, diagnostics);
1338
+ }
1339
+
1340
+ // src/output-twine2.ts
1341
+ var CREATOR_NAME = "Twee-ts";
1342
+ var CREATOR_VERSION = "0.1.0";
1343
+ function toTwine2Archive(story, startName, diagnostics) {
1344
+ return getTwine2DataChunk(story, startName, diagnostics) + "\n";
1345
+ }
1346
+ function toTwine2HTML(story, format, startName, diagnostics) {
1347
+ let template = readFormatSource(format);
1348
+ if (template.includes("{{STORY_NAME}}")) {
1349
+ template = template.replaceAll("{{STORY_NAME}}", htmlEscape(story.name));
1350
+ }
1351
+ if (template.includes("{{STORY_DATA}}")) {
1352
+ template = template.replace("{{STORY_DATA}}", getTwine2DataChunk(story, startName, diagnostics));
1353
+ }
1354
+ return template;
1355
+ }
1356
+ function getTwine2DataChunk(story, startName, diagnostics) {
1357
+ ensureIFID(story, diagnostics);
1358
+ const parts = [];
1359
+ let startID = "";
1360
+ let pid = 0;
1361
+ const scripts = [];
1362
+ const stylesheets = [];
1363
+ for (const p of story.passages) {
1364
+ if (hasTag(p, "Twine.private")) continue;
1365
+ if (hasTag(p, "script")) scripts.push(p);
1366
+ else if (hasTag(p, "stylesheet")) stylesheets.push(p);
1367
+ }
1368
+ let styleContent = "";
1369
+ if (stylesheets.length === 1) {
1370
+ styleContent = stylesheets[0].text;
1371
+ } else if (stylesheets.length > 1) {
1372
+ let pidS = 1;
1373
+ for (const p of stylesheets) {
1374
+ if (pidS > 1 && !styleContent.endsWith("\n")) styleContent += "\n";
1375
+ styleContent += `/* twine-user-stylesheet #${pidS}: "${p.name}" */
1376
+ `;
1377
+ styleContent += p.text;
1378
+ pidS++;
1379
+ }
1380
+ }
1381
+ parts.push(`<style role="stylesheet" id="twine-user-stylesheet" type="text/twine-css">${styleContent}</style>`);
1382
+ let scriptContent = "";
1383
+ if (scripts.length === 1) {
1384
+ scriptContent = scripts[0].text;
1385
+ } else if (scripts.length > 1) {
1386
+ let pidS = 1;
1387
+ for (const p of scripts) {
1388
+ if (pidS > 1 && !scriptContent.endsWith("\n")) scriptContent += "\n";
1389
+ scriptContent += `/* twine-user-script #${pidS}: "${p.name}" */
1390
+ `;
1391
+ scriptContent += p.text;
1392
+ pidS++;
1393
+ }
1394
+ }
1395
+ parts.push(`<script role="script" id="twine-user-script" type="text/twine-javascript">${scriptContent}</script>`);
1396
+ for (const [tag, color] of story.twine2.tagColors) {
1397
+ parts.push(`<tw-tag name="${attrEscape(tag)}" color="${attrEscape(color)}"></tw-tag>`);
1398
+ }
1399
+ pid = 1;
1400
+ for (const p of story.passages) {
1401
+ if (p.name === "StoryTitle" || p.name === "StoryData" || hasAnyTag(p, "script", "stylesheet", "Twine.private")) {
1402
+ continue;
1403
+ }
1404
+ if (p.name === "StorySettings" && story.twine1.settings.size === 0) {
1405
+ continue;
1406
+ }
1407
+ parts.push(passageToPassagedata(p, pid));
1408
+ if (startName === p.name) {
1409
+ startID = String(pid);
1410
+ }
1411
+ pid++;
1412
+ }
1413
+ const opts = [];
1414
+ for (const [opt, val] of story.twine2.options) {
1415
+ if (val) opts.push(opt);
1416
+ }
1417
+ const options = opts.join(" ");
1418
+ const zoom = story.twine2.zoom === Math.floor(story.twine2.zoom) ? story.twine2.zoom.toString() : story.twine2.zoom.toFixed(1);
1419
+ const wrapper = `<!-- UUID://${story.ifid}// --><tw-storydata name="${attrEscape(story.name)}" startnode="${startID}" creator="${attrEscape(CREATOR_NAME)}" creator-version="${attrEscape(CREATOR_VERSION)}" ifid="${attrEscape(story.ifid)}" zoom="${attrEscape(zoom)}" format="${attrEscape(story.twine2.format)}" format-version="${attrEscape(story.twine2.formatVersion)}" options="${attrEscape(options)}" hidden>`;
1420
+ return wrapper + parts.join("") + "</tw-storydata>";
1421
+ }
1422
+ function ensureIFID(story, diagnostics) {
1423
+ if (story.ifid !== "") return;
1424
+ if (story.legacyIFID !== "") {
1425
+ diagnostics.push({
1426
+ level: "warning",
1427
+ message: 'Story IFID not found; reusing "ifid" entry from the "StorySettings" special passage.'
1428
+ });
1429
+ story.ifid = story.legacyIFID;
1430
+ } else {
1431
+ story.ifid = generateIFID();
1432
+ diagnostics.push({
1433
+ level: "warning",
1434
+ message: `Story IFID not found; generated ${story.ifid} for your project. Add it to a StoryData passage.`
1435
+ });
1436
+ }
1437
+ }
1438
+
1439
+ // src/output-twine1.ts
1440
+ var import_node_fs4 = require("fs");
1441
+ var import_node_path5 = require("path");
1442
+ var CREATOR_NAME2 = "twee-ts";
1443
+ var CREATOR_VERSION2 = "0.1.0";
1444
+ function toTwine1Archive(story, _startName) {
1445
+ const { data, count } = getTwine1PassageChunk(story);
1446
+ return `<div id="storeArea" data-size="${count}" hidden>${data}</div>
1447
+ `;
1448
+ }
1449
+ function toTwine1HTML(story, format, startName, _diagnostics) {
1450
+ const formatDir = (0, import_node_path5.dirname)(format.filename);
1451
+ const parentDir = (0, import_node_path5.dirname)(formatDir);
1452
+ let template = readFormatSource(format);
1453
+ const { data, count } = getTwine1PassageChunk(story);
1454
+ template = tryReplaceComponent(template, '"USER_LIB"', (0, import_node_path5.join)(formatDir, "userlib.js"), false);
1455
+ template = tryReplaceComponent(template, '"ENGINE"', (0, import_node_path5.join)(parentDir, "engine.js"), true);
1456
+ template = tryReplaceComponent(template, '"SUGARCANE"', (0, import_node_path5.join)(formatDir, "code.js"), true);
1457
+ template = tryReplaceComponent(template, '"JONAH"', (0, import_node_path5.join)(formatDir, "code.js"), true);
1458
+ if (story.twine1.settings.get("jquery") === "on") {
1459
+ template = tryReplaceComponent(template, '"JQUERY"', (0, import_node_path5.join)(parentDir, "jquery.js"), true);
1460
+ }
1461
+ if (story.twine1.settings.get("modernizr") === "on") {
1462
+ template = tryReplaceComponent(template, '"MODERNIZR"', (0, import_node_path5.join)(parentDir, "modernizr.js"), true);
1463
+ }
1464
+ const displayStart = startName === "Start" ? "" : startName;
1465
+ template = template.replace('"VERSION"', `Compiled with ${CREATOR_NAME2}, ${CREATOR_VERSION2}`);
1466
+ template = template.replace('"TIME"', `Built on ${(/* @__PURE__ */ new Date()).toUTCString()}`);
1467
+ template = template.replace('"START_AT"', `"${displayStart}"`);
1468
+ template = template.replace('"STORY_SIZE"', `"${count}"`);
1469
+ if (template.includes('"STORY"')) {
1470
+ template = template.replace('"STORY"', data);
1471
+ } else {
1472
+ let footer;
1473
+ try {
1474
+ footer = (0, import_node_fs4.readFileSync)((0, import_node_path5.join)(formatDir, "footer.html"), "utf-8");
1475
+ } catch {
1476
+ footer = "</div>\n</body>\n</html>\n";
1477
+ }
1478
+ template += data + footer;
1479
+ }
1480
+ if (story.ifid) {
1481
+ if (template.includes('<div id="store-area"')) {
1482
+ template = template.replace('<div id="store-area"', `<!-- UUID://${story.ifid}// --><div id="store-area"`);
1483
+ } else {
1484
+ template = template.replace('<div id="storeArea"', `<!-- UUID://${story.ifid}// --><div id="storeArea"`);
1485
+ }
1486
+ }
1487
+ return template;
1488
+ }
1489
+ function getTwine1PassageChunk(story) {
1490
+ let data = "";
1491
+ let count = 0;
1492
+ for (const p of story.passages) {
1493
+ if (hasTag(p, "Twine.private")) continue;
1494
+ count++;
1495
+ data += passageToTiddler(p, count);
1496
+ }
1497
+ return { data, count };
1498
+ }
1499
+ function tryReplaceComponent(template, placeholder, componentPath, _required) {
1500
+ if (!template.includes(placeholder)) return template;
1501
+ try {
1502
+ let content = (0, import_node_fs4.readFileSync)(componentPath, "utf-8");
1503
+ if (content.charCodeAt(0) === 65279) content = content.slice(1);
1504
+ return template.replace(placeholder, content);
1505
+ } catch {
1506
+ return template;
1507
+ }
1508
+ }
1509
+
1510
+ // src/output-twee.ts
1511
+ function toTwee(story, outMode) {
1512
+ let data = "";
1513
+ for (const p of story.passages) {
1514
+ data += passageToTwee(p, outMode);
1515
+ }
1516
+ return data;
1517
+ }
1518
+
1519
+ // src/modules.ts
1520
+ var import_node_fs5 = require("fs");
1521
+ var import_node_path6 = require("path");
1522
+ function readUTF83(filename) {
1523
+ let content = (0, import_node_fs5.readFileSync)(filename, "utf-8");
1524
+ if (content.charCodeAt(0) === 65279) content = content.slice(1);
1525
+ return content.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1526
+ }
1527
+ function readBase642(filename) {
1528
+ return (0, import_node_fs5.readFileSync)(filename).toString("base64");
1529
+ }
1530
+ function loadModules(filenames) {
1531
+ const processed = /* @__PURE__ */ new Set();
1532
+ const headTags = [];
1533
+ for (const filename of filenames) {
1534
+ if (processed.has(filename)) continue;
1535
+ const ext = normalizedFileExt(filename);
1536
+ let tag = null;
1537
+ switch (ext) {
1538
+ case "css":
1539
+ tag = loadModuleTagged("style", filename);
1540
+ break;
1541
+ case "js":
1542
+ tag = loadModuleTagged("script", filename);
1543
+ break;
1544
+ case "otf":
1545
+ case "ttf":
1546
+ case "woff":
1547
+ case "woff2":
1548
+ tag = loadModuleFont(filename);
1549
+ break;
1550
+ default:
1551
+ continue;
1552
+ }
1553
+ if (tag) headTags.push(tag);
1554
+ processed.add(filename);
1555
+ }
1556
+ return headTags.join("\n");
1557
+ }
1558
+ function loadModuleTagged(tag, filename) {
1559
+ const source = readUTF83(filename).trim();
1560
+ if (source.length === 0) return null;
1561
+ const family = (0, import_node_path6.basename)(filename).split(".")[0];
1562
+ const idSlug = `${tag}-module-${slugify(family)}`;
1563
+ const mimeType = tag === "script" ? "text/javascript" : "text/css";
1564
+ return `<${tag} id="${idSlug}" type="${mimeType}">${source}</${tag}>`;
1565
+ }
1566
+ function loadModuleFont(filename) {
1567
+ const source = readBase642(filename);
1568
+ const family = (0, import_node_path6.basename)(filename).split(".")[0];
1569
+ const idSlug = `style-module-${slugify(family)}`;
1570
+ const ext = normalizedFileExt(filename);
1571
+ const mediaType = mediaTypeFromExt(ext);
1572
+ const hint = fontFormatHint(ext);
1573
+ return `<style id="${idSlug}" type="text/css">@font-face {
1574
+ font-family: "${family}";
1575
+ src: url("data:${mediaType};base64,${source}") format("${hint}");
1576
+ }</style>`;
1577
+ }
1578
+ function modifyHead(html, modulePaths, headFile) {
1579
+ const parts = [];
1580
+ if (modulePaths.length > 0) {
1581
+ const modules = loadModules(modulePaths).trim();
1582
+ if (modules.length > 0) parts.push(modules);
1583
+ }
1584
+ if (headFile) {
1585
+ try {
1586
+ const source = readUTF83(headFile).trim();
1587
+ if (source.length > 0) parts.push(source);
1588
+ } catch {
1589
+ }
1590
+ }
1591
+ if (parts.length > 0) {
1592
+ parts.push("</head>");
1593
+ return html.replace("</head>", parts.join("\n"));
1594
+ }
1595
+ return html;
1596
+ }
1597
+
1598
+ // src/remote-formats.ts
1599
+ var import_node_fs6 = require("fs");
1600
+ var import_node_path7 = require("path");
1601
+ var import_node_os2 = require("os");
1602
+ var DEFAULT_SFA_INDICES = [
1603
+ "https://videlais.github.io/story-formats-archive/official/index.json",
1604
+ "https://videlais.github.io/story-formats-archive/unofficial/index.json"
1605
+ ];
1606
+ function getCacheDir() {
1607
+ const xdg = process.env["XDG_CACHE_HOME"];
1608
+ const base = xdg || (0, import_node_path7.join)((0, import_node_os2.homedir)(), ".cache");
1609
+ return (0, import_node_path7.join)(base, "twee-ts", "storyformats");
1610
+ }
1611
+ var indexCache = /* @__PURE__ */ new Map();
1612
+ function clearIndexCache() {
1613
+ indexCache.clear();
1614
+ }
1615
+ async function fetchIndex(url) {
1616
+ const cached = indexCache.get(url);
1617
+ if (cached) return cached;
1618
+ const res = await fetch(url);
1619
+ if (!res.ok) {
1620
+ throw new Error(`Failed to fetch format index from ${url}: ${res.status} ${res.statusText}`);
1621
+ }
1622
+ const data = await res.json();
1623
+ indexCache.set(url, data);
1624
+ return data;
1625
+ }
1626
+ function findEntry(index, name, version) {
1627
+ const wanted = parseSemver(version);
1628
+ const entries = [...index.twine2 ?? [], ...index.twine1 ?? []];
1629
+ let bestEntry;
1630
+ let bestVersion = null;
1631
+ for (const entry of entries) {
1632
+ if (entry.name.toLowerCase() !== name.toLowerCase()) continue;
1633
+ const have = parseSemver(entry.version);
1634
+ if (!have) continue;
1635
+ if (wanted && semverCompare(have, wanted) === 0) return entry;
1636
+ if (wanted === null || have[0] === wanted[0] && semverCompare(have, wanted) >= 0) {
1637
+ if (!bestVersion || semverCompare(have, bestVersion) > 0) {
1638
+ bestVersion = have;
1639
+ bestEntry = entry;
1640
+ }
1641
+ }
1642
+ }
1643
+ return bestEntry;
1644
+ }
1645
+ async function verifySHA256(content, expectedHex) {
1646
+ const digest = await crypto.subtle.digest("SHA-256", content);
1647
+ const hex = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
1648
+ return hex === expectedHex.toLowerCase();
1649
+ }
1650
+ function getDownloadUrl(indexUrl, entry) {
1651
+ const base = indexUrl.replace(/\/index\.json$/, "");
1652
+ return `${base}/twine2/${entry.name}/${entry.version}/format.js`;
1653
+ }
1654
+ async function fetchAndCacheFormat(entry, downloadUrl) {
1655
+ const res = await fetch(downloadUrl);
1656
+ if (!res.ok) {
1657
+ throw new Error(`Failed to download format from ${downloadUrl}: ${res.status} ${res.statusText}`);
1658
+ }
1659
+ const text = await res.text();
1660
+ const checksumKey = Object.keys(entry.checksums ?? {}).find((k) => k.endsWith("format.js"));
1661
+ if (checksumKey) {
1662
+ const expected = entry.checksums[checksumKey];
1663
+ const encoder = new TextEncoder();
1664
+ const valid = await verifySHA256(encoder.encode(text), expected);
1665
+ if (!valid) {
1666
+ throw new Error(`Checksum verification failed for ${entry.name} ${entry.version}`);
1667
+ }
1668
+ }
1669
+ const id = `${entry.name.toLowerCase().replace(/\s+/g, "-")}-${parseSemver(entry.version)?.[0] ?? "0"}`;
1670
+ const data = parseFormatJSON(text, id);
1671
+ if (!data) {
1672
+ throw new Error(`Failed to parse format JSON from ${downloadUrl}`);
1673
+ }
1674
+ const cacheDir = getCacheDir();
1675
+ const formatDir = (0, import_node_path7.join)(cacheDir, entry.name, entry.version);
1676
+ (0, import_node_fs6.mkdirSync)(formatDir, { recursive: true });
1677
+ const formatPath = (0, import_node_path7.join)(formatDir, "format.js");
1678
+ (0, import_node_fs6.writeFileSync)(formatPath, text, "utf-8");
1679
+ return {
1680
+ id,
1681
+ filename: formatPath,
1682
+ isTwine2: true,
1683
+ name: data.name,
1684
+ version: data.version,
1685
+ proofing: data.proofing ?? false
1686
+ };
1687
+ }
1688
+ async function fetchDirectFormat(url) {
1689
+ const res = await fetch(url);
1690
+ if (!res.ok) {
1691
+ throw new Error(`Failed to download format from ${url}: ${res.status} ${res.statusText}`);
1692
+ }
1693
+ const text = await res.text();
1694
+ const tempId = "direct-url";
1695
+ const data = parseFormatJSON(text, tempId);
1696
+ if (!data) {
1697
+ throw new Error(`Failed to parse format JSON from ${url}`);
1698
+ }
1699
+ const id = `${data.name.toLowerCase().replace(/\s+/g, "-")}-${parseSemver(data.version)?.[0] ?? "0"}`;
1700
+ const cacheDir = getCacheDir();
1701
+ const formatDir = (0, import_node_path7.join)(cacheDir, data.name, data.version);
1702
+ (0, import_node_fs6.mkdirSync)(formatDir, { recursive: true });
1703
+ const formatPath = (0, import_node_path7.join)(formatDir, "format.js");
1704
+ (0, import_node_fs6.writeFileSync)(formatPath, text, "utf-8");
1705
+ return {
1706
+ id,
1707
+ filename: formatPath,
1708
+ isTwine2: true,
1709
+ name: data.name,
1710
+ version: data.version,
1711
+ proofing: data.proofing ?? false
1712
+ };
1713
+ }
1714
+ async function resolveRemoteFormat(name, version, indices, urls) {
1715
+ if (urls) {
1716
+ for (const url of urls) {
1717
+ try {
1718
+ const info = await fetchDirectFormat(url);
1719
+ if (info.name.toLowerCase() === name.toLowerCase()) {
1720
+ const wanted = parseSemver(version);
1721
+ const have = parseSemver(info.version);
1722
+ if (!wanted || have && have[0] === wanted[0] && semverCompare(have, wanted) >= 0) {
1723
+ return info;
1724
+ }
1725
+ }
1726
+ } catch {
1727
+ }
1728
+ }
1729
+ }
1730
+ const allIndices = [...indices ?? [], ...DEFAULT_SFA_INDICES];
1731
+ for (const indexUrl of allIndices) {
1732
+ try {
1733
+ const index = await fetchIndex(indexUrl);
1734
+ const entry = findEntry(index, name, version);
1735
+ if (entry) {
1736
+ const cached = getCachedFormat(entry.name, entry.version);
1737
+ if (cached) return cached;
1738
+ const downloadUrl = getDownloadUrl(indexUrl, entry);
1739
+ return await fetchAndCacheFormat(entry, downloadUrl);
1740
+ }
1741
+ } catch {
1742
+ }
1743
+ }
1744
+ return void 0;
1745
+ }
1746
+ function getCachedFormat(name, version) {
1747
+ const formatPath = (0, import_node_path7.join)(getCacheDir(), name, version, "format.js");
1748
+ try {
1749
+ if (!(0, import_node_fs6.existsSync)(formatPath)) return void 0;
1750
+ const source = (0, import_node_fs6.readFileSync)(formatPath, "utf-8");
1751
+ const id = `${name.toLowerCase().replace(/\s+/g, "-")}-${parseSemver(version)?.[0] ?? "0"}`;
1752
+ const data = parseFormatJSON(source, id);
1753
+ if (!data) return void 0;
1754
+ return {
1755
+ id,
1756
+ filename: formatPath,
1757
+ isTwine2: true,
1758
+ name: data.name,
1759
+ version: data.version,
1760
+ proofing: data.proofing ?? false
1761
+ };
1762
+ } catch {
1763
+ return void 0;
1764
+ }
1765
+ }
1766
+ function discoverCachedFormats() {
1767
+ const formats = /* @__PURE__ */ new Map();
1768
+ const cacheDir = getCacheDir();
1769
+ try {
1770
+ if (!(0, import_node_fs6.existsSync)(cacheDir)) return formats;
1771
+ } catch {
1772
+ return formats;
1773
+ }
1774
+ let names;
1775
+ try {
1776
+ names = (0, import_node_fs6.readdirSync)(cacheDir);
1777
+ } catch {
1778
+ return formats;
1779
+ }
1780
+ for (const name of names) {
1781
+ const nameDir = (0, import_node_path7.join)(cacheDir, name);
1782
+ try {
1783
+ if (!(0, import_node_fs6.statSync)(nameDir).isDirectory()) continue;
1784
+ } catch {
1785
+ continue;
1786
+ }
1787
+ let versions;
1788
+ try {
1789
+ versions = (0, import_node_fs6.readdirSync)(nameDir);
1790
+ } catch {
1791
+ continue;
1792
+ }
1793
+ for (const version of versions) {
1794
+ const info = getCachedFormat(name, version);
1795
+ if (info) {
1796
+ formats.set(`${info.id}-${version}`, info);
1797
+ }
1798
+ }
1799
+ }
1800
+ return formats;
1801
+ }
1802
+
1803
+ // src/compiler.ts
1804
+ var DEFAULT_FORMAT_ID = "sugarcube-2";
1805
+ var DEFAULT_START_NAME = "Start";
1806
+ var TweeTsError = class extends Error {
1807
+ constructor(message, diagnostics = []) {
1808
+ super(message);
1809
+ this.diagnostics = diagnostics;
1810
+ this.name = "TweeTsError";
1811
+ }
1812
+ };
1813
+ async function compile(options) {
1814
+ return buildOutput(options);
1815
+ }
1816
+ async function compileToFile(options) {
1817
+ const result = await compile(options);
1818
+ (0, import_node_fs7.writeFileSync)(options.outFile, result.output, "utf-8");
1819
+ return result;
1820
+ }
1821
+ async function watch(options) {
1822
+ const controller = new AbortController();
1823
+ const filePaths = options.sources.filter((s) => typeof s === "string");
1824
+ const modulePaths = options.modules ?? [];
1825
+ const allPaths = [...filePaths, ...modulePaths];
1826
+ const handle = watchFilesystem(allPaths, options.outFile, () => {
1827
+ buildOutput(options).then((result) => {
1828
+ (0, import_node_fs7.writeFileSync)(options.outFile, result.output, "utf-8");
1829
+ options.onBuild?.(result);
1830
+ }).catch((e) => {
1831
+ options.onError?.(e instanceof Error ? e : new Error(String(e)));
1832
+ });
1833
+ });
1834
+ controller.signal.addEventListener("abort", () => handle.close());
1835
+ return controller;
1836
+ }
1837
+ async function buildOutput(options) {
1838
+ const diagnostics = [];
1839
+ const outputMode = options.outputMode ?? "html";
1840
+ const trim = options.trim ?? true;
1841
+ const twee2Compat = options.twee2Compat ?? false;
1842
+ const testMode = options.testMode ?? false;
1843
+ const noRemote = options.noRemote ?? false;
1844
+ clearIndexCache();
1845
+ const filePaths = [];
1846
+ const inlineSources = [];
1847
+ for (const source of options.sources) {
1848
+ if (typeof source === "string") {
1849
+ filePaths.push(source);
1850
+ } else {
1851
+ inlineSources.push(source);
1852
+ }
1853
+ }
1854
+ const sourceFilenames = getFilenames(filePaths);
1855
+ const story = createStory();
1856
+ const processedFiles = /* @__PURE__ */ new Set();
1857
+ loadSources(story, sourceFilenames, { trim, twee2Compat }, diagnostics, processedFiles);
1858
+ loadInlineSources(story, inlineSources, { trim, twee2Compat }, diagnostics);
1859
+ if (options.tagAliases) {
1860
+ applyTagAliases(story.passages, options.tagAliases);
1861
+ }
1862
+ const fatalErrors = diagnostics.filter((d) => d.level === "error");
1863
+ if (fatalErrors.length > 0 && outputMode === "html") {
1864
+ }
1865
+ let format;
1866
+ let formatId = options.formatId ?? "";
1867
+ if (outputMode === "html") {
1868
+ const formatSearchDirs = getFormatSearchDirs(
1869
+ options.formatPaths,
1870
+ options.useTweegoPath ?? true
1871
+ );
1872
+ const formats = discoverFormats(formatSearchDirs);
1873
+ if (!formatId && story.twine2.format) {
1874
+ formatId = getFormatIdByNameAndVersion(formats, story.twine2.format, story.twine2.formatVersion) ?? "";
1875
+ }
1876
+ if (!formatId) {
1877
+ formatId = DEFAULT_FORMAT_ID;
1878
+ }
1879
+ format = formats.get(formatId);
1880
+ if (!format && !noRemote) {
1881
+ const remoteName = story.twine2.format || formatId;
1882
+ const remoteVersion = story.twine2.formatVersion || "";
1883
+ try {
1884
+ format = await resolveRemoteFormat(
1885
+ remoteName,
1886
+ remoteVersion,
1887
+ options.formatIndices,
1888
+ options.formatUrls
1889
+ );
1890
+ } catch {
1891
+ }
1892
+ }
1893
+ if (!format) {
1894
+ const reason = noRemote ? " (remote fetching disabled)" : "";
1895
+ diagnostics.push({
1896
+ level: "error",
1897
+ message: `Story format "${formatId}" is not available${reason}. Found: ${[...formats.keys()].join(", ") || "none"}`
1898
+ });
1899
+ }
1900
+ }
1901
+ let startName;
1902
+ if (options.startPassage) {
1903
+ startName = options.startPassage;
1904
+ } else if (story.twine2.start) {
1905
+ startName = story.twine2.start;
1906
+ } else {
1907
+ startName = DEFAULT_START_NAME;
1908
+ }
1909
+ if (testMode) {
1910
+ story.twine2.options.set("debug", true);
1911
+ }
1912
+ let output;
1913
+ switch (outputMode) {
1914
+ case "twee3":
1915
+ case "twee1":
1916
+ output = toTwee(story, outputMode);
1917
+ break;
1918
+ case "twine2-archive":
1919
+ output = toTwine2Archive(story, startName, diagnostics);
1920
+ break;
1921
+ case "twine1-archive":
1922
+ output = toTwine1Archive(story, startName);
1923
+ break;
1924
+ case "json":
1925
+ output = storyToJSON(story);
1926
+ break;
1927
+ case "html":
1928
+ default: {
1929
+ if (!storyHas(story, startName)) {
1930
+ diagnostics.push({
1931
+ level: "error",
1932
+ message: `Starting passage "${startName}" not found.`
1933
+ });
1934
+ }
1935
+ if (!format) {
1936
+ throw new TweeTsError("No story format available for HTML output.", diagnostics);
1937
+ }
1938
+ if (format.isTwine2) {
1939
+ output = toTwine2HTML(story, format, startName, diagnostics);
1940
+ } else {
1941
+ if (story.name === "" && !storyHas(story, "StoryTitle")) {
1942
+ diagnostics.push({
1943
+ level: "error",
1944
+ message: 'Special passage "StoryTitle" not found.'
1945
+ });
1946
+ }
1947
+ output = toTwine1HTML(story, format, startName, diagnostics);
1948
+ }
1949
+ const modulePaths = options.modules ? getFilenames(options.modules) : [];
1950
+ output = modifyHead(output, modulePaths, options.headFile);
1951
+ break;
1952
+ }
1953
+ }
1954
+ const stats = {
1955
+ ...getStoryStats(story),
1956
+ files: [...processedFiles]
1957
+ };
1958
+ return { output, story, format, diagnostics, stats };
1959
+ }
1960
+ function storyToJSON(story) {
1961
+ return JSON.stringify({
1962
+ name: story.name,
1963
+ ifid: story.ifid,
1964
+ passages: story.passages.map((p) => ({
1965
+ name: p.name,
1966
+ tags: p.tags,
1967
+ text: p.text,
1968
+ metadata: p.metadata ?? null
1969
+ })),
1970
+ twine2: {
1971
+ format: story.twine2.format,
1972
+ formatVersion: story.twine2.formatVersion,
1973
+ start: story.twine2.start,
1974
+ tagColors: Object.fromEntries(story.twine2.tagColors),
1975
+ options: Object.fromEntries(story.twine2.options),
1976
+ zoom: story.twine2.zoom
1977
+ }
1978
+ }, null, 2);
1979
+ }
1980
+
1981
+ // src/inspect.ts
1982
+ function extractLinksFromText(text) {
1983
+ const targets = /* @__PURE__ */ new Set();
1984
+ const wikiLinkRe = /\[\[([^\]]+)\]\]/g;
1985
+ let m;
1986
+ while ((m = wikiLinkRe.exec(text)) !== null) {
1987
+ const content = m[1];
1988
+ const arrowIdx = content.indexOf("->");
1989
+ if (arrowIdx !== -1) {
1990
+ targets.add(content.slice(arrowIdx + 2).trim());
1991
+ continue;
1992
+ }
1993
+ const pipeIdx = content.indexOf("|");
1994
+ if (pipeIdx !== -1) {
1995
+ targets.add(content.slice(pipeIdx + 1).trim());
1996
+ continue;
1997
+ }
1998
+ targets.add(content.trim());
1999
+ }
2000
+ const gotoRe = /<<goto\s+["']([^"']+)["']\s*>>/g;
2001
+ while ((m = gotoRe.exec(text)) !== null) {
2002
+ targets.add(m[1]);
2003
+ }
2004
+ const linkMacroRe = /<<link\s+["'][^"']*["']\s+["']([^"']+)["']\s*>>/g;
2005
+ while ((m = linkMacroRe.exec(text)) !== null) {
2006
+ targets.add(m[1]);
2007
+ }
2008
+ return [...targets];
2009
+ }
2010
+ function storyInspect(story) {
2011
+ const allNames = new Set(story.passages.map((p) => p.name));
2012
+ const passages = [];
2013
+ const storyPassages = [];
2014
+ const infoPassages = [];
2015
+ const tagSet = /* @__PURE__ */ new Set();
2016
+ const passagesByTag = /* @__PURE__ */ new Map();
2017
+ const tagsByPassage = /* @__PURE__ */ new Map();
2018
+ const links = /* @__PURE__ */ new Map();
2019
+ for (const p of story.passages) {
2020
+ passages.push(p.name);
2021
+ if (isStoryPassage(p)) {
2022
+ storyPassages.push(p.name);
2023
+ }
2024
+ if (isInfoPassage(p)) {
2025
+ infoPassages.push(p.name);
2026
+ }
2027
+ tagsByPassage.set(p.name, [...p.tags]);
2028
+ for (const tag of p.tags) {
2029
+ tagSet.add(tag);
2030
+ let list = passagesByTag.get(tag);
2031
+ if (!list) {
2032
+ list = [];
2033
+ passagesByTag.set(tag, list);
2034
+ }
2035
+ list.push(p.name);
2036
+ }
2037
+ const targets = extractLinksFromText(p.text);
2038
+ links.set(p.name, targets);
2039
+ }
2040
+ const brokenLinks = [];
2041
+ for (const [from, targets] of links) {
2042
+ for (const to of targets) {
2043
+ if (!allNames.has(to)) {
2044
+ brokenLinks.push({ from, to });
2045
+ }
2046
+ }
2047
+ }
2048
+ const deadEnds = [];
2049
+ for (const name of storyPassages) {
2050
+ const targets = links.get(name);
2051
+ if (!targets || targets.length === 0) {
2052
+ deadEnds.push(name);
2053
+ }
2054
+ }
2055
+ const start = story.twine2.start || "Start";
2056
+ const linkedTo = /* @__PURE__ */ new Set();
2057
+ for (const targets of links.values()) {
2058
+ for (const t of targets) {
2059
+ linkedTo.add(t);
2060
+ }
2061
+ }
2062
+ const orphans = [];
2063
+ for (const name of storyPassages) {
2064
+ if (name !== start && !linkedTo.has(name)) {
2065
+ orphans.push(name);
2066
+ }
2067
+ }
2068
+ return {
2069
+ passages,
2070
+ storyPassages,
2071
+ infoPassages,
2072
+ tags: [...tagSet].sort(),
2073
+ passagesByTag,
2074
+ tagsByPassage,
2075
+ links,
2076
+ brokenLinks,
2077
+ deadEnds,
2078
+ orphans,
2079
+ start
2080
+ };
2081
+ }
2082
+
2083
+ // src/config.ts
2084
+ var import_node_fs8 = require("fs");
2085
+ var import_node_path8 = require("path");
2086
+ var CONFIG_FILENAME = "twee-ts.config.json";
2087
+ var VALID_OUTPUT_MODES = ["html", "twee3", "twee1", "twine2-archive", "twine1-archive", "json"];
2088
+ function loadConfig(dir) {
2089
+ const base = dir ?? process.cwd();
2090
+ const configPath = (0, import_node_path8.join)(base, CONFIG_FILENAME);
2091
+ if (!(0, import_node_fs8.existsSync)(configPath)) return null;
2092
+ let raw;
2093
+ try {
2094
+ raw = (0, import_node_fs8.readFileSync)(configPath, "utf-8");
2095
+ } catch {
2096
+ return null;
2097
+ }
2098
+ let data;
2099
+ try {
2100
+ data = JSON.parse(raw);
2101
+ } catch (e) {
2102
+ throw new Error(`Invalid JSON in ${configPath}: ${e instanceof Error ? e.message : String(e)}`);
2103
+ }
2104
+ const errors = validateConfig(data);
2105
+ if (errors.length > 0) {
2106
+ throw new Error(`Invalid config in ${configPath}:
2107
+ ${errors.join("\n ")}`);
2108
+ }
2109
+ return data;
2110
+ }
2111
+ function loadConfigFile(filePath) {
2112
+ let raw;
2113
+ try {
2114
+ raw = (0, import_node_fs8.readFileSync)(filePath, "utf-8");
2115
+ } catch (e) {
2116
+ throw new Error(`Cannot read config file ${filePath}: ${e instanceof Error ? e.message : String(e)}`);
2117
+ }
2118
+ let data;
2119
+ try {
2120
+ data = JSON.parse(raw);
2121
+ } catch (e) {
2122
+ throw new Error(`Invalid JSON in ${filePath}: ${e instanceof Error ? e.message : String(e)}`);
2123
+ }
2124
+ const errors = validateConfig(data);
2125
+ if (errors.length > 0) {
2126
+ throw new Error(`Invalid config in ${filePath}:
2127
+ ${errors.join("\n ")}`);
2128
+ }
2129
+ return data;
2130
+ }
2131
+ function validateConfig(data) {
2132
+ const errors = [];
2133
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
2134
+ errors.push("Config must be a JSON object.");
2135
+ return errors;
2136
+ }
2137
+ const obj = data;
2138
+ for (const key of ["output", "formatId", "startPassage", "headFile"]) {
2139
+ if (key in obj && typeof obj[key] !== "string") {
2140
+ errors.push(`"${key}" must be a string.`);
2141
+ }
2142
+ }
2143
+ for (const key of ["useTweegoPath", "trim", "twee2Compat", "testMode", "noRemote"]) {
2144
+ if (key in obj && typeof obj[key] !== "boolean") {
2145
+ errors.push(`"${key}" must be a boolean.`);
2146
+ }
2147
+ }
2148
+ for (const key of ["sources", "formatPaths", "formatIndices", "formatUrls", "modules"]) {
2149
+ if (key in obj) {
2150
+ if (!Array.isArray(obj[key])) {
2151
+ errors.push(`"${key}" must be an array.`);
2152
+ } else if (!obj[key].every((v) => typeof v === "string")) {
2153
+ errors.push(`"${key}" must be an array of strings.`);
2154
+ }
2155
+ }
2156
+ }
2157
+ if ("tagAliases" in obj) {
2158
+ if (typeof obj["tagAliases"] !== "object" || obj["tagAliases"] === null || Array.isArray(obj["tagAliases"])) {
2159
+ errors.push('"tagAliases" must be an object.');
2160
+ } else {
2161
+ const aliases = obj["tagAliases"];
2162
+ for (const [key, val] of Object.entries(aliases)) {
2163
+ if (typeof val !== "string") {
2164
+ errors.push(`"tagAliases.${key}" must be a string.`);
2165
+ }
2166
+ }
2167
+ }
2168
+ }
2169
+ if ("outputMode" in obj) {
2170
+ if (typeof obj["outputMode"] !== "string" || !VALID_OUTPUT_MODES.includes(obj["outputMode"])) {
2171
+ errors.push(`"outputMode" must be one of: ${VALID_OUTPUT_MODES.join(", ")}.`);
2172
+ }
2173
+ }
2174
+ return errors;
2175
+ }
2176
+ function scaffoldConfig() {
2177
+ const config = {
2178
+ sources: ["src/"],
2179
+ output: "story.html"
2180
+ };
2181
+ return JSON.stringify(config, null, 2) + "\n";
2182
+ }
2183
+ // Annotate the CommonJS export names for ESM import in node:
2184
+ 0 && (module.exports = {
2185
+ CONFIG_FILENAME,
2186
+ TweeLexer,
2187
+ TweeTsError,
2188
+ applyTagAliases,
2189
+ compile,
2190
+ compileToFile,
2191
+ discoverCachedFormats,
2192
+ discoverFormats,
2193
+ fetchAndCacheFormat,
2194
+ fetchDirectFormat,
2195
+ generateIFID,
2196
+ getCacheDir,
2197
+ getFormatSearchDirs,
2198
+ loadConfig,
2199
+ loadConfigFile,
2200
+ parseFormatJSON,
2201
+ parseSemver,
2202
+ parseTwee,
2203
+ resolveRemoteFormat,
2204
+ scaffoldConfig,
2205
+ semverCompare,
2206
+ storyInspect,
2207
+ tweeLexer,
2208
+ validateConfig,
2209
+ validateIFID,
2210
+ watch
2211
+ });
2212
+ //# sourceMappingURL=index.cjs.map