@uxf/router 10.0.0-beta.3 → 10.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 CHANGED
@@ -119,13 +119,13 @@ Create sitemap items
119
119
  ```tsx
120
120
  // sitemap-items.ts in @app-routes
121
121
 
122
- import { sitemapGenerator } from "@app-routes";
122
+ import { createSitemapGenerator, routeToUrl } from "@app-routes";
123
123
 
124
- export const sitemapItems = sitemapGenerator
125
- .add("index", async () => ({ loc: "http://localhost", lastmod: "2021-01-01", priority: 1 }))
126
- .add("blog/detail", async () => [
127
- { loc: "http://localhost/bolg/1", priority: 2 },
128
- { loc: "http://localhost/bolg/2", priority: 2 },
124
+ export const sitemapItems = createSitemapGenerator({baseUrl: 'http://localhost:3000', defaultPriority: 1})
125
+ .add("index", async (route) => ({ loc: routeToUrl(route) }))
126
+ .add("blog/detail", async (route) => [
127
+ { loc: routeToUrl(route, {id: 1}), priority: 2 },
128
+ { loc: routeToUrl(route, {id: 2}), priority: 2 },
129
129
  ])
130
130
  .skip("admin/index")
131
131
  .exhaustive();
package/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
+ export * from "./helper";
1
2
  export * from "./router";
2
3
  export * from "./types";
3
- export * from "./helper";
package/index.js CHANGED
@@ -14,6 +14,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./helper"), exports);
17
18
  __exportStar(require("./router"), exports);
18
19
  __exportStar(require("./types"), exports);
19
- __exportStar(require("./helper"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uxf/router",
3
- "version": "10.0.0-beta.3",
3
+ "version": "10.0.0",
4
4
  "description": "UXF Router",
5
5
  "author": "UXFans <dev@uxf.cz>",
6
6
  "homepage": "https://gitlab.com/uxf-npm/router#readme",
@@ -23,10 +23,13 @@
23
23
  "url": "https://gitlab.com/uxf-npm/router/issues"
24
24
  },
25
25
  "dependencies": {
26
- "qs": "^6.10.1"
26
+ "qs": "6.11.2"
27
27
  },
28
28
  "peerDependencies": {
29
- "react": "17 - 18",
30
- "react-dom": "17 - 18"
29
+ "next": ">= 12"
30
+ },
31
+ "devDependencies": {
32
+ "@types/qs": "6.9.8",
33
+ "next": "13.5.4"
31
34
  }
32
35
  }
package/router.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { LinkProps } from "next/link";
2
- import { SitemapGeneratorType } from "./sitemapGenerator";
2
+ import { SitemapGeneratorOptions, SitemapGeneratorType } from "./sitemapGenerator";
3
3
  import { QueryParams } from "./types";
4
4
  export type FunctionParametersGenerator<RouteList> = {
5
5
  [K in keyof RouteList]: RouteList[K] extends null ? [K] : [K, RouteList[K]];
@@ -9,7 +9,7 @@ type RouteToUrlFunction<RouteList> = (...args: FunctionParametersGenerator<Route
9
9
  type Router<RouteList> = {
10
10
  route: RouteFunction<RouteList>;
11
11
  routeToUrl: RouteToUrlFunction<RouteList>;
12
- sitemapGenerator: SitemapGeneratorType<RouteList>;
12
+ createSitemapGenerator: (options?: SitemapGeneratorOptions) => SitemapGeneratorType<RouteList>;
13
13
  routes: {
14
14
  [key in keyof RouteList]: string;
15
15
  };
package/router.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createRouter = void 0;
4
+ const router_1 = require("next/router");
4
5
  const qs_1 = require("qs");
5
6
  const sitemapGenerator_1 = require("./sitemapGenerator");
6
- const router_1 = require("next/router");
7
7
  function createRouter(routes) {
8
8
  return {
9
9
  route: (route, params = undefined) => ({
@@ -20,8 +20,38 @@ function createRouter(routes) {
20
20
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
21
21
  Object.keys(params !== null && params !== void 0 ? params : {}).forEach((key) => {
22
22
  const value = params[key];
23
- if (pathname.includes(`[${key}]`)) {
24
- pathname = pathname.replace(`[${key}]`, value);
23
+ const segment = `[${key}]`;
24
+ const catchAllSegments = `[...${key}]`;
25
+ const catchAllSegmentsOptional = `[[...${key}]]`;
26
+ if (pathname.includes(segment)) {
27
+ pathname = pathname.replace(segment, value);
28
+ }
29
+ else if (pathname.includes(catchAllSegmentsOptional)) {
30
+ if ((Array.isArray(value) && value.length === 0) ||
31
+ value === null ||
32
+ value === undefined ||
33
+ value === "") {
34
+ pathname = pathname.replace(`/${catchAllSegmentsOptional}`, "");
35
+ }
36
+ else if (Array.isArray(value)) {
37
+ // catch all segments optional
38
+ pathname = pathname.replace(catchAllSegmentsOptional, value.join("/"));
39
+ }
40
+ else {
41
+ pathname = pathname.replace(catchAllSegmentsOptional, value);
42
+ }
43
+ }
44
+ else if (pathname.includes(catchAllSegments)) {
45
+ // catch all segments
46
+ if (Array.isArray(value)) {
47
+ if (value.length === 0) {
48
+ throw new Error(`Parameter '${key}' can not be empty array for route '${String(route)}'`);
49
+ }
50
+ pathname = pathname.replace(catchAllSegments, value.join("/"));
51
+ }
52
+ else {
53
+ pathname = pathname.replace(catchAllSegments, value);
54
+ }
25
55
  }
26
56
  else {
27
57
  restParams[key] = value;
@@ -40,7 +70,7 @@ function createRouter(routes) {
40
70
  }
41
71
  return activeRoute;
42
72
  },
43
- sitemapGenerator: (0, sitemapGenerator_1.createSitemapGenerator)(),
73
+ createSitemapGenerator: sitemapGenerator_1.createSitemapGenerator,
44
74
  routes,
45
75
  useQueryParams: () => (0, router_1.useRouter)().query,
46
76
  };
@@ -0,0 +1 @@
1
+ export {};
package/router.test.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const router_1 = require("./router");
4
+ const { routeToUrl } = (0, router_1.createRouter)({
5
+ index: "/",
6
+ catchAllSegments: "/catch-all/[...pathParams]",
7
+ optionalCatchAllSegments: "/catch-all-optional/[[...pathParams]]",
8
+ });
9
+ test("routeToUrl", () => {
10
+ expect(routeToUrl("index", {})).toBe("/");
11
+ expect(routeToUrl("index", { queryParam: "value" })).toBe("/?queryParam=value");
12
+ expect(routeToUrl("catchAllSegments", { pathParams: ["param1", "param2"] })).toBe("/catch-all/param1/param2");
13
+ expect(routeToUrl("catchAllSegments", { pathParams: ["param1", "param2"], queryParam: "value" })).toBe("/catch-all/param1/param2?queryParam=value");
14
+ expect(routeToUrl("optionalCatchAllSegments", { pathParams: ["param1", "param2"], queryParam: "value" })).toBe("/catch-all-optional/param1/param2?queryParam=value");
15
+ expect(routeToUrl("optionalCatchAllSegments", { pathParams: [] })).toBe("/catch-all-optional");
16
+ expect(routeToUrl("optionalCatchAllSegments", { pathParams: null })).toBe("/catch-all-optional");
17
+ expect(routeToUrl("optionalCatchAllSegments", { pathParams: undefined })).toBe("/catch-all-optional");
18
+ expect(routeToUrl("optionalCatchAllSegments", { pathParams: "" })).toBe("/catch-all-optional");
19
+ expect(routeToUrl("optionalCatchAllSegments", { pathParams: "", queryParam: "value" })).toBe("/catch-all-optional?queryParam=value");
20
+ });
@@ -1,9 +1,11 @@
1
+ type ChangeFrequency = "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
1
2
  export type SitemapItem = {
2
3
  loc: string;
3
- priority: number;
4
+ priority?: number;
4
5
  lastmod?: string | null;
6
+ changefreq?: ChangeFrequency;
5
7
  };
6
- type RouteResolverResult = SitemapItem | SitemapItem[];
8
+ type RouteResolverResult = null | undefined | SitemapItem | Array<SitemapItem | null | undefined>;
7
9
  type RouteResolver<Route> = (route: Route) => Promise<RouteResolverResult>;
8
10
  type MissingRoutesError<Routes> = {
9
11
  __nonExhaustive: never;
@@ -16,5 +18,10 @@ export type SitemapGeneratorType<RouteList> = {
16
18
  toXml: keyof RouteList extends never ? () => Promise<string> : MissingRoutesError<keyof RouteList>;
17
19
  toJson: keyof RouteList extends never ? () => Promise<any> : MissingRoutesError<keyof RouteList>;
18
20
  };
19
- export declare const createSitemapGenerator: <RouteList>() => SitemapGeneratorType<RouteList>;
21
+ export type SitemapGeneratorOptions = {
22
+ baseUrl?: string;
23
+ defaultPriority?: number;
24
+ defaultChangeFreq?: ChangeFrequency;
25
+ };
26
+ export declare const createSitemapGenerator: <RouteList>(options?: SitemapGeneratorOptions) => SitemapGeneratorType<RouteList>;
20
27
  export {};
@@ -1,42 +1,59 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createSitemapGenerator = void 0;
4
+ function filterNullish(val) {
5
+ return val.filter((item) => item !== null && item !== undefined);
6
+ }
4
7
  class SitemapGenerator {
5
- constructor() {
8
+ constructor(options) {
6
9
  this.routeResolvers = {};
10
+ this.options = null;
7
11
  this.exhaustive = () => this;
8
12
  this.toXml = () => {
9
13
  return this.getSitemapItems().then((sitemapItems) => {
10
14
  return `<?xml version="1.0" encoding="UTF-8"?>
11
15
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
12
16
  ${sitemapItems
13
- .map((item) => `<url>
14
- <loc>${item.loc}</loc>
15
- <priority>${item.priority}</priority>
16
- ${item.lastmod ? `<lastmod>${item.lastmod}</lastmod>` : "<changefreq>monthly</changefreq>"}
17
- </url>`)
17
+ .map((item) => {
18
+ var _a, _b;
19
+ return `<url>
20
+ <loc>${(_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.baseUrl) !== null && _b !== void 0 ? _b : ""}${item.loc}</loc>
21
+ ${item.priority ? `<priority>${item.priority}</priority>` : ""}
22
+ ${item.lastmod ? `<lastmod>${item.lastmod}</lastmod>` : ""}
23
+ ${item.changefreq ? `<changefreq>${item.changefreq}</changefreq>` : ""}
24
+ </url>`;
25
+ })
18
26
  .join("")}
19
27
  </urlset>`;
20
28
  });
21
29
  };
22
30
  this.toJson = () => this.getSitemapItems().then(JSON.stringify);
31
+ this.options = options !== null && options !== void 0 ? options : null;
23
32
  }
24
33
  async getSitemapItems() {
25
34
  const routes = Object.keys(this.routeResolvers);
26
- return Promise.all(routes.map((route) => { var _a, _b; return (_b = (_a = this.routeResolvers)[route]) === null || _b === void 0 ? void 0 : _b.call(_a, route); })).then((resolverResults) => {
35
+ const allSitemapItems = await Promise.all(routes.map((route) => { var _a, _b; return (_b = (_a = this.routeResolvers)[route]) === null || _b === void 0 ? void 0 : _b.call(_a, route); })).then((resolverResults) => {
27
36
  const sitemapItems = [];
28
37
  resolverResults.forEach((result) => {
29
38
  if (!result) {
30
39
  return;
31
40
  }
32
41
  if (Array.isArray(result)) {
33
- sitemapItems.push(...result);
42
+ sitemapItems.push(...filterNullish(result));
34
43
  return;
35
44
  }
36
45
  sitemapItems.push(result);
37
46
  });
38
47
  return sitemapItems;
39
48
  });
49
+ return allSitemapItems.map((sitemapItem) => {
50
+ var _a, _b;
51
+ return ({
52
+ ...sitemapItem,
53
+ changefreq: sitemapItem.changefreq !== undefined ? sitemapItem.changefreq : (_a = this.options) === null || _a === void 0 ? void 0 : _a.defaultChangeFreq,
54
+ priority: sitemapItem.priority !== undefined ? sitemapItem.priority : (_b = this.options) === null || _b === void 0 ? void 0 : _b.defaultPriority,
55
+ });
56
+ });
40
57
  }
41
58
  add(route, resolver) {
42
59
  this.routeResolvers[route] = resolver;
@@ -46,5 +63,5 @@ class SitemapGenerator {
46
63
  return this;
47
64
  }
48
65
  }
49
- const createSitemapGenerator = () => new SitemapGenerator();
66
+ const createSitemapGenerator = (options) => new SitemapGenerator(options);
50
67
  exports.createSitemapGenerator = createSitemapGenerator;
package/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { GetStaticProps, GetServerSideProps, PreviewData as NextPreviewData } from "next";
1
+ import { GetServerSideProps, GetStaticProps, PreviewData as NextPreviewData } from "next";
2
2
  export type QueryParams<RouteList, Route extends keyof RouteList> = RouteList[Route] extends null ? never : {
3
3
  [key in keyof RouteList[Route]]: string | string[] | undefined;
4
4
  };