@alice-lib/generator-routes 1.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/README.md ADDED
@@ -0,0 +1,3 @@
1
+ ### @alice-lib/generator-routes
2
+
3
+
@@ -0,0 +1,5 @@
1
+ import type { PageModules, RouteItem } from './types';
2
+ /** 生成路由配置 */
3
+ export declare const generateRoutes: (modules: PageModules) => Promise<RouteItem[]>;
4
+ /** 扁平化路由树 */
5
+ export declare const flattenRoutes: (routes: RouteItem[]) => RouteItem[];
@@ -0,0 +1,370 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
3
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
5
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
6
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
7
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
8
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
9
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
10
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
11
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
12
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
13
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
14
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
15
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
16
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
17
+ import { Navigate } from 'react-router-dom';
18
+ import { jsx as _jsx } from "react/jsx-runtime";
19
+ /** 需要排除的目录名(小写匹配) */
20
+ var EXCLUDED_DIRS = new Set(['component', 'components', 'util', 'utils', 'constant', 'constants', 'hook', 'hooks', 'service', 'services', 'store', 'stores', 'style', 'styles', 'type', 'types']);
21
+
22
+ /** 解析文件名中的排序前缀,如 `1__user` → { order: 1, name: 'user' } */
23
+ var parseOrderedName = function parseOrderedName(name) {
24
+ var match = name.match(/^(\d+)__(.+)$/);
25
+ if (match) {
26
+ return {
27
+ order: parseInt(match[1], 10),
28
+ name: match[2]
29
+ };
30
+ }
31
+ return {
32
+ name: name
33
+ };
34
+ };
35
+
36
+ /** 检查路径段是否应该被排除 */
37
+ var shouldExclude = function shouldExclude(segment) {
38
+ if (segment.startsWith('_')) return true;
39
+ var baseName = parseOrderedName(segment).name.toLowerCase();
40
+ return EXCLUDED_DIRS.has(baseName);
41
+ };
42
+ /** 构建路由树 */
43
+ var buildRouteTree = function buildRouteTree(modules) {
44
+ var root = {
45
+ segment: '',
46
+ fullPath: '',
47
+ children: new Map()
48
+ };
49
+ for (var _i = 0, _Object$keys = Object.keys(modules); _i < _Object$keys.length; _i++) {
50
+ var modulePath = _Object$keys[_i];
51
+ var match = modulePath.match(/^\/src\/pages\/(.+?)(?:\/index)?\.tsx$/);
52
+ if (!match) continue;
53
+ var pathPart = match[1];
54
+ var segments = pathPart === 'index' ? [] : pathPart.split('/');
55
+ if (segments.some(shouldExclude)) continue;
56
+ var current = root;
57
+ var accumulatedPath = '';
58
+ var _iterator = _createForOfIteratorHelper(segments),
59
+ _step;
60
+ try {
61
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
62
+ var segment = _step.value;
63
+ var _parseOrderedName = parseOrderedName(segment),
64
+ order = _parseOrderedName.order,
65
+ name = _parseOrderedName.name;
66
+ accumulatedPath += "/".concat(name);
67
+ if (!current.children.has(segment)) {
68
+ current.children.set(segment, {
69
+ segment: name,
70
+ fileOrder: order,
71
+ fullPath: accumulatedPath,
72
+ children: new Map()
73
+ });
74
+ }
75
+ current = current.children.get(segment);
76
+ }
77
+ } catch (err) {
78
+ _iterator.e(err);
79
+ } finally {
80
+ _iterator.f();
81
+ }
82
+ current.modulePath = modulePath;
83
+ }
84
+ return root;
85
+ };
86
+
87
+ /** 解析节点:加载模块配置 */
88
+ var resolveNode = /*#__PURE__*/function () {
89
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(node, modules) {
90
+ var config, hasComponent, _module$routerConfig, module, children, _iterator2, _step2, child;
91
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
92
+ while (1) switch (_context.prev = _context.next) {
93
+ case 0:
94
+ config = {};
95
+ hasComponent = false;
96
+ if (!node.modulePath) {
97
+ _context.next = 8;
98
+ break;
99
+ }
100
+ _context.next = 5;
101
+ return modules[node.modulePath]();
102
+ case 5:
103
+ module = _context.sent;
104
+ config = (_module$routerConfig = module.routerConfig) !== null && _module$routerConfig !== void 0 ? _module$routerConfig : {};
105
+ hasComponent = !!module.default;
106
+ case 8:
107
+ children = [];
108
+ _iterator2 = _createForOfIteratorHelper(node.children.values());
109
+ _context.prev = 10;
110
+ _iterator2.s();
111
+ case 12:
112
+ if ((_step2 = _iterator2.n()).done) {
113
+ _context.next = 21;
114
+ break;
115
+ }
116
+ child = _step2.value;
117
+ _context.t0 = children;
118
+ _context.next = 17;
119
+ return resolveNode(child, modules);
120
+ case 17:
121
+ _context.t1 = _context.sent;
122
+ _context.t0.push.call(_context.t0, _context.t1);
123
+ case 19:
124
+ _context.next = 12;
125
+ break;
126
+ case 21:
127
+ _context.next = 26;
128
+ break;
129
+ case 23:
130
+ _context.prev = 23;
131
+ _context.t2 = _context["catch"](10);
132
+ _iterator2.e(_context.t2);
133
+ case 26:
134
+ _context.prev = 26;
135
+ _iterator2.f();
136
+ return _context.finish(26);
137
+ case 29:
138
+ return _context.abrupt("return", {
139
+ node: node,
140
+ config: config,
141
+ hasComponent: hasComponent,
142
+ children: children
143
+ });
144
+ case 30:
145
+ case "end":
146
+ return _context.stop();
147
+ }
148
+ }, _callee, null, [[10, 23, 26, 29]]);
149
+ }));
150
+ return function resolveNode(_x, _x2) {
151
+ return _ref.apply(this, arguments);
152
+ };
153
+ }();
154
+
155
+ /** 排序函数:routerConfig.order > 文件名 order > 字母顺序 */
156
+ var sortResolvedNodes = function sortResolvedNodes(nodes) {
157
+ return nodes.sort(function (a, b) {
158
+ var _a$config$order, _b$config$order;
159
+ // 优先使用 routerConfig.order,其次使用文件名 order
160
+ var orderA = (_a$config$order = a.config.order) !== null && _a$config$order !== void 0 ? _a$config$order : a.node.fileOrder;
161
+ var orderB = (_b$config$order = b.config.order) !== null && _b$config$order !== void 0 ? _b$config$order : b.node.fileOrder;
162
+
163
+ // 都有 order 时按数字排序
164
+ if (orderA !== undefined && orderB !== undefined) {
165
+ if (orderA !== orderB) return orderA - orderB;
166
+ }
167
+ // 只有一个有 order 时,有 order 的优先
168
+ if (orderA !== undefined && orderB === undefined) return -1;
169
+ if (orderA === undefined && orderB !== undefined) return 1;
170
+
171
+ // 都没有 order 时按 segment 字母排序
172
+ return a.node.segment.localeCompare(b.node.segment);
173
+ });
174
+ };
175
+
176
+ /** 获取第一个子路由的路径 */
177
+ var getFirstChildPath = function getFirstChildPath(children) {
178
+ var first = children[0];
179
+ if (!first) return undefined;
180
+ if ('path' in first && first.path) return first.path;
181
+ return undefined;
182
+ };
183
+
184
+ /** 将解析后的节点转换为路由对象 */
185
+ var resolvedToRoutes = function resolvedToRoutes(resolved, modules) {
186
+ var isRoot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
187
+ var routes = [];
188
+ var sortedChildren = sortResolvedNodes(resolved.children);
189
+ var _iterator3 = _createForOfIteratorHelper(sortedChildren),
190
+ _step3;
191
+ try {
192
+ var _loop = function _loop() {
193
+ var _config$order;
194
+ var child = _step3.value;
195
+ var childRoutes = resolvedToRoutes(child, modules);
196
+ var node = child.node,
197
+ config = child.config,
198
+ hasComponent = child.hasComponent;
199
+ var finalOrder = (_config$order = config.order) !== null && _config$order !== void 0 ? _config$order : node.fileOrder;
200
+ if (hasComponent && node.modulePath) {
201
+ var _config$path;
202
+ // 有组件的路由
203
+ var _moduleLoader = modules[node.modulePath];
204
+ var route = {
205
+ path: (_config$path = config.path) !== null && _config$path !== void 0 ? _config$path : node.segment,
206
+ lazy: function () {
207
+ var _lazy2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
208
+ var mod;
209
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
210
+ while (1) switch (_context3.prev = _context3.next) {
211
+ case 0:
212
+ _context3.next = 2;
213
+ return _moduleLoader();
214
+ case 2:
215
+ mod = _context3.sent;
216
+ return _context3.abrupt("return", {
217
+ Component: mod.default
218
+ });
219
+ case 4:
220
+ case "end":
221
+ return _context3.stop();
222
+ }
223
+ }, _callee3);
224
+ }));
225
+ function lazy() {
226
+ return _lazy2.apply(this, arguments);
227
+ }
228
+ return lazy;
229
+ }(),
230
+ meta: _objectSpread(_objectSpread({}, config), {}, {
231
+ order: finalOrder
232
+ })
233
+ };
234
+
235
+ // 处理显式配置的重定向或子路由
236
+ if (config.redirect) {
237
+ route.children = [{
238
+ index: true,
239
+ element: /*#__PURE__*/_jsx(Navigate, {
240
+ to: config.redirect,
241
+ replace: true
242
+ })
243
+ }].concat(_toConsumableArray(childRoutes));
244
+ } else if (childRoutes.length > 0) {
245
+ route.children = childRoutes;
246
+ }
247
+ routes.push(route);
248
+ } else if (childRoutes.length > 0 || node.modulePath) {
249
+ var _config$redirect, _config$path2;
250
+ // 无组件的目录节点(纯目录或只导出 routerConfig)
251
+ var redirectPath = (_config$redirect = config.redirect) !== null && _config$redirect !== void 0 ? _config$redirect : getFirstChildPath(childRoutes);
252
+ var dirRoute = {
253
+ path: (_config$path2 = config.path) !== null && _config$path2 !== void 0 ? _config$path2 : node.segment,
254
+ meta: _objectSpread(_objectSpread({}, config), {}, {
255
+ order: finalOrder,
256
+ redirect: redirectPath
257
+ })
258
+ };
259
+ if (redirectPath && childRoutes.length > 0) {
260
+ dirRoute.children = [{
261
+ index: true,
262
+ element: /*#__PURE__*/_jsx(Navigate, {
263
+ to: redirectPath,
264
+ replace: true
265
+ })
266
+ }].concat(_toConsumableArray(childRoutes));
267
+ } else if (childRoutes.length > 0) {
268
+ dirRoute.children = childRoutes;
269
+ }
270
+ routes.push(dirRoute);
271
+ }
272
+ };
273
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
274
+ _loop();
275
+ }
276
+
277
+ // 处理根目录的 index 页面
278
+ } catch (err) {
279
+ _iterator3.e(err);
280
+ } finally {
281
+ _iterator3.f();
282
+ }
283
+ if (isRoot && resolved.hasComponent && resolved.node.modulePath) {
284
+ var moduleLoader = modules[resolved.node.modulePath];
285
+ var indexRoute = {
286
+ index: true,
287
+ lazy: function () {
288
+ var _lazy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
289
+ var mod;
290
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
291
+ while (1) switch (_context2.prev = _context2.next) {
292
+ case 0:
293
+ _context2.next = 2;
294
+ return moduleLoader();
295
+ case 2:
296
+ mod = _context2.sent;
297
+ return _context2.abrupt("return", {
298
+ Component: mod.default
299
+ });
300
+ case 4:
301
+ case "end":
302
+ return _context2.stop();
303
+ }
304
+ }, _callee2);
305
+ }));
306
+ function lazy() {
307
+ return _lazy.apply(this, arguments);
308
+ }
309
+ return lazy;
310
+ }(),
311
+ meta: resolved.config
312
+ };
313
+ routes.unshift(indexRoute);
314
+ }
315
+ return routes;
316
+ };
317
+
318
+ /** 生成路由配置 */
319
+ export var generateRoutes = /*#__PURE__*/function () {
320
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(modules) {
321
+ var tree, indexModule, resolved;
322
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
323
+ while (1) switch (_context4.prev = _context4.next) {
324
+ case 0:
325
+ tree = buildRouteTree(modules);
326
+ indexModule = Object.keys(modules).find(function (p) {
327
+ return p === '/src/pages/index.tsx';
328
+ });
329
+ if (indexModule) {
330
+ tree.modulePath = indexModule;
331
+ }
332
+ _context4.next = 5;
333
+ return resolveNode(tree, modules);
334
+ case 5:
335
+ resolved = _context4.sent;
336
+ return _context4.abrupt("return", resolvedToRoutes(resolved, modules, true));
337
+ case 7:
338
+ case "end":
339
+ return _context4.stop();
340
+ }
341
+ }, _callee4);
342
+ }));
343
+ return function generateRoutes(_x3) {
344
+ return _ref2.apply(this, arguments);
345
+ };
346
+ }();
347
+
348
+ /** 扁平化路由树 */
349
+ export var flattenRoutes = function flattenRoutes(routes) {
350
+ var result = [];
351
+ var traverse = function traverse(items) {
352
+ var _iterator4 = _createForOfIteratorHelper(items),
353
+ _step4;
354
+ try {
355
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
356
+ var item = _step4.value;
357
+ result.push(item);
358
+ if ('children' in item && item.children) {
359
+ traverse(item.children);
360
+ }
361
+ }
362
+ } catch (err) {
363
+ _iterator4.e(err);
364
+ } finally {
365
+ _iterator4.f();
366
+ }
367
+ };
368
+ traverse(routes);
369
+ return result;
370
+ };
package/lib/hooks.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { RouteConfig } from './types';
2
+ /** 获取当前路由的配置信息 */
3
+ export declare const useRouteConfig: () => RouteConfig | undefined;
4
+ /** 获取所有匹配路由的配置信息(从根到当前) */
5
+ export declare const useRouteConfigs: () => RouteConfig[];
package/lib/hooks.js ADDED
@@ -0,0 +1,16 @@
1
+ import { useMatches } from 'react-router-dom';
2
+ /** 获取当前路由的配置信息 */
3
+ export var useRouteConfig = function useRouteConfig() {
4
+ var _ref;
5
+ var matches = useMatches();
6
+ var current = matches[matches.length - 1];
7
+ return (_ref = current === null || current === void 0 ? void 0 : current.handle) !== null && _ref !== void 0 ? _ref : undefined;
8
+ };
9
+
10
+ /** 获取所有匹配路由的配置信息(从根到当前) */
11
+ export var useRouteConfigs = function useRouteConfigs() {
12
+ var matches = useMatches();
13
+ return matches.map(function (m) {
14
+ return m.handle;
15
+ }).filter(Boolean);
16
+ };
package/lib/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { generateRoutes } from './generator';
2
+ export { useRouteConfig, useRouteConfigs } from './hooks';
3
+ export type { PageModule, RouteConfig, RouteItem } from './types';
package/lib/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { generateRoutes } from "./generator";
2
+ export { useRouteConfig, useRouteConfigs } from "./hooks";
package/lib/types.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { IndexRouteObject, NonIndexRouteObject } from 'react-router-dom';
2
+ import type { ComponentType } from 'react';
3
+ export interface RouteConfig {
4
+ /** 排序权重,数字越小越靠前 */
5
+ order?: number;
6
+ /** 页面标题 */
7
+ title?: string;
8
+ /** 菜单图标 */
9
+ icon?: string;
10
+ /** 是否在导航中隐藏 */
11
+ hidden?: boolean;
12
+ /** 是否为首页(index route) */
13
+ index?: boolean;
14
+ /** 自定义路径,默认根据目录结构生成 */
15
+ path?: string;
16
+ /** 是否使用 Layout 包裹,默认 true */
17
+ useLayout?: boolean;
18
+ /** 重定向路径 */
19
+ redirect?: string;
20
+ /** 其他元数据 */
21
+ [key: string]: unknown;
22
+ }
23
+ export interface PageModule {
24
+ default?: ComponentType;
25
+ routerConfig?: RouteConfig;
26
+ }
27
+ export type PageModuleLoader = () => Promise<PageModule>;
28
+ export type PageModules = Record<string, PageModuleLoader>;
29
+ type BaseRouteItem = {
30
+ meta?: RouteConfig;
31
+ handle?: RouteConfig;
32
+ };
33
+ export type IndexRouteItem = Omit<IndexRouteObject, 'children'> & BaseRouteItem;
34
+ export type NonIndexRouteItem = Omit<NonIndexRouteObject, 'children' | 'index'> & BaseRouteItem & {
35
+ index?: false;
36
+ children?: RouteItem[];
37
+ };
38
+ export type RouteItem = IndexRouteItem | NonIndexRouteItem;
39
+ export {};
package/lib/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@alice-lib/generator-routes",
3
+ "author": "senjyouhara",
4
+ "version": "1.0.0",
5
+ "description": "自动生成路由信息",
6
+ "main": "lib/index.js",
7
+ "module": "lib/index.js",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./lib/index.js",
11
+ "require": "./lib/index.js",
12
+ "default": "./lib/index.js"
13
+ }
14
+ },
15
+ "scripts": {
16
+ "start": "dumi dev",
17
+ "build": "father build",
18
+ "prepublishOnly": "npm run build"
19
+ },
20
+ "files": [
21
+ "lib"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "registry": "https://registry.npmjs.org/"
26
+ },
27
+ "peerDependencies": {
28
+ "react": "^17.0.0",
29
+ "react-dom": "^17.0.0",
30
+ "react-router-dom": "^6.0.0"
31
+ },
32
+ "dependencies": {},
33
+ "devDependencies": {
34
+ "raf": "^3.4.1"
35
+ }
36
+ }