UNPKG

convert-route

Version:

Convert between rou3, Next.js, and path-to-regexp route patterns

41 lines (39 loc) 1.08 kB
import { SegmentMapper } from "./utils/mapper.js"; import { join } from "./utils/join.js"; //#region src/adapters/rou3.ts const mapper = new SegmentMapper().match(/^\*$/, (_, __, ___, index, array) => ({ optional: index === array.length - 1, catchAll: { greedy: false } })).match(/^\*\*$/, () => ({ optional: true, catchAll: { greedy: true } })).match(/^\*:(.+)$/, (match) => ({ optional: true, catchAll: { greedy: false, name: match[1] } })).match(/^\*\*:(.+)$/, (match) => ({ catchAll: { greedy: true, name: match[1] } })).match(/^:(.+)$/, (match) => ({ catchAll: { greedy: false, name: match[1] } })); function fromRou3(path) { return { pattern: path, params: mapper.exec(path) }; } function toRou3(route) { let i = 0; const response = route.params.map((r) => { if (r.catchAll?.greedy) return !r.optional ? `**:${r.catchAll.name || `_${++i}`}` : "**"; if (r.catchAll && !r.catchAll.greedy) return r.optional ? [null, `*`] : `:${r.catchAll.name || `_${++i}`}`; return r.value; }); return join(response); } //#endregion export { fromRou3, toRou3 };