-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.ts
More file actions
1901 lines (1697 loc) · 71.1 KB
/
vite.config.ts
File metadata and controls
1901 lines (1697 loc) · 71.1 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
import { spawn, spawnSync } from "node:child_process";
import nodeCrypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import jsYaml from "js-yaml";
import { sanitizeModel, stableStringify } from "./src/lib/model";
import {
parseFrontmatter,
serializeFrontmatter,
renderMarkdown,
hljs,
} from "./src/lib/markdown";
import type { PlatformKitConfig, RssFeedConfig, ContentCollectionConfig } from "./src/lib/config";
import { buildRssFeed, escapeXml as escapeRssXml } from "./src/lib/rss";
import { generateOgPages } from "./src/lib/og-prerender";
import type { ContentCollectionDef } from "./src/lib/layout-manifest";
import { migrateCollectionItem } from "./src/lib/collection-migrations";
import type { CollectionMigrationConfig } from "./src/lib/collection-migrations";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// ── Load platformkit.config.js/.ts (optional) ───────────────────────
/** Load a single PlatformKitConfig file from a directory. Returns {} if none found. */
const loadConfigFrom = async (dir: string, names?: string[]): Promise<PlatformKitConfig> => {
const fileNames = names ?? ["platformkit.config.ts", "platformkit.config.js", "platformkit.config.mjs"];
for (const name of fileNames) {
const configPath = path.resolve(dir, name);
if (!fs.existsSync(configPath)) continue;
if (name.endsWith(".ts")) {
try {
const localRequire = createRequire(path.resolve(__dirname, "package.json"));
const esbuild = localRequire("esbuild") as typeof import("esbuild");
const tmpPath = configPath + ".__tmp.mjs";
// Use buildSync to bundle local imports (e.g. build-hooks/) into a single file.
// External: node builtins and npm packages — only local .ts/.js are inlined.
esbuild.buildSync({
entryPoints: [configPath],
outfile: tmpPath,
bundle: true,
format: "esm",
platform: "node",
target: "node18",
packages: "external",
loader: { ".vue": "empty" },
});
try {
const mod = await import(`${tmpPath}?t=${Date.now()}`);
return mod.default ?? mod;
} finally {
try { fs.unlinkSync(tmpPath); } catch {}
}
} catch (err: any) {
console.warn(`[platformkit] Failed to load ${configPath}: ${err?.message}`);
}
} else {
try {
const mod = await import(`${configPath}?t=${Date.now()}`);
return mod.default ?? mod;
} catch (err: any) {
console.warn(`[platformkit] Failed to load ${configPath}: ${err?.message}`);
}
}
}
return {};
};
/**
* Deep-merge two PlatformKitConfig objects.
* - Objects: recursively merged (override extends/overwrites keys)
* - `buildHooks`: concatenated (all levels run)
* - Arrays (other than buildHooks): override replaces
* - Scalars / functions: override wins
*/
const mergeBuildConfigs = (base: PlatformKitConfig, override: PlatformKitConfig): PlatformKitConfig => {
const deepMerge = (target: any, source: any): any => {
if (source === undefined || source === null) return target;
if (target === undefined || target === null) return source;
if (Array.isArray(source)) return source;
if (
source && typeof source === "object" && !Array.isArray(source) &&
target && typeof target === "object" && !Array.isArray(target)
) {
const result = { ...target };
for (const key of Object.keys(source)) {
result[key] = deepMerge(target[key], source[key]);
}
return result;
}
return source;
};
const merged = deepMerge(base, override) as PlatformKitConfig;
// Special case: buildHooks are concatenated, not replaced
if (base.buildHooks || override.buildHooks) {
merged.buildHooks = [...(base.buildHooks ?? []), ...(override.buildHooks ?? [])];
}
return merged;
};
/**
* Load and merge PlatformKitConfig from all three levels:
* 1. Root platformkit.config.ts — platform defaults
* 2. src/themes/<active>/platformkit.config.ts — theme config
* 3. src/overrides/platformkit.config.ts — user overrides (final say)
*
* The active theme is detected from the CMS data file.
*/
const loadPlatformKitConfig = async (): Promise<PlatformKitConfig> => {
// 1. Root config
let config = await loadConfigFrom(__dirname);
// 2. Detect active theme from CMS data
const cmsPath = path.resolve(__dirname, "cms-data.json");
const defaultPath = path.resolve(__dirname, "default-data.json");
let themeName = "bento"; // fallback
for (const p of [cmsPath, defaultPath]) {
if (fs.existsSync(p)) {
try {
const d = JSON.parse(fs.readFileSync(p, "utf8"));
if (d?.theme?.layout) { themeName = d.theme.layout; break; }
} catch {}
}
}
// 2b. Load theme config (platformkit.config.ts)
// .vue imports are externalized by the esbuild loader so build-time
// loading works even when the config references Vue editor components.
const themeDir = path.resolve(__dirname, "src", "themes", themeName);
if (fs.existsSync(themeDir)) {
const themeConfig = await loadConfigFrom(themeDir);
config = mergeBuildConfigs(config, themeConfig);
}
// 3. Load user overrides (platformkit.config.ts)
const overridesDir = path.resolve(__dirname, "src", "overrides");
if (fs.existsSync(overridesDir)) {
const userConfig = await loadConfigFrom(overridesDir);
config = mergeBuildConfigs(config, userConfig);
}
return config;
};
// ── Hot config reload: watch all platformkit.config.ts files and reload config/collections on change ──
import chokidar from "chokidar";
let pkConfig: PlatformKitConfig = await loadPlatformKitConfig();
let collectionDefs: ContentCollectionDef[] = Object.entries(pkConfig.contentCollections ?? {}).map(
([key, cfg]) => ({
key,
label: cfg.label ?? key.charAt(0).toUpperCase() + key.slice(1),
directory: cfg.directory,
format: cfg.format ?? "markdown",
slugField: cfg.slugField ?? "title",
sortField: cfg.sortField,
sortOrder: cfg.sortOrder ?? "desc",
version: cfg.version ?? 0,
recursive: cfg.recursive ?? false,
}),
);
const configFilesToWatch = [
path.resolve(__dirname, "platformkit.config.ts"),
path.resolve(__dirname, "src/themes/bento/platformkit.config.ts"),
path.resolve(__dirname, "src/overrides/platformkit.config.ts"),
];
if (process.env.NODE_ENV === "development") {
chokidar.watch(configFilesToWatch, { ignoreInitial: true }).on("change", async (file) => {
console.log(`[platformkit] Detected config change in ${file}, reloading config...`);
pkConfig = await loadPlatformKitConfig();
collectionDefs = Object.entries(pkConfig.contentCollections ?? {}).map(
([key, cfg]) => ({
key,
label: cfg.label ?? key.charAt(0).toUpperCase() + key.slice(1),
directory: cfg.directory,
format: cfg.format ?? "markdown",
slugField: cfg.slugField ?? "title",
sortField: cfg.sortField,
sortOrder: cfg.sortOrder ?? "desc",
version: cfg.version ?? 0,
recursive: cfg.recursive ?? false,
}),
);
console.log(`[platformkit] Config and collections reloaded.`);
});
}
// ── Load user Vite config (staged by CLI as vite.user.config.js) ─────
const loadUserViteConfig = async (): Promise<Record<string, any>> => {
const configPath = path.resolve(__dirname, "vite.user.config.js");
if (!fs.existsSync(configPath)) return {};
try {
const mod = await import(`${configPath}?t=${Date.now()}`);
const resolved = mod.default ?? mod;
console.log("[user-vite-config] Loaded vite.user.config.js");
return typeof resolved === "object" && resolved !== null ? resolved : {};
} catch (err: any) {
console.warn(`[user-vite-config] Failed to load vite.user.config.js: ${err?.message}`);
return {};
}
};
const userViteConfig = await loadUserViteConfig();
const dataFilePath = path.resolve(__dirname, "cms-data.json");
const defaultDataFilePath = path.resolve(__dirname, "default-data.json");
const publicDataFilePath = path.resolve(__dirname, "public/content/data.json");
// ...existing code...
// ── File-based collection helpers ───────────────────────────────────
const COLLECTION_FORMAT_EXT: Record<string, string> = {
markdown: ".md",
json: ".json",
yaml: ".yaml",
};
/**
* Read a _meta.json file if it exists. Returns an ordered array of child names
* (filenames without extensions, or subfolder names) and optional display labels.
* Format: { "order": ["getting-started", "configuration"], "labels": { "getting-started": "Getting Started" } }
* Or simply an array: ["getting-started", "configuration"]
*/
interface MetaFile {
order?: string[];
labels?: Record<string, string>;
}
const readMetaFile = (dir: string): MetaFile | null => {
const metaPath = path.join(dir, "_meta.json");
if (!fs.existsSync(metaPath)) return null;
try {
const raw = JSON.parse(fs.readFileSync(metaPath, "utf8"));
if (Array.isArray(raw)) return { order: raw };
return raw as MetaFile;
} catch {
return null;
}
};
/**
* Recursively scan a directory for collection files, returning relative
* path-based slugs (e.g. "introduction/getting-started").
* Respects _meta.json ordering at each level.
*/
const scanCollectionDir = (
baseDir: string,
ext: string,
recursive: boolean,
relPrefix = "",
): string[] => {
if (!fs.existsSync(baseDir)) return [];
const entries = fs.readdirSync(baseDir, { withFileTypes: true });
const meta = readMetaFile(baseDir);
// Separate files and directories
const files = entries.filter((e) => e.isFile() && e.name.endsWith(ext) && e.name !== "_meta.json");
const dirs = recursive ? entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")) : [];
// Build name→type map for ordering
const childNames: Array<{ name: string; type: "file" | "dir" }> = [];
for (const f of files) childNames.push({ name: path.basename(f.name, ext), type: "file" });
for (const d of dirs) childNames.push({ name: d.name, type: "dir" });
// Apply _meta.json ordering if present, otherwise natural sort
if (meta?.order) {
const orderSet = new Set(meta.order);
const ordered = meta.order
.map((n) => childNames.find((c) => c.name === n))
.filter(Boolean) as typeof childNames;
const unordered = childNames.filter((c) => !orderSet.has(c.name));
childNames.length = 0;
childNames.push(...ordered, ...unordered);
} else {
childNames.sort((a, b) => a.name.localeCompare(b.name));
}
const result: string[] = [];
for (const child of childNames) {
const slug = relPrefix ? `${relPrefix}/${child.name}` : child.name;
if (child.type === "file") {
result.push(slug);
} else {
// Recurse into subdirectory
result.push(...scanCollectionDir(path.join(baseDir, child.name), ext, true, slug));
}
}
return result;
};
/** Read a collection file and return its parsed data + slug. */
const readCollectionFile = (
filePath: string,
format: "markdown" | "json" | "yaml",
): { data: Record<string, unknown>; body?: string } => {
const raw = fs.readFileSync(filePath, "utf8");
switch (format) {
case "markdown": {
const { meta, body } = parseFrontmatter(raw);
return { data: meta as Record<string, unknown>, body };
}
case "json":
return { data: JSON.parse(raw) };
case "yaml":
return { data: (jsYaml.load(raw) as Record<string, unknown>) ?? {} };
}
};
/** Serialize collection item data to the appropriate file format. */
const writeCollectionFile = (
filePath: string,
format: "markdown" | "json" | "yaml",
data: Record<string, unknown>,
body?: string,
): void => {
switch (format) {
case "markdown": {
const { content: _c, body: _b, html: _h, slug: _s, ...meta } = data;
fs.writeFileSync(filePath, serializeFrontmatter(meta, body ?? (data.content as string) ?? ""));
break;
}
case "json":
fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
break;
case "yaml":
fs.writeFileSync(filePath, jsYaml.dump(data, { lineWidth: 120 }));
break;
}
};
/** Build a CollectionMigrationConfig from a collection key's config. */
const getMigrationConfig = (key: string): CollectionMigrationConfig | null => {
const cfg = (pkConfig.contentCollections ?? {})[key];
if (!cfg) return null;
const version = cfg.version ?? 0;
if (version === 0 && !cfg.fieldRenames && !cfg.fieldDefaults && !cfg.migrations?.length) return null;
return {
version,
fieldRenames: cfg.fieldRenames ?? {},
fieldDefaults: cfg.fieldDefaults ?? {},
migrations: [...(cfg.migrations ?? [])].sort((a, b) => a.toVersion - b.toVersion),
};
};
/** Apply collection migrations to an item, optionally writing back to disk if changed. */
const migrateItem = (
item: Record<string, unknown>,
migrationConfig: CollectionMigrationConfig,
filePath?: string,
format?: "markdown" | "json" | "yaml",
body?: string,
): Record<string, unknown> => {
const { item: migrated, changed } = migrateCollectionItem(item, migrationConfig);
if (changed && filePath && format) {
const { slug: _s, html: _h, content: _c, ...dataToWrite } = migrated;
writeCollectionFile(filePath, format, dataToWrite, body);
}
return migrated;
};
/** Check if a schedulable item is currently visible based on its dates. */
const isScheduleVisibleNow = (item: { publishDate?: string; expirationDate?: string }): boolean => {
const today = new Date().toISOString().slice(0, 10);
if (item.publishDate && today < item.publishDate) return false;
if (item.expirationDate && today > item.expirationDate) return false;
return true;
};
const readDefaultModel = () => {
if (!fs.existsSync(defaultDataFilePath)) {
return sanitizeModel({});
}
try {
const raw = fs.readFileSync(defaultDataFilePath, "utf8");
return sanitizeModel(JSON.parse(raw));
} catch (err) {
console.warn(`[platformkit] Failed to parse default-data.json, using empty fallback:`, err);
return sanitizeModel({});
}
};
const ensureSeedData = () => {
const seed = readDefaultModel();
const payload = stableStringify(seed);
if (!fs.existsSync(dataFilePath)) {
fs.writeFileSync(dataFilePath, payload);
}
if (!fs.existsSync(publicDataFilePath)) {
const publicContentDir = path.dirname(publicDataFilePath);
if (!fs.existsSync(publicContentDir)) {
fs.mkdirSync(publicContentDir, { recursive: true });
}
fs.writeFileSync(publicDataFilePath, payload);
}
};
const collectRequestBody = async (req: NodeJS.ReadableStream) => {
const chunks: Uint8Array[] = [];
for await (const chunk of req) {
chunks.push(chunk as Uint8Array);
}
return Buffer.concat(chunks).toString("utf8");
};
type GitCommandResult = {
code: number;
stdout: string;
stderr: string;
};
type GitCommandError = Error &
GitCommandResult;
const runGitCommand = (args: string[]): Promise<GitCommandResult> => {
return new Promise((resolve, reject) => {
const proc = spawn("git", args, {
cwd: __dirname,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
proc.stdout?.on("data", (chunk) => {
stdout += chunk.toString();
});
proc.stderr?.on("data", (chunk) => {
stderr += chunk.toString();
});
proc.on("close", (code) => {
const result: GitCommandResult = {
code: code ?? 0,
stdout: stdout.trim(),
stderr: stderr.trim(),
};
if (result.code === 0) {
resolve(result);
return;
}
const error = new Error(`git ${args.join(" ")} exited with code ${result.code}`) as GitCommandError;
error.code = result.code;
error.stdout = result.stdout;
error.stderr = result.stderr;
reject(error);
});
proc.on("error", (error) => {
reject(error);
});
});
};
const isGitCommandError = (error: unknown): error is GitCommandError => {
if (!error || typeof error !== "object") return false;
const candidate = error as Partial<GitCommandError>;
return (
typeof candidate.code === "number" &&
typeof candidate.stdout === "string" &&
typeof candidate.stderr === "string"
);
};
const nothingToCommit = (error: GitCommandError) => {
const combined = `${error.stdout}\n${error.stderr}`.toLowerCase();
return error.code === 1 && combined.includes("nothing to commit");
};
const sanitizeCommitMessage = (input?: string) => {
const fallback = "Update CMS data";
if (!input) return fallback;
const normalized = input
.replace(/\s+/g, " ")
.replace(/[\u0000-\u0019]/g, "")
.trim();
if (!normalized) return fallback;
return normalized.slice(0, 140);
};
// reuse some helper logic from production upload naming
const generateUploadFileName = (inputName: unknown): string => {
const extract = (val: unknown): string => {
if (!val) return "";
if (typeof val === "string") return val;
if (typeof val === "object") {
// common File-like objects
const anyv = val as any;
if (typeof anyv.name === "string") return anyv.name;
if (typeof anyv.filename === "string") return anyv.filename;
}
return String(val);
};
const raw = extract(inputName).trim() || "image.png";
const lastDot = raw.lastIndexOf(".");
const baseRaw = lastDot >= 0 ? raw.slice(0, lastDot) : raw;
const extensionRaw = lastDot >= 0 ? raw.slice(lastDot).toLowerCase() : "";
// sanitize base: keep letters, numbers, dash, underscore and dot; replace others with '-'
const safeBase = baseRaw.replace(/[^a-zA-Z0-9._-]+/g, "-").slice(0, 80) || "image";
const extension = extensionRaw || ".png";
const timestamp = new Date()
.toISOString()
.replaceAll("-", "")
.replaceAll(":", "")
.replaceAll(".", "")
.replaceAll("T", "")
.replaceAll("Z", "")
.slice(0, 15);
const token = Math.random().toString(16).slice(2, 8);
return `${safeBase}-${timestamp}-${token}${extension}`;
};
const asResultPayload = (result?: GitCommandResult | null) =>
result
? {
code: result.code,
stdout: result.stdout,
stderr: result.stderr,
}
: undefined;
// Vite plugin that registers CMS dev endpoints as middleware. Using a plugin
// ensures the hook runs on the dev server lifecycle in newer Vite versions.
/** Build a PWA manifest object from CMS data. */
const buildManifest = (siteModel: any) => {
const name = pkConfig.site?.name || siteModel?.profile?.displayName || "PlatformKit";
const description = pkConfig.site?.tagline || siteModel?.profile?.tagline || "";
const bg = siteModel?.theme?.bg || "#f5f7fb";
const brand = siteModel?.theme?.colorBrand || "#3b82f6";
const ogImage = siteModel?.profile?.ogImageUrl || "/pwa-logo.png";
const favicon = siteModel?.profile?.faviconUrl || "/pwa-logo.png";
const icons: { src: string; sizes: string; type: string; purpose?: string }[] = [];
// Prefer the OG/social image as the large PWA icon
if (ogImage) {
icons.push({ src: ogImage, sizes: "512x512", type: "image/jpeg", purpose: "any" });
}
// Use favicon as a smaller icon if available
if (favicon) {
icons.push({ src: favicon, sizes: "192x192", type: "image/png", purpose: "any maskable" });
}
return {
name,
short_name: name,
description,
start_url: pkConfig.pwa?.startUrl || "/",
display: pkConfig.pwa?.display || "standalone",
background_color: bg,
theme_color: brand,
...(icons.length > 0 ? { icons } : {}),
};
};
// ── CMS endpoint paths (configurable via platformkit.config.ts) ──────
const CMS_ENDPOINTS = {
upload: pkConfig.cms?.uploadEndpoint || "/cms-upload",
data: pkConfig.cms?.dataEndpoint || "/__cms-data",
push: pkConfig.cms?.pushEndpoint || "/__cms-push",
};
// Allowed file extensions for uploads (R1)
const ALLOWED_UPLOAD_EXTENSIONS = new Set([
// Images
".jpg", ".jpeg", ".png", ".gif", ".webp", ".avif", ".svg", ".ico", ".bmp",
// Audio
".mp3", ".wav", ".webm", ".m4a", ".ogg", ".flac", ".aac",
// Video
".mp4", ".webm", ".mov", ".avi",
// Documents
".pdf", ".json",
]);
// Max upload size: 50 MB (R2)
const MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
const cmsMiddlewarePlugin = () => ({
name: "cms-middleware",
configureServer: (server: any) => {
server.middlewares.use(async (req: any, res: any, next: any) => {
const url = (req.url ?? "").split("?")[0];
if (url === CMS_ENDPOINTS.upload) {
if (server.config.mode !== "development") {
res.statusCode = 403;
res.end("Forbidden");
return;
}
if (req.method !== "POST") {
res.statusCode = 405;
res.end("Method Not Allowed");
return;
}
// Enforce upload size limit (R2)
const contentLength = parseInt(req.headers["content-length"] || "0", 10);
if (contentLength > MAX_UPLOAD_BYTES) {
res.statusCode = 413;
res.end("File too large (max 50 MB)");
return;
}
const uploadsDir = path.resolve(__dirname, "public/content/uploads");
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
const requireCJS = createRequire(import.meta.url);
const createBusboy = requireCJS("busboy");
const bb = createBusboy({ headers: req.headers, limits: { fileSize: MAX_UPLOAD_BYTES } });
let returnedUrl = "";
let uploadError = "";
let conversionWarning = "";
let writeComplete: Promise<void> = Promise.resolve();
bb.on("file", (_fieldname: string, fileStream: NodeJS.ReadableStream, filename: any) => {
// incoming filename argument may already be an object produced by busboy
// containing { filename, encoding, mimeType }
let orig = filename;
let mimeType = "";
if (orig && typeof orig === "object" && typeof orig.filename === "string") {
mimeType = orig.mimeType || "";
orig = orig.filename;
}
if (!orig || typeof orig !== "string") {
const f = fileStream as any;
if (f && typeof f.name === "string") orig = f.name;
else if (f && typeof f.filename === "string") orig = f.filename;
else if (f && typeof f.path === "string") orig = path.basename(f.path as string);
else orig = String(filename || "image.png");
}
// R3: Strip path segments to prevent path traversal
orig = path.basename(orig);
// R1: Validate file extension against allowlist
const extRaw = orig.includes(".") ? orig.slice(orig.lastIndexOf(".")).toLowerCase() : "";
if (!extRaw || !ALLOWED_UPLOAD_EXTENSIONS.has(extRaw)) {
uploadError = `File type not allowed: ${extRaw || "(none)"}`;
fileStream.resume(); // drain the stream
return;
}
// If the filename already looks like a deterministic target (e.g.
// "avatar.jpg", "voice.mp3", "voice.wav") use it directly so re-uploads
// overwrite the previous file instead of accumulating copies.
const isDeterministic = /^[a-zA-Z0-9_-]+\.(jpg|jpeg|png|gif|webp|mp3|wav|webm|m4a)$/i.test(orig);
const isAudio = mimeType.startsWith("audio/");
const baseName = isDeterministic ? orig.replace(/\.[^.]+$/, "") : generateUploadFileName(orig).replace(/\.[^.]+$/, "");
const ext = isAudio ? ".mp3" : extRaw;
const safe = baseName + ext;
const outPath = path.join(uploadsDir, safe);
// R3: Final check — ensure resolved path is inside uploadsDir
const resolved = path.resolve(outPath);
if (!resolved.startsWith(uploadsDir + path.sep) && resolved !== uploadsDir) {
uploadError = "Invalid filename";
fileStream.resume();
return;
}
const write = fs.createWriteStream(outPath);
write.on("error", (err) => {
uploadError = `Write failed: ${(err as Error).message}`;
});
fileStream.pipe(write);
returnedUrl = `/content/uploads/${safe}`;
// For audio files, convert to MP3 using ffmpeg after write completes
if (isAudio) {
writeComplete = new Promise<void>((resolveWrite) => {
write.on("finish", () => {
// If input was not mp3, convert
if (!orig.toLowerCase().endsWith(".mp3")) {
const tempPath = outPath + ".temp";
fs.renameSync(outPath, tempPath);
try {
const { spawnSync } = require("child_process");
const result = spawnSync("ffmpeg", ["-y", "-i", tempPath, "-b:a", "128k", "-ac", "1", outPath], {
stdio: "inherit",
timeout: 120_000,
});
if (result.status === 0) {
fs.unlinkSync(tempPath);
} else {
console.error(`ffmpeg conversion failed (exit ${result.status})`);
// Conversion failed, keep original
fs.renameSync(tempPath, outPath);
conversionWarning = "Audio conversion failed; file saved in original format";
}
} catch (err) {
console.error("ffmpeg not available or errored:", err);
// ffmpeg not available, keep original
fs.renameSync(tempPath, outPath);
conversionWarning = "Audio conversion unavailable; file saved in original format";
}
}
resolveWrite();
});
});
} else {
writeComplete = new Promise<void>((resolveWrite) => {
write.on("finish", () => resolveWrite());
});
}
});
bb.on("finish", async () => {
await writeComplete;
if (uploadError) {
res.statusCode = 400;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ error: uploadError }));
return;
}
res.setHeader("Content-Type", "application/json");
const body: Record<string, string> = { url: returnedUrl };
if (conversionWarning) body.warning = conversionWarning;
res.end(JSON.stringify(body));
});
req.pipe(bb);
return;
}
// ── Manifest.json (dynamic, from CMS data) ──────────────────
if (url === "/manifest.json" && req.method === "GET") {
ensureSeedData();
const raw = fs.readFileSync(dataFilePath, "utf8");
const siteModel = sanitizeModel(JSON.parse(raw));
res.setHeader("Content-Type", "application/manifest+json");
res.end(JSON.stringify(buildManifest(siteModel), null, 2));
return;
}
if (url === CMS_ENDPOINTS.data) {
ensureSeedData();
if (req.method === "OPTIONS") {
res.statusCode = 204;
res.end();
return;
}
if (req.method === "GET") {
const payload = fs.readFileSync(dataFilePath, "utf8");
res.setHeader("Content-Type", "application/json");
res.end(payload);
return;
}
if (req.method === "POST") {
const body = await collectRequestBody(req);
const parsed = sanitizeModel(body ? JSON.parse(body) : {});
const serialized = stableStringify(parsed);
// R12: Atomic write via temp file + rename to prevent partial writes
const tmpFile = dataFilePath + "." + Math.random().toString(16).slice(2) + ".tmp";
fs.writeFileSync(tmpFile, serialized);
fs.renameSync(tmpFile, dataFilePath);
res.statusCode = 204;
res.end();
return;
}
res.statusCode = 405;
res.end("Method Not Allowed");
return;
}
if (url === CMS_ENDPOINTS.push && req.method === "POST") {
// Run the export-to-github script to push content to the remote repo
const scriptPath = path.resolve(__dirname, "scripts/export-to-github.mjs");
if (!fs.existsSync(scriptPath)) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ error: "Push script not found." }));
return;
}
// Read optional commit message from body
const body = await collectRequestBody(req);
let commitMessage = "Update CMS data";
try {
const parsed = JSON.parse(body);
if (parsed?.message) commitMessage = sanitizeCommitMessage(parsed.message);
} catch {
// ignore
}
// Sync cms-data.json → public/content/data.json before pushing
if (fs.existsSync(dataFilePath)) {
fs.writeFileSync(publicDataFilePath, fs.readFileSync(dataFilePath, "utf8"));
}
const proc = spawn("node", [scriptPath], {
cwd: __dirname,
env: { ...process.env, CMS_COMMIT_MESSAGE: commitMessage },
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
proc.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
proc.stderr?.on("data", (chunk) => { stderr += chunk.toString(); });
proc.on("close", (code) => {
res.setHeader("Content-Type", "application/json");
if (code === 0) {
res.statusCode = 200;
res.end(JSON.stringify({ ok: true, stdout: stdout.trim() }));
} else {
res.statusCode = 500;
res.end(JSON.stringify({ error: `Push failed (exit ${code})`, stdout: stdout.trim(), stderr: stderr.trim() }));
}
});
proc.on("error", (err) => {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ error: err.message }));
});
return;
}
// ── Generic file collection CRUD ─────────────────────────────
const collectionMatch = url.match(/^\/__collection\/([a-zA-Z0-9_-]+)$/);
if (collectionMatch) {
const collectionKey = collectionMatch[1];
const def = collectionDefs.find((d) => d.key === collectionKey);
if (!def) {
res.statusCode = 404;
res.end(`Unknown collection: ${collectionKey}`);
return;
}
const ext = COLLECTION_FORMAT_EXT[def.format];
const dir = path.resolve(__dirname, def.directory);
// GET — list all items or single item by ?slug=
if (req.method === "GET") {
const fullUrl = new URL(req.url ?? "", "http://localhost");
const slug = fullUrl.searchParams.get("slug") ?? "";
if (slug) {
// Single item — support path-based slugs for recursive collections
let safeName: string;
let filePath: string;
if (def.recursive && slug.includes("/")) {
// Path-based slug like "introduction/getting-started"
const parts = slug.split("/").map((p) => path.basename(p));
safeName = parts.join("/");
filePath = path.join(dir, ...parts) + ext;
} else {
safeName = path.basename(slug);
filePath = path.join(dir, `${safeName}${ext}`);
}
if (!fs.existsSync(filePath)) {
res.statusCode = 404;
res.end("Not found");
return;
}
const { data, body } = readCollectionFile(filePath, def.format);
let item: Record<string, unknown> = { ...data, slug: safeName };
if (def.recursive && safeName.includes("/")) {
const slugParts = safeName.split("/");
const parentDirRel = slugParts.slice(0, -1).join("/");
const parentDir = path.join(dir, parentDirRel);
const meta = readMetaFile(parentDir);
const dirName = slugParts[slugParts.length - 2];
if (!item.section) {
item.section = meta?.labels?.[dirName] ?? dirName.charAt(0).toUpperCase() + dirName.slice(1);
}
item._path = slugParts.slice(0, -1).join("/");
}
const mc = getMigrationConfig(collectionKey);
if (mc) item = migrateItem(item, mc, filePath, def.format, body);
if (def.format === "markdown" && body !== undefined) {
item.content = body;
item.html = renderMarkdown(body);
}
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(item));
return;
}
// List all (recursive-aware)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const slugs = scanCollectionDir(dir, ext, def.recursive);
const mc = getMigrationConfig(collectionKey);
// Read _meta.json cache for recursive
const metaCache = new Map<string, MetaFile | null>();
const getMetaForDir = (dirPath: string): MetaFile | null => {
if (!metaCache.has(dirPath)) metaCache.set(dirPath, readMetaFile(dirPath));
return metaCache.get(dirPath) ?? null;
};
const items = slugs.map((slug: string) => {
const fp = path.join(dir, `${slug}${ext}`);
const { data, body } = readCollectionFile(fp, def.format);
let item: Record<string, unknown> = { ...data, slug };
if (def.recursive && slug.includes("/")) {
const parts = slug.split("/");
const parentDirRel = parts.slice(0, -1).join("/");
const parentDir = path.join(dir, parentDirRel);
const meta = getMetaForDir(parentDir);
const dirName = parts[parts.length - 2];
if (!item.section) {
item.section = meta?.labels?.[dirName] ?? dirName.charAt(0).toUpperCase() + dirName.slice(1);
}
item._path = parts.slice(0, -1).join("/");
}
if (mc) item = migrateItem(item, mc, fp, def.format, body);
return item;
});
// Sort (skip for recursive — order comes from _meta.json / scanCollectionDir)
if (def.sortField && !def.recursive) {
const sf = def.sortField;
const dir = def.sortOrder === "asc" ? 1 : -1;
items.sort((a, b) => {
const av = (a as any)[sf] ?? "";
const bv = (b as any)[sf] ?? "";
return av > bv ? dir : av < bv ? -dir : 0;
});
}
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(items));
return;
}
// POST — create / update item
if (req.method === "POST") {
const rawBody = await collectRequestBody(req);
const payload = JSON.parse(rawBody);
const slugValue: string = payload.slug ?? "";
if (!slugValue) {
res.statusCode = 400;
res.end("Missing slug");
return;
}
const safeName = path.basename(slugValue).replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 120);
if (!safeName || safeName === "-") {
res.statusCode = 400;
res.end("Invalid slug");
return;
}
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const filePath = path.join(dir, `${safeName}${ext}`);
const { slug: _s, html: _h, ...itemData } = payload;
writeCollectionFile(filePath, def.format, itemData, payload.content);
res.statusCode = 204;
res.end();
return;
}
// DELETE — remove item by ?slug=
if (req.method === "DELETE") {
const fullUrl = new URL(req.url ?? "", "http://localhost");
const slug = fullUrl.searchParams.get("slug") ?? "";
if (!slug) {
res.statusCode = 400;
res.end("Missing slug parameter");
return;
}
const safeName = path.basename(slug);
const filePath = path.join(dir, `${safeName}${ext}`);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
res.statusCode = 204;
res.end();