-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.js
More file actions
1840 lines (1518 loc) · 57.2 KB
/
Copy pathbuild.js
File metadata and controls
1840 lines (1518 loc) · 57.2 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
const fs = require("node:fs");
const path = require("node:path");
const crypto = require("node:crypto");
const { execSync } = require("node:child_process");
const ROOT = process.cwd();
const PUBLIC_DIR = path.join(ROOT, "public");
const BUILD_CACHE_PATH = path.join(ROOT, "manual", "build-cache.json");
const BUILD_CACHE_VERSION = 1;
const ROOT_PAGES_DIR = ROOT;
const ROADMAP_LABS_DIR = path.join(ROOT, "roadmap", "labs");
const ROADMAP_DIR = path.join(ROOT, "roadmap");
const PROJECTS_DIR = path.join(ROOT, "projects");
const COMMUNITY_DIR = path.join(ROOT, "community");
const LAYOUTS_DIR = path.join(ROOT, "layouts");
const ASSETS_DIR = path.join(ROOT, "assets");
const SYSTEM_RUNTIME_FILES = ["robots.txt", "sitemap.xml"];
const PROGRAMMING_TOPIC_FOLDERS = [
"ada",
"assembly",
"bash",
"c",
"carbon",
"cpp",
"csharp",
"css",
"dart",
"flutter",
"fortran",
"go",
"html",
"java",
"julia",
"nim",
"php",
"plsql",
"python",
"react",
"ruby",
"rust",
"scala",
"script",
"svelte",
"swift",
"wasm",
"tscript",
"zig"
];
const LAB_ROUTE_MAP = {
engineering: "cse",
programming: "csp",
videos: "videos"
};
function getSupabaseBuildConfig() {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL || "";
const anonKey =
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY ||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||
process.env.SUPABASE_ANON_KEY ||
"";
const schema = process.env.SUPABASE_SCHEMA || "public";
if (!url || !anonKey) {
return null;
}
return { url, anonKey, schema };
}
function writeSupabaseConfigAsset() {
const sourcePath = path.join(ASSETS_DIR, "js", "supabase-config.js");
const destinationPath = path.join(PUBLIC_DIR, "assets", "js", "supabase-config.js");
const runtimeConfig = getSupabaseBuildConfig();
if (!fs.existsSync(sourcePath)) {
return;
}
if (!runtimeConfig) {
copyRecursive(sourcePath, destinationPath);
return;
}
const contents = [
"// Generated during build from Vercel environment variables.",
"(function () {",
" window.__SUPABASE_CONFIG__ = {",
` url: ${JSON.stringify(runtimeConfig.url)},`,
` anonKey: ${JSON.stringify(runtimeConfig.anonKey)},`,
` schema: ${JSON.stringify(runtimeConfig.schema)}`,
" };",
"})();",
""
].join("\n");
ensureDir(path.dirname(destinationPath));
fs.writeFileSync(destinationPath, contents, "utf8");
}
const ASSET_PATH_REWRITES = [
{ pattern: /(["'])\/(sage\.css)\1/g, replacement: "$1/assets/css/sage.css$1" },
{ pattern: /(["'])\/(carousel\.css)\1/g, replacement: "$1/assets/css/carousel.css$1" },
{ pattern: /(["'])\/(manifesto\.css)\1/g, replacement: "$1/assets/css/manifesto.css$1" },
{ pattern: /(["'])\/(prism\.css)\1/g, replacement: "$1/assets/css/prism.css$1" },
{ pattern: /(["'])\/(sage\.js)\1/g, replacement: "$1/assets/js/sage.js$1" },
{ pattern: /(["'])\/(sidebar\.js)\1/g, replacement: "$1/assets/js/sidebar.js$1" },
{ pattern: /(["'])\/(progress\.js)\1/g, replacement: "$1/assets/js/progress.js$1" },
{ pattern: /(["'])\/(home\.js)\1/g, replacement: "$1/assets/js/home.js$1" },
{ pattern: /(["'])\/(prism\.js)\1/g, replacement: "$1/assets/js/prism.js$1" },
{ pattern: /(["'])\/common\/([^"']+\.js)\1/g, replacement: "$1/assets/js/$2$1" },
{ pattern: /(["'])\.\.\/\.\.\/common\/([^"']+\.js)\1/g, replacement: "$1/assets/js/$2$1" },
{ pattern: /(["'])\.\.\/common\/([^"']+\.js)\1/g, replacement: "$1/assets/js/$2$1" },
{ pattern: /(["'])\.\/common\/([^"']+\.js)\1/g, replacement: "$1/assets/js/$2$1" },
{ pattern: /(["'])common\/([^"']+\.js)\1/g, replacement: "$1/assets/js/$2$1" },
{ pattern: /(["'])\/(images\/)\1/g, replacement: "$1/assets/images/$1" },
{ pattern: /(["'])\.\.\/\.\.\/images\//g, replacement: "$1/assets/images/" },
{ pattern: /(["'])\.\.\/images\//g, replacement: "$1/assets/images/" },
{ pattern: /(["'])\.\/images\//g, replacement: "$1/assets/images/" },
{ pattern: /(["'])images\//g, replacement: "$1/assets/images/" },
{ pattern: /(["'])\.\.\/\.\.\/sage\.css\1/g, replacement: "$1/assets/css/sage.css$1" },
{ pattern: /(["'])\.\.\/sage\.css\1/g, replacement: "$1/assets/css/sage.css$1" },
{ pattern: /(["'])\.\/sage\.css\1/g, replacement: "$1/assets/css/sage.css$1" },
{ pattern: /(["'])sage\.css\1/g, replacement: "$1/assets/css/sage.css$1" },
{ pattern: /(["'])\.\.\/\.\.\/prism\.css\1/g, replacement: "$1/assets/css/prism.css$1" },
{ pattern: /(["'])\.\.\/prism\.css\1/g, replacement: "$1/assets/css/prism.css$1" },
{ pattern: /(["'])\.\/prism\.css\1/g, replacement: "$1/assets/css/prism.css$1" },
{ pattern: /(["'])prism\.css\1/g, replacement: "$1/assets/css/prism.css$1" },
{ pattern: /(["'])\.\.\/\.\.\/prism\.js\1/g, replacement: "$1/assets/js/prism.js$1" },
{ pattern: /(["'])\.\.\/prism\.js\1/g, replacement: "$1/assets/js/prism.js$1" },
{ pattern: /(["'])\.\/prism\.js\1/g, replacement: "$1/assets/js/prism.js$1" },
{ pattern: /(["'])prism\.js\1/g, replacement: "$1/assets/js/prism.js$1" },
{ pattern: /(["'])\.\.\/\.\.\/sage\.js\1/g, replacement: "$1/assets/js/sage.js$1" },
{ pattern: /(["'])\.\.\/sage\.js\1/g, replacement: "$1/assets/js/sage.js$1" },
{ pattern: /(["'])\.\/sage\.js\1/g, replacement: "$1/assets/js/sage.js$1" },
{ pattern: /(["'])sage\.js\1/g, replacement: "$1/assets/js/sage.js$1" }
];
function ensureDir(dirPath) {
fs.mkdirSync(dirPath, { recursive: true });
}
function isPathInside(filePath, directoryPath) {
const relative = path.relative(directoryPath, filePath);
return Boolean(relative) && !relative.startsWith("..") && !path.isAbsolute(relative);
}
function hashFileContent(filePath) {
return crypto.createHash("sha1").update(fs.readFileSync(filePath)).digest("hex");
}
function collectFilesRecursive(dir, result = []) {
if (!fs.existsSync(dir)) {
return result;
}
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
collectFilesRecursive(fullPath, result);
} else if (entry.isFile()) {
result.push(fullPath);
}
}
return result;
}
function collectBuildInputFiles() {
const sourceFiles = new Set();
sourceFiles.add(__filename);
for (const fileName of SYSTEM_RUNTIME_FILES) {
const filePath = path.join(ROOT, fileName);
if (fs.existsSync(filePath)) {
sourceFiles.add(filePath);
}
}
for (const htmlPath of collectTopLevelHtmlFiles(ROOT_PAGES_DIR)) {
sourceFiles.add(htmlPath);
}
for (const filePath of collectFilesRecursive(LAYOUTS_DIR)) {
sourceFiles.add(filePath);
}
for (const filePath of collectFilesRecursive(ASSETS_DIR)) {
sourceFiles.add(filePath);
}
for (const filePath of collectFilesRecursive(ROADMAP_DIR)) {
sourceFiles.add(filePath);
}
for (const filePath of collectFilesRecursive(PROJECTS_DIR)) {
sourceFiles.add(filePath);
}
for (const filePath of collectFilesRecursive(COMMUNITY_DIR)) {
sourceFiles.add(filePath);
}
return Array.from(sourceFiles).sort();
}
function createSourceHashMap(files) {
const hashes = {};
for (const filePath of files) {
hashes[filePath] = hashFileContent(filePath);
}
return hashes;
}
function loadBuildCache() {
if (!fs.existsSync(BUILD_CACHE_PATH)) {
return null;
}
try {
const parsed = JSON.parse(readTextOrEmpty(BUILD_CACHE_PATH));
if (!parsed || parsed.version !== BUILD_CACHE_VERSION || typeof parsed.sourceHashes !== "object") {
return null;
}
return parsed;
} catch {
return null;
}
}
function saveBuildCache(sourceHashes, mode) {
const payload = {
version: BUILD_CACHE_VERSION,
generatedAtUtc: new Date().toISOString(),
mode,
sourceHashes
};
ensureDir(path.dirname(BUILD_CACHE_PATH));
fs.writeFileSync(BUILD_CACHE_PATH, JSON.stringify(payload, null, 2), "utf8");
}
function diffSourceHashes(previousHashes, currentHashes) {
const changed = [];
const deleted = [];
const previous = previousHashes || {};
const current = currentHashes || {};
for (const [filePath, currentHash] of Object.entries(current)) {
if (!Object.prototype.hasOwnProperty.call(previous, filePath) || previous[filePath] !== currentHash) {
changed.push(filePath);
}
}
for (const filePath of Object.keys(previous)) {
if (!Object.prototype.hasOwnProperty.call(current, filePath)) {
deleted.push(filePath);
}
}
return { changed, deleted };
}
function cleanPublicDir() {
if (fs.existsSync(PUBLIC_DIR)) {
fs.rmSync(PUBLIC_DIR, { recursive: true, force: true });
}
ensureDir(PUBLIC_DIR);
}
function readTextOrEmpty(filePath) {
if (!fs.existsSync(filePath)) {
return "";
}
return fs.readFileSync(filePath, "utf8");
}
function copyRecursive(src, dest) {
if (!fs.existsSync(src)) {
return;
}
const stat = fs.statSync(src);
if (stat.isDirectory()) {
ensureDir(dest);
for (const entry of fs.readdirSync(src)) {
copyRecursive(path.join(src, entry), path.join(dest, entry));
}
return;
}
ensureDir(path.dirname(dest));
fs.copyFileSync(src, dest);
}
function copyHtmlOnlyRecursive(src, dest) {
if (!fs.existsSync(src)) {
return;
}
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
const sourcePath = path.join(src, entry.name);
const targetPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
copyHtmlOnlyRecursive(sourcePath, targetPath);
continue;
}
if (
entry.isFile() &&
entry.name.toLowerCase().endsWith(".html") &&
entry.name.toLowerCase() !== "template.html"
) {
ensureDir(path.dirname(targetPath));
fs.copyFileSync(sourcePath, targetPath);
}
}
}
function shouldCopyLabStaticAsset(fileName) {
const ext = path.extname(fileName).toLowerCase();
const staticAssetExtensions = new Set([
".png",
".jpg",
".jpeg",
".gif",
".svg",
".webp",
".bmp",
".ico",
".avif",
".mp3",
".wav",
".ogg",
".mp4",
".webm",
".mov",
".m4v",
".css",
".js",
".woff",
".woff2",
".ttf",
".otf",
".eot",
".json"
]);
return staticAssetExtensions.has(ext);
}
function copyLabStaticAssetsRecursive(src, dest) {
if (!fs.existsSync(src)) {
return;
}
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
const sourcePath = path.join(src, entry.name);
const targetPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
// Allow recursion into subdirectories like 'data'
copyLabStaticAssetsRecursive(sourcePath, targetPath);
continue;
}
if (!entry.isFile()) {
continue;
}
// Allow any file within a "demo" directory to be copied
const isInDemoDir = sourcePath.split(path.sep).includes("demo");
// Always copy .json files in roadmap/labs or roadmap/*/data
if (!isInDemoDir && !shouldCopyLabStaticAsset(entry.name) && path.extname(entry.name) !== ".json") {
continue;
}
ensureDir(path.dirname(targetPath));
fs.copyFileSync(sourcePath, targetPath);
}
}
function collectHtmlFiles(dir, result = []) {
if (!fs.existsSync(dir)) {
return result;
}
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
collectHtmlFiles(fullPath, result);
} else if (entry.isFile() && entry.name.toLowerCase().endsWith(".html")) {
result.push(fullPath);
}
}
return result;
}
function collectTopLevelHtmlFiles(dir) {
if (!fs.existsSync(dir)) {
return [];
}
return fs
.readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".html"))
.map((entry) => path.join(dir, entry.name));
}
function sanitizeTitle(raw) {
return raw
.replace(/[-_]/g, " ")
.replace(/\s+/g, " ")
.trim()
.replace(/\b\w/g, (char) => char.toUpperCase());
}
function detectTitle(content, sourcePath) {
const explicitMatch = content.match(/<!--\s*@page-title:\s*(.*?)\s*-->/i);
if (explicitMatch) {
return explicitMatch[1].trim();
}
const h1Match = content.match(/<h1[^>]*>(.*?)<\/h1>/i);
if (h1Match) {
return h1Match[1].replace(/<[^>]+>/g, "").trim();
}
const fileName = path.basename(sourcePath, ".html");
return sanitizeTitle(fileName || "Sage-Code");
}
function buildMaintenanceBanner() {
if ((process.env.MIGRATION_MAINTENANCE_MODE || "").toLowerCase() !== "true") {
return "";
}
return [
'<div class="migration-banner" role="status" aria-live="polite">',
" Maintenance: this page is being migrated to the new static architecture.",
"</div>"
].join("\n");
}
function renderFromTemplate(content, sourcePath, templates) {
const { baseTemplate, headerTemplate, footerTemplate } = templates;
const title = detectTitle(content, sourcePath);
const maintenanceBanner = buildMaintenanceBanner();
const description = "Sage-Code static page";
return baseTemplate
.replace("{{title}}", title)
.replace("{{meta_description}}", description)
.replace("{{head_extra}}", "")
.replace("{{maintenance_banner}}", maintenanceBanner)
.replace("{{header}}", headerTemplate)
.replace("{{content}}", content)
.replace("{{footer}}", footerTemplate);
}
function rewritePublishedRoutePrefix(html, sourcePrefix, publishedPrefix) {
const pattern = new RegExp(`(["'])\\/${sourcePrefix}\\/`, "gi");
return html.replace(pattern, `$1/${publishedPrefix}/`);
}
function rewriteAssetPaths(html) {
let transformed = html;
for (const rule of ASSET_PATH_REWRITES) {
transformed = transformed.replace(rule.pattern, rule.replacement);
}
// Normalize roadmap publish routes under /roadmap and standalone project routes under /projects.
transformed = rewritePublishedRoutePrefix(transformed, "engineering", "roadmap/cse");
transformed = rewritePublishedRoutePrefix(transformed, "programming", "roadmap");
transformed = rewritePublishedRoutePrefix(transformed, "cse", "roadmap/cse");
transformed = rewritePublishedRoutePrefix(transformed, "csp", "roadmap");
transformed = rewritePublishedRoutePrefix(transformed, "csa", "roadmap/csa");
transformed = rewritePublishedRoutePrefix(transformed, "dsa", "roadmap/dsa");
transformed = rewritePublishedRoutePrefix(transformed, "itc", "roadmap/hpc");
transformed = rewritePublishedRoutePrefix(transformed, "hpc", "roadmap/hpc");
transformed = rewritePublishedRoutePrefix(transformed, "tek", "roadmap/tek");
transformed = rewritePublishedRoutePrefix(transformed, "ops", "roadmap/tek");
transformed = rewritePublishedRoutePrefix(transformed, "dba", "roadmap/dba");
transformed = rewritePublishedRoutePrefix(transformed, "sml", "roadmap/sml");
transformed = rewritePublishedRoutePrefix(transformed, "osd", "roadmap/osd");
transformed = rewritePublishedRoutePrefix(transformed, "dsk", "roadmap/dsk");
transformed = rewritePublishedRoutePrefix(transformed, "das", "roadmap/sml");
transformed = rewritePublishedRoutePrefix(transformed, "csd", "roadmap/sml");
transformed = rewritePublishedRoutePrefix(transformed, "pro", "projects");
// MAJ assets and media now live under the standalone /projects namespace.
transformed = transformed.replace(/(["'])\/maj\/\.\.\/projects\//gi, "$1/projects/");
transformed = transformed.replace(/(["'])\/content\/maj\//gi, "$1/projects/maj/");
transformed = transformed.replace(/(["'])\/maj\//gi, "$1/projects/maj/");
transformed = transformed.replace(/(["'])\/maj\/img\//gi, "$1/projects/maj/img/");
transformed = transformed.replace(/(["'])((?:\.\.\/)+)maj\/img\//gi, "$1$2projects/maj/img/");
// Normalize legacy image roots to the centralized assets folder.
transformed = transformed.replace(/(["'])\/images\//g, "$1/assets/images/");
// Several legacy references use .jpg while only .svg diagrams exist in assets/images.
transformed = transformed.replace(/assets\/images\/(array|decision|ladder|for-loop|while|switch|function)\.jpg/gi, "assets/images/$1.svg");
return transformed;
}
function getRelativeRootPrefix(sourcePath) {
const relativePath = path.relative(PUBLIC_DIR, sourcePath);
if (!relativePath || relativePath.startsWith("..")) {
return "./";
}
const depth = relativePath.split(path.sep).length - 1;
if (depth <= 0) {
return "./";
}
return "../".repeat(depth);
}
function relativizeInternalRootLinks(html, sourcePath) {
const prefix = getRelativeRootPrefix(sourcePath);
let transformed = html;
// Convert exact site-root links first (e.g., href="/").
transformed = transformed.replace(/\b(href|src)=(["'])\/\2/gi, (match, attr, quote) => {
return `${attr}=${quote}${prefix}${quote}`;
});
// Convert root-relative href/src links to page-relative paths for local /public serving.
return transformed.replace(/\b(href|src)=(["'])\/([^"']*)\2/gi, (match, attr, quote, value) => {
// Keep protocol-relative URLs unchanged.
if (value.startsWith("/")) {
return match;
}
// Anchor-only references remain unchanged.
if (value.startsWith("#")) {
return match;
}
const relative = `${prefix}${value}`;
return `${attr}=${quote}${relative}${quote}`;
});
}
function normalizeSharedBrandAssets(html, sourcePath) {
// Keep shared brand assets rooted at /assets so they resolve on clean-url routes.
const logoPath = `/assets/images/sage-logo.svg`;
const faviconPath = `/assets/images/favicon.ico`;
let transformed = html;
transformed = transformed.replace(/\bsrc=(['"])(?:[^"']*\/)?sage-logo\.svg\1/gi, (match, quote) => {
return `src=${quote}${logoPath}${quote}`;
});
transformed = transformed.replace(/\bhref=(['"])(?:[^"']*\/)?favicon\.ico\1/gi, (match, quote) => {
return `href=${quote}${faviconPath}${quote}`;
});
return transformed;
}
function shouldRelativizeRootLinks(sourcePath) {
const normalized = sourcePath.replace(/\\/g, "/").toLowerCase();
if (normalized.includes("/public/roadmap/")) {
return false;
}
// Project subpages are served by Vercel as clean directory URLs (for
// example, /projects/bee/features/). Their virtual route depth differs
// from the published .html path, so page-relative shared asset URLs break.
if (normalized.includes("/public/projects/")) {
return false;
}
// Vercel's cleanUrls + trailingSlash config serves top-level pages like
// /legal.html and /manifesto.html at a virtual /legal/ and /manifesto/
// route (one directory level deeper than the file actually sits in
// /public). Page-relative "./assets/..." links resolve incorrectly under
// that virtual route, so keep root-absolute links for every top-level
// page except index.html, whose clean route is "/" itself.
if (path.dirname(sourcePath) === PUBLIC_DIR && path.basename(sourcePath).toLowerCase() !== "index.html") {
return false;
}
return true;
}
function escapeHtml(value) {
return String(value)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function getSourceRouteForPublicRoute(publicRoute) {
for (const [sourceRoute, publishedRoute] of Object.entries(LAB_ROUTE_MAP)) {
if (publishedRoute === publicRoute) {
return sourceRoute;
}
}
return publicRoute;
}
function resolveContentRouteSourceDir(publicRoute) {
const directRouteDir = path.join(ROADMAP_DIR, publicRoute);
if (fs.existsSync(directRouteDir)) {
return directRouteDir;
}
const sourceTopLevelRoute = getSourceRouteForPublicRoute(publicRoute);
const legacyRouteDir = path.join(ROADMAP_LABS_DIR, sourceTopLevelRoute);
if (fs.existsSync(legacyRouteDir)) {
return legacyRouteDir;
}
return null;
}
function resolveSidebarJsonPath(publicHtmlPath) {
const relativePath = path.relative(PUBLIC_DIR, publicHtmlPath);
if (!relativePath || relativePath.startsWith("..")) {
return null;
}
const publicPathParts = relativePath.split(path.sep);
if (publicPathParts[0].toLowerCase() === "projects") {
if (publicPathParts.length < 3) {
return null;
}
const projectDir = path.join(PROJECTS_DIR, publicPathParts[1]);
const relativeJsonPath = publicPathParts.slice(2).join(path.sep).replace(/\.html$/i, ".json");
const jsonPath = path.join(projectDir, relativeJsonPath);
return fs.existsSync(jsonPath) ? jsonPath : null;
}
if (publicPathParts.length < 2) {
return null;
}
const contentRootOffset = publicPathParts[0].toLowerCase() === "roadmap" ? 1 : 0;
if (publicPathParts.length < contentRootOffset + 2) {
return null;
}
const topLevelRoute = publicPathParts[contentRootOffset].toLowerCase();
const contentRouteDir = resolveContentRouteSourceDir(topLevelRoute);
if (!contentRouteDir) {
return null;
}
const relativeJsonPath = publicPathParts.slice(contentRootOffset + 1).join(path.sep).replace(/\.html$/i, ".json");
const jsonPath = path.join(contentRouteDir, relativeJsonPath);
return fs.existsSync(jsonPath) ? jsonPath : null;
}
function resolveRoadmapTopicContext(publicHtmlPath) {
const relativePath = path.relative(PUBLIC_DIR, publicHtmlPath);
if (!relativePath || relativePath.startsWith("..")) {
return null;
}
const publicPathParts = relativePath.split(path.sep);
const rootNamespace = (publicPathParts[0] || "").toLowerCase();
const isProjectTopic = rootNamespace === "projects";
if (publicPathParts.length < (isProjectTopic ? 3 : 3)) {
return null;
}
const contentRootOffset = rootNamespace === "roadmap" || isProjectTopic ? 1 : 0;
if (publicPathParts.length < contentRootOffset + 2) {
return null;
}
const topLevelRoute = publicPathParts[contentRootOffset].toLowerCase();
const hasProjectRoute = isProjectTopic && fs.existsSync(path.join(PROJECTS_DIR, topLevelRoute));
if (!hasProjectRoute && !resolveContentRouteSourceDir(topLevelRoute)) {
return null;
}
const fileName = publicPathParts[publicPathParts.length - 1] || "";
const topicId = path.basename(fileName, path.extname(fileName));
if (!topicId || topicId.toLowerCase() === "index") {
return null;
}
const sidebarJsonPath = resolveSidebarJsonPath(publicHtmlPath);
if (!sidebarJsonPath) {
return null;
}
return {
namespace: isProjectTopic ? "projects" : "roadmap",
topLevelRoute,
topicId
};
}
function getLabIdFromRoute(route) {
if (route === "cse") {
return "engineering";
}
if (route === "csp") {
return "programming";
}
if (PROGRAMMING_TOPIC_FOLDERS.includes(route)) {
return "programming";
}
return route;
}
function renderSidebarItems(items, state = { index: 0 }, level = 0) {
let html = "";
for (const item of items) {
const title = escapeHtml(item.title || "Untitled");
const link = item.link || (item.target ? `#${item.target}` : "#");
const safeLink = escapeHtml(link);
const isAnchorLink = link.startsWith("#");
if (!isAnchorLink) {
if (Array.isArray(item.children) && item.children.length > 0) {
html += renderSidebarItems(item.children, state, level);
}
continue;
}
const itemId = `sidebar-item-${state.index}`;
state.index += 1;
const sectionKey = escapeHtml(link.slice(1));
const nodeId = `node-${sectionKey}-static-${state.index}`;
const hasChildren = Array.isArray(item.children) && item.children.length > 0;
const icon = hasChildren
? `<button type="button" class="nav-tree-toggle" data-node-id="${nodeId}" aria-expanded="${level === 0 ? "true" : "false"}" aria-label="${level === 0 ? "Collapse topic folder" : "Expand topic folder"}"><i class="bi ${level === 0 ? "bi-folder2-open" : "bi-folder2"}" aria-hidden="true"></i></button>`
: '<span class="nav-file-icon"><i class="bi bi-file-earmark-text" aria-hidden="true"></i></span>';
html += `<li class="nav-item mb-2 nav-tree-item" id="${itemId}" data-sidebar-level="${level}" data-tree-level="${level}" data-node-id="${nodeId}" data-section-key="${sectionKey}"${hasChildren ? ' data-has-children="true"' : ""}>`;
html += `<div class="nav-node-row" data-node-id="${nodeId}" data-section-key="${sectionKey}">`;
const checkboxId = `nav-progress-${state.index}`;
html += `${icon}<input type="checkbox" class="nav-progress-checkbox" id="${checkboxId}" data-is-trackable="true" data-link="${safeLink}" data-section-key="${sectionKey}" tabindex="-1" aria-hidden="true">`;
html += `<a href="${safeLink}" class="nav-tree-link text-decoration-none" data-section-key="${sectionKey}" role="treeitem" aria-level="${level + 1}" tabindex="-1">${title}</a>`;
html += `</div>`;
if (hasChildren) {
html += `<ul class="list-unstyled ms-4 mt-1 nav-tree-children${level === 0 ? "" : " is-collapsed"}" data-sidebar-group="children" data-sidebar-level="${level + 1}" data-parent-node-id="${nodeId}" role="group">`;
html += renderSidebarItems(item.children, state, level + 1);
html += "</ul>";
}
html += "</li>";
}
return html;
}
// Clean URLs + trailing slashes serve topic pages from a virtual directory, so a
// relative "./index.html" resolves back onto the current page instead of the track index.
function resolveReturnToRoadmapHref(sourcePath) {
const context = resolveRoadmapTopicContext(sourcePath);
if (context) {
if (context.namespace === "projects") {
return `/projects/${context.topLevelRoute}/#topic-${context.topicId}`;
}
return `/roadmap/${context.topLevelRoute}/#topic-${context.topicId}`;
}
const parentRoute = path
.relative(PUBLIC_DIR, path.dirname(sourcePath))
.split(path.sep)
.filter(Boolean)
.join("/");
return parentRoute ? `/${parentRoute}/` : "/";
}
function renderReturnToRoadmapItem(sourcePath) {
const href = escapeHtml(resolveReturnToRoadmapHref(sourcePath));
return `<li class="nav-item mb-2 return-roadmap-link"><a href="${href}" class="text-info text-decoration-none">Return to Roadmap</a></li>`;
}
function findBookmarkListBounds(html) {
const openTagRegex = /<ul[^>]*id=["']bookmark-list["'][^>]*>/i;
const openMatch = openTagRegex.exec(html);
if (!openMatch) {
return null;
}
const openStart = openMatch.index;
const openTag = openMatch[0];
const openEnd = openStart + openTag.length;
const ulTagRegex = /<\/?ul\b[^>]*>/gi;
ulTagRegex.lastIndex = openEnd;
let depth = 1;
for (let match = ulTagRegex.exec(html); match; match = ulTagRegex.exec(html)) {
const token = match[0].toLowerCase();
if (token.startsWith("</ul")) {
depth -= 1;
if (depth === 0) {
return {
openStart,
openEnd,
closeStart: match.index,
closeEnd: ulTagRegex.lastIndex,
openTag
};
}
} else {
depth += 1;
}
}
return null;
}
function markBookmarkListAsStatic(openTag) {
if (/\bdata-static-sidebar\s*=\s*["']true["']/i.test(openTag)) {
return openTag;
}
return openTag.replace(/>$/, ' data-static-sidebar="true">');
}
function ensureReturnToRoadmapLink(html, sourcePath) {
const bounds = findBookmarkListBounds(html);
if (!bounds) {
return html;
}
const inner = html.slice(bounds.openEnd, bounds.closeStart);
if (/return-roadmap-link|Return to Roadmap/i.test(inner)) {
return html;
}
const trimmedInner = inner.trimEnd();
const separator = trimmedInner.length > 0 ? "\n" : "";
const updatedInner = `${trimmedInner}${separator}${renderReturnToRoadmapItem(sourcePath)}\n`;
return `${html.slice(0, bounds.openEnd)}${updatedInner}${html.slice(bounds.closeStart)}`;
}
function injectStaticSidebar(html, sourcePath) {
const bounds = findBookmarkListBounds(html);
if (!bounds) {
return html;
}
if (/\bdata-static-sidebar\s*=\s*["']true["']/i.test(bounds.openTag)) {
return html;
}
const jsonPath = resolveSidebarJsonPath(sourcePath);
if (!jsonPath) {
return html;
}
let navItems = [];
try {
navItems = JSON.parse(readTextOrEmpty(jsonPath));
} catch {
return html;
}
if (!Array.isArray(navItems) || navItems.length === 0) {
return html;
}
let transformed = html;
transformed = transformed.replace(
/<aside class=["']side-bar\b([^"']*)["']/i,
'<aside id="topic-sidebar" class="side-bar$1"'
);
const refreshedBounds = findBookmarkListBounds(transformed);
if (!refreshedBounds) {
return transformed;
}
const staticOpenTag = markBookmarkListAsStatic(refreshedBounds.openTag);
const renderedList = `${renderSidebarItems(navItems)}\n${renderReturnToRoadmapItem(sourcePath)}`;
transformed =
`${transformed.slice(0, refreshedBounds.openStart)}` +
`${staticOpenTag}\n${renderedList}\n` +
`${transformed.slice(refreshedBounds.closeStart)}`;
return transformed;
}
function injectInlineHeader(html, headerTemplate) {
if (!headerTemplate.trim()) {
return html;
}
const headerWithPlaceholderRegex = /<header[^>]*id=["']dynamic-header["'][^>]*>\s*<\/header>/i;
if (headerWithPlaceholderRegex.test(html)) {
return html.replace(headerWithPlaceholderRegex, headerTemplate);
}
return html;
}
function injectInlineFooter(html, footerTemplate, enforceCommonFooter = false) {
if (!footerTemplate.trim()) {
return html;
}
const normalizedFooter = footerTemplate.trim();
const footerWithPlaceholderRegex = /<footer[^>]*id=["']dynamic-footer["'][^>]*>\s*<\/footer>/i;
if (footerWithPlaceholderRegex.test(html)) {
return html.replace(footerWithPlaceholderRegex, normalizedFooter);
}
if (!enforceCommonFooter) {
if (/<footer[\s>]/i.test(html)) {
return html;
}
if (/<\/body>/i.test(html)) {
return html.replace(/<\/body>/i, `${normalizedFooter}\n</body>`);
}
return `${html}\n${normalizedFooter}`;
}
if (/<footer[\s>]/i.test(html)) {
return html.replace(/<footer\b[\s\S]*?<\/footer>/i, normalizedFooter);
}
const bodyCloseWithContainerEndRegex = /(\s*<\/div>\s*)(<\/body>)/i;
if (bodyCloseWithContainerEndRegex.test(html)) {
return html.replace(bodyCloseWithContainerEndRegex, `\n${normalizedFooter}\n$1$2`);
}
if (/<\/body>/i.test(html)) {
return html.replace(/<\/body>/i, `${normalizedFooter}\n</body>`);
}
return `${html}\n${normalizedFooter}`;
}
function ensureBootstrapIconsForTopic(html) {
if (!/<ul[^>]*id=["']bookmark-list["']/i.test(html) || /bootstrap-icons/i.test(html)) {
return html;
}
const iconStylesheet = '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">';
if (/<\/head>/i.test(html)) {
return html.replace(/<\/head>/i, `${iconStylesheet}\n</head>`);
}
return html;
}
function shouldEnforceCommonFooter(sourcePath) {
const normalized = sourcePath.replace(/\\/g, "/").toLowerCase();
return normalized.includes("/public/") && normalized.endsWith(".html");
}
function shouldInjectRoadmapProgressScripts(html) {
return /window\.TOPIC_CONFIG\s*=|data-sage-roadmap=/i.test(html);
}
function injectRoadmapProgressScripts(html) {
if (!shouldInjectRoadmapProgressScripts(html)) {
return html;
}
const needsAuthStack = !/supabase-client\.js/i.test(html) || !/roadmap-state\.js/i.test(html);
const needsProgressSync = !/roadmap-progress-sync\.js/i.test(html);
if (!needsAuthStack && !needsProgressSync) {
return html;
}
const scripts = [];
if (needsAuthStack) {
scripts.push(
'<script src="/assets/js/supabase-config.js"></script>',
'<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>',
'<script src="/assets/js/supabase-client.js"></script>',
'<script src="/assets/js/roadmap-state.js"></script>'