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