-
Notifications
You must be signed in to change notification settings - Fork 35
/
util.ts
53 lines (38 loc) · 1.35 KB
/
util.ts
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
import { join } from "path";
export const convertFilenameToPathname = (filename: string) => {
const pathname = filename
.replace(/(\.page)?\.(ts|tsx)$/, "")
.replace(/(\/)?index/, "");
const segments = pathname.split("/");
const convertedSegments = segments.map(replaceSquareBracketsWithColons).join("/");
const result = `/${convertedSegments}`;
return result;
};
interface Entry {
filename: string;
pathname: string;
}
const constructImportStatement = ({ filename }: Entry, index: number) =>
`import * as $${index} from "./routes/${filename}";`;
const constructRouteStatement = ({ pathname }: Entry, index: number) => `'${pathname}': $${index},`;
export const generate = async (entries: Entry[]) => {
const output = `// DO NOT EDIT. This file is automatically generated.
import type { Manifest } from 'kretes';
${entries.map(constructImportStatement).join("\n")}
const manifest: Manifest = {
routes: {
${entries.map(constructRouteStatement).join("\n")}
},
};
export default manifest;
`;
await Deno.writeTextFile("./manifest.g.ts", output);
};
// PRIVATE
const replaceSquareBracketsWithColons = (segment: string) => {
const wildcardMatch = segment.match(/\[\.\.\.(.+)\]/);
if (wildcardMatch) return `:${wildcardMatch[1]}*`;
const regularMatch = segment.match(/\[(.+)\]/);
if (regularMatch) return `:${regularMatch[1]}`;
return segment;
};