@uxf/router 15.0.0 → 16.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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +85 -12
  3. package/create-client-router.d.ts +12 -5
  4. package/create-client-router.js +13 -7
  5. package/create-router.d.ts +10 -4
  6. package/create-router.js +7 -0
  7. package/esm/schema/array.js +10 -0
  8. package/esm/schema/boolean.js +11 -0
  9. package/esm/schema/index.js +6 -0
  10. package/esm/schema/integer.js +14 -0
  11. package/index.d.ts +1 -0
  12. package/index.js +3 -0
  13. package/package.json +13 -16
  14. package/query-params-validation.d.ts +17 -0
  15. package/query-params-validation.js +46 -0
  16. package/schema/array.d.ts +8 -0
  17. package/schema/array.js +46 -0
  18. package/schema/boolean.d.ts +6 -0
  19. package/schema/boolean.js +47 -0
  20. package/{superstruct → schema}/index.d.ts +1 -1
  21. package/{superstruct → schema}/index.js +6 -4
  22. package/schema/integer.d.ts +9 -0
  23. package/schema/integer.js +50 -0
  24. package/types.d.ts +17 -3
  25. package/create-router.test.d.ts +0 -1
  26. package/create-router.test.js +0 -237
  27. package/helper.test.d.ts +0 -1
  28. package/helper.test.js +0 -89
  29. package/routes-check/routes-check.test.d.ts +0 -1
  30. package/routes-check/routes-check.test.js +0 -33
  31. package/sitemap-generator.test.d.ts +0 -1
  32. package/sitemap-generator.test.js +0 -56
  33. package/superstruct/array.d.ts +0 -7
  34. package/superstruct/array.js +0 -14
  35. package/superstruct/boolean.d.ts +0 -1
  36. package/superstruct/boolean.js +0 -8
  37. package/superstruct/integer.d.ts +0 -1
  38. package/superstruct/integer.js +0 -12
  39. package/utils/object-to-xml.test.d.ts +0 -1
  40. package/utils/object-to-xml.test.js +0 -43
  41. package/utils/path-specificity.test.d.ts +0 -1
  42. package/utils/path-specificity.test.js +0 -72
  43. package/utils/path-to-regex.test.d.ts +0 -1
  44. package/utils/path-to-regex.test.js +0 -109
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022–2026 UX Fans s.r.o.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,14 +1,20 @@
1
1
  # @uxf/router
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/@uxf/router)](https://www.npmjs.com/package/@uxf/router)
4
+
3
5
  ## Installation
4
6
 
5
7
  ```
6
8
  yarn add @uxf/router
7
9
  ```
8
10
 
11
+ Route schemas are [Standard Schema](https://standardschema.dev) schemas. `@uxf/router/schema` gives you
12
+ [Valibot](https://valibot.dev) schemas that read params from the URL, so `valibot` is a peer dependency
13
+ (`yarn dependencies:fix` installs it). Upgrading from 15.x: see [Upgrading from 15.x](#upgrading-from-15x).
14
+
9
15
  There are two factories:
10
16
 
11
- - `createRouter` from `@uxf/router` is the default. It is server-safe (no React hooks, no client-only imports) and can be used anywhere, including React Server Components. It returns `routeToUrl`, `route`, `routes`, `getRouteInfo`, `createRouteMatcher` and `createSitemapGenerator`.
17
+ - `createRouter` from `@uxf/router` is the default. It is server-safe (no React hooks, no client-only imports) and can be used anywhere, including React Server Components. It returns `routeToUrl`, `route`, `routes`, `getRouteInfo`, `createRouteMatcher`, `createSitemapGenerator` and `validateQueryParams`.
12
18
  - `createClientRouter` from `@uxf/router/client` is a superset that adds the React hooks (`useQueryParams`, `useQueryParamsStatic`, `usePageParams`, `useRouteInfo`). It imports `next/navigation` and `next/router`, so it must only be used in client components.
13
19
 
14
20
  Define the routes once as plain data, then build each router from it:
@@ -16,7 +22,7 @@ Define the routes once as plain data, then build each router from it:
16
22
  ```ts
17
23
  // routes/routes.ts – plain route definitions, importable anywhere
18
24
 
19
- import { number, object, optional, string } from "superstruct";
25
+ import { integer, object, optional, string } from "@uxf/router/schema";
20
26
 
21
27
  export const routes = {
22
28
  index: {
@@ -25,13 +31,13 @@ export const routes = {
25
31
  "admin/index": {
26
32
  path: "/admin",
27
33
  schema: object({
28
- param1: optional(number()),
34
+ param1: optional(integer()),
29
35
  }),
30
36
  },
31
37
  "blog/detail": {
32
38
  path: "/blog/[id]",
33
39
  schema: object({
34
- id: number(),
40
+ id: integer(),
35
41
  }),
36
42
  },
37
43
  "localized-route": {
@@ -60,10 +66,8 @@ import { createRouter, ExtractSchema, UxfGetServerSideProps, UxfGetStaticProps }
60
66
  import { PreviewData as NextPreviewData } from "next/types";
61
67
  import { RouteList, routerOptions, routes } from "./routes";
62
68
 
63
- export const { route, routeToUrl, getRouteInfo, createRouteMatcher, createSitemapGenerator } = createRouter(
64
- routes,
65
- routerOptions,
66
- );
69
+ export const { route, routeToUrl, getRouteInfo, createRouteMatcher, createSitemapGenerator, validateQueryParams } =
70
+ createRouter(routes, routerOptions);
67
71
 
68
72
  export type GetRouteSchema<K extends keyof RouteList> = ExtractSchema<RouteList[K]>;
69
73
 
@@ -88,10 +92,8 @@ export type GetServerSideProps<
88
92
  import { createClientRouter } from "@uxf/router/client";
89
93
  import { routerOptions, routes } from "./routes";
90
94
 
91
- export const { useQueryParams, useQueryParamsStatic, usePageParams, useRouteInfo } = createClientRouter(
92
- routes,
93
- routerOptions,
94
- );
95
+ export const { useQueryParams, useQueryParamsStatic, usePageParams, useRouteInfo, validateQueryParams } =
96
+ createClientRouter(routes, routerOptions);
95
97
  ```
96
98
 
97
99
  Add configuration to `tsconfig.json`
@@ -179,6 +181,77 @@ const [query, { push, replace }] = useQueryParams("route-name");
179
181
  const [query, { push, replace }] = useQueryParamsStatic("route-name");
180
182
  ```
181
183
 
184
+ Both hooks parse the page params (path params merged with search params) by the route schema. **Params that do not
185
+ match the schema throw `QueryParamsError`** (`?id=abc` for an `integer()`), with the route name and the Standard Schema
186
+ `issues`. An error boundary can tell it from other errors:
187
+
188
+ ```tsx
189
+ import { QueryParamsError } from "@uxf/router";
190
+
191
+ // app/error.tsx, or the fallback of an ErrorBoundary
192
+ if (error instanceof QueryParamsError) {
193
+ return <NotFound />;
194
+ }
195
+ ```
196
+
197
+ To handle invalid params without throwing, validate them yourself. `validateQueryParams` is on both routers and never
198
+ throws for invalid params; it returns `{ value }` or `{ issues }`:
199
+
200
+ ```tsx
201
+ const pageParams = usePageParams();
202
+ const result = pageParams ? validateQueryParams("blog/detail", pageParams) : null;
203
+
204
+ if (result?.issues) {
205
+ // show a message, redirect, …
206
+ }
207
+ ```
208
+
209
+ ## Route schemas
210
+
211
+ `schema` takes any **synchronous** [Standard Schema](https://standardschema.dev) (Valibot, Zod, ArkType, …). It gets
212
+ the params as the URL gives them, strings and arrays of strings, and its output types `routeToUrl`, `route`,
213
+ `createRouteMatcher`, `GetRouteSchema` and the hooks. A schema that validates asynchronously throws a `TypeError`: the
214
+ router reads params during render.
215
+
216
+ `@uxf/router/schema` has the Valibot schemas that read URL strings:
217
+
218
+ | Schema | Accepts | Output |
219
+ | ------------- | -------------------------------------------------------------------------------------------------------- | --------- |
220
+ | `integer()` | a safe integer, or a string read by `parseInt` (`"12"` → `12`); `"abc"` and `"9999999999999999999"` fail | `number` |
221
+ | `boolean()` | a boolean; the strings `"1"`, `"true"` and `""` (`?flag`) are `true` | `boolean` |
222
+ | `array(item)` | an array, or a single string wrapped into one (`?a=x` → `["x"]`) | `Item[]` |
223
+ | `object` | Valibot `object`: strips the keys it does not name | |
224
+ | `optional` | Valibot `optional` | |
225
+ | `string` | Valibot `string` | |
226
+
227
+ Anything else comes from `valibot` itself, e.g. `picklist(Object.values(GqlEnum))` or `enum_(GqlEnum)` for an enum,
228
+ `nullable(…)`. Do not use Valibot's own `array` or `number` for a param: they do not read the URL form, so `?id=1` or
229
+ `?tags=a` would fail.
230
+
231
+ ```ts
232
+ import { array, integer, object, optional, string } from "@uxf/router/schema";
233
+ import { picklist } from "valibot";
234
+ import { ProductSort } from "@generated/gql/enums";
235
+
236
+ export const routes = {
237
+ "product/list": {
238
+ path: "/products",
239
+ schema: object({
240
+ page: optional(integer()),
241
+ sort: optional(picklist(Object.values(ProductSort))),
242
+ tags: optional(array(string())),
243
+ }),
244
+ },
245
+ } as const;
246
+ ```
247
+
248
+ ## Upgrading from 15.x
249
+
250
+ Up to 15.x route schemas were Superstruct structs and `@uxf/router/superstruct` shipped the URL helpers. Both are
251
+ gone: move every routes file to `@uxf/router/schema` in the same step as the router upgrade. For routes that use
252
+ only `object`, `optional`, `string`, `integer`, `boolean` and `array`, that is a change of the import path; the steps
253
+ for the rest are in `docs/migration/router-standard-schema.md` in the fe-monorepo.
254
+
182
255
  ## Next Link
183
256
 
184
257
  ```tsx
@@ -1,7 +1,6 @@
1
1
  import { Params } from "next/dist/server/request/params";
2
- import { Infer } from "superstruct";
3
2
  import { RouteInfo, Router, RouterOptions } from "./create-router";
4
- import { QueryParams, RoutesDefinition } from "./types";
3
+ import { QueryParams, RouteParams, RoutesDefinition } from "./types";
5
4
  export interface TransitionOptions {
6
5
  shallow?: boolean;
7
6
  locale?: string | false;
@@ -9,10 +8,10 @@ export interface TransitionOptions {
9
8
  unstable_skipClientCache?: boolean;
10
9
  }
11
10
  type QueryParamsResult<Nullable extends boolean, T extends keyof RouteList, Locales extends string[], RouteList extends RoutesDefinition<Locales>> = [
12
- Nullable extends true ? Infer<NonNullable<RouteList[T]["schema"]>> | null : Infer<NonNullable<RouteList[T]["schema"]>>,
11
+ Nullable extends true ? RouteParams<RouteList, T> | null : RouteParams<RouteList, T>,
13
12
  {
14
- push: (params: Infer<NonNullable<RouteList[T]["schema"]>>, options?: TransitionOptions) => Promise<boolean>;
15
- replace: (params: Infer<NonNullable<RouteList[T]["schema"]>>, options?: TransitionOptions) => Promise<boolean>;
13
+ push: (params: RouteParams<RouteList, T>, options?: TransitionOptions) => Promise<boolean>;
14
+ replace: (params: RouteParams<RouteList, T>, options?: TransitionOptions) => Promise<boolean>;
16
15
  }
17
16
  ];
18
17
  /**
@@ -30,7 +29,15 @@ export type ClientRouter<Locales extends string[], RouteList extends RoutesDefin
30
29
  * Returns path params merged with search params
31
30
  */
32
31
  usePageParams: () => Params | null;
32
+ /**
33
+ * Page params parsed by the route schema. Throws `QueryParamsError` when they do not match it (`?id=abc` for an
34
+ * `integer()`), and an `Error` when the router is not ready (static pages; use `useQueryParamsStatic` there).
35
+ */
33
36
  useQueryParams: <T extends keyof RouteList>(routeName: T) => QueryParamsResult<false, T, Locales, RouteList>;
37
+ /**
38
+ * Like `useQueryParams`, but returns `null` while the router is not ready. Throws `QueryParamsError` when the
39
+ * params do not match the route schema.
40
+ */
34
41
  useQueryParamsStatic: <T extends keyof RouteList>(routeName: T) => QueryParamsResult<true, T, Locales, RouteList>;
35
42
  };
36
43
  /**
@@ -7,8 +7,8 @@ const is_not_nil_1 = require("@uxf/core/utils/is-not-nil");
7
7
  const throw_error_1 = require("@uxf/core/utils/throw-error");
8
8
  const navigation_1 = require("next/navigation");
9
9
  const router_1 = require("next/router");
10
- const superstruct_1 = require("superstruct");
11
10
  const create_router_1 = require("./create-router");
11
+ const query_params_validation_1 = require("./query-params-validation");
12
12
  /**
13
13
  * Creates the client router – everything `createRouter` returns plus the React hooks
14
14
  * (`useQueryParams`, `useQueryParamsStatic`, `usePageParams`, `useRouteInfo`).
@@ -19,6 +19,15 @@ const create_router_1 = require("./create-router");
19
19
  function createClientRouter(routes, routerOptions) {
20
20
  const base = (0, create_router_1.createRouter)(routes, routerOptions);
21
21
  const { routeToUrl, getRouteInfo } = base;
22
+ const parseQueryParams = (routeName, pageParams) => {
23
+ var _a;
24
+ const schema = (_a = routes[routeName].schema) !== null && _a !== void 0 ? _a : (0, throw_error_1.throwError)(`Route '${String(routeName)}' has no schema.`);
25
+ const result = (0, query_params_validation_1.validateSync)(String(routeName), schema, pageParams);
26
+ if (result.issues) {
27
+ throw new query_params_validation_1.QueryParamsError(String(routeName), result.issues);
28
+ }
29
+ return result.value;
30
+ };
22
31
  const useRouteInfo = () => {
23
32
  const pathname = (0, navigation_1.usePathname)();
24
33
  return (0, is_not_nil_1.isNotNil)(pathname) ? getRouteInfo(pathname) : null;
@@ -54,15 +63,13 @@ function createClientRouter(routes, routerOptions) {
54
63
  usePageParams,
55
64
  useQueryParamsDeprecated: () => (0, router_1.useRouter)().query,
56
65
  useQueryParams(routeName) {
57
- var _a;
58
66
  const router = (0, navigation_1.useRouter)();
59
67
  const pageParams = usePageParams();
60
68
  if ((0, is_nil_1.isNil)(pageParams)) {
61
69
  throw new Error("Router is not ready. Use useQueryParamsStatic instead of useQueryParams.");
62
70
  }
63
- const schema = (_a = routes[routeName].schema) !== null && _a !== void 0 ? _a : (0, throw_error_1.throwError)(`Route '${String(routeName)}' has no schema.`);
64
71
  return [
65
- (0, superstruct_1.mask)(pageParams, schema),
72
+ parseQueryParams(routeName, pageParams),
66
73
  {
67
74
  push: (params, options) => {
68
75
  router.push(routeToUrl(routeName, params, {}), options);
@@ -78,12 +85,11 @@ function createClientRouter(routes, routerOptions) {
78
85
  useQueryParamsStatic(routeName) {
79
86
  const router = (0, navigation_1.useRouter)();
80
87
  const pageParams = usePageParams();
81
- const schema = routes[routeName].schema;
82
- if (!schema) {
88
+ if (!routes[routeName].schema) {
83
89
  throw new Error(`Route '${String(routeName)}' has no schema.`);
84
90
  }
85
91
  return [
86
- (0, is_not_nil_1.isNotNil)(pageParams) ? (0, superstruct_1.mask)(pageParams, schema) : null,
92
+ (0, is_not_nil_1.isNotNil)(pageParams) ? parseQueryParams(routeName, pageParams) : null,
87
93
  {
88
94
  push: (params) => {
89
95
  router.push(routeToUrl(routeName, params, {}));
@@ -1,10 +1,10 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
1
2
  import type { LinkProps } from "next/link";
2
- import type { Struct } from "superstruct";
3
3
  import { SitemapGeneratorOptions, SitemapGeneratorType, SitemapRouteResolvers } from "./sitemap-generator";
4
- import { RouteDefinition, RoutesDefinition } from "./types";
4
+ import { RouteDefinition, RouteParams, RoutesDefinition, RoutesWithSchema } from "./types";
5
5
  export type ExtractSchema<T> = T extends {
6
- schema: Struct<infer U, any>;
7
- } ? U : null;
6
+ schema: infer S extends StandardSchemaV1;
7
+ } ? StandardSchemaV1.InferOutput<S> : null;
8
8
  type Options = {
9
9
  shouldBeAbsolute?: boolean;
10
10
  };
@@ -39,6 +39,12 @@ export type Router<Locales extends string[], RouteList extends RoutesDefinition<
39
39
  routes: RouteList;
40
40
  getRouteInfo: (pathname: string) => RouteInfo | null;
41
41
  createRouteMatcher: (...args: FunctionParametersGeneratorWithPartialParams<Locales, RouteList>) => RouteMatcher;
42
+ /**
43
+ * Validates page params (path params merged with search params, as `usePageParams` returns them, or
44
+ * `context.query` in `getServerSideProps`) against the route schema. Never throws for invalid params: the result
45
+ * is `{ value }` or `{ issues }`, as the Standard Schema `validate` returns it.
46
+ */
47
+ validateQueryParams: <T extends RoutesWithSchema<RouteList>>(routeName: T, params: unknown) => StandardSchemaV1.Result<RouteParams<RouteList, T>>;
42
48
  };
43
49
  export type RouterOptions<L extends string[]> = {
44
50
  baseUrl?: string;
package/create-router.js CHANGED
@@ -6,6 +6,7 @@ const is_empty_1 = require("@uxf/core/utils/is-empty");
6
6
  const is_not_empty_1 = require("@uxf/core/utils/is-not-empty");
7
7
  const qs_1 = require("@uxf/core/utils/qs");
8
8
  const throw_error_1 = require("@uxf/core/utils/throw-error");
9
+ const query_params_validation_1 = require("./query-params-validation");
9
10
  const sitemap_generator_1 = require("./sitemap-generator");
10
11
  const path_specificity_1 = require("./utils/path-specificity");
11
12
  const path_to_regex_1 = require("./utils/path-to-regex");
@@ -117,6 +118,11 @@ function createRouter(routes, routerOptions) {
117
118
  routeDefinition: routesWithRegex[routeName],
118
119
  };
119
120
  };
121
+ const validateQueryParams = (routeName, params) => {
122
+ var _a;
123
+ const schema = (_a = routes[routeName].schema) !== null && _a !== void 0 ? _a : (0, throw_error_1.throwError)(`Route '${String(routeName)}' has no schema.`);
124
+ return (0, query_params_validation_1.validateSync)(String(routeName), schema, params);
125
+ };
120
126
  return {
121
127
  route(...args) {
122
128
  var _a;
@@ -134,6 +140,7 @@ function createRouter(routes, routerOptions) {
134
140
  },
135
141
  routes,
136
142
  getRouteInfo,
143
+ validateQueryParams,
137
144
  createRouteMatcher(...args) {
138
145
  const [requiredRouteName, requiredParams] = args;
139
146
  return (pathname, pageParams) => {
@@ -0,0 +1,10 @@
1
+ import * as v from "valibot";
2
+ /**
3
+ * An array that also accepts a single string.
4
+ *
5
+ * Next.js writes an array into the URL as `?item=a&item=b`, so it cannot tell `?item=a` (an array of one item) from
6
+ * a plain string. A string is therefore wrapped into an array before the items are validated.
7
+ */
8
+ export function array(item) {
9
+ return v.pipe(v.union([v.array(v.unknown()), v.string()]), v.transform((value) => (Array.isArray(value) ? value : [value])), v.array(item));
10
+ }
@@ -0,0 +1,11 @@
1
+ import * as v from "valibot";
2
+ /**
3
+ * A boolean that also accepts its URL form: `"1"`, `"true"` and `""` (a bare `?flag`) read as `true`, any other
4
+ * string as `false`.
5
+ */
6
+ export function boolean() {
7
+ return v.union([
8
+ v.boolean(),
9
+ v.pipe(v.string(), v.transform((value) => value === "1" || value === "true" || value === "")),
10
+ ]);
11
+ }
@@ -0,0 +1,6 @@
1
+ // Entry point for `@uxf/router/schema`: Valibot schemas for route params, which come from the URL as strings.
2
+ // `object` strips the keys the schema does not name, so tracking params (`utm_source`, `fbclid`) do not break a route.
3
+ export { object, optional, string } from "valibot";
4
+ export * from "./array";
5
+ export * from "./boolean";
6
+ export * from "./integer";
@@ -0,0 +1,14 @@
1
+ import * as v from "valibot";
2
+ /**
3
+ * An integer that also accepts its URL form: Next.js hands every path and query param over as a string.
4
+ *
5
+ * A string is read with `Number.parseInt(value, 10)`, as the router always did, so `"12abc"` reads as `12`. A string
6
+ * that is not a number at all (`?id=abc`, `?id=`) is a validation issue, not a thrown error, and so is a number
7
+ * outside the safe integer range (`?id=9999999999999999999`), which a JavaScript number cannot hold exactly.
8
+ */
9
+ export function integer() {
10
+ return v.pipe(v.union([
11
+ v.number(),
12
+ v.pipe(v.string(), v.transform((value) => Number.parseInt(value, 10))),
13
+ ]), v.number(), v.safeInteger());
14
+ }
package/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./create-router";
2
2
  export * from "./helper";
3
3
  export * from "./merge-route-matchers";
4
+ export { QueryParamsError } from "./query-params-validation";
4
5
  export * from "./types";
package/index.js CHANGED
@@ -16,7 +16,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
17
17
  };
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.QueryParamsError = void 0;
19
20
  __exportStar(require("./create-router"), exports);
20
21
  __exportStar(require("./helper"), exports);
21
22
  __exportStar(require("./merge-route-matchers"), exports);
23
+ var query_params_validation_1 = require("./query-params-validation");
24
+ Object.defineProperty(exports, "QueryParamsError", { enumerable: true, get: function () { return query_params_validation_1.QueryParamsError; } });
22
25
  __exportStar(require("./types"), exports);
package/package.json CHANGED
@@ -1,38 +1,35 @@
1
1
  {
2
2
  "name": "@uxf/router",
3
- "version": "15.0.0",
3
+ "version": "16.0.0",
4
4
  "description": "UXF Router",
5
- "author": "UXFans <dev@uxf.cz>",
6
- "homepage": "https://gitlab.com/uxf-npm/router#readme",
7
- "license": "ISC",
5
+ "author": "UX Fans s.r.o. <dev@uxf.cz>",
6
+ "homepage": "https://fe.uxf.dev/docs/router",
7
+ "license": "MIT",
8
8
  "main": "index.js",
9
9
  "typings": "index.d.ts",
10
10
  "module": "index.js",
11
11
  "publishConfig": {
12
12
  "access": "public"
13
13
  },
14
- "repository": {
15
- "type": "git",
16
- "url": "git+https://gitlab.com/uxf-npm/router.git"
17
- },
18
14
  "scripts": {
19
- "build": "tsc -P tsconfig.json",
15
+ "build": "tsc -P tsconfig.json && tsc -P tsconfig.esm.json",
20
16
  "typecheck": "tsc --noEmit"
21
17
  },
22
- "bugs": {
23
- "url": "https://gitlab.com/uxf-npm/router/issues"
18
+ "browser": {
19
+ "./schema/index.js": "./esm/schema/index.js"
24
20
  },
25
21
  "dependencies": {
22
+ "@standard-schema/spec": "1.1.0",
26
23
  "true-case-path": "2.2.1"
27
24
  },
28
25
  "peerDependencies": {
29
- "@uxf/core": "15.0.0",
26
+ "@uxf/core": "15.2.1",
30
27
  "next": ">=16.4.3",
31
- "superstruct": "^2.0.2"
28
+ "valibot": "^1.5.0"
32
29
  },
33
30
  "devDependencies": {
34
- "@uxf/core": "15.0.0",
35
- "next": "16.4.3",
36
- "superstruct": "^2.0.2"
31
+ "@uxf/core": "15.2.1",
32
+ "next": "16.4.6",
33
+ "valibot": "^1.5.0"
37
34
  }
38
35
  }
@@ -0,0 +1,17 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ /**
3
+ * The page params do not match the route schema, e.g. `?id=abc` for an `integer()` param.
4
+ *
5
+ * Thrown by `useQueryParams` and `useQueryParamsStatic`. An error boundary can tell it from other render errors by
6
+ * `instanceof QueryParamsError` and show a 404; `validateQueryParams` returns the same issues without throwing.
7
+ */
8
+ export declare class QueryParamsError extends Error {
9
+ readonly routeName: string;
10
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
11
+ constructor(routeName: string, issues: ReadonlyArray<StandardSchemaV1.Issue>);
12
+ }
13
+ /**
14
+ * Runs a Standard Schema synchronously. The router reads params during render, so a schema whose `validate` returns
15
+ * a Promise (an async Valibot schema, a Zod schema with an async refinement) cannot be used for a route.
16
+ */
17
+ export declare function validateSync<Output>(routeName: string, schema: StandardSchemaV1<unknown, Output>, value: unknown): StandardSchemaV1.Result<Output>;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QueryParamsError = void 0;
4
+ exports.validateSync = validateSync;
5
+ function formatIssue(issue) {
6
+ var _a;
7
+ const path = ((_a = issue.path) !== null && _a !== void 0 ? _a : [])
8
+ .map((segment) => String(typeof segment === "object" ? segment.key : segment))
9
+ .join(".");
10
+ return path ? `${path}: ${issue.message}` : issue.message;
11
+ }
12
+ /**
13
+ * The page params do not match the route schema, e.g. `?id=abc` for an `integer()` param.
14
+ *
15
+ * Thrown by `useQueryParams` and `useQueryParamsStatic`. An error boundary can tell it from other render errors by
16
+ * `instanceof QueryParamsError` and show a 404; `validateQueryParams` returns the same issues without throwing.
17
+ */
18
+ class QueryParamsError extends Error {
19
+ constructor(routeName, issues) {
20
+ super(`Invalid params for route '${routeName}': ${issues.map(formatIssue).join("; ")}`);
21
+ this.name = "QueryParamsError";
22
+ this.routeName = routeName;
23
+ this.issues = issues;
24
+ }
25
+ }
26
+ exports.QueryParamsError = QueryParamsError;
27
+ function isPromiseLike(value) {
28
+ return typeof (value === null || value === void 0 ? void 0 : value.then) === "function";
29
+ }
30
+ /**
31
+ * Runs a Standard Schema synchronously. The router reads params during render, so a schema whose `validate` returns
32
+ * a Promise (an async Valibot schema, a Zod schema with an async refinement) cannot be used for a route.
33
+ */
34
+ function validateSync(routeName, schema, value) {
35
+ // The type rules it out, but a project that skips the typecheck (or casts) can still pass a Superstruct struct,
36
+ // which would otherwise end in "Cannot read properties of undefined (reading 'validate')".
37
+ const standard = schema["~standard"];
38
+ if (typeof (standard === null || standard === void 0 ? void 0 : standard.validate) !== "function") {
39
+ throw new TypeError(`Route '${routeName}' schema is not a Standard Schema; Superstruct schemas are no longer supported, see docs/migration/router-standard-schema.md`);
40
+ }
41
+ const result = standard.validate(value);
42
+ if (isPromiseLike(result)) {
43
+ throw new TypeError(`Schema of route '${routeName}' validates asynchronously. Route schemas have to be synchronous.`);
44
+ }
45
+ return result;
46
+ }
@@ -0,0 +1,8 @@
1
+ import * as v from "valibot";
2
+ /**
3
+ * An array that also accepts a single string.
4
+ *
5
+ * Next.js writes an array into the URL as `?item=a&item=b`, so it cannot tell `?item=a` (an array of one item) from
6
+ * a plain string. A string is therefore wrapped into an array before the items are validated.
7
+ */
8
+ export declare function array<const TItem extends v.GenericSchema>(item: TItem): v.SchemaWithPipe<readonly [v.UnionSchema<[v.ArraySchema<v.UnknownSchema, undefined>, v.StringSchema<undefined>], undefined>, v.TransformAction<string | unknown[], unknown[]>, v.ArraySchema<TItem, undefined>]>;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.array = array;
37
+ const v = __importStar(require("valibot"));
38
+ /**
39
+ * An array that also accepts a single string.
40
+ *
41
+ * Next.js writes an array into the URL as `?item=a&item=b`, so it cannot tell `?item=a` (an array of one item) from
42
+ * a plain string. A string is therefore wrapped into an array before the items are validated.
43
+ */
44
+ function array(item) {
45
+ return v.pipe(v.union([v.array(v.unknown()), v.string()]), v.transform((value) => (Array.isArray(value) ? value : [value])), v.array(item));
46
+ }
@@ -0,0 +1,6 @@
1
+ import * as v from "valibot";
2
+ /**
3
+ * A boolean that also accepts its URL form: `"1"`, `"true"` and `""` (a bare `?flag`) read as `true`, any other
4
+ * string as `false`.
5
+ */
6
+ export declare function boolean(): v.UnionSchema<[v.BooleanSchema<undefined>, v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TransformAction<string, boolean>]>], undefined>;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.boolean = boolean;
37
+ const v = __importStar(require("valibot"));
38
+ /**
39
+ * A boolean that also accepts its URL form: `"1"`, `"true"` and `""` (a bare `?flag`) read as `true`, any other
40
+ * string as `false`.
41
+ */
42
+ function boolean() {
43
+ return v.union([
44
+ v.boolean(),
45
+ v.pipe(v.string(), v.transform((value) => value === "1" || value === "true" || value === "")),
46
+ ]);
47
+ }
@@ -1,4 +1,4 @@
1
- export { object, optional, string } from "superstruct";
1
+ export { object, optional, string } from "valibot";
2
2
  export * from "./array";
3
3
  export * from "./boolean";
4
4
  export * from "./integer";
@@ -15,10 +15,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.string = exports.optional = exports.object = void 0;
18
- var superstruct_1 = require("superstruct");
19
- Object.defineProperty(exports, "object", { enumerable: true, get: function () { return superstruct_1.object; } });
20
- Object.defineProperty(exports, "optional", { enumerable: true, get: function () { return superstruct_1.optional; } });
21
- Object.defineProperty(exports, "string", { enumerable: true, get: function () { return superstruct_1.string; } });
18
+ // Entry point for `@uxf/router/schema`: Valibot schemas for route params, which come from the URL as strings.
19
+ // `object` strips the keys the schema does not name, so tracking params (`utm_source`, `fbclid`) do not break a route.
20
+ var valibot_1 = require("valibot");
21
+ Object.defineProperty(exports, "object", { enumerable: true, get: function () { return valibot_1.object; } });
22
+ Object.defineProperty(exports, "optional", { enumerable: true, get: function () { return valibot_1.optional; } });
23
+ Object.defineProperty(exports, "string", { enumerable: true, get: function () { return valibot_1.string; } });
22
24
  __exportStar(require("./array"), exports);
23
25
  __exportStar(require("./boolean"), exports);
24
26
  __exportStar(require("./integer"), exports);