@granite-js/plugin-router 2.5.5 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,231 @@
1
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from "fs";
2
+ import { join, parse } from "path";
3
+ import { parseFileSync } from "@swc/core";
4
+ import { kebabCase, pascalCase } from "es-toolkit";
5
+ import { readFile, writeFile } from "fs/promises";
6
+ import chokidar from "chokidar";
7
+
8
+ //#region src/shared/checkExportRoute.ts
9
+ /**
10
+ * Checks if Route is exported from the file.
11
+ */
12
+ function checkExportRoute(path) {
13
+ try {
14
+ const ast = parseFileSync(path, {
15
+ syntax: "typescript",
16
+ tsx: true
17
+ });
18
+ if (ast.body.some((node) => {
19
+ if (node.type !== "ExportNamedDeclaration") return false;
20
+ return node.specifiers?.some((specifier) => {
21
+ if (specifier.type !== "ExportSpecifier") return false;
22
+ return specifier.orig?.value === "Route" || specifier.exported?.value === "Route";
23
+ });
24
+ })) return true;
25
+ return ast.body.some((node) => {
26
+ if (node.type !== "ExportDeclaration") return false;
27
+ if (node.declaration.type !== "VariableDeclaration") return false;
28
+ return node.declaration.declarations.some((declaration) => declaration.id.type === "Identifier" && declaration.id.value === "Route");
29
+ });
30
+ } catch {
31
+ return false;
32
+ }
33
+ }
34
+
35
+ //#endregion
36
+ //#region src/shared/getComponentName.ts
37
+ function getComponentName(filePath) {
38
+ const segments = filePath.replace(/^pages\//, "").replace(/\.(tsx|ts)$/, "").split("/").filter(Boolean);
39
+ if (segments[segments.length - 1] === "index") segments.pop();
40
+ return segments.map((segment) => pascalCase(segment)).join("") || "Index";
41
+ }
42
+
43
+ //#endregion
44
+ //#region src/shared/getPath.ts
45
+ function getPath(filePath) {
46
+ let path = filePath.replace(/^pages\//, "").replace(/\.[^/.]+$/, "");
47
+ if (path.endsWith("/index")) path = path.replace(/\/index$/, "");
48
+ else if (path === "index") path = "";
49
+ return `/${path}`;
50
+ }
51
+
52
+ //#endregion
53
+ //#region src/shared/template.ts
54
+ const NEW_ROUTE_FILE_TEMPLATE = `import React from 'react';
55
+ import { Text, View } from 'react-native';
56
+ import { createRoute } from '@granite-js/react-native';
57
+
58
+ export const Route = createRoute('%%path%%', {
59
+ validateParams: (params) => params,
60
+ component: %%componentName%%,
61
+ });
62
+
63
+ function %%componentName%%() {
64
+ return (
65
+ <View>
66
+ <Text>Hello %%componentName%%</Text>
67
+ </View>
68
+ );
69
+ }
70
+ `;
71
+ const ROUTER_GEN_TEMPLATE = `/* eslint-disable */
72
+ // This file is auto-generated by @granite-js/react-native. DO NOT EDIT.
73
+ %%pageImports%%
74
+
75
+ declare module '@granite-js/react-native' {
76
+ interface RegisterScreenInput {
77
+ %%pageInputRoutes%%
78
+ }
79
+
80
+ interface RegisterScreen {
81
+ %%pageRoutes%%
82
+ }
83
+ }
84
+ `;
85
+ const NEW_LAYOUT_FILE_TEMPLATE = `import React, { PropsWithChildren } from 'react';
86
+
87
+ export default function %%componentName%%Layout({ children }: PropsWithChildren) {
88
+ return (
89
+ <>
90
+ {children}
91
+ </>
92
+ );
93
+ }
94
+ `;
95
+
96
+ //#endregion
97
+ //#region src/shared/utils/transformTemplate.ts
98
+ /**
99
+ * 템플릿 문자열에서 %%key%% 형식의 플레이스홀더를 values 객체의 값으로 대체합니다.
100
+ * 제네릭 타입 T를 통해 템플릿 문자열의 플레이스홀더 키를 자동으로 추론합니다.
101
+ * 이를 통해 타입 안정성을 보장합니다.
102
+ *
103
+ * @example
104
+ * const str = "안녕하세요 %%name%%님, 당신의 나이는 %%age%%살 입니다."
105
+ * const result = transformTemplate(str, { name: "홍길동", age: "20" })
106
+ * // 결과: "안녕하세요 홍길동님, 당신의 나이는 20살 입니다."
107
+ */
108
+ function transformTemplate(templateString, values) {
109
+ let result = templateString;
110
+ for (const key in values) {
111
+ const placeholder = `%%${key}%%`;
112
+ result = result.replace(new RegExp(placeholder, "g"), values[key]);
113
+ }
114
+ return result;
115
+ }
116
+
117
+ //#endregion
118
+ //#region src/shared/generateRouterFile.ts
119
+ function generateRouterFile(cwd = process.cwd()) {
120
+ function getPageFiles(dir, prefix = "") {
121
+ return readdirSync(join(cwd, dir), { withFileTypes: true }).reduce((acc, file) => {
122
+ if (file.isDirectory()) return [...acc, ...getPageFiles(`${dir}/${file.name}`, `${prefix}${file.name}/`)];
123
+ if (file.name.endsWith(".tsx") || file.name.endsWith(".ts")) {
124
+ const name = parse(file.name).name;
125
+ const ext = parse(file.name).ext;
126
+ return [...acc, `${prefix}${name}${ext}`];
127
+ }
128
+ return acc;
129
+ }, []);
130
+ }
131
+ const allPages = getPageFiles("pages");
132
+ const exportRouteMap = new Map(allPages.map((page) => [page, checkExportRoute(join(cwd, "pages", page))]));
133
+ const pageFiles = allPages.filter((page) => !page.startsWith("_") && exportRouteMap.get(page));
134
+ const generatedContent = transformTemplate(ROUTER_GEN_TEMPLATE, {
135
+ pageImports: pageFiles.map((page) => {
136
+ return transformTemplate("import { Route as _%%componentName%%Route } from '../pages%%pagePath%%';", {
137
+ componentName: getComponentName(page),
138
+ pagePath: getPath(page)
139
+ });
140
+ }).join("\n"),
141
+ pageInputRoutes: pageFiles.map((page) => {
142
+ return transformTemplate(" '%%pagePath%%': (typeof _%%componentName%%Route)['_inputType'];", {
143
+ componentName: getComponentName(page),
144
+ pagePath: getPath(page)
145
+ });
146
+ }).join("\n"),
147
+ pageRoutes: pageFiles.map((page) => {
148
+ return transformTemplate(" '%%pagePath%%': (typeof _%%componentName%%Route)['_outputType'];", {
149
+ componentName: getComponentName(page),
150
+ pagePath: getPath(page)
151
+ });
152
+ }).join("\n")
153
+ });
154
+ const routerFilePath = join(cwd, "src", "router.gen.ts");
155
+ if (existsSync(routerFilePath)) {
156
+ if (readFileSync(routerFilePath, "utf-8") === generatedContent) return;
157
+ }
158
+ writeFileSync(routerFilePath, generatedContent);
159
+ console.log("✅ Router file generated successfully!");
160
+ }
161
+
162
+ //#endregion
163
+ //#region src/shared/getPageName.ts
164
+ function getPageName(filePath) {
165
+ const parts = filePath.split("/");
166
+ const indexOfPages = parts.indexOf("pages");
167
+ if (indexOfPages === -1) return "";
168
+ const relevantParts = parts.slice(indexOfPages + 1);
169
+ if (relevantParts.at(-1)?.startsWith("_")) relevantParts.pop();
170
+ const lastPart = relevantParts.at(-1);
171
+ if (!lastPart) return "";
172
+ return pascalCase(lastPart);
173
+ }
174
+
175
+ //#endregion
176
+ //#region src/shared/transformNewRouteFile.ts
177
+ async function transformNewRouteFile(path) {
178
+ return transformTemplate(NEW_ROUTE_FILE_TEMPLATE, {
179
+ path: getPath(path),
180
+ componentName: getComponentName(path)
181
+ });
182
+ }
183
+ async function transformNewLayoutFile(path) {
184
+ return transformTemplate(NEW_LAYOUT_FILE_TEMPLATE, { componentName: getPageName(path) });
185
+ }
186
+
187
+ //#endregion
188
+ //#region src/shared/watchRouter.ts
189
+ function watchRouter(root = process.cwd()) {
190
+ const generate = () => generateRouterFile(root);
191
+ const watcher = chokidar.watch("./pages", {
192
+ ignored: (path, stats) => {
193
+ return Boolean(stats?.isFile() && !path.endsWith(".ts") && !path.endsWith(".tsx"));
194
+ },
195
+ ignoreInitial: true,
196
+ persistent: true,
197
+ cwd: root
198
+ });
199
+ const handleAdd = async (path) => {
200
+ const file = join(root, path);
201
+ if (await readFile(file, "utf8") !== "") return;
202
+ const filename = parse(path).name;
203
+ if (filename.startsWith("_")) switch (filename) {
204
+ case "_layout":
205
+ console.log("👀 Layout file has been added");
206
+ await writeFile(file, await transformNewLayoutFile(path));
207
+ return;
208
+ default: return;
209
+ }
210
+ const componentName = kebabCase(filename);
211
+ if (componentName !== filename) {
212
+ console.log(`❌ File name should be in kebab-case format. Would you like to rename ${filename} to ${componentName}?`);
213
+ return;
214
+ }
215
+ console.log(`👀 File ${path} has been added`);
216
+ await writeFile(file, await transformNewRouteFile(path));
217
+ generate();
218
+ };
219
+ watcher.on("add", handleAdd);
220
+ watcher.on("change", generate);
221
+ watcher.on("unlink", generate);
222
+ return async () => {
223
+ watcher.off("add", handleAdd);
224
+ watcher.off("change", generate);
225
+ watcher.off("unlink", generate);
226
+ await watcher.close();
227
+ };
228
+ }
229
+
230
+ //#endregion
231
+ export { generateRouterFile as n, watchRouter as t };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@granite-js/plugin-router",
3
3
  "type": "module",
4
- "version": "2.5.5",
4
+ "version": "3.0.0",
5
5
  "license": "Apache-2.0",
6
6
  "description": "A Route Generator for Granite project",
7
7
  "main": "./dist/index.cjs",
@@ -23,6 +23,16 @@
23
23
  "default": "./dist/index.cjs"
24
24
  }
25
25
  },
26
+ "./mpack": {
27
+ "import": {
28
+ "types": "./dist/mpack.d.ts",
29
+ "default": "./dist/mpack.js"
30
+ },
31
+ "require": {
32
+ "types": "./dist/mpack.d.cts",
33
+ "default": "./dist/mpack.cjs"
34
+ }
35
+ },
26
36
  "./package.json": "./package.json"
27
37
  },
28
38
  "scripts": {
@@ -38,15 +48,24 @@
38
48
  "devDependencies": {
39
49
  "@types/node": "24.10.12",
40
50
  "@vitest/coverage-v8": "^4.0.12",
51
+ "rollipop": "1.0.0-alpha.32",
41
52
  "tsdown": "0.20.3",
42
53
  "typescript": "5.9.3",
43
54
  "vitest": "^4.0.12"
44
55
  },
45
56
  "dependencies": {
46
- "@granite-js/plugin-core": "2.5.5",
57
+ "@granite-js/plugin-core": "3.0.0",
47
58
  "@swc/core": "1.15.46",
48
59
  "chokidar": "4.0.1",
49
60
  "es-toolkit": "^1.39.8"
50
61
  },
62
+ "peerDependencies": {
63
+ "rollipop": "*"
64
+ },
65
+ "peerDependenciesMeta": {
66
+ "rollipop": {
67
+ "optional": true
68
+ }
69
+ },
51
70
  "sideEffects": false
52
71
  }