-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
1557 lines (1362 loc) · 65.6 KB
/
app.ts
File metadata and controls
1557 lines (1362 loc) · 65.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// useful — instructional course builder
// Run: deno run --allow-net --allow-read --allow-write --allow-env=HOME --allow-run app.ts [--config <path>]
// deno-lint-ignore-file no-explicit-any
import { parseSlides } from "./core/slide-parser.js";
// ─── Paths ───────────────────────────────────────────────────────────────────
const BASE = import.meta.dirname!;
const cfgFlagIdx = Deno.args.indexOf("--config");
const CONFDIR = (cfgFlagIdx >= 0 && Deno.args[cfgFlagIdx + 1])
? Deno.args[cfgFlagIdx + 1]
: `${BASE}/.config`;
const CONFILE = `${CONFDIR}/config.json`;
const STATIC = `${BASE}/core`;
const EXTRA = `${BASE}/extra`;
// ─── ffmpeg availability (checked at startup) ─────────────────────────────────
let FFMPEG_AVAILABLE = false;
// ─── Types ───────────────────────────────────────────────────────────────────
interface Config { projectDir: string | null; exportDir: string | null; }
interface CourseMeta { title?: string; description?: string; thumbnail?: string; author?: string; tags?: string[]; siteUrl?: string; }
interface ModuleMeta { title?: string; description?: string; type?: string; }
interface Course { name: string; contents: string[]; }
interface AudioMeta { text: string; duration: number; }
interface TrackClip { file: string; startTime: number; duration: number; }
// ─── Config ──────────────────────────────────────────────────────────────────
async function readConfig(): Promise<Config> {
try {
const data = JSON.parse(await Deno.readTextFile(CONFILE));
return { projectDir: data.projectDir ?? null, exportDir: data.exportDir ?? null };
}
catch { return { projectDir: null, exportDir: null }; }
}
async function writeConfig(config: Config): Promise<void> {
await Deno.mkdir(CONFDIR, { recursive: true });
await Deno.writeTextFile(CONFILE, JSON.stringify(config, null, 2));
}
// ─── Voice preference (per-project) ──────────────────────────────────────────
function voiceFile(pd: string) { return `${pd}/_voice.json`; }
async function readVoice(pd: string): Promise<string> {
try { return (JSON.parse(await Deno.readTextFile(voiceFile(pd)))).voice ?? "cosette"; }
catch { return "cosette"; }
}
async function writeVoice(pd: string, voice: string): Promise<void> {
await Deno.writeTextFile(voiceFile(pd), JSON.stringify({ voice }, null, 2));
}
// ─── Course / module metadata ────────────────────────────────────────────────
function courseMetaFile(pd: string, course: string) { return `${pd}/${course}/_meta.json`; }
function moduleMetaFile(pd: string, course: string, mod: string) { return `${pd}/${course}/${mod}/_meta.json`; }
async function readMeta<T>(path: string): Promise<T> {
try { return JSON.parse(await Deno.readTextFile(path)); }
catch { return {} as T; }
}
async function writeMeta(path: string, data: unknown): Promise<void> {
await Deno.writeTextFile(path, JSON.stringify(data, null, 2));
}
// ─── TTS server management ────────────────────────────────────────────────────
let TTS_PORT = 0;
async function waitForTtsServer(port: number): Promise<void> {
for (let i = 0; i < 60; i++) {
await new Promise(r => setTimeout(r, 500));
try {
const r = await fetch(`http://localhost:${port}/v1/voices`);
await r.body?.cancel();
if (r.ok) return;
} catch { /* not ready yet */ }
}
throw new Error(`TTS server did not start on port ${port}`);
}
// Re-register all stored custom voices after a TTS server restart
async function registerStoredVoices(port: number, voicesDir: string): Promise<void> {
try {
for await (const entry of Deno.readDir(voicesDir)) {
if (!entry.name.endsWith(".wav")) continue;
const name = entry.name.replace(/\.wav$/, "");
try {
const wav = await Deno.readFile(`${voicesDir}/${entry.name}`);
await fetch(
`http://localhost:${port}/v1/voices?name=${encodeURIComponent(name)}`,
{ method: "POST", headers: { "Content-Type": "audio/wav" }, body: wav },
);
} catch { /* skip failed registrations */ }
}
} catch { /* voices dir may not exist yet */ }
}
// ─── Courses ─────────────────────────────────────────────────────────────────
async function listCourses(dir: string): Promise<Course[]> {
const courses: Course[] = [];
for await (const entry of Deno.readDir(dir)) {
if (!entry.isDirectory || entry.name.startsWith("_")) continue;
const contents: string[] = [];
try {
for await (const sub of Deno.readDir(`${dir}/${entry.name}`)) {
contents.push(sub.name);
}
} catch { /* skip unreadable */ }
courses.push({ name: entry.name, contents });
}
return courses.sort((a, b) => a.name.localeCompare(b.name));
}
// ─── Modules ─────────────────────────────────────────────────────────────────
const INITIAL_SLIDES = `=== 5\nWelcome to this module.\n\n=== 5\nAdd your slide content here.\n`;
function mDir(pd: string, c: string, m: string) { return `${pd}/${c}/${m}`; }
function modulesFile(pd: string, c: string) { return `${pd}/${c}/modules.json`; }
function slidesFile(pd: string, c: string, m: string) { return `${mDir(pd,c,m)}/slides.txt`; }
function trackFile(pd: string, c: string, m: string) { return `${mDir(pd,c,m)}/track.json`; }
function audioDir(pd: string, c: string, m: string) { return `${mDir(pd,c,m)}/audio`; }
async function readModules(pd: string, course: string): Promise<string[]> {
try { return JSON.parse(await Deno.readTextFile(modulesFile(pd, course))); }
catch { return []; }
}
async function writeModules(pd: string, course: string, mods: string[]): Promise<void> {
await Deno.writeTextFile(modulesFile(pd, course), JSON.stringify(mods, null, 2));
}
// Fix WAV header sizes (streaming WAVs use 0xFFFFFFFF sentinel) and return duration in seconds.
async function fixAndMeasureWav(path: string): Promise<number> {
try {
const fileSize = (await Deno.stat(path)).size;
const fh = await Deno.open(path, { read: true, write: true });
const buf = new Uint8Array(512);
const n = (await fh.read(buf)) ?? 0;
if (n < 12) { fh.close(); return 0; }
const view = new DataView(buf.buffer, 0, n);
let pos = 12; // skip RIFF(4) + fileSize(4) + WAVE(4)
let byteRate = 0;
let dataPos = -1;
while (pos + 8 <= n) {
const id = String.fromCharCode(buf[pos], buf[pos+1], buf[pos+2], buf[pos+3]);
const chunkSize = view.getUint32(pos + 4, true);
if (id === 'fmt ' && pos + 20 <= n) {
byteRate = view.getUint32(pos + 16, true);
pos += 8 + chunkSize + (chunkSize & 1);
} else if (id === 'data') {
dataPos = pos;
break;
} else {
pos += 8 + chunkSize + (chunkSize & 1);
}
}
if (dataPos < 0 || byteRate === 0) { fh.close(); return 0; }
const dataSize = fileSize - (dataPos + 8);
view.setUint32(4, fileSize - 8, true); // fix RIFF chunk size
view.setUint32(dataPos + 4, dataSize, true); // fix data chunk size
await fh.seek(0, Deno.SeekMode.Start);
await fh.write(buf.subarray(0, n));
fh.close();
return byteRate > 0 ? dataSize / byteRate : 0;
} catch { return 0; }
}
// ─── Static file serving ─────────────────────────────────────────────────────
const MIME: Record<string, string> = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".png": "image/png",
".jpg": "image/jpeg",
".wav": "audio/wav",
};
async function serveFile(pathname: string): Promise<Response> {
if (pathname.includes("..")) return new Response("Forbidden", { status: 403 });
const target = (pathname === "/" || pathname === "")
? `${STATIC}/index.html`
: `${STATIC}${pathname}`;
const ext = "." + target.split(".").pop()!.toLowerCase();
try {
const data = await Deno.readFile(target);
return new Response(data, { headers: { "Content-Type": MIME[ext] ?? "application/octet-stream" } });
} catch {
return new Response("Not Found", { status: 404 });
}
}
// ─── Export engine ───────────────────────────────────────────────────────────
interface ExportModState { state: "pending" | "done" | "error"; error?: string; }
interface ExportJob {
state: "running" | "done" | "error";
progress: { done: number; total: number };
modules: Record<string, ExportModState>;
path?: string;
error?: string;
}
interface ModuleEntry {
slug: string; title: string; description: string; type: string;
duration: number; path: string; audioError?: string;
}
const exportJobs = new Map<string, ExportJob>();
function slugify(s: string): string {
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "untitled";
}
function escapeHtml(s: string): string {
return String(s)
.replace(/&/g, "&").replace(/</g, "<")
.replace(/>/g, ">").replace(/"/g, """);
}
function spansToHtml(spans: any[]): string {
return (spans ?? []).map((s: any): string => {
switch (s.type) {
case "text": return escapeHtml(s.text ?? "");
case "bold": return `<strong>${spansToHtml(s.children)}</strong>`;
case "italic": return `<em>${spansToHtml(s.children)}</em>`;
case "underline": return `<u>${spansToHtml(s.children)}</u>`;
default: return "";
}
}).join("");
}
function blockToHtml(b: any, assetBase: string): string {
switch (b.type) {
case "paragraph": return `<p>${spansToHtml(b.spans)}</p>`;
case "heading": {
const lv = (b.level ?? 1) + 1; // slide h1 → <h2> (h1 is module title)
return `<h${lv}>${spansToHtml(b.spans)}</h${lv}>`;
}
case "list": {
const tag = b.ordered ? "ol" : "ul";
const items = (b.items ?? []).map((i: any[]) => `<li>${spansToHtml(i)}</li>`).join("");
return `<${tag}>${items}</${tag}>`;
}
case "code": {
const cls = b.lang ? ` class="language-${escapeHtml(b.lang)}"` : "";
return `<pre><code${cls}>${escapeHtml(b.text ?? "")}</code></pre>`;
}
case "image": {
const file = decodeURIComponent((b.src ?? "").replace("/api/inject/", ""));
return `<figure><img src="${assetBase}/${escapeHtml(file)}" alt="" loading="lazy"></figure>`;
}
case "emph":
return `<div class="emph">${(b.blocks ?? []).map((x: any) => blockToHtml(x, assetBase)).join("")}</div>`;
case "columns":
return `<div class="columns">${(b.cols ?? []).map((c: any) =>
`<div class="col">${(c.blocks ?? []).map((x: any) => blockToHtml(x, assetBase)).join("")}</div>`
).join("")}</div>`;
case "plugin":
return `<!-- plugin: ${escapeHtml(b.file ?? "")} -->`;
default: return "";
}
}
// Collect inject file references from a slide AST block (recursive)
function collectInjectRefs(block: any, refs: Set<string>, pluginFiles: Set<string>): void {
if (block.type === "image") {
const src: string = block.src ?? "";
if (src.startsWith("/api/inject/")) refs.add(decodeURIComponent(src.slice(12)));
} else if (block.type === "plugin") {
if (block.file) { refs.add(block.file); pluginFiles.add(block.file); }
if (block.dataFile) refs.add(block.dataFile);
} else if (Array.isArray(block.blocks)) {
for (const b of block.blocks) collectInjectRefs(b, refs, pluginFiles);
} else if (Array.isArray(block.cols)) {
// columns block — each col has a .blocks array
for (const col of block.cols) {
for (const b of col.blocks ?? []) collectInjectRefs(b, refs, pluginFiles);
}
}
}
// Analyse which _inject/ files a course actually references across all modules
async function analyzeInjectFiles(course: string, pd: string): Promise<{
referencedFiles: string[];
hasPlugins: boolean;
allInjectFiles: string[];
}> {
const modules = await readModules(pd, course);
const courseMeta = await readMeta<CourseMeta>(courseMetaFile(pd, course));
const refs = new Set<string>();
const pluginFiles = new Set<string>();
if (courseMeta.thumbnail) refs.add(courseMeta.thumbnail);
for (const mod of modules) {
try {
const text = await Deno.readTextFile(slidesFile(pd, course, mod));
const slides = parseSlides(text);
for (const slide of slides) {
for (const block of (slide as any).body ?? []) {
collectInjectRefs(block, refs, pluginFiles);
}
}
} catch { /* slides.txt missing */ }
}
// Safety: reject filenames that look like path traversal
const safe = (f: string) => f.length > 0 && !f.includes("/") && !f.includes("..");
const referencedFiles = [...refs].filter(safe);
const allInjectFiles: string[] = [];
try {
for await (const e of Deno.readDir(`${pd}/_inject`)) {
if (e.isFile) allInjectFiles.push(e.name);
}
allInjectFiles.sort();
} catch { /* _inject may not exist */ }
return { referencedFiles, hasPlugins: pluginFiles.size > 0, allInjectFiles };
}
// Rewrite /api/inject/<file> → assets/<file> in parsed slide AST (for slides.json)
function rewriteInjectPaths(obj: any): any {
return JSON.parse(JSON.stringify(obj), (_: string, v: any) => {
if (typeof v === "string" && v.startsWith("/api/inject/")) {
return `assets/${decodeURIComponent(v.slice(12))}`;
}
return v;
});
}
// Extract plain text of the first heading across all slides (description fallback)
function firstHeadingText(slides: any[]): string {
for (const slide of slides) {
for (const b of (slide.body ?? [])) {
if (b.type === "heading") return spansToHtml(b.spans).replace(/<[^>]+>/g, "");
}
}
return "";
}
// Run ffmpeg to assemble audio clips → HLS stream in outDir.
// slidesDuration caps the output so audio never runs past the last slide.
async function runHlsExport(clips: TrackClip[], aDir: string, outDir: string, slidesDuration: number): Promise<void> {
const inputArgs: string[] = [];
for (const c of clips) inputArgs.push("-i", `${aDir}/${c.file}`);
let filterComplex: string;
if (clips.length === 1) {
const ms = Math.round(clips[0].startTime * 1000);
filterComplex = `[0:a]adelay=${ms}|${ms}[out]`;
} else {
const parts: string[] = [];
const labels: string[] = [];
for (let i = 0; i < clips.length; i++) {
const ms = Math.round(clips[i].startTime * 1000);
parts.push(`[${i}:a]adelay=${ms}|${ms}[a${i}]`);
labels.push(`[a${i}]`);
}
// normalize=0: keep each clip at original volume (default normalize=1 scales by 1/N)
parts.push(`${labels.join("")}amix=inputs=${clips.length}:duration=longest:normalize=0[out]`);
filterComplex = parts.join(";");
}
const clipsDuration = clips.reduce((max, c) => Math.max(max, c.startTime + c.duration), 0);
// Cap at slidesDuration: slides are authoritative for runtime
const totalDuration = Math.min(clipsDuration, slidesDuration);
const r = await new Deno.Command("ffmpeg", {
args: [
"-y", ...inputArgs,
"-filter_complex", filterComplex,
"-map", "[out]",
"-t", String(totalDuration),
"-c:a", "aac", "-b:a", "64k", "-ar", "22050", "-ac", "1",
"-hls_time", "4",
"-hls_playlist_type", "vod",
"-hls_segment_filename", `${outDir}/audio-%03d.ts`,
`${outDir}/audio.m3u8`,
],
stdout: "null",
stderr: "piped",
}).output();
if (!r.success) {
throw new Error(`ffmpeg: ${new TextDecoder().decode(r.stderr).slice(-500)}`);
}
}
// ── HTML templates ────────────────────────────────────────────────────────────
const DEFAULT_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<rect width="100" height="100" rx="20" fill="#1a1a2e"/>
<text x="50" y="68" font-size="60" text-anchor="middle" font-family="sans-serif" fill="#7c6af7">U</text>
</svg>`;
function buildModuleHtml(opts: {
courseTitle: string; modTitle: string; modSlug: string;
description: string; slides: any[]; thumbnail: string | null; siteUrl?: string;
}): string {
const { courseTitle, modTitle, modSlug, description, slides, thumbnail, siteUrl } = opts;
const assetBase = "../../assets";
const base = siteUrl ? siteUrl.replace(/\/$/, "") : "";
const absThumb = base && thumbnail ? `${base}/assets/thumbnail.jpg` : "";
const ogImg = absThumb || (thumbnail ? `../../${thumbnail}` : "");
const ogUrl = base ? `${base}/modules/${modSlug}/` : "";
const body = slides.map((s: any, i: number) => {
const blocks = (s.body ?? []).map((b: any) => ` ${blockToHtml(b, assetBase)}`).join("\n");
return ` <section class="slide" data-duration="${s.duration}" data-index="${i}">\n${blocks}\n </section>`;
}).join("\n");
const ld = JSON.stringify({
"@context": "https://schema.org",
"@type": "CourseSection",
"name": modTitle,
"description": description,
"isPartOf": { "@type": "Course", "name": courseTitle },
});
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(modTitle)} — ${escapeHtml(courseTitle)}</title>
<meta name="description" content="${escapeHtml(description)}">
<meta property="og:title" content="${escapeHtml(modTitle)}">
<meta property="og:description" content="${escapeHtml(description)}">
${ogImg ? `<meta property="og:image" content="${escapeHtml(ogImg)}">` : ""}
<meta property="og:type" content="article">
${ogUrl ? `<meta property="og:url" content="${escapeHtml(ogUrl)}">` : ""}
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="${escapeHtml(modTitle)}">
<meta name="twitter:description" content="${escapeHtml(description)}">
${absThumb ? `<meta name="twitter:image" content="${escapeHtml(absThumb)}">` : ""}
<link rel="canonical" href="../../index.html#module=${encodeURIComponent(modSlug)}">
<link rel="icon" href="../../favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="../../player.css">
<link rel="manifest" href="../../manifest.webmanifest">
<script type="application/ld+json">${ld}</script>
</head>
<body>
<main id="app" data-module="${escapeHtml(modSlug)}" data-course-root="../..">
<article class="module-content" aria-label="Module slide content">
<h1>${escapeHtml(modTitle)}</h1>
${body}
</article>
</main>
<script type="module" src="../../player.js"></script>
</body>
</html>`;
}
function buildCourseIndexHtml(meta: CourseMeta, courseName: string, modules: ModuleEntry[]): string {
const title = meta.title ?? courseName;
const description = meta.description ?? "";
const thumbnail = meta.thumbnail ? "assets/thumbnail.jpg" : "";
const base = meta.siteUrl ? meta.siteUrl.replace(/\/$/, "") : "";
const absThumb = base && thumbnail ? `${base}/${thumbnail}` : "";
const ogImg = absThumb || thumbnail;
const ogUrl = base || "";
const modList = modules.map(m =>
` <li><a href="${escapeHtml(m.path)}">${escapeHtml(m.title)}</a></li>`
).join("\n");
const ld = JSON.stringify({
"@context": "https://schema.org",
"@type": "Course",
"name": title,
"description": description,
...(meta.author ? { "author": { "@type": "Person", "name": meta.author } } : {}),
"hasPart": modules.map((m, i) => ({
"@type": "CourseSection", "position": i + 1, "name": m.title, "description": m.description,
})),
});
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(title)}</title>
<meta name="description" content="${escapeHtml(description)}">
<meta property="og:title" content="${escapeHtml(title)}">
<meta property="og:description" content="${escapeHtml(description)}">
${ogImg ? `<meta property="og:image" content="${escapeHtml(ogImg)}">` : ""}
<meta property="og:type" content="website">
${ogUrl ? `<meta property="og:url" content="${escapeHtml(ogUrl)}/">` : ""}
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="${escapeHtml(title)}">
<meta name="twitter:description" content="${escapeHtml(description)}">
${absThumb ? `<meta name="twitter:image" content="${escapeHtml(absThumb)}">` : ""}
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="player.css">
<link rel="manifest" href="manifest.webmanifest">
<script type="application/ld+json">${ld}</script>
</head>
<body>
<main id="app">
<nav id="module-list" aria-label="Course modules">
<h1>${escapeHtml(title)}</h1>
<ul>
${modList}
</ul>
</nav>
<section id="player"></section>
</main>
<script type="module" src="player.js"></script>
</body>
</html>`;
}
function buildWebManifest(meta: CourseMeta, courseName: string, pngIconSizes: number[] = []): Record<string, unknown> {
const name = meta.title ?? courseName;
const words = name.split(/\s+/);
const shortName = words.length > 3 ? words.slice(0, 3).join(" ") : name;
const icons = pngIconSizes.map(size => ({
src: `assets/icon-${size}.png`, sizes: `${size}x${size}`, type: "image/png", purpose: "any",
}));
const manifest: Record<string, unknown> = {
name, short_name: shortName,
description: meta.description ?? "",
start_url: "./index.html",
display: "standalone",
background_color: "#0d0d0f",
theme_color: "#0d0d0f",
};
if (icons.length) manifest.icons = icons;
return manifest;
}
function buildSwJs(timestamp: number, assets: string[], hashes: Record<string, string>, sizes: Record<string, number>): string {
// Split into static assets (fetched in parallel) and HLS segments (fetched sequentially
// to avoid saturating the server). Both are precached during install.
// Using fetch(new Request(url)) (plain GET, no Range header) ensures Caddy returns 200
// rather than 206, which is required for cache.put().
const segments = assets.filter(a => a.endsWith('.ts'));
const statics = assets.filter(a => !a.endsWith('.ts'));
const hashJson = JSON.stringify(hashes, null, 2);
const staticList = JSON.stringify(statics.map(a => `./${a}`), null, 2);
const segList = JSON.stringify(segments.map(a => `./${a}`), null, 2);
// Segment sizes (bytes) keyed by URL — used by GET_UPDATE_SIZE to estimate download delta.
const segSizes: Record<string, number> = {};
for (const s of segments) segSizes[`./${s}`] = sizes[`./${s}`] ?? 0;
const sizesJson = JSON.stringify(segSizes, null, 2);
return `// Generated service worker — useful course export
const CACHE = 'useful-course-${timestamp}';
const HASHES = ${hashJson};
const SIZES = ${sizesJson};
const STATIC = ${staticList};
const SEGMENTS = ${segList};
// First install: no previous cache → activate immediately so the page is
// controlled before hls.js makes its first segment request.
// Update (re-export): previous cache exists → stay in waiting until the user
// confirms the update via the player UI (receives SKIP_WAITING message).
self.addEventListener('install', e => {
e.waitUntil((async () => {
const oldKey = (await caches.keys()).find(k => k !== CACHE && k.startsWith('useful-course-'));
if (!oldKey) self.skipWaiting();
})());
});
self.addEventListener('activate', e => {
e.waitUntil((async () => {
const newCache = await caches.open(CACHE);
// Find the previous cache (if any) to reuse files whose hash hasn't changed,
// avoiding a full re-download on every re-export.
const oldKey = (await caches.keys()).find(k => k !== CACHE && k.startsWith('useful-course-'));
const oldCache = oldKey ? await caches.open(oldKey) : null;
const oldHashes = oldCache
? await oldCache.match('__hashes').then(r => r ? r.json() : {}).catch(() => ({}))
: {};
async function cacheOne(url) {
// Skip if already in new cache (e.g. stored by the runtime populate handler)
if (await newCache.match(url)) return;
const hash = HASHES[url];
if (hash && oldCache && oldHashes[url] === hash) {
const hit = await oldCache.match(url);
if (hit) { await newCache.put(url, hit); return; }
}
try {
const r = await fetch(new Request(url));
if (r.status === 200) await newCache.put(url, r);
} catch {}
}
// Claim clients first so the runtime fetch handler starts intercepting
// immediately — any segment fetched live by hls.js will be cached on the fly.
await self.clients.claim();
// Static assets (fast, parallel).
await Promise.all(STATIC.map(cacheOne));
// Migrate HLS segments. Runs on re-export (oldCache exists) so the
// offline-first state is fully preserved and extended after content updates:
// • Unchanged segment (hash match) → copied in-memory, zero network.
// • Changed or new segment → fetched from network.
// Every segment ends up in the new cache so the course remains fully
// available offline without a second manual install step.
// Progress messages let the player show a caching status bar.
// First installs (no oldCache) still defer segments to the install-prompt path.
if (oldCache) {
const total = SEGMENTS.length;
const step = Math.max(1, Math.floor(total * 0.05));
let done = 0;
async function notifyClients(msg) {
const clients = await self.clients.matchAll({ type: 'window' });
for (const c of clients) c.postMessage(msg);
}
if (total > 0) await notifyClients({ type: 'sw-caching', done: 0, total });
for (const url of SEGMENTS) {
if (!await newCache.match(url)) {
const oldEntry = await oldCache.match(url);
const hash = HASHES[url];
if (oldEntry && hash && oldHashes[url] === hash) {
await newCache.put(url, oldEntry); // unchanged — copy, no network hit
} else {
try {
const r = await fetch(new Request(url));
if (r.status === 200) await newCache.put(url, r);
} catch {}
}
}
done++;
if (done % step === 0 || done === total) {
await notifyClients({ type: 'sw-caching', done, total });
}
}
if (total > 0) await notifyClients({ type: 'sw-ready' });
}
// Persist hash snapshot (statics + segments) for the next re-export comparison.
await newCache.put('__hashes', new Response(JSON.stringify(HASHES),
{ headers: { 'Content-Type': 'application/json' } }));
// Delete old cache only after everything has been safely migrated.
if (oldKey) await caches.delete(oldKey);
})());
});
// Triggered by the player when the user accepts the PWA install prompt.
// Downloads all HLS segments so the full course is available offline.
// Also handles SKIP_WAITING sent when the user confirms a content update,
// and GET_UPDATE_SIZE which queries how many bytes will need to be downloaded.
self.addEventListener('message', e => {
if (e.data?.type === 'SKIP_WAITING') { self.skipWaiting(); return; }
// Reply with the number of bytes that would be fetched from the network on
// update: segments whose hash has changed or that are entirely new.
// Uses a MessageChannel port so the reply goes only to the asking client.
if (e.data?.type === 'GET_UPDATE_SIZE') {
(async () => {
const oldKey = (await caches.keys()).find(k => k !== CACHE && k.startsWith('useful-course-'));
const oldCache = oldKey ? await caches.open(oldKey) : null;
const oldHashes = oldCache
? await oldCache.match('__hashes').then(r => r ? r.json() : {}).catch(() => ({}))
: {};
let bytes = 0;
for (const url of SEGMENTS) {
if (oldHashes[url] !== HASHES[url]) bytes += SIZES[url] ?? 0;
}
e.ports[0]?.postMessage({ bytes });
})();
return;
}
if (e.data?.type !== 'precache-segments') return;
e.waitUntil((async () => {
const cache = await caches.open(CACHE);
async function notifyClients(msg) {
const clients = await self.clients.matchAll({ type: 'window' });
for (const c of clients) c.postMessage(msg);
}
const total = SEGMENTS.length;
await notifyClients({ type: 'sw-caching', done: 0, total });
const step = Math.max(1, Math.floor(total * 0.05));
let done = 0;
for (const url of SEGMENTS) {
if (!await cache.match(url)) {
try {
const r = await fetch(new Request(url));
if (r.status === 200) await cache.put(url, r);
} catch {}
}
done++;
if (done % step === 0 || done === total) {
await notifyClients({ type: 'sw-caching', done, total });
}
}
await notifyClients({ type: 'sw-ready' });
})());
});
self.addEventListener('fetch', e => {
// Only intercept same-origin GET requests.
// ignoreVary: true prevents Vary header mismatches from causing cache misses
// when hls.js or the browser adds headers (e.g. Accept-Encoding) that differ
// from those used during the install-time precache fetch.
if (e.request.method !== 'GET') return;
e.respondWith((async () => {
const cached = await caches.match(e.request, { ignoreVary: true });
if (cached) return cached;
// Cache miss — fetch live and populate the cache so segments fetched by
// hls.js before the SW claimed the page are available offline from now on.
const response = await fetch(e.request);
if (response.status === 200) {
const cache = await caches.open(CACHE);
cache.put(e.request, response.clone());
}
return response;
})());
});
`;
}
// ── Main export pipeline ──────────────────────────────────────────────────────
async function runExport(course: string, pd: string, expDir: string, includeFiles?: string[]): Promise<void> {
const job = exportJobs.get(course)!;
try {
const modules = await readModules(pd, course);
if (modules.length === 0) throw new Error("Course has no modules");
const courseSlug = slugify(course);
const outDir = `${expDir}/${courseSlug}`;
try { await Deno.remove(outDir, { recursive: true }); } catch { /* doesn't exist yet */ }
await Deno.mkdir(`${outDir}/assets`, { recursive: true });
const allFiles: string[] = [];
// hls.js
await Deno.copyFile(`${BASE}/extra/hls.js`, `${outDir}/hls.js`);
allFiles.push("hls.js");
// Open Sans fonts
await Deno.mkdir(`${outDir}/assets/fonts`, { recursive: true });
for (const font of ["OpenSans-Regular.woff2", "OpenSans-SemiBold.woff2", "OpenSans-Italic.woff2"]) {
try {
await Deno.copyFile(`${BASE}/extra/${font}`, `${outDir}/assets/fonts/${font}`);
allFiles.push(`assets/fonts/${font}`);
} catch { /* font file missing from extra/ — player will fall back to system-ui */ }
}
// Icons font (lives in core/font/)
try {
await Deno.copyFile(`${BASE}/core/font/icons.woff2`, `${outDir}/assets/fonts/icons.woff2`);
allFiles.push(`assets/fonts/icons.woff2`);
} catch { /* icons font missing */ }
// player.css + player.js — copy from core/export/ if present, else write stubs
for (const f of ["player.css", "player.js"]) {
const dst = `${outDir}/${f}`;
try { await Deno.copyFile(`${BASE}/core/export/${f}`, dst); }
catch {
await Deno.writeTextFile(dst, f.endsWith(".css")
? "/* player.css — phase 3 */"
: "// player.js — phase 3\nif ('serviceWorker' in navigator) {\n navigator.serviceWorker.register('./sw.js', { scope: './' }).catch(() => {});\n}\n");
}
allFiles.push(f);
}
// Course metadata
const courseMeta = await readMeta<CourseMeta>(courseMetaFile(pd, course));
const courseTitle = courseMeta.title ?? course;
// Thumbnail (source: _inject/<filename>)
if (courseMeta.thumbnail) {
try {
await Deno.copyFile(`${pd}/_inject/${courseMeta.thumbnail}`, `${outDir}/assets/thumbnail.jpg`);
allFiles.push("assets/thumbnail.jpg");
} catch { /* thumbnail missing from _inject */ }
}
// Icon (PWA)
try { await Deno.copyFile(`${BASE}/core/export/icon.svg`, `${outDir}/assets/icon.svg`); }
catch { await Deno.writeTextFile(`${outDir}/assets/icon.svg`, DEFAULT_ICON_SVG); }
allFiles.push("assets/icon.svg");
// PNG icons for PWA manifest (pre-generated; see core/export/icon-*.png)
const pngIconSizes: number[] = [];
for (const size of [192, 512]) {
try {
await Deno.copyFile(`${BASE}/core/export/icon-${size}.png`, `${outDir}/assets/icon-${size}.png`);
allFiles.push(`assets/icon-${size}.png`);
pngIconSizes.push(size);
} catch { /* PNG missing — skip */ }
}
// Favicon
try { await Deno.copyFile(`${BASE}/core/export/favicon.svg`, `${outDir}/favicon.svg`); }
catch { await Deno.writeTextFile(`${outDir}/favicon.svg`, DEFAULT_ICON_SVG); }
allFiles.push("favicon.svg");
// Copy selected _inject/ files to assets/ (auto-detected if not specified)
const filesToInclude = includeFiles ?? (await analyzeInjectFiles(course, pd)).referencedFiles;
for (const name of filesToInclude) {
if (name.includes("..") || name.includes("/")) continue;
await Deno.copyFile(`${pd}/_inject/${name}`, `${outDir}/assets/${name}`).catch(() => {});
const key = `assets/${name}`;
if (!allFiles.includes(key)) allFiles.push(key);
}
// Process each module
job.progress.total = modules.length;
const moduleEntries: ModuleEntry[] = [];
for (const modName of modules) {
const modSlug = slugify(modName);
const modOutDir = `${outDir}/modules/${modSlug}`;
await Deno.mkdir(modOutDir, { recursive: true });
job.modules[modSlug] = { state: "pending" };
try {
const modMeta = await readMeta<ModuleMeta>(moduleMetaFile(pd, course, modName));
const modTitle = modMeta.title ?? modName;
const modType = modMeta.type ?? "slides";
const rawSlides = parseSlides(
await Deno.readTextFile(slidesFile(pd, course, modName)).catch(() => "")
);
// Add audioStart offsets
let t = 0;
const timedSlides = rawSlides.map((s: any) => {
const audioStart = t;
t += (s.duration ?? 0);
return { ...s, audioStart };
});
const totalDuration = t;
const clips: TrackClip[] = JSON.parse(
await Deno.readTextFile(trackFile(pd, course, modName)).catch(() => "[]")
);
// HLS audio assembly
let hlsFile: string | null = null;
let audioError: string | undefined;
if (clips.length > 0) {
try {
await runHlsExport(clips, audioDir(pd, course, modName), modOutDir, totalDuration);
hlsFile = "audio.m3u8";
allFiles.push(`modules/${modSlug}/audio.m3u8`);
for await (const e of Deno.readDir(modOutDir)) {
if (e.name.endsWith(".ts")) allFiles.push(`modules/${modSlug}/${e.name}`);
}
} catch (e) {
audioError = String(e);
}
}
// slides.json
const slidesJson: Record<string, unknown> = {
audio: hlsFile,
totalDuration,
slides: timedSlides.map(rewriteInjectPaths),
};
if (audioError) slidesJson.audioError = audioError;
await Deno.writeTextFile(`${modOutDir}/slides.json`, JSON.stringify(slidesJson, null, 2));
allFiles.push(`modules/${modSlug}/slides.json`);
const description = modMeta.description ?? firstHeadingText(rawSlides);
// module index.html
await Deno.writeTextFile(`${modOutDir}/index.html`, buildModuleHtml({
courseTitle, modTitle, modSlug, description,
slides: rawSlides, thumbnail: courseMeta.thumbnail ? "assets/thumbnail.jpg" : null,
siteUrl: courseMeta.siteUrl,
}));
allFiles.push(`modules/${modSlug}/index.html`);
moduleEntries.push({
slug: modSlug, title: modTitle, description, type: modType,
duration: totalDuration, path: `modules/${modSlug}/index.html`,
...(audioError ? { audioError } : {}),
});
job.modules[modSlug] = { state: "done" };
} catch (e) {
job.modules[modSlug] = { state: "error", error: String(e) };
moduleEntries.push({
slug: modSlug, title: modName, description: "", type: "slides",
duration: 0, path: `modules/${modSlug}/index.html`,
});
}
job.progress.done++;
}
// modules/index.html — redirect to course root so bare /modules/ URLs don't 404
await Deno.writeTextFile(`${outDir}/modules/index.html`,
`<!doctype html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta http-equiv="refresh" content="0; url=../index.html">\n <link rel="canonical" href="../index.html">\n <title>Redirecting…</title>\n</head>\n<body>\n <p><a href="../index.html">Go to course</a></p>\n</body>\n</html>`);
allFiles.push("modules/index.html");
// Compute total HLS segment bytes for offline-size estimation shown in the player UI.
// Done here (before hash loop) so we can read each .ts file only once.
let offlineBytes = 0;
for (const f of allFiles) {
if (f.endsWith('.ts')) {
try { offlineBytes += (await Deno.stat(`${outDir}/${f}`)).size; } catch { /* ignore */ }
}
}
// manifest.json
const manifest: Record<string, unknown> = {
title: courseTitle,
description: courseMeta.description ?? "",
tags: courseMeta.tags ?? [],
modules: moduleEntries,
offlineBytes,
};
if (courseMeta.author) manifest.author = courseMeta.author;
if (courseMeta.thumbnail) manifest.thumbnail = "assets/thumbnail.jpg";
await Deno.writeTextFile(`${outDir}/manifest.json`, JSON.stringify(manifest, null, 2));
allFiles.push("manifest.json");
// course index.html
await Deno.writeTextFile(`${outDir}/index.html`,
buildCourseIndexHtml(courseMeta, course, moduleEntries));
allFiles.push("index.html");
// manifest.webmanifest
await Deno.writeTextFile(`${outDir}/manifest.webmanifest`,
JSON.stringify(buildWebManifest(courseMeta, course, pngIconSizes), null, 2));
allFiles.push("manifest.webmanifest");
// Compute SHA-256 hashes and byte sizes for all exported files.
// Hashes drive selective cache reuse on re-export; sizes are baked into sw.js
// so the player can show an estimated download cost before caching segments.
const hashes: Record<string, string> = {};
const sizes: Record<string, number> = {};
for (const f of allFiles) {
try {
const data = await Deno.readFile(`${outDir}/${f}`);
const buf = await crypto.subtle.digest('SHA-256', data);
hashes[`./${f}`] = Array.from(new Uint8Array(buf))
.map(b => b.toString(16).padStart(2, '0')).join('');
if (f.endsWith('.ts')) sizes[`./${f}`] = data.byteLength;
} catch { /* skip if file somehow missing */ }
}
// sw-manifest.json — asset list with integrity hashes (useful for debugging/tooling)
await Deno.writeTextFile(`${outDir}/sw-manifest.json`,
JSON.stringify(allFiles.map(f => ({ path: f, hash: hashes[`./${f}`] ?? '' })), null, 2));
// sw.js (precache list + hashes + segment sizes baked in)
await Deno.writeTextFile(`${outDir}/sw.js`, buildSwJs(Date.now(), allFiles, hashes, sizes));
allFiles.push("sw.js");
job.state = "done";
job.path = outDir;
} catch (e) {
job.state = "error";
job.error = String(e);
}
}
// ─── Request router ──────────────────────────────────────────────────────────
async function handle(req: Request): Promise<Response> {
const { pathname, searchParams } = new URL(req.url);
const method = req.method;
const seg = pathname.split("/").filter(Boolean); // ['api', 'resource', ...]
// ── Config ───────────────────────────────────────────────────────────────
if (pathname === "/api/config" && method === "GET") {
return Response.json(await readConfig());
}
if (pathname === "/api/config" && method === "POST") {
const body = await req.json() as { projectDir?: unknown };
if (typeof body.projectDir !== "string") {