@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.
- package/CHANGELOG.md +24 -0
- package/README.md +17 -0
- package/dist/index.cjs +54 -268
- package/dist/index.d.cts +3 -6
- package/dist/index.d.ts +3 -6
- package/dist/index.js +53 -240
- package/dist/mpack.cjs +30 -0
- package/dist/mpack.d.cts +9 -0
- package/dist/mpack.d.ts +9 -0
- package/dist/mpack.js +29 -0
- package/dist/watchRouter-CfoP6FM2.cjs +276 -0
- package/dist/watchRouter-opiv55Vn.js +231 -0
- package/package.json +21 -2
package/dist/index.js
CHANGED
|
@@ -1,255 +1,68 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
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";
|
|
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/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/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}`;
|
|
1
|
+
import { n as generateRouterFile, t as watchRouter } from "./watchRouter-opiv55Vn.js";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
|
|
4
|
+
//#region src/next/index.ts
|
|
5
|
+
const REQUIRE_CONTEXT_IMPORT = /^(?:\.{1,2}\/)+(?:[^/]+\/)*require\.context(?:\.[^/]+)*$/;
|
|
6
|
+
const REQUIRE_CONTEXT_MODULE = /[\\/]require\.context(?:\.[^/\\]+)*$/;
|
|
7
|
+
function router() {
|
|
8
|
+
return [
|
|
9
|
+
routeGenerator(),
|
|
10
|
+
routeWatcher(),
|
|
11
|
+
pageImports()
|
|
12
|
+
];
|
|
50
13
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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/utils/transformTemplate.ts
|
|
98
|
-
/**
|
|
99
|
-
* 템플릿 문자열에서 %%key%% 형식의 플레이스홀더를 values 객체의 값으로 대체합니다.
|
|
100
|
-
* 제네릭 타입 T를 통해 템플릿 문자열의 플레이스홀더 키를 자동으로 추론하여 타입 안정성을 보장합니다.
|
|
101
|
-
*
|
|
102
|
-
* @example
|
|
103
|
-
* const str = "안녕하세요 %%name%%님, 당신의 나이는 %%age%%살 입니다."
|
|
104
|
-
* const result = transformTemplate(str, { name: "홍길동", age: "20" })
|
|
105
|
-
* // 결과: "안녕하세요 홍길동님, 당신의 나이는 20살 입니다."
|
|
106
|
-
*/
|
|
107
|
-
function transformTemplate(templateString, values) {
|
|
108
|
-
let result = templateString;
|
|
109
|
-
for (const key in values) {
|
|
110
|
-
const placeholder = `%%${key}%%`;
|
|
111
|
-
result = result.replace(new RegExp(placeholder, "g"), values[key]);
|
|
112
|
-
}
|
|
113
|
-
return result;
|
|
14
|
+
function routeGenerator() {
|
|
15
|
+
return {
|
|
16
|
+
name: "granite:router:generate",
|
|
17
|
+
configResolved(config) {
|
|
18
|
+
generateRouterFile(config.root);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
114
21
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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)
|
|
22
|
+
function routeWatcher() {
|
|
23
|
+
return {
|
|
24
|
+
name: "granite:router:watch",
|
|
25
|
+
configureServer(server) {
|
|
26
|
+
const close = watchRouter(server.config.root);
|
|
27
|
+
server.instance.addHook("onClose", async () => {
|
|
28
|
+
await close();
|
|
151
29
|
});
|
|
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/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/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/watchRouter.ts
|
|
189
|
-
function watchRouter() {
|
|
190
|
-
const watcher = chokidar.watch("./pages", {
|
|
191
|
-
ignored: (path, stats) => {
|
|
192
|
-
return Boolean(stats?.isFile() && !path.endsWith(".ts") && !path.endsWith(".tsx"));
|
|
193
|
-
},
|
|
194
|
-
ignoreInitial: true,
|
|
195
|
-
persistent: true,
|
|
196
|
-
cwd: process.cwd()
|
|
197
|
-
});
|
|
198
|
-
const handleAdd = async (path) => {
|
|
199
|
-
if (await readFile(join(process.cwd(), path), "utf8") !== "") return;
|
|
200
|
-
const filename = parse(path).name;
|
|
201
|
-
if (filename.startsWith("_")) switch (filename) {
|
|
202
|
-
case "_layout":
|
|
203
|
-
console.log("👀 Layout file has been added");
|
|
204
|
-
await writeFile(path, await transformNewLayoutFile(path));
|
|
205
|
-
return;
|
|
206
|
-
default: return;
|
|
207
|
-
}
|
|
208
|
-
const componentName = kebabCase(filename);
|
|
209
|
-
if (componentName !== filename) {
|
|
210
|
-
console.log(`❌ File name should be in kebab-case format. Would you like to rename ${filename} to ${componentName}?`);
|
|
211
|
-
return;
|
|
212
30
|
}
|
|
213
|
-
console.log(`👀 File ${path} has been added`);
|
|
214
|
-
await writeFile(path, await transformNewRouteFile(path));
|
|
215
|
-
await generateRouterFile();
|
|
216
|
-
};
|
|
217
|
-
watcher.on("add", handleAdd);
|
|
218
|
-
watcher.on("change", generateRouterFile);
|
|
219
|
-
watcher.on("unlink", generateRouterFile);
|
|
220
|
-
return () => {
|
|
221
|
-
watcher.off("add", handleAdd);
|
|
222
|
-
watcher.off("change", generateRouterFile);
|
|
223
|
-
watcher.off("unlink", generateRouterFile);
|
|
224
|
-
watcher.close();
|
|
225
31
|
};
|
|
226
32
|
}
|
|
227
|
-
|
|
228
|
-
//#endregion
|
|
229
|
-
//#region src/routerPlugin.ts
|
|
230
|
-
const DEFAULT_OPTIONS = { watch: true };
|
|
231
|
-
const router = (options = DEFAULT_OPTIONS) => {
|
|
232
|
-
const resolvedOptions = {
|
|
233
|
-
...DEFAULT_OPTIONS,
|
|
234
|
-
...options
|
|
235
|
-
};
|
|
33
|
+
function pageImports() {
|
|
236
34
|
return {
|
|
237
|
-
name: "router-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
handler
|
|
241
|
-
|
|
35
|
+
name: "granite:router:page-imports",
|
|
36
|
+
resolveId: {
|
|
37
|
+
filter: { id: REQUIRE_CONTEXT_IMPORT },
|
|
38
|
+
handler(source, importer) {
|
|
39
|
+
return importer == null ? null : path.resolve(path.dirname(importer), source);
|
|
242
40
|
}
|
|
243
41
|
},
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
handler
|
|
247
|
-
|
|
248
|
-
|
|
42
|
+
load: {
|
|
43
|
+
filter: { id: REQUIRE_CONTEXT_MODULE },
|
|
44
|
+
handler() {
|
|
45
|
+
return `
|
|
46
|
+
const modules = import.meta.glob('./**/*.{js,jsx,ts,tsx}', { base: './pages', eager: true });
|
|
47
|
+
|
|
48
|
+
export const context = Object.assign(
|
|
49
|
+
(key) => {
|
|
50
|
+
if (!Object.prototype.hasOwnProperty.call(modules, key)) {
|
|
51
|
+
throw new Error(\`Unknown screen: \${key}\`);
|
|
52
|
+
}
|
|
53
|
+
return modules[key];
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
keys: () => Object.keys(modules),
|
|
57
|
+
resolve: (key) => key,
|
|
58
|
+
id: 'pages',
|
|
59
|
+
}
|
|
60
|
+
);
|
|
61
|
+
`;
|
|
249
62
|
}
|
|
250
63
|
}
|
|
251
64
|
};
|
|
252
|
-
}
|
|
65
|
+
}
|
|
253
66
|
|
|
254
67
|
//#endregion
|
|
255
68
|
export { router };
|
package/dist/mpack.cjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_watchRouter = require('./watchRouter-CfoP6FM2.cjs');
|
|
3
|
+
|
|
4
|
+
//#region src/routerPlugin.ts
|
|
5
|
+
const DEFAULT_OPTIONS = { watch: true };
|
|
6
|
+
const router = (options = DEFAULT_OPTIONS) => {
|
|
7
|
+
const resolvedOptions = {
|
|
8
|
+
...DEFAULT_OPTIONS,
|
|
9
|
+
...options
|
|
10
|
+
};
|
|
11
|
+
return {
|
|
12
|
+
name: "router-plugin",
|
|
13
|
+
build: {
|
|
14
|
+
order: "pre",
|
|
15
|
+
handler: () => {
|
|
16
|
+
require_watchRouter.generateRouterFile();
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
dev: {
|
|
20
|
+
order: "pre",
|
|
21
|
+
handler: () => {
|
|
22
|
+
require_watchRouter.generateRouterFile();
|
|
23
|
+
if (resolvedOptions.watch) require_watchRouter.watchRouter();
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
//#endregion
|
|
30
|
+
exports.router = router;
|
package/dist/mpack.d.cts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { GranitePluginCore } from "@granite-js/plugin-core";
|
|
2
|
+
|
|
3
|
+
//#region src/routerPlugin.d.ts
|
|
4
|
+
interface RouterPluginOptions {
|
|
5
|
+
watch?: boolean;
|
|
6
|
+
}
|
|
7
|
+
declare const router: (options?: RouterPluginOptions) => GranitePluginCore;
|
|
8
|
+
//#endregion
|
|
9
|
+
export { router };
|
package/dist/mpack.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { GranitePluginCore } from "@granite-js/plugin-core";
|
|
2
|
+
|
|
3
|
+
//#region src/routerPlugin.d.ts
|
|
4
|
+
interface RouterPluginOptions {
|
|
5
|
+
watch?: boolean;
|
|
6
|
+
}
|
|
7
|
+
declare const router: (options?: RouterPluginOptions) => GranitePluginCore;
|
|
8
|
+
//#endregion
|
|
9
|
+
export { router };
|
package/dist/mpack.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { n as generateRouterFile, t as watchRouter } from "./watchRouter-opiv55Vn.js";
|
|
2
|
+
|
|
3
|
+
//#region src/routerPlugin.ts
|
|
4
|
+
const DEFAULT_OPTIONS = { watch: true };
|
|
5
|
+
const router = (options = DEFAULT_OPTIONS) => {
|
|
6
|
+
const resolvedOptions = {
|
|
7
|
+
...DEFAULT_OPTIONS,
|
|
8
|
+
...options
|
|
9
|
+
};
|
|
10
|
+
return {
|
|
11
|
+
name: "router-plugin",
|
|
12
|
+
build: {
|
|
13
|
+
order: "pre",
|
|
14
|
+
handler: () => {
|
|
15
|
+
generateRouterFile();
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
dev: {
|
|
19
|
+
order: "pre",
|
|
20
|
+
handler: () => {
|
|
21
|
+
generateRouterFile();
|
|
22
|
+
if (resolvedOptions.watch) watchRouter();
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
//#endregion
|
|
29
|
+
export { router };
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __copyProps = (to, from, except, desc) => {
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
10
|
+
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
13
|
+
__defProp(to, key, {
|
|
14
|
+
get: ((k) => from[k]).bind(null, key),
|
|
15
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return to;
|
|
21
|
+
};
|
|
22
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
23
|
+
value: mod,
|
|
24
|
+
enumerable: true
|
|
25
|
+
}) : target, mod));
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
let fs = require("fs");
|
|
29
|
+
let path = require("path");
|
|
30
|
+
let _swc_core = require("@swc/core");
|
|
31
|
+
let es_toolkit = require("es-toolkit");
|
|
32
|
+
let fs_promises = require("fs/promises");
|
|
33
|
+
let chokidar = require("chokidar");
|
|
34
|
+
chokidar = __toESM(chokidar);
|
|
35
|
+
|
|
36
|
+
//#region src/shared/checkExportRoute.ts
|
|
37
|
+
/**
|
|
38
|
+
* Checks if Route is exported from the file.
|
|
39
|
+
*/
|
|
40
|
+
function checkExportRoute(path) {
|
|
41
|
+
try {
|
|
42
|
+
const ast = (0, _swc_core.parseFileSync)(path, {
|
|
43
|
+
syntax: "typescript",
|
|
44
|
+
tsx: true
|
|
45
|
+
});
|
|
46
|
+
if (ast.body.some((node) => {
|
|
47
|
+
if (node.type !== "ExportNamedDeclaration") return false;
|
|
48
|
+
return node.specifiers?.some((specifier) => {
|
|
49
|
+
if (specifier.type !== "ExportSpecifier") return false;
|
|
50
|
+
return specifier.orig?.value === "Route" || specifier.exported?.value === "Route";
|
|
51
|
+
});
|
|
52
|
+
})) return true;
|
|
53
|
+
return ast.body.some((node) => {
|
|
54
|
+
if (node.type !== "ExportDeclaration") return false;
|
|
55
|
+
if (node.declaration.type !== "VariableDeclaration") return false;
|
|
56
|
+
return node.declaration.declarations.some((declaration) => declaration.id.type === "Identifier" && declaration.id.value === "Route");
|
|
57
|
+
});
|
|
58
|
+
} catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/shared/getComponentName.ts
|
|
65
|
+
function getComponentName(filePath) {
|
|
66
|
+
const segments = filePath.replace(/^pages\//, "").replace(/\.(tsx|ts)$/, "").split("/").filter(Boolean);
|
|
67
|
+
if (segments[segments.length - 1] === "index") segments.pop();
|
|
68
|
+
return segments.map((segment) => (0, es_toolkit.pascalCase)(segment)).join("") || "Index";
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
//#endregion
|
|
72
|
+
//#region src/shared/getPath.ts
|
|
73
|
+
function getPath(filePath) {
|
|
74
|
+
let path = filePath.replace(/^pages\//, "").replace(/\.[^/.]+$/, "");
|
|
75
|
+
if (path.endsWith("/index")) path = path.replace(/\/index$/, "");
|
|
76
|
+
else if (path === "index") path = "";
|
|
77
|
+
return `/${path}`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/shared/template.ts
|
|
82
|
+
const NEW_ROUTE_FILE_TEMPLATE = `import React from 'react';
|
|
83
|
+
import { Text, View } from 'react-native';
|
|
84
|
+
import { createRoute } from '@granite-js/react-native';
|
|
85
|
+
|
|
86
|
+
export const Route = createRoute('%%path%%', {
|
|
87
|
+
validateParams: (params) => params,
|
|
88
|
+
component: %%componentName%%,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
function %%componentName%%() {
|
|
92
|
+
return (
|
|
93
|
+
<View>
|
|
94
|
+
<Text>Hello %%componentName%%</Text>
|
|
95
|
+
</View>
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
`;
|
|
99
|
+
const ROUTER_GEN_TEMPLATE = `/* eslint-disable */
|
|
100
|
+
// This file is auto-generated by @granite-js/react-native. DO NOT EDIT.
|
|
101
|
+
%%pageImports%%
|
|
102
|
+
|
|
103
|
+
declare module '@granite-js/react-native' {
|
|
104
|
+
interface RegisterScreenInput {
|
|
105
|
+
%%pageInputRoutes%%
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
interface RegisterScreen {
|
|
109
|
+
%%pageRoutes%%
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
`;
|
|
113
|
+
const NEW_LAYOUT_FILE_TEMPLATE = `import React, { PropsWithChildren } from 'react';
|
|
114
|
+
|
|
115
|
+
export default function %%componentName%%Layout({ children }: PropsWithChildren) {
|
|
116
|
+
return (
|
|
117
|
+
<>
|
|
118
|
+
{children}
|
|
119
|
+
</>
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
`;
|
|
123
|
+
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/shared/utils/transformTemplate.ts
|
|
126
|
+
/**
|
|
127
|
+
* 템플릿 문자열에서 %%key%% 형식의 플레이스홀더를 values 객체의 값으로 대체합니다.
|
|
128
|
+
* 제네릭 타입 T를 통해 템플릿 문자열의 플레이스홀더 키를 자동으로 추론합니다.
|
|
129
|
+
* 이를 통해 타입 안정성을 보장합니다.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* const str = "안녕하세요 %%name%%님, 당신의 나이는 %%age%%살 입니다."
|
|
133
|
+
* const result = transformTemplate(str, { name: "홍길동", age: "20" })
|
|
134
|
+
* // 결과: "안녕하세요 홍길동님, 당신의 나이는 20살 입니다."
|
|
135
|
+
*/
|
|
136
|
+
function transformTemplate(templateString, values) {
|
|
137
|
+
let result = templateString;
|
|
138
|
+
for (const key in values) {
|
|
139
|
+
const placeholder = `%%${key}%%`;
|
|
140
|
+
result = result.replace(new RegExp(placeholder, "g"), values[key]);
|
|
141
|
+
}
|
|
142
|
+
return result;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
//#endregion
|
|
146
|
+
//#region src/shared/generateRouterFile.ts
|
|
147
|
+
function generateRouterFile(cwd = process.cwd()) {
|
|
148
|
+
function getPageFiles(dir, prefix = "") {
|
|
149
|
+
return (0, fs.readdirSync)((0, path.join)(cwd, dir), { withFileTypes: true }).reduce((acc, file) => {
|
|
150
|
+
if (file.isDirectory()) return [...acc, ...getPageFiles(`${dir}/${file.name}`, `${prefix}${file.name}/`)];
|
|
151
|
+
if (file.name.endsWith(".tsx") || file.name.endsWith(".ts")) {
|
|
152
|
+
const name = (0, path.parse)(file.name).name;
|
|
153
|
+
const ext = (0, path.parse)(file.name).ext;
|
|
154
|
+
return [...acc, `${prefix}${name}${ext}`];
|
|
155
|
+
}
|
|
156
|
+
return acc;
|
|
157
|
+
}, []);
|
|
158
|
+
}
|
|
159
|
+
const allPages = getPageFiles("pages");
|
|
160
|
+
const exportRouteMap = new Map(allPages.map((page) => [page, checkExportRoute((0, path.join)(cwd, "pages", page))]));
|
|
161
|
+
const pageFiles = allPages.filter((page) => !page.startsWith("_") && exportRouteMap.get(page));
|
|
162
|
+
const generatedContent = transformTemplate(ROUTER_GEN_TEMPLATE, {
|
|
163
|
+
pageImports: pageFiles.map((page) => {
|
|
164
|
+
return transformTemplate("import { Route as _%%componentName%%Route } from '../pages%%pagePath%%';", {
|
|
165
|
+
componentName: getComponentName(page),
|
|
166
|
+
pagePath: getPath(page)
|
|
167
|
+
});
|
|
168
|
+
}).join("\n"),
|
|
169
|
+
pageInputRoutes: pageFiles.map((page) => {
|
|
170
|
+
return transformTemplate(" '%%pagePath%%': (typeof _%%componentName%%Route)['_inputType'];", {
|
|
171
|
+
componentName: getComponentName(page),
|
|
172
|
+
pagePath: getPath(page)
|
|
173
|
+
});
|
|
174
|
+
}).join("\n"),
|
|
175
|
+
pageRoutes: pageFiles.map((page) => {
|
|
176
|
+
return transformTemplate(" '%%pagePath%%': (typeof _%%componentName%%Route)['_outputType'];", {
|
|
177
|
+
componentName: getComponentName(page),
|
|
178
|
+
pagePath: getPath(page)
|
|
179
|
+
});
|
|
180
|
+
}).join("\n")
|
|
181
|
+
});
|
|
182
|
+
const routerFilePath = (0, path.join)(cwd, "src", "router.gen.ts");
|
|
183
|
+
if ((0, fs.existsSync)(routerFilePath)) {
|
|
184
|
+
if ((0, fs.readFileSync)(routerFilePath, "utf-8") === generatedContent) return;
|
|
185
|
+
}
|
|
186
|
+
(0, fs.writeFileSync)(routerFilePath, generatedContent);
|
|
187
|
+
console.log("✅ Router file generated successfully!");
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
//#endregion
|
|
191
|
+
//#region src/shared/getPageName.ts
|
|
192
|
+
function getPageName(filePath) {
|
|
193
|
+
const parts = filePath.split("/");
|
|
194
|
+
const indexOfPages = parts.indexOf("pages");
|
|
195
|
+
if (indexOfPages === -1) return "";
|
|
196
|
+
const relevantParts = parts.slice(indexOfPages + 1);
|
|
197
|
+
if (relevantParts.at(-1)?.startsWith("_")) relevantParts.pop();
|
|
198
|
+
const lastPart = relevantParts.at(-1);
|
|
199
|
+
if (!lastPart) return "";
|
|
200
|
+
return (0, es_toolkit.pascalCase)(lastPart);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
//#endregion
|
|
204
|
+
//#region src/shared/transformNewRouteFile.ts
|
|
205
|
+
async function transformNewRouteFile(path) {
|
|
206
|
+
return transformTemplate(NEW_ROUTE_FILE_TEMPLATE, {
|
|
207
|
+
path: getPath(path),
|
|
208
|
+
componentName: getComponentName(path)
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
async function transformNewLayoutFile(path) {
|
|
212
|
+
return transformTemplate(NEW_LAYOUT_FILE_TEMPLATE, { componentName: getPageName(path) });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
//#endregion
|
|
216
|
+
//#region src/shared/watchRouter.ts
|
|
217
|
+
function watchRouter(root = process.cwd()) {
|
|
218
|
+
const generate = () => generateRouterFile(root);
|
|
219
|
+
const watcher = chokidar.default.watch("./pages", {
|
|
220
|
+
ignored: (path$1, stats) => {
|
|
221
|
+
return Boolean(stats?.isFile() && !path$1.endsWith(".ts") && !path$1.endsWith(".tsx"));
|
|
222
|
+
},
|
|
223
|
+
ignoreInitial: true,
|
|
224
|
+
persistent: true,
|
|
225
|
+
cwd: root
|
|
226
|
+
});
|
|
227
|
+
const handleAdd = async (path$2) => {
|
|
228
|
+
const file = (0, path.join)(root, path$2);
|
|
229
|
+
if (await (0, fs_promises.readFile)(file, "utf8") !== "") return;
|
|
230
|
+
const filename = (0, path.parse)(path$2).name;
|
|
231
|
+
if (filename.startsWith("_")) switch (filename) {
|
|
232
|
+
case "_layout":
|
|
233
|
+
console.log("👀 Layout file has been added");
|
|
234
|
+
await (0, fs_promises.writeFile)(file, await transformNewLayoutFile(path$2));
|
|
235
|
+
return;
|
|
236
|
+
default: return;
|
|
237
|
+
}
|
|
238
|
+
const componentName = (0, es_toolkit.kebabCase)(filename);
|
|
239
|
+
if (componentName !== filename) {
|
|
240
|
+
console.log(`❌ File name should be in kebab-case format. Would you like to rename ${filename} to ${componentName}?`);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
console.log(`👀 File ${path$2} has been added`);
|
|
244
|
+
await (0, fs_promises.writeFile)(file, await transformNewRouteFile(path$2));
|
|
245
|
+
generate();
|
|
246
|
+
};
|
|
247
|
+
watcher.on("add", handleAdd);
|
|
248
|
+
watcher.on("change", generate);
|
|
249
|
+
watcher.on("unlink", generate);
|
|
250
|
+
return async () => {
|
|
251
|
+
watcher.off("add", handleAdd);
|
|
252
|
+
watcher.off("change", generate);
|
|
253
|
+
watcher.off("unlink", generate);
|
|
254
|
+
await watcher.close();
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
//#endregion
|
|
259
|
+
Object.defineProperty(exports, '__toESM', {
|
|
260
|
+
enumerable: true,
|
|
261
|
+
get: function () {
|
|
262
|
+
return __toESM;
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
Object.defineProperty(exports, 'generateRouterFile', {
|
|
266
|
+
enumerable: true,
|
|
267
|
+
get: function () {
|
|
268
|
+
return generateRouterFile;
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
Object.defineProperty(exports, 'watchRouter', {
|
|
272
|
+
enumerable: true,
|
|
273
|
+
get: function () {
|
|
274
|
+
return watchRouter;
|
|
275
|
+
}
|
|
276
|
+
});
|