@native-router/react 1.6.1 → 1.7.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 (74) hide show
  1. package/README.md +2 -2
  2. package/dist/components/Link.cjs +2 -0
  3. package/dist/components/Link.cjs.map +1 -0
  4. package/dist/components/Link.js +3 -0
  5. package/dist/components/Link.js.map +1 -0
  6. package/dist/components/NavLink.cjs +2 -0
  7. package/dist/components/NavLink.cjs.map +1 -0
  8. package/dist/components/NavLink.js +3 -0
  9. package/dist/components/NavLink.js.map +1 -0
  10. package/dist/components/PrefetchLink.cjs +2 -0
  11. package/dist/components/PrefetchLink.cjs.map +1 -0
  12. package/dist/components/PrefetchLink.js +3 -0
  13. package/dist/components/PrefetchLink.js.map +1 -0
  14. package/dist/components/RouteErrorBoundary.cjs +2 -0
  15. package/dist/components/RouteErrorBoundary.cjs.map +1 -0
  16. package/dist/components/RouteErrorBoundary.js +2 -0
  17. package/dist/components/RouteErrorBoundary.js.map +1 -0
  18. package/dist/components/Router.cjs +2 -0
  19. package/dist/components/Router.cjs.map +1 -0
  20. package/dist/components/Router.js +4 -0
  21. package/dist/components/Router.js.map +1 -0
  22. package/dist/components/ScrollRestoration.cjs +2 -0
  23. package/dist/components/ScrollRestoration.cjs.map +1 -0
  24. package/dist/components/ScrollRestoration.js +2 -0
  25. package/dist/components/ScrollRestoration.js.map +1 -0
  26. package/dist/components/TypedLink.cjs +2 -0
  27. package/dist/components/TypedLink.cjs.map +1 -0
  28. package/dist/components/TypedLink.js +3 -0
  29. package/dist/components/TypedLink.js.map +1 -0
  30. package/dist/components/link-behavior.cjs +2 -0
  31. package/dist/components/link-behavior.cjs.map +1 -0
  32. package/dist/components/link-behavior.js +2 -0
  33. package/dist/components/link-behavior.js.map +1 -0
  34. package/dist/context.cjs +2 -0
  35. package/dist/context.cjs.map +1 -0
  36. package/dist/context.js +4 -0
  37. package/dist/context.js.map +1 -0
  38. package/dist/create-routes.cjs +2 -0
  39. package/dist/create-routes.cjs.map +1 -0
  40. package/dist/create-routes.js +2 -0
  41. package/dist/create-routes.js.map +1 -0
  42. package/dist/index.cjs +1 -2
  43. package/dist/index.js +1 -6
  44. package/dist/resolve-view.cjs +2 -0
  45. package/dist/resolve-view.cjs.map +1 -0
  46. package/dist/resolve-view.js +3 -0
  47. package/dist/resolve-view.js.map +1 -0
  48. package/dist/server.cjs +2 -1
  49. package/dist/server.cjs.map +1 -0
  50. package/dist/server.js +3 -1
  51. package/dist/server.js.map +1 -0
  52. package/dist/ssr.cjs +2 -0
  53. package/dist/ssr.cjs.map +1 -0
  54. package/dist/ssr.js +2 -0
  55. package/dist/ssr.js.map +1 -0
  56. package/dist/types/index.d.ts +0 -1
  57. package/dist/types/server.d.ts +11 -1
  58. package/dist/types/ssr.d.ts +3 -11
  59. package/dist/types/use-blocker.d.ts +59 -2
  60. package/dist/use-blocker.cjs +2 -0
  61. package/dist/use-blocker.cjs.map +1 -0
  62. package/dist/use-blocker.js +2 -0
  63. package/dist/use-blocker.js.map +1 -0
  64. package/dist/use-search-params.cjs +2 -0
  65. package/dist/use-search-params.cjs.map +1 -0
  66. package/dist/use-search-params.js +2 -0
  67. package/dist/use-search-params.js.map +1 -0
  68. package/package.json +9 -5
  69. package/dist/index.cjs.map +0 -1
  70. package/dist/index.js.map +0 -1
  71. package/dist/ssr-873l9jA-.js +0 -8
  72. package/dist/ssr-873l9jA-.js.map +0 -1
  73. package/dist/ssr-C-Bgsx5W.cjs +0 -2
  74. package/dist/ssr-C-Bgsx5W.cjs.map +0 -1
package/dist/server.cjs CHANGED
@@ -1 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./ssr-C-Bgsx5W.cjs");exports.resolveServerView=e.resolveServerView;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./resolve-view.cjs"),r=require("./components/Router.cjs");let t=require("history"),i=require("react/jsx-runtime"),o=require("@native-router/core"),n=require("@native-router/core/util");function s(t,n,s){return(0,o.resolve)(t,n).then(o=>{const a=e.getViewData(o),u=t.history.location.state?.index||0;return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(r.Router,{router:t,children:o}),(0,i.jsx)("script",{...s?.scriptAttributes,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:`window.${s?.hydrateKey||"_nativeRouterReactSSRData"} = ${c={data:a,location:n,index:u},JSON.stringify(c).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};`}})]});var c})}exports.resolveServerView=function(r,i,{scriptAttributes:a,hydrateKey:u,...c}={}){const l=(0,o.create)(r,(0,t.createMemoryHistory)({initialEntries:[i]}),e.resolveViewServer,c);return s(l,(0,n.isString)(i)?(0,o.toLocation)(l,i):i,{scriptAttributes:a,hydrateKey:u})},exports.resolveServerViewBase=s;
2
+ //# sourceMappingURL=server.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.cjs","names":[],"sources":["../src/server.tsx"],"sourcesContent":["import {createMemoryHistory} from 'history';\nimport {ReactElement, ReactNode} from 'react';\nimport {create, resolve, toLocation} from '@native-router/core';\nimport type {\n HistoryState,\n Location,\n Options,\n RouterInstance\n} from '@native-router/core';\nimport {isString} from '@native-router/core/util';\nimport {Router} from './components/Router';\nimport {getViewData, resolveViewServer} from './resolve-view';\nimport type {Route} from './types';\n\nconst defaultHydrateKey = '_nativeRouterReactSSRData';\n\n/**\n * Serialize the SSR payload for embedding in a script element.\n * `JSON.stringify` does not escape `<`, U+2028 and U+2029,\n * so route data like `</script>` would break out of the script element.\n * @param payload the payload to serialize\n * @returns the escaped JSON string\n */\nfunction serializePayload(payload: {\n data?: any[];\n location: Location;\n index: number;\n}) {\n return JSON.stringify(payload)\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n}\n\nexport function resolveServerViewBase(\n router: RouterInstance<Route, ReactNode>,\n location: Location,\n options?: {\n scriptAttributes?: Record<string, string>;\n hydrateKey?: string;\n }\n) {\n return resolve<Route, ReactNode>(router, location).then((view) => {\n const data = getViewData(view as ReactElement);\n const index =\n (router.history.location.state as HistoryState | undefined)?.index || 0;\n return (\n <>\n <Router router={router}>{view}</Router>\n <script\n {...options?.scriptAttributes}\n suppressHydrationWarning\n // eslint-disable-next-line @eslint-react/dom-no-dangerously-set-innerhtml -- serialized state for hydration\n dangerouslySetInnerHTML={{\n __html: `window.${\n options?.hydrateKey || defaultHydrateKey\n } = ${serializePayload({data, location, index})};`\n }}\n />\n </>\n );\n });\n}\n\nexport function resolveServerView(\n routes: Route | Route[],\n location: Location | string,\n {\n scriptAttributes,\n hydrateKey,\n ...options\n }: Options<ReactElement> & {\n scriptAttributes?: Record<string, string>;\n hydrateKey?: string;\n } = {}\n) {\n const router = create(\n routes,\n createMemoryHistory({initialEntries: [location]}),\n resolveViewServer,\n options\n );\n\n return resolveServerViewBase(\n router,\n isString(location) ? toLocation(router, location) : location,\n {\n scriptAttributes,\n hydrateKey\n }\n );\n}\n"],"mappings":"6QAkCA,SAAgB,EACd,EACA,EACA,GAKA,OAAA,EAAO,EAAA,SAA0B,EAAQ,GAAU,KAAM,IACvD,MAAM,EAAO,EAAA,YAAY,GACnB,EACH,EAAO,QAAQ,SAAS,OAAoC,OAAS,EACxE,OACE,EAAA,EAAA,MAAA,EAAA,SAAA,CAAA,SAAA,EACE,EAAA,EAAA,KAAC,EAAA,OAAD,CAAgB,SAAS,SAAA,KACzB,EAAA,EAAA,KAAC,SAAD,IACM,GAAS,iBACb,0BAAA,EAEA,wBAAyB,CACvB,OAAQ,UACN,GAAS,YAzCG,iCASA,EAiCS,CAAC,OAAM,WAAU,SA5B3C,KAAK,UAAU,GACnB,QAAQ,KAAM,WACd,QAAQ,UAAW,WACnB,QAAQ,UAAW,oBARxB,IAA0B,GAuC1B,2BAEA,SACE,EACA,GACA,iBACE,EAAA,WACA,KACG,GAID,CAAC,GAEL,MAAM,GAAA,EAAS,EAAA,QACb,GAAA,EACA,EAAA,qBAAoB,CAAC,eAAgB,CAAC,KACtC,EAAA,kBACA,GAGF,OAAO,EACL,GAAA,EACA,EAAA,UAAS,IAAQ,EAAI,EAAA,YAAW,EAAQ,GAAY,EACpD,CACE,mBACA,cAGN"}
package/dist/server.js CHANGED
@@ -1 +1,3 @@
1
- import{n as r}from"./ssr-873l9jA-.js";export{r as resolveServerView};
1
+ import{getViewData as t,resolveViewServer as r}from"./resolve-view.js";import{Router as e}from"./components/Router.js";import{createMemoryHistory as i}from"history";import{Fragment as o,jsx as n,jsxs as a}from"react/jsx-runtime";import{create as s,resolve as u,toLocation as c}from"@native-router/core";import{isString as p}from"@native-router/core/util";function m(r,i,s){return u(r,i).then(u=>{const c=t(u),p=r.history.location.state?.index||0;/* @__PURE__ */
2
+ return a(o,{children:[/* @__PURE__ */n(e,{router:r,children:u}),/* @__PURE__ */n("script",{...s?.scriptAttributes,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:`window.${s?.hydrateKey||"_nativeRouterReactSSRData"} = ${m={data:c,location:i,index:p},JSON.stringify(m).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};`}})]});var m})}function l(t,e,{scriptAttributes:o,hydrateKey:n,...a}={}){const u=s(t,i({initialEntries:[e]}),r,a);return m(u,p(e)?c(u,e):e,{scriptAttributes:o,hydrateKey:n})}export{l as resolveServerView,m as resolveServerViewBase};
3
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","names":[],"sources":["../src/server.tsx"],"sourcesContent":["import {createMemoryHistory} from 'history';\nimport {ReactElement, ReactNode} from 'react';\nimport {create, resolve, toLocation} from '@native-router/core';\nimport type {\n HistoryState,\n Location,\n Options,\n RouterInstance\n} from '@native-router/core';\nimport {isString} from '@native-router/core/util';\nimport {Router} from './components/Router';\nimport {getViewData, resolveViewServer} from './resolve-view';\nimport type {Route} from './types';\n\nconst defaultHydrateKey = '_nativeRouterReactSSRData';\n\n/**\n * Serialize the SSR payload for embedding in a script element.\n * `JSON.stringify` does not escape `<`, U+2028 and U+2029,\n * so route data like `</script>` would break out of the script element.\n * @param payload the payload to serialize\n * @returns the escaped JSON string\n */\nfunction serializePayload(payload: {\n data?: any[];\n location: Location;\n index: number;\n}) {\n return JSON.stringify(payload)\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n}\n\nexport function resolveServerViewBase(\n router: RouterInstance<Route, ReactNode>,\n location: Location,\n options?: {\n scriptAttributes?: Record<string, string>;\n hydrateKey?: string;\n }\n) {\n return resolve<Route, ReactNode>(router, location).then((view) => {\n const data = getViewData(view as ReactElement);\n const index =\n (router.history.location.state as HistoryState | undefined)?.index || 0;\n return (\n <>\n <Router router={router}>{view}</Router>\n <script\n {...options?.scriptAttributes}\n suppressHydrationWarning\n // eslint-disable-next-line @eslint-react/dom-no-dangerously-set-innerhtml -- serialized state for hydration\n dangerouslySetInnerHTML={{\n __html: `window.${\n options?.hydrateKey || defaultHydrateKey\n } = ${serializePayload({data, location, index})};`\n }}\n />\n </>\n );\n });\n}\n\nexport function resolveServerView(\n routes: Route | Route[],\n location: Location | string,\n {\n scriptAttributes,\n hydrateKey,\n ...options\n }: Options<ReactElement> & {\n scriptAttributes?: Record<string, string>;\n hydrateKey?: string;\n } = {}\n) {\n const router = create(\n routes,\n createMemoryHistory({initialEntries: [location]}),\n resolveViewServer,\n options\n );\n\n return resolveServerViewBase(\n router,\n isString(location) ? toLocation(router, location) : location,\n {\n scriptAttributes,\n hydrateKey\n }\n );\n}\n"],"mappings":"mWAkCA,SAAgB,EACd,EACA,EACA,GAKA,OAAO,EAA0B,EAAQ,GAAU,KAAM,IACvD,MAAM,EAAO,EAAY,GACnB,EACH,EAAO,QAAQ,SAAS,OAAoC,OAAS;AACxE,OACE,EAAA,EAAA,CAAA,SAAA,gBACE,EAAC,EAAD,CAAgB,SAAS,SAAA,mBACzB,EAAC,SAAD,IACM,GAAS,iBACb,0BAAA,EAEA,wBAAyB,CACvB,OAAQ,UACN,GAAS,YAzCG,iCASA,EAiCS,CAAC,OAAM,WAAU,SA5B3C,KAAK,UAAU,GACnB,QAAQ,KAAM,WACd,QAAQ,UAAW,WACnB,QAAQ,UAAW,oBARxB,IAA0B,GAuC1B,CAEA,SAAgB,EACd,EACA,GACA,iBACE,EAAA,WACA,KACG,GAID,CAAC,GAEL,MAAM,EAAS,EACb,EACA,EAAoB,CAAC,eAAgB,CAAC,KACtC,EACA,GAGF,OAAO,EACL,EACA,EAAS,GAAY,EAAW,EAAQ,GAAY,EACpD,CACE,mBACA,cAGN"}
package/dist/ssr.cjs ADDED
@@ -0,0 +1,2 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./resolve-view.cjs");let t=require("history"),r=require("@native-router/core");exports.hydrate=function(o,a){const{data:i,location:c,index:n=0}=window[a?.hydrateKey||"_nativeRouterReactSSRData"],s=(0,t.createBrowserHistory)();s.replace((0,t.createPath)(s.location),{index:n});const l=(0,r.create)(o,s,e.createHydrateResolveView(i),a);return(0,r.resolve)(l,c).then(t=>(l.viewStack[0]=t,l.resolveView=e.default,{view:t,router:l}))};
2
+ //# sourceMappingURL=ssr.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssr.cjs","names":[],"sources":["../src/ssr.tsx"],"sourcesContent":["import {createBrowserHistory, createPath} from 'history';\nimport {ReactElement, ReactNode} from 'react';\nimport {create, resolve} from '@native-router/core';\nimport type {Location, Options, RouterInstance} from '@native-router/core';\nimport defaultResolveView, {createHydrateResolveView} from './resolve-view';\nimport type {Route} from './types';\n\nconst defaultHydrateKey = '_nativeRouterReactSSRData';\n\n/**\n * Hydrate the SSR result of {@link resolveServerView} on the client.\n * The router is bound to the browser history(aligned with the index\n * in the SSR payload), so navigation after hydration updates the address bar.\n * @param routes routes config, must match the server side\n * @param options options, `hydrateKey` must match the server side\n * @returns the resolved view and the router instance, for example:\n * `const {router} = await hydrate(routes);`\n * `hydrateRoot(root, <Router router={router}/>)`\n * @group Methods\n */\nexport function hydrate(\n routes: Route | Route[],\n options?: Options<ReactElement> & {\n hydrateKey?: string;\n }\n): Promise<{view: ReactNode; router: RouterInstance<Route, ReactNode>}> {\n const {\n data,\n location,\n index = 0\n } = (window as any)[options?.hydrateKey || defaultHydrateKey] as {\n data: any[];\n location: Location;\n index?: number;\n };\n const history = createBrowserHistory();\n history.replace(createPath(history.location), {index});\n const router = create<Route, ReactNode>(\n routes,\n history,\n createHydrateResolveView(data),\n options\n );\n return resolve<Route, ReactNode>(router, location).then((view) => {\n // Seed the resolved view into the view stack: one-shot resolves do\n // not enter it, but `getCurrentView(router)` must return the view\n // for the hydration render. With the stack seeded, a plain\n // `<Router router={router}/>` renders the store view — its first\n // (hydration) render matches the server HTML and later navigations\n // update through the same store.\n router.viewStack[0] = view;\n // The payload-backed resolver only covers the initial chain; every\n // later navigation resolves through the default resolver and runs\n // its own data loaders.\n router.resolveView = defaultResolveView;\n return {view, router};\n });\n}\n"],"mappings":"mLAoBA,SACE,EACA,GAIA,MAAM,KACJ,EAAA,SACA,EAAA,MACA,EAAQ,GACL,OAAe,GAAS,YAvBL,6BA4BlB,GAAA,EAAU,EAAA,wBAChB,EAAQ,SAAA,EAAQ,EAAA,YAAW,EAAQ,UAAW,CAAC,UAC/C,MAAM,GAAA,EAAS,EAAA,QACb,EACA,EACA,EAAA,yBAAyB,GACzB,GAEF,OAAA,EAAO,EAAA,SAA0B,EAAQ,GAAU,KAAM,IAOvD,EAAO,UAAU,GAAK,EAItB,EAAO,YAAc,EAAA,QACd,CAAC,OAAM,WAElB"}
package/dist/ssr.js ADDED
@@ -0,0 +1,2 @@
1
+ import e,{createHydrateResolveView as o}from"./resolve-view.js";import{createBrowserHistory as t,createPath as r}from"history";import{create as i,resolve as n}from"@native-router/core";function a(a,c){const{data:v,location:m,index:s=0}=window[c?.hydrateKey||"_nativeRouterReactSSRData"],w=t();w.replace(r(w.location),{index:s});const d=i(a,w,o(v),c);return n(d,m).then(o=>(d.viewStack[0]=o,d.resolveView=e,{view:o,router:d}))}export{a as hydrate};
2
+ //# sourceMappingURL=ssr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssr.js","names":[],"sources":["../src/ssr.tsx"],"sourcesContent":["import {createBrowserHistory, createPath} from 'history';\nimport {ReactElement, ReactNode} from 'react';\nimport {create, resolve} from '@native-router/core';\nimport type {Location, Options, RouterInstance} from '@native-router/core';\nimport defaultResolveView, {createHydrateResolveView} from './resolve-view';\nimport type {Route} from './types';\n\nconst defaultHydrateKey = '_nativeRouterReactSSRData';\n\n/**\n * Hydrate the SSR result of {@link resolveServerView} on the client.\n * The router is bound to the browser history(aligned with the index\n * in the SSR payload), so navigation after hydration updates the address bar.\n * @param routes routes config, must match the server side\n * @param options options, `hydrateKey` must match the server side\n * @returns the resolved view and the router instance, for example:\n * `const {router} = await hydrate(routes);`\n * `hydrateRoot(root, <Router router={router}/>)`\n * @group Methods\n */\nexport function hydrate(\n routes: Route | Route[],\n options?: Options<ReactElement> & {\n hydrateKey?: string;\n }\n): Promise<{view: ReactNode; router: RouterInstance<Route, ReactNode>}> {\n const {\n data,\n location,\n index = 0\n } = (window as any)[options?.hydrateKey || defaultHydrateKey] as {\n data: any[];\n location: Location;\n index?: number;\n };\n const history = createBrowserHistory();\n history.replace(createPath(history.location), {index});\n const router = create<Route, ReactNode>(\n routes,\n history,\n createHydrateResolveView(data),\n options\n );\n return resolve<Route, ReactNode>(router, location).then((view) => {\n // Seed the resolved view into the view stack: one-shot resolves do\n // not enter it, but `getCurrentView(router)` must return the view\n // for the hydration render. With the stack seeded, a plain\n // `<Router router={router}/>` renders the store view — its first\n // (hydration) render matches the server HTML and later navigations\n // update through the same store.\n router.viewStack[0] = view;\n // The payload-backed resolver only covers the initial chain; every\n // later navigation resolves through the default resolver and runs\n // its own data loaders.\n router.resolveView = defaultResolveView;\n return {view, router};\n });\n}\n"],"mappings":"yLAoBA,SAAgB,EACd,EACA,GAIA,MAAM,KACJ,EAAA,SACA,EAAA,MACA,EAAQ,GACL,OAAe,GAAS,YAvBL,6BA4BlB,EAAU,IAChB,EAAQ,QAAQ,EAAW,EAAQ,UAAW,CAAC,UAC/C,MAAM,EAAS,EACb,EACA,EACA,EAAyB,GACzB,GAEF,OAAO,EAA0B,EAAQ,GAAU,KAAM,IAOvD,EAAO,UAAU,GAAK,EAItB,EAAO,YAAc,EACd,CAAC,OAAM,WAElB"}
@@ -10,4 +10,3 @@ export { useSearchParams, useSearch, useSetSearch } from './use-search-params';
10
10
  export { useBlocker } from './use-blocker';
11
11
  export { default as defaultResolveView } from './resolve-view';
12
12
  export * from './types';
13
- export { hydrate } from './ssr';
@@ -1 +1,11 @@
1
- export { resolveServerView } from './ssr';
1
+ import { ReactElement, ReactNode } from 'react';
2
+ import type { Location, Options, RouterInstance } from '@native-router/core';
3
+ import type { Route } from './types';
4
+ export declare function resolveServerViewBase(router: RouterInstance<Route, ReactNode>, location: Location, options?: {
5
+ scriptAttributes?: Record<string, string>;
6
+ hydrateKey?: string;
7
+ }): Promise<import("react").JSX.Element>;
8
+ export declare function resolveServerView(routes: Route | Route[], location: Location | string, { scriptAttributes, hydrateKey, ...options }?: Options<ReactElement> & {
9
+ scriptAttributes?: Record<string, string>;
10
+ hydrateKey?: string;
11
+ }): Promise<import("react").JSX.Element>;
@@ -1,14 +1,6 @@
1
1
  import { ReactElement, ReactNode } from 'react';
2
- import type { Location, Options, RouterInstance } from '@native-router/core';
2
+ import type { Options, RouterInstance } from '@native-router/core';
3
3
  import type { Route } from './types';
4
- export declare function resolveServerViewBase(router: RouterInstance<Route, ReactNode>, location: Location, options?: {
5
- scriptAttributes?: Record<string, string>;
6
- hydrateKey?: string;
7
- }): Promise<import("react").JSX.Element>;
8
- export declare function resolveServerView(routes: Route | Route[], location: Location | string, { scriptAttributes, hydrateKey, ...options }?: Options<ReactElement> & {
9
- scriptAttributes?: Record<string, string>;
10
- hydrateKey?: string;
11
- }): Promise<import("react").JSX.Element>;
12
4
  /**
13
5
  * Hydrate the SSR result of {@link resolveServerView} on the client.
14
6
  * The router is bound to the browser history(aligned with the index
@@ -16,8 +8,8 @@ export declare function resolveServerView(routes: Route | Route[], location: Loc
16
8
  * @param routes routes config, must match the server side
17
9
  * @param options options, `hydrateKey` must match the server side
18
10
  * @returns the resolved view and the router instance, for example:
19
- * `const {view, router} = await hydrate(routes);`
20
- * `hydrateRoot(root, <Router router={router}>{view}</Router>)`
11
+ * `const {router} = await hydrate(routes);`
12
+ * `hydrateRoot(root, <Router router={router}/>)`
21
13
  * @group Methods
22
14
  */
23
15
  export declare function hydrate(routes: Route | Route[], options?: Options<ReactElement> & {
@@ -1,4 +1,34 @@
1
1
  import type { BlockerFn } from '@native-router/core';
2
+ /**
3
+ * A vetoed navigation waiting for a decision, exposed on
4
+ * {@link Blocker.state}: the user was asked, the router stayed on
5
+ * {@link BlockerState.from from}.
6
+ */
7
+ export type BlockerState = {
8
+ /** The vetoed navigation's target path (pathname, search, hash). */
9
+ location: string;
10
+ /** The path the vetoed navigation tried to leave. */
11
+ from: string;
12
+ };
13
+ /**
14
+ * What {@link useBlocker} returns: whether a navigation is waiting for
15
+ * a decision, plus the decision channel. Both actions are no-ops while
16
+ * `state` is `null`.
17
+ */
18
+ export type Blocker = {
19
+ /** The pending ask, or `null` while nothing waits — drive your confirm UI off it. */
20
+ state: BlockerState | null;
21
+ /**
22
+ * Retry the vetoed navigation. Only this hook's own blocker is
23
+ * bypassed — the user has answered it — while other registered
24
+ * blockers and the guard chain still get asked on the retry. A
25
+ * blocked-by-another-blocker retry re-enters this hook as a fresh
26
+ * veto and re-opens the ask.
27
+ */
28
+ proceed(): void;
29
+ /** Dismiss the ask; the router stays where it is. */
30
+ reset(): void;
31
+ };
2
32
  /**
3
33
  * Block navigations away from the current page while the component is
4
34
  * mounted — the unsaved-changes guard.
@@ -17,9 +47,36 @@ import type { BlockerFn } from '@native-router/core';
17
47
  * here touches `window`, and the registration itself is an effect that
18
48
  * never runs on the server.
19
49
  *
50
+ * Every veto is tracked on the returned {@link Blocker}, so the
51
+ * confirm UI is a three-liner instead of a hand-rolled ref/state pair:
52
+ *
53
+ * ```tsx
54
+ * const blocker = useBlocker(() => isDirtyRef.current);
55
+ *
56
+ * return (
57
+ * <>
58
+ * <Editor />
59
+ * <ConfirmDialog
60
+ * open={blocker.state != null}
61
+ * onCancel={blocker.reset}
62
+ * onConfirm={blocker.proceed}
63
+ * />
64
+ * </>
65
+ * );
66
+ * ```
67
+ *
68
+ * `proceed()` retries the vetoed navigation bypassing this hook's own
69
+ * blocker only — other registered blockers (and the route guards) are
70
+ * still asked, in registration order. Note the retry is a fresh push
71
+ * navigation: for a vetoed browser POP it appends an entry rather than
72
+ * re-running the history traversal.
73
+ *
20
74
  * @group Hooks
21
75
  * @param fn blocker predicate; `to` is the target path, `from` the
22
- * current path
76
+ * current path. Return `false` to veto (and open the ask), `true` to
77
+ * let the navigation through
78
+ * @returns {@link Blocker} — the pending ask and its proceed/reset
79
+ * channel
23
80
  * @see {@link setBlocker}
24
81
  */
25
- export declare function useBlocker(fn: BlockerFn): void;
82
+ export declare function useBlocker(fn: BlockerFn): Blocker;
@@ -0,0 +1,2 @@
1
+ const e=require("./components/Router.cjs");let r=require("react"),t=require("@native-router/core");exports.useBlocker=function(u){const c=e.useRouter(),n=(0,r.useRef)(u);n.current=u;const[o,l]=(0,r.useState)(null),s=(0,r.useRef)(null),a=(0,r.useRef)(!1);return(0,r.useEffect)(()=>(0,t.setBlocker)(c,(e,r)=>a.current?(a.current=!1,!0):!!n.current(e,r)||(s.current={location:e,from:r},l({location:e,from:r}),!1)),[c]),{state:o,proceed:(0,r.useCallback)(()=>{const e=s.current;e&&(s.current=null,l(null),a.current=!0,(0,t.navigate)(c,e.location).catch(()=>{}))},[c]),reset:(0,r.useCallback)(()=>{s.current=null,l(null)},[])}};
2
+ //# sourceMappingURL=use-blocker.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-blocker.cjs","names":[],"sources":["../src/use-blocker.ts"],"sourcesContent":["import {useCallback, useEffect, useRef, useState} from 'react';\nimport {navigate, setBlocker} from '@native-router/core';\nimport type {BlockerFn} from '@native-router/core';\nimport {useRouter} from './components/Router';\n\n/**\n * A vetoed navigation waiting for a decision, exposed on\n * {@link Blocker.state}: the user was asked, the router stayed on\n * {@link BlockerState.from from}.\n */\nexport type BlockerState = {\n /** The vetoed navigation's target path (pathname, search, hash). */\n location: string;\n /** The path the vetoed navigation tried to leave. */\n from: string;\n};\n\n/**\n * What {@link useBlocker} returns: whether a navigation is waiting for\n * a decision, plus the decision channel. Both actions are no-ops while\n * `state` is `null`.\n */\nexport type Blocker = {\n /** The pending ask, or `null` while nothing waits — drive your confirm UI off it. */\n state: BlockerState | null;\n /**\n * Retry the vetoed navigation. Only this hook's own blocker is\n * bypassed — the user has answered it — while other registered\n * blockers and the guard chain still get asked on the retry. A\n * blocked-by-another-blocker retry re-enters this hook as a fresh\n * veto and re-opens the ask.\n */\n proceed(): void;\n /** Dismiss the ask; the router stays where it is. */\n reset(): void;\n};\n\n/**\n * Block navigations away from the current page while the component is\n * mounted — the unsaved-changes guard.\n *\n * The predicate is the core `setBlocker` veto: `(to, from) => boolean`\n * over path strings(including search and hash), asked synchronously at\n * the head of every navigation and before a history POP lands. Return\n * `false` to veto: a vetoed navigation never starts and a vetoed POP is\n * rewound. `refresh` and guard redirects are never blocked; the effect\n * releases the blocker on unmount, so the guard lives exactly as long\n * as the guarding component.\n *\n * The predicate is stored in a ref and re-synced on every render, so a\n * navigation is always asked the latest closure — a `confirmed` flag it\n * captured works without re-registering anything. SSR-safe: nothing\n * here touches `window`, and the registration itself is an effect that\n * never runs on the server.\n *\n * Every veto is tracked on the returned {@link Blocker}, so the\n * confirm UI is a three-liner instead of a hand-rolled ref/state pair:\n *\n * ```tsx\n * const blocker = useBlocker(() => isDirtyRef.current);\n *\n * return (\n * <>\n * <Editor />\n * <ConfirmDialog\n * open={blocker.state != null}\n * onCancel={blocker.reset}\n * onConfirm={blocker.proceed}\n * />\n * </>\n * );\n * ```\n *\n * `proceed()` retries the vetoed navigation bypassing this hook's own\n * blocker only — other registered blockers (and the route guards) are\n * still asked, in registration order. Note the retry is a fresh push\n * navigation: for a vetoed browser POP it appends an entry rather than\n * re-running the history traversal.\n *\n * @group Hooks\n * @param fn blocker predicate; `to` is the target path, `from` the\n * current path. Return `false` to veto (and open the ask), `true` to\n * let the navigation through\n * @returns {@link Blocker} — the pending ask and its proceed/reset\n * channel\n * @see {@link setBlocker}\n */\nexport function useBlocker(fn: BlockerFn): Blocker {\n const router = useRouter();\n const fnRef = useRef(fn);\n // Always ask the latest closure: re-rendering with new state must not\n // require re-registering the blocker.\n fnRef.current = fn;\n const [ask, setAsk] = useState<BlockerState | null>(null);\n // The pending ask, readable synchronously from proceed/reset — the\n // confirm callbacks must not depend on the render closure's freshness.\n const pendingRef = useRef<BlockerState | null>(null);\n // One-shot bypass for the proceed retry: set right before the retry\n // navigation, cleared once it has been asked. A plain ref — the flag\n // must be visible to the synchronously-asked blocker, not to React.\n const bypassRef = useRef(false);\n\n useEffect(\n () =>\n setBlocker(router, (to, from) => {\n // The proceed retry: the user already answered this blocker.\n // Still ask the other registered ones (setBlocker iterates the\n // registry in order) and reset the flag once we are asked.\n if (bypassRef.current) {\n bypassRef.current = false;\n return true;\n }\n if (fnRef.current(to, from)) return true;\n // Vetoed: open the ask. A navigation superseding an open ask\n // replaces it — the older target is never proceeded to.\n pendingRef.current = {location: to, from};\n setAsk({location: to, from});\n return false;\n }),\n [router]\n );\n\n const proceed = useCallback(() => {\n const pending = pendingRef.current;\n if (!pending) return;\n pendingRef.current = null;\n setAsk(null);\n bypassRef.current = true;\n void navigate(router, pending.location).catch(() => undefined);\n }, [router]);\n\n const reset = useCallback(() => {\n pendingRef.current = null;\n setAsk(null);\n }, []);\n\n return {state: ask, proceed, reset};\n}\n"],"mappings":"sHAuFA,SAA2B,GACzB,MAAM,EAAS,EAAA,YACT,GAAA,EAAQ,EAAA,QAAO,GAGrB,EAAM,QAAU,EAChB,MAAO,EAAK,IAAA,EAAU,EAAA,UAA8B,MAG9C,GAAA,EAAa,EAAA,QAA4B,MAIzC,GAAA,EAAY,EAAA,SAAO,GAoCzB,OAlCA,EAAA,EAAA,WAAA,KAAA,EAEI,EAAA,YAAW,EAAA,CAAS,EAAI,IAIlB,EAAU,SACZ,EAAU,SAAU,GACb,KAEL,EAAM,QAAQ,EAAI,KAGtB,EAAW,QAAU,CAAC,SAAU,EAAI,QACpC,EAAO,CAAC,SAAU,EAAI,UACf,IAEX,CAAC,IAiBI,CAAC,MAAO,EAAK,SAAA,EAdJ,EAAA,aAAA,KACd,MAAM,EAAU,EAAW,QACtB,IACL,EAAW,QAAU,KACrB,EAAO,MACP,EAAU,SAAU,GACpB,EAAK,EAAA,UAAS,EAAQ,EAAQ,UAAU,MAAA,UACvC,CAAC,IAOyB,OAAA,EALf,EAAA,aAAA,KACZ,EAAW,QAAU,KACrB,EAAO,OACN,IAGL"}
@@ -0,0 +1,2 @@
1
+ import{useRouter as r}from"./components/Router.js";import{useCallback as t,useEffect as n,useRef as o,useState as c}from"react";import{navigate as e,setBlocker as u}from"@native-router/core";function l(l){const m=r(),i=o(l);i.current=l;const[a,s]=c(null),f=o(null),p=o(!1);return n(()=>u(m,(r,t)=>p.current?(p.current=!1,!0):!!i.current(r,t)||(f.current={location:r,from:t},s({location:r,from:t}),!1)),[m]),{state:a,proceed:t(()=>{const r=f.current;r&&(f.current=null,s(null),p.current=!0,e(m,r.location).catch(()=>{}))},[m]),reset:t(()=>{f.current=null,s(null)},[])}}export{l as useBlocker};
2
+ //# sourceMappingURL=use-blocker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-blocker.js","names":[],"sources":["../src/use-blocker.ts"],"sourcesContent":["import {useCallback, useEffect, useRef, useState} from 'react';\nimport {navigate, setBlocker} from '@native-router/core';\nimport type {BlockerFn} from '@native-router/core';\nimport {useRouter} from './components/Router';\n\n/**\n * A vetoed navigation waiting for a decision, exposed on\n * {@link Blocker.state}: the user was asked, the router stayed on\n * {@link BlockerState.from from}.\n */\nexport type BlockerState = {\n /** The vetoed navigation's target path (pathname, search, hash). */\n location: string;\n /** The path the vetoed navigation tried to leave. */\n from: string;\n};\n\n/**\n * What {@link useBlocker} returns: whether a navigation is waiting for\n * a decision, plus the decision channel. Both actions are no-ops while\n * `state` is `null`.\n */\nexport type Blocker = {\n /** The pending ask, or `null` while nothing waits — drive your confirm UI off it. */\n state: BlockerState | null;\n /**\n * Retry the vetoed navigation. Only this hook's own blocker is\n * bypassed — the user has answered it — while other registered\n * blockers and the guard chain still get asked on the retry. A\n * blocked-by-another-blocker retry re-enters this hook as a fresh\n * veto and re-opens the ask.\n */\n proceed(): void;\n /** Dismiss the ask; the router stays where it is. */\n reset(): void;\n};\n\n/**\n * Block navigations away from the current page while the component is\n * mounted — the unsaved-changes guard.\n *\n * The predicate is the core `setBlocker` veto: `(to, from) => boolean`\n * over path strings(including search and hash), asked synchronously at\n * the head of every navigation and before a history POP lands. Return\n * `false` to veto: a vetoed navigation never starts and a vetoed POP is\n * rewound. `refresh` and guard redirects are never blocked; the effect\n * releases the blocker on unmount, so the guard lives exactly as long\n * as the guarding component.\n *\n * The predicate is stored in a ref and re-synced on every render, so a\n * navigation is always asked the latest closure — a `confirmed` flag it\n * captured works without re-registering anything. SSR-safe: nothing\n * here touches `window`, and the registration itself is an effect that\n * never runs on the server.\n *\n * Every veto is tracked on the returned {@link Blocker}, so the\n * confirm UI is a three-liner instead of a hand-rolled ref/state pair:\n *\n * ```tsx\n * const blocker = useBlocker(() => isDirtyRef.current);\n *\n * return (\n * <>\n * <Editor />\n * <ConfirmDialog\n * open={blocker.state != null}\n * onCancel={blocker.reset}\n * onConfirm={blocker.proceed}\n * />\n * </>\n * );\n * ```\n *\n * `proceed()` retries the vetoed navigation bypassing this hook's own\n * blocker only — other registered blockers (and the route guards) are\n * still asked, in registration order. Note the retry is a fresh push\n * navigation: for a vetoed browser POP it appends an entry rather than\n * re-running the history traversal.\n *\n * @group Hooks\n * @param fn blocker predicate; `to` is the target path, `from` the\n * current path. Return `false` to veto (and open the ask), `true` to\n * let the navigation through\n * @returns {@link Blocker} — the pending ask and its proceed/reset\n * channel\n * @see {@link setBlocker}\n */\nexport function useBlocker(fn: BlockerFn): Blocker {\n const router = useRouter();\n const fnRef = useRef(fn);\n // Always ask the latest closure: re-rendering with new state must not\n // require re-registering the blocker.\n fnRef.current = fn;\n const [ask, setAsk] = useState<BlockerState | null>(null);\n // The pending ask, readable synchronously from proceed/reset — the\n // confirm callbacks must not depend on the render closure's freshness.\n const pendingRef = useRef<BlockerState | null>(null);\n // One-shot bypass for the proceed retry: set right before the retry\n // navigation, cleared once it has been asked. A plain ref — the flag\n // must be visible to the synchronously-asked blocker, not to React.\n const bypassRef = useRef(false);\n\n useEffect(\n () =>\n setBlocker(router, (to, from) => {\n // The proceed retry: the user already answered this blocker.\n // Still ask the other registered ones (setBlocker iterates the\n // registry in order) and reset the flag once we are asked.\n if (bypassRef.current) {\n bypassRef.current = false;\n return true;\n }\n if (fnRef.current(to, from)) return true;\n // Vetoed: open the ask. A navigation superseding an open ask\n // replaces it — the older target is never proceeded to.\n pendingRef.current = {location: to, from};\n setAsk({location: to, from});\n return false;\n }),\n [router]\n );\n\n const proceed = useCallback(() => {\n const pending = pendingRef.current;\n if (!pending) return;\n pendingRef.current = null;\n setAsk(null);\n bypassRef.current = true;\n void navigate(router, pending.location).catch(() => undefined);\n }, [router]);\n\n const reset = useCallback(() => {\n pendingRef.current = null;\n setAsk(null);\n }, []);\n\n return {state: ask, proceed, reset};\n}\n"],"mappings":"+LAuFA,SAAgB,EAAW,GACzB,MAAM,EAAS,IACT,EAAQ,EAAO,GAGrB,EAAM,QAAU,EAChB,MAAO,EAAK,GAAU,EAA8B,MAG9C,EAAa,EAA4B,MAIzC,EAAY,GAAO,GAoCzB,OAlCA,EAAA,IAEI,EAAW,EAAA,CAAS,EAAI,IAIlB,EAAU,SACZ,EAAU,SAAU,GACb,KAEL,EAAM,QAAQ,EAAI,KAGtB,EAAW,QAAU,CAAC,SAAU,EAAI,QACpC,EAAO,CAAC,SAAU,EAAI,UACf,IAEX,CAAC,IAiBI,CAAC,MAAO,EAAK,QAdJ,EAAA,KACd,MAAM,EAAU,EAAW,QACtB,IACL,EAAW,QAAU,KACrB,EAAO,MACP,EAAU,SAAU,EACpB,EAAc,EAAQ,EAAQ,UAAU,MAAA,UACvC,CAAC,IAOyB,MALf,EAAA,KACZ,EAAW,QAAU,KACrB,EAAO,OACN,IAGL"}
@@ -0,0 +1,2 @@
1
+ const e=require("./components/Router.cjs");let r=require("react"),t=require("@native-router/core"),n=require("use-sync-external-store/shim");function a(e){return Object.entries(e).filter(([,e])=>null!=e).map(([e,r])=>(Array.isArray(r)?r:[r]).map(r=>`${encodeURIComponent(e)}=${encodeURIComponent(String(r))}`).join("&")).join("&")}function o(e,r,n){const{history:a}=e,{pathname:o,hash:c}=a.location,s=o+(r?`?${r}`:"")+c;return n?.replace?(0,t.resolveEntry)(e,(0,t.toLocation)(e,s)).then(r=>(0,t.commitReplace)(e,r.task,r.location)):(0,t.navigate)(e,s)}exports.useSearch=function(a){const o=e.useRouter(),c=(0,r.useCallback)(e=>o.history.listen(()=>e()),[o]),s=(0,r.useCallback)(()=>o.history.location.search,[o]),u=(0,r.useCallback)(()=>"",[]),i=(0,n.useSyncExternalStore)(c,s,u);return a?(0,t.parseSearchSync)(a,i):(0,t.parseSearchInput)(i)},exports.useSearchParams=function(){const t=e.useRouter(),a=(0,r.useCallback)(e=>t.history.listen(()=>e()),[t]),c=(0,r.useCallback)(()=>t.history.location.search,[t]),s=(0,r.useCallback)(()=>"",[]);return[new URLSearchParams((0,n.useSyncExternalStore)(a,c,s)),(0,r.useCallback)((e,r)=>{const{history:n}=t,a="function"==typeof e?e(new URLSearchParams(n.location.search)):e;return o(t,a.toString(),r)},[t])]},exports.useSetSearch=function(n){const c=e.useRouter();return(0,r.useCallback)((e,r)=>{const{history:s}=c,u="function"==typeof e?e((0,t.parseSearchInput)(s.location.search)):e,i=(0,t.parseSearchSync)(n,a(u));return o(c,a(i),r)},[c,n])};
2
+ //# sourceMappingURL=use-search-params.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-search-params.cjs","names":[],"sources":["../src/use-search-params.ts"],"sourcesContent":["import {useCallback} from 'react';\nimport {\n commitReplace,\n navigate,\n parseSearchInput,\n parseSearchSync,\n resolveEntry,\n toLocation\n} from '@native-router/core';\nimport type {\n SearchInput,\n SearchOutputOf,\n StandardSchemaV1\n} from '@native-router/core';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './components/Router';\n\ntype SetSearchParams = (\n next: URLSearchParams | ((prev: URLSearchParams) => URLSearchParams),\n opts?: {replace?: boolean}\n) => Promise<void> | void;\n\n/**\n * Read and write the search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as the Router Component), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; a fresh `URLSearchParams` view is derived from that string\n * on each render.\n *\n * The setter navigates like any other route change: by default the new\n * search is pushed onto the history stack(mainstream react-router\n * semantics), pass `{replace: true}` to rewrite the current entry instead.\n * Since the search is part of the location, every write re-resolves the\n * matched route, so route `data` fetchers(see {@link useData}) observe the\n * new search on the next {@link useData} read.\n *\n * @group Hooks\n * @returns [searchParams, setSearchParams] - the current search params and\n * the setter(functional updates receive the live previous params); the\n * setter returns a `Promise<void>` that resolves once the navigation\n * commits, so callers may optionally `await` it\n */\nexport function useSearchParams(): [URLSearchParams, SetSearchParams] {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a URLSearchParams instance) to keep the\n // snapshot reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n const searchParams = new URLSearchParams(\n useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n );\n\n const setSearchParams = useCallback<SetSearchParams>(\n (next, opts) => {\n const {history} = router;\n const params =\n typeof next === 'function'\n ? // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n next(new URLSearchParams(history.location.search))\n : next;\n return setSearch(router, params.toString(), opts);\n },\n [router]\n );\n\n return [searchParams, setSearchParams];\n}\n\n/**\n * Write the search params of the current location through a schema, the\n * setter-side twin of `useSearch(schema)`: the next value is serialized\n * to a query string, degraded with `parseSearchInput` and validated by\n * the SAME schema before any navigation happens. A schema that rejects\n * the value throws its issues(`SearchError`) without touching the\n * location; the value the schema would default or coerce on the read\n * side never gets silently written.\n *\n * Synchronous schemas only(the `useSearch` flavor); an async `validate`\n * rejects without navigating.\n *\n * The navigation semantics follow `useSearchParams`' setter: push by\n * default, `{replace: true}` rewrites the current entry, guards run,\n * and the returned `Promise<void>` resolves once the navigation commits.\n *\n * @group Hooks\n * @param schema a Standard Schema validator of the search — must\n * validate synchronously\n * @returns the schema-aware setter; functional updates receive the live\n * previous params\n * @throws {SearchError} when `schema` rejects the next value, before\n * any navigation\n */\nexport function useSetSearch<S extends StandardSchemaV1>(\n schema: S\n): (\n next: SearchInput | ((prev: SearchInput) => SearchInput),\n opts?: {replace?: boolean}\n) => Promise<void> | void {\n const router = useRouter();\n\n return useCallback(\n (next, opts) => {\n const {history} = router;\n const input =\n typeof next === 'function'\n ? next(parseSearchInput(history.location.search))\n : next;\n // Validate the whole next value — not a diff — the same way a\n // navigation to the resulting URL would: parseSearchSync throws\n // SearchError with the schema's issues, and no navigation happens.\n const validated = parseSearchSync(schema, stringifySearch(input));\n // The schema output is authoritative: defaults applied and values\n // coerced to strings, so a partially-filled input still writes the\n // fully-defaulted query.\n return setSearch(\n router,\n stringifySearch(validated as Record<string, unknown>),\n opts\n );\n },\n [router, schema]\n );\n}\n\nfunction stringifySearch(input: Record<string, unknown>): string {\n return Object.entries(input)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) =>\n (Array.isArray(value) ? value : [value])\n .map(\n (v) => `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`\n )\n .join('&')\n )\n .join('&');\n}\n\nfunction setSearch(\n router: ReturnType<typeof useRouter>,\n qs: string,\n opts?: {replace?: boolean}\n): Promise<void> | void {\n const {history} = router;\n const {pathname, hash} = history.location;\n const to = pathname + (qs ? `?${qs}` : '') + hash;\n if (opts?.replace) {\n // Route guards run like any other navigation(align with the push\n // branch): the entry carries the terminal location, so a redirect\n // replaces the current entry with its final target.\n return resolveEntry(router, toLocation(router, to)).then((entry) =>\n commitReplace(router, entry.task, entry.location)\n );\n }\n return navigate(router, to);\n}\n\n/**\n * Read the parsed search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as {@link useSearchParams}), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; the parse itself runs on each render.\n *\n * Without a schema the hook degrades to the raw input object of\n * `parseSearchInput` — strings, arrays for repeated keys\n * (`{page: '2', tag: ['a', 'b']}`). With a schema — any zod/valibot/\n * arktype schema, see the route {@link Route.search search field} — the\n * returned object is the schema's parsed output, so coercion and defaults\n * apply, e.g. `useSearch(pageSchema).page` is a number.\n *\n * Prefer declaring the schema once on the route: its `data` loader then\n * receives a parsed `ctx.search` during resolve, and an invalid search\n * fails the navigation through the existing error channels instead of\n * throwing during render.\n *\n * @group Hooks\n * @param schema an optional Standard Schema validator of the search; it\n * must validate synchronously\n * @returns the parsed search params of the current location\n * @throws {SearchError} when `schema` rejects the current search\n */\nexport function useSearch<S extends StandardSchemaV1>(\n schema: S\n): SearchOutputOf<S>;\nexport function useSearch(): SearchInput;\nexport function useSearch(schema?: StandardSchemaV1): unknown {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a parsed object) to keep the snapshot\n // reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n const search = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n );\n\n return schema ? parseSearchSync(schema, search) : parseSearchInput(search);\n}\n"],"mappings":"6IA2IA,SAAS,EAAgB,GACvB,OAAO,OAAO,QAAQ,GACnB,OAAA,EAAQ,CAAG,KAAW,SACtB,IAAA,EAAM,EAAK,MACT,MAAM,QAAQ,GAAS,EAAQ,CAAC,IAC9B,IACE,GAAM,GAAG,mBAAmB,MAAQ,mBAAmB,OAAO,OAEhE,KAAK,MAET,KAAK,IACV,CAEA,SAAS,EACP,EACA,EACA,GAEA,MAAM,QAAC,GAAW,GACZ,SAAC,EAAA,KAAU,GAAQ,EAAQ,SAC3B,EAAK,GAAY,EAAK,IAAI,IAAO,IAAM,EAC7C,OAAI,GAAM,SAIR,EAAO,EAAA,cAAa,GAAA,EAAQ,EAAA,YAAW,EAAQ,IAAK,KAAM,IAAA,EACxD,EAAA,eAAc,EAAQ,EAAM,KAAM,EAAM,YAG5C,EAAO,EAAA,UAAS,EAAQ,EAC1B,mBAgCA,SAA0B,GACxB,MAAM,EAAS,EAAA,YAIT,GAAA,EAAY,EAAA,aACf,GAA8B,EAAO,QAAQ,OAAA,IAAa,KAC3D,CAAC,IAIG,GAAA,EAAc,EAAA,aAAA,IACZ,EAAO,QAAQ,SAAS,OAC9B,CAAC,IAGG,GAAA,EAAoB,EAAA,aAAA,IAAkB,GAAI,IAE1C,GAAA,EAAS,EAAA,sBACb,EACA,EACA,GAGF,OAAO,GAAA,EAAS,EAAA,iBAAgB,EAAQ,IAAM,EAAI,EAAA,kBAAiB,EACrE,0BAtLA,WACE,MAAM,EAAS,EAAA,YAIT,GAAA,EAAY,EAAA,aACf,GAA8B,EAAO,QAAQ,OAAA,IAAa,KAC3D,CAAC,IAIG,GAAA,EAAc,EAAA,aAAA,IACZ,EAAO,QAAQ,SAAS,OAC9B,CAAC,IAGG,GAAA,EAAoB,EAAA,aAAA,IAAkB,GAAI,IAoBhD,MAAO,CAAC,IAjBiB,iBAAA,EACvB,EAAA,sBAAqB,EAAW,EAAa,KAgBvC,EAbgB,EAAA,aAAA,CACrB,EAAM,KACL,MAAM,QAAC,GAAW,EACZ,EACY,mBAAT,EAEH,EAAK,IAAI,gBAAgB,EAAQ,SAAS,SAC1C,EACN,OAAO,EAAU,EAAQ,EAAO,WAAY,IAE9C,CAAC,IAIL,uBA0BA,SACE,GAKA,MAAM,EAAS,EAAA,YAEf,OAAA,EAAO,EAAA,aAAA,CACJ,EAAM,KACL,MAAM,QAAC,GAAW,EACZ,EACY,mBAAT,EACH,GAAA,EAAK,EAAA,kBAAiB,EAAQ,SAAS,SACvC,EAIA,GAAA,EAAY,EAAA,iBAAgB,EAAQ,EAAgB,IAI1D,OAAO,EACL,EACA,EAAgB,GAChB,IAGJ,CAAC,EAAQ,GAEb"}
@@ -0,0 +1,2 @@
1
+ import{useRouter as t}from"./components/Router.js";import{useCallback as o}from"react";import{commitReplace as n,navigate as r,parseSearchInput as e,parseSearchSync as i,resolveEntry as c,toLocation as s}from"@native-router/core";import{useSyncExternalStore as a}from"use-sync-external-store/shim";function h(){const n=t(),r=o(t=>n.history.listen(()=>t()),[n]),e=o(()=>n.history.location.search,[n]),i=o(()=>"",[]);return[new URLSearchParams(a(r,e,i)),o((t,o)=>{const{history:r}=n,e="function"==typeof t?t(new URLSearchParams(r.location.search)):t;return f(n,e.toString(),o)},[n])]}function u(n){const r=t();return o((t,o)=>{const{history:c}=r,s="function"==typeof t?t(e(c.location.search)):t,a=i(n,m(s));return f(r,m(a),o)},[r,n])}function m(t){return Object.entries(t).filter(([,t])=>null!=t).map(([t,o])=>(Array.isArray(o)?o:[o]).map(o=>`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`).join("&")).join("&")}function f(t,o,e){const{history:i}=t,{pathname:a,hash:h}=i.location,u=a+(o?`?${o}`:"")+h;return e?.replace?c(t,s(t,u)).then(o=>n(t,o.task,o.location)):r(t,u)}function p(n){const r=t(),c=o(t=>r.history.listen(()=>t()),[r]),s=o(()=>r.history.location.search,[r]),h=o(()=>"",[]),u=a(c,s,h);return n?i(n,u):e(u)}export{p as useSearch,h as useSearchParams,u as useSetSearch};
2
+ //# sourceMappingURL=use-search-params.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-search-params.js","names":[],"sources":["../src/use-search-params.ts"],"sourcesContent":["import {useCallback} from 'react';\nimport {\n commitReplace,\n navigate,\n parseSearchInput,\n parseSearchSync,\n resolveEntry,\n toLocation\n} from '@native-router/core';\nimport type {\n SearchInput,\n SearchOutputOf,\n StandardSchemaV1\n} from '@native-router/core';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './components/Router';\n\ntype SetSearchParams = (\n next: URLSearchParams | ((prev: URLSearchParams) => URLSearchParams),\n opts?: {replace?: boolean}\n) => Promise<void> | void;\n\n/**\n * Read and write the search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as the Router Component), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; a fresh `URLSearchParams` view is derived from that string\n * on each render.\n *\n * The setter navigates like any other route change: by default the new\n * search is pushed onto the history stack(mainstream react-router\n * semantics), pass `{replace: true}` to rewrite the current entry instead.\n * Since the search is part of the location, every write re-resolves the\n * matched route, so route `data` fetchers(see {@link useData}) observe the\n * new search on the next {@link useData} read.\n *\n * @group Hooks\n * @returns [searchParams, setSearchParams] - the current search params and\n * the setter(functional updates receive the live previous params); the\n * setter returns a `Promise<void>` that resolves once the navigation\n * commits, so callers may optionally `await` it\n */\nexport function useSearchParams(): [URLSearchParams, SetSearchParams] {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a URLSearchParams instance) to keep the\n // snapshot reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n const searchParams = new URLSearchParams(\n useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n );\n\n const setSearchParams = useCallback<SetSearchParams>(\n (next, opts) => {\n const {history} = router;\n const params =\n typeof next === 'function'\n ? // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n next(new URLSearchParams(history.location.search))\n : next;\n return setSearch(router, params.toString(), opts);\n },\n [router]\n );\n\n return [searchParams, setSearchParams];\n}\n\n/**\n * Write the search params of the current location through a schema, the\n * setter-side twin of `useSearch(schema)`: the next value is serialized\n * to a query string, degraded with `parseSearchInput` and validated by\n * the SAME schema before any navigation happens. A schema that rejects\n * the value throws its issues(`SearchError`) without touching the\n * location; the value the schema would default or coerce on the read\n * side never gets silently written.\n *\n * Synchronous schemas only(the `useSearch` flavor); an async `validate`\n * rejects without navigating.\n *\n * The navigation semantics follow `useSearchParams`' setter: push by\n * default, `{replace: true}` rewrites the current entry, guards run,\n * and the returned `Promise<void>` resolves once the navigation commits.\n *\n * @group Hooks\n * @param schema a Standard Schema validator of the search — must\n * validate synchronously\n * @returns the schema-aware setter; functional updates receive the live\n * previous params\n * @throws {SearchError} when `schema` rejects the next value, before\n * any navigation\n */\nexport function useSetSearch<S extends StandardSchemaV1>(\n schema: S\n): (\n next: SearchInput | ((prev: SearchInput) => SearchInput),\n opts?: {replace?: boolean}\n) => Promise<void> | void {\n const router = useRouter();\n\n return useCallback(\n (next, opts) => {\n const {history} = router;\n const input =\n typeof next === 'function'\n ? next(parseSearchInput(history.location.search))\n : next;\n // Validate the whole next value — not a diff — the same way a\n // navigation to the resulting URL would: parseSearchSync throws\n // SearchError with the schema's issues, and no navigation happens.\n const validated = parseSearchSync(schema, stringifySearch(input));\n // The schema output is authoritative: defaults applied and values\n // coerced to strings, so a partially-filled input still writes the\n // fully-defaulted query.\n return setSearch(\n router,\n stringifySearch(validated as Record<string, unknown>),\n opts\n );\n },\n [router, schema]\n );\n}\n\nfunction stringifySearch(input: Record<string, unknown>): string {\n return Object.entries(input)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) =>\n (Array.isArray(value) ? value : [value])\n .map(\n (v) => `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`\n )\n .join('&')\n )\n .join('&');\n}\n\nfunction setSearch(\n router: ReturnType<typeof useRouter>,\n qs: string,\n opts?: {replace?: boolean}\n): Promise<void> | void {\n const {history} = router;\n const {pathname, hash} = history.location;\n const to = pathname + (qs ? `?${qs}` : '') + hash;\n if (opts?.replace) {\n // Route guards run like any other navigation(align with the push\n // branch): the entry carries the terminal location, so a redirect\n // replaces the current entry with its final target.\n return resolveEntry(router, toLocation(router, to)).then((entry) =>\n commitReplace(router, entry.task, entry.location)\n );\n }\n return navigate(router, to);\n}\n\n/**\n * Read the parsed search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as {@link useSearchParams}), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; the parse itself runs on each render.\n *\n * Without a schema the hook degrades to the raw input object of\n * `parseSearchInput` — strings, arrays for repeated keys\n * (`{page: '2', tag: ['a', 'b']}`). With a schema — any zod/valibot/\n * arktype schema, see the route {@link Route.search search field} — the\n * returned object is the schema's parsed output, so coercion and defaults\n * apply, e.g. `useSearch(pageSchema).page` is a number.\n *\n * Prefer declaring the schema once on the route: its `data` loader then\n * receives a parsed `ctx.search` during resolve, and an invalid search\n * fails the navigation through the existing error channels instead of\n * throwing during render.\n *\n * @group Hooks\n * @param schema an optional Standard Schema validator of the search; it\n * must validate synchronously\n * @returns the parsed search params of the current location\n * @throws {SearchError} when `schema` rejects the current search\n */\nexport function useSearch<S extends StandardSchemaV1>(\n schema: S\n): SearchOutputOf<S>;\nexport function useSearch(): SearchInput;\nexport function useSearch(schema?: StandardSchemaV1): unknown {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a parsed object) to keep the snapshot\n // reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n const search = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n );\n\n return schema ? parseSearchSync(schema, search) : parseSearchInput(search);\n}\n"],"mappings":"0SA4CA,SAAgB,IACd,MAAM,EAAS,IAIT,EAAY,EACf,GAA8B,EAAO,QAAQ,OAAA,IAAa,KAC3D,CAAC,IAIG,EAAc,EAAA,IACZ,EAAO,QAAQ,SAAS,OAC9B,CAAC,IAGG,EAAoB,EAAA,IAAkB,GAAI,IAoBhD,MAAO,CAAC,IAjBiB,gBACvB,EAAqB,EAAW,EAAa,IAGvB,EAAA,CACrB,EAAM,KACL,MAAM,QAAC,GAAW,EACZ,EACY,mBAAT,EAEH,EAAK,IAAI,gBAAgB,EAAQ,SAAS,SAC1C,EACN,OAAO,EAAU,EAAQ,EAAO,WAAY,IAE9C,CAAC,IAIL,CA0BA,SAAgB,EACd,GAKA,MAAM,EAAS,IAEf,OAAO,EAAA,CACJ,EAAM,KACL,MAAM,QAAC,GAAW,EACZ,EACY,mBAAT,EACH,EAAK,EAAiB,EAAQ,SAAS,SACvC,EAIA,EAAY,EAAgB,EAAQ,EAAgB,IAI1D,OAAO,EACL,EACA,EAAgB,GAChB,IAGJ,CAAC,EAAQ,GAEb,CAEA,SAAS,EAAgB,GACvB,OAAO,OAAO,QAAQ,GACnB,OAAA,EAAQ,CAAG,KAAW,SACtB,IAAA,EAAM,EAAK,MACT,MAAM,QAAQ,GAAS,EAAQ,CAAC,IAC9B,IACE,GAAM,GAAG,mBAAmB,MAAQ,mBAAmB,OAAO,OAEhE,KAAK,MAET,KAAK,IACV,CAEA,SAAS,EACP,EACA,EACA,GAEA,MAAM,QAAC,GAAW,GACZ,SAAC,EAAA,KAAU,GAAQ,EAAQ,SAC3B,EAAK,GAAY,EAAK,IAAI,IAAO,IAAM,EAC7C,OAAI,GAAM,QAID,EAAa,EAAQ,EAAW,EAAQ,IAAK,KAAM,GACxD,EAAc,EAAQ,EAAM,KAAM,EAAM,WAGrC,EAAS,EAAQ,EAC1B,CAgCA,SAAgB,EAAU,GACxB,MAAM,EAAS,IAIT,EAAY,EACf,GAA8B,EAAO,QAAQ,OAAA,IAAa,KAC3D,CAAC,IAIG,EAAc,EAAA,IACZ,EAAO,QAAQ,SAAS,OAC9B,CAAC,IAGG,EAAoB,EAAA,IAAkB,GAAI,IAE1C,EAAS,EACb,EACA,EACA,GAGF,OAAO,EAAS,EAAgB,EAAQ,GAAU,EAAiB,EACrE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@native-router/react",
3
- "version": "1.6.1",
3
+ "version": "1.7.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -8,6 +8,11 @@
8
8
  "import": "./dist/index.js",
9
9
  "require": "./dist/index.cjs"
10
10
  },
11
+ "./ssr": {
12
+ "types": "./dist/types/ssr.d.ts",
13
+ "import": "./dist/ssr.js",
14
+ "require": "./dist/ssr.cjs"
15
+ },
11
16
  "./server": {
12
17
  "types": "./dist/types/server.d.ts",
13
18
  "import": "./dist/server.js",
@@ -73,17 +78,16 @@
73
78
  "@babel/preset-typescript": "^8.0.1",
74
79
  "@eslint-react/eslint-plugin": "^5.18.6",
75
80
  "@eslint/js": "^10.0.1",
76
- "@linaria/babel-preset": "^5.0.4",
77
81
  "@linaria/core": "^8.2.0",
78
- "@linaria/vite": "^5.0.4",
79
82
  "@testing-library/dom": "^10.4.1",
80
83
  "@testing-library/react": "^16.3.2",
81
- "@types/node": "^26.3.0",
84
+ "@types/node": "^26.4.0",
82
85
  "@types/react": "^19.2.18",
83
86
  "@types/react-dom": "^19.2.5",
84
87
  "@vitejs/plugin-react": "^6.1.0",
85
88
  "@vitest/coverage-v8": "^4.1.11",
86
89
  "@vitest/ui": "^4.1.11",
90
+ "@wyw-in-js/vite": "^2.4.3",
87
91
  "babel-plugin-transform-jsx-class": "^0.1.3",
88
92
  "babel-plugin-transform-jsx-condition": "^0.1.3",
89
93
  "babel-runtime-jsx-plus": "^0.1.5",
@@ -109,7 +113,7 @@
109
113
  "react-dom": "^19.2.8",
110
114
  "rollup-plugin-type-as-json-schema": "^0.2.6",
111
115
  "semantic-release": "^25.0.9",
112
- "terser": "^5.50.0",
116
+ "terser": "^5.51.0",
113
117
  "tsc-alias": "^1.9.2",
114
118
  "typedoc": "^0.28.20",
115
119
  "typedoc-plugin-mark-react-functional-components": "^0.2.2",
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../src/components/link-behavior.ts","../src/components/Link.tsx","../src/components/NavLink.tsx","../src/components/PrefetchLink.tsx","../src/components/ScrollRestoration.tsx","../src/components/TypedLink.tsx","../src/create-routes.js","../src/use-search-params.ts","../src/use-blocker.ts"],"sourcesContent":["/**\n * Checks whether a click on an anchor should be intercepted and handled as an\n * in-app navigation, following the standard link interception semantics of\n * react-router/wouter: plain left clicks only.\n *\n * The browser keeps the default behavior whenever this returns `false`, so\n * modified clicks, middle clicks and links to other browsing contexts open in\n * a new tab/window as the user expects.\n *\n * @param e The click event to inspect.\n * @param target The anchor's `target` attribute, if any.\n * @param rel The anchor's `rel` attribute, if any.\n * @group Components\n */\n\nexport function shouldNavigate(\n e: {\n button: number;\n defaultPrevented: boolean;\n metaKey: boolean;\n ctrlKey: boolean;\n shiftKey: boolean;\n altKey: boolean;\n },\n target?: string,\n rel?: string\n): boolean {\n return (\n !e.defaultPrevented &&\n e.button === 0 &&\n !e.metaKey &&\n !e.ctrlKey &&\n !e.shiftKey &&\n !e.altKey &&\n target !== '_blank' &&\n target !== '_parent' &&\n target !== '_top' &&\n !(rel ?? '').split(/\\s+/).includes('external')\n );\n}\n","import {createHref, navigate} from '@native-router/core';\nimport type {AsLinkProps, LinkProps} from '@@/types';\nimport {\n forwardRef,\n useRef,\n type ElementType,\n type MouseEvent,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\n// The implementation works on the loose shape; the typed signature is\n// attached below so the `as` generic is not threaded through forwardRef's\n// typings(the same pattern TypedLink uses for its discriminated union).\ntype LinkImplProps = LinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n/**\n * Link for navigate in app.\n *\n * Pass an `as` component to render through it instead of the plain anchor:\n * the computed `href` and the navigation-aware click handling are injected,\n * the component's non-conflicting props are accepted directly on the link\n * and its conflicting ones go through `asProps`(see {@link AsLinkProps}).\n * The component should forward its ref and spread the rest props onto the\n * DOM element it renders.\n * @param props\n * @group Components\n */\nfunction LinkImpl(\n {to, as, asProps, onClick, ...rest}: LinkImplProps,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const lockRef = useRef(false);\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n\n if (lockRef.current) return;\n lockRef.current = true;\n navigate(router, to)\n .catch(() => undefined)\n .finally(() => {\n lockRef.current = false;\n });\n }\n\n const A = (as ?? 'a') as ElementType;\n // `aria-current` is NavLink's active-state injection(or a plain anchor\n // attribute on the others): a managed key, so it is injected after\n // asProps like href/onClick instead of traveling through the rest.\n const {'aria-current': ariaCurrent, ...anchorProps} = rest;\n return (\n <A\n {...anchorProps}\n {...asProps}\n ref={ref}\n href={createHref(router, to)}\n onClick={handleClick}\n aria-current={ariaCurrent}\n />\n );\n}\n\n// Two call signatures, generic first: call sites resolve through the `as`\n// generic, while the plain non-generic signature placed LAST is what\n// `ComponentProps<typeof Link>`-style helpers read — without it the\n// uninstantiated generic collapses to its `ElementType` constraint and the\n// ref becomes required `any`. The tail signature is exactly the pre-`as`\n// public shape. The displayName slot keeps the component name settable\n// despite the cast(the forwardRef wrapper shows its own name otherwise).\nconst Link = forwardRef(LinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<LinkProps, A>\n ): ReactElement | null;\n (props: LinkProps): ReactElement | null;\n displayName?: string;\n};\n\nLink.displayName = 'Link';\n\nexport default Link;\n","import {toLocation} from '@native-router/core';\nimport type {AsLinkProps, NavLinkProps, NavLinkState} from '@@/types';\nimport {\n forwardRef,\n useCallback,\n type ElementType,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './Router';\nimport Link from './Link';\n\ntype NavLinkImplProps = NavLinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n// Internal delegation to Link with the implementation-loose `as` shape;\n// the public generic typing lives on both components' public signatures.\nconst LooseLink = Link as (props: any) => ReactElement | null;\n\n/**\n * Link that knows whether its target matches the current location.\n *\n * Active rules(aligned with react-router's `NavLink`):\n *\n * - `target` is the pathname of `toLocation(router, to)`(baseUrl prepended),\n * `current` is `router.history.location.pathname`; both are lowercased\n * unless `caseSensitive` is set.\n * - `isExactActive`: `current === target`.\n * - `isActive`: `isExactActive` when `end` is set, otherwise `current` equals\n * `target` or starts with `target` plus a trailing `/`(so `to=\"/\"` is active\n * for every path).\n *\n * While active the anchor renders `aria-current={ariaCurrent ?? 'page'}` and\n * `className`/`style`/`children` receive the active state when given as\n * functions. Click behavior is delegated to {@link Link}, inheriting the\n * modified-click guard and the double-click lock.\n *\n * Pass an `as` component to render through it instead of the plain anchor\n * (see {@link AsLinkProps}): the active-state callbacks, the computed\n * `className`/`style` and the injected `aria-current` flow to it like any\n * other prop.\n * @param props\n * @group Components\n */\nfunction NavLinkImpl(\n {\n to,\n end = false,\n caseSensitive = false,\n className,\n style,\n ariaCurrent,\n children,\n as,\n asProps,\n ...rest\n }: NavLinkImplProps,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n // Subscribe to the history location so the active state stays in sync even\n // when rendered outside the routed view(e.g. a nav bar beside <View />).\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n const getSnapshot = useCallback(\n () => router.history.location.pathname,\n [router]\n );\n const current = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const target = toLocation(router, to).pathname;\n const [currentPath, targetPath] = caseSensitive\n ? [current, target]\n : [current.toLowerCase(), target.toLowerCase()];\n\n const isExactActive = currentPath === targetPath;\n // A root `to=\"/\"` normalizes to the \"/\" prefix and matches every path.\n const isActive =\n end || isExactActive\n ? isExactActive\n : currentPath.startsWith(\n targetPath.endsWith('/') ? targetPath : `${targetPath}/`\n );\n\n const state: NavLinkState = {isActive, isExactActive};\n\n return (\n <LooseLink\n to={to}\n {...rest}\n as={as}\n asProps={asProps}\n ref={ref}\n className={typeof className === 'function' ? className(state) : className}\n style={typeof style === 'function' ? style(state) : style}\n aria-current={isActive ? (ariaCurrent ?? 'page') : undefined}\n >\n {typeof children === 'function' ? children(state) : children}\n </LooseLink>\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link).\nconst NavLink = forwardRef(NavLinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<NavLinkProps, A>\n ): ReactElement | null;\n (props: NavLinkProps): ReactElement | null;\n displayName?: string;\n};\n\nNavLink.displayName = 'NavLink';\n\nexport default NavLink;\n","import {commit, createHref, preload} from '@native-router/core';\nimport type {ResolvedEntry} from '@native-router/core';\nimport type {AsLinkProps, LinkProps, Route} from '@@/types';\nimport {\n createContext,\n forwardRef,\n MouseEvent,\n ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ElementType,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\ntype PrefetchLinkContext = {loading: boolean; error?: Error; view?: ReactNode};\n\nconst Context = createContext<PrefetchLinkContext>({loading: false});\n\n/**\n * Get the prefetch context. Use for render a preview view.\n * @group Hooks\n */\nexport function usePrefetch() {\n return useContext(Context);\n}\n\ntype PrefetchLinkImplProps = LinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n/**\n * Link with prefetch support.\n *\n * The `prefetch` prop controls when the target view is resolved:\n * - `'intent'` (default): prefetch on hover or focus.\n * - `'render'`: prefetch as soon as the link mounts.\n * - `'viewport'`: prefetch when the link scrolls into the viewport.\n * - `'none'`: never prefetch; the target is resolved on click.\n *\n * Pass an `as` component to render through it instead of the plain anchor\n * (see {@link AsLinkProps}); every strategy keeps working. The `viewport`\n * strategy observes the DOM node the component forwards its ref to, so a\n * component that does not forward the ref down to a DOM element never\n * triggers a viewport prefetch.\n * @param props\n * @group Components\n */\nfunction PrefetchLinkImpl(\n {\n to,\n prefetch = 'intent',\n children,\n as,\n asProps,\n onClick,\n ...rest\n }: PrefetchLinkImplProps,\n forwardedRef: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const anchorRef = useRef<HTMLAnchorElement>(null);\n const entryRef = useRef<Promise<ResolvedEntry<ReactNode>> | undefined>(\n undefined\n );\n const failedRef = useRef(false);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error>();\n const [view, setView] = useState<ReactNode>();\n\n // Feed both the internal viewport-observation ref and the user's ref.\n const setAnchorRef = useCallback(\n (node: HTMLAnchorElement | null) => {\n anchorRef.current = node;\n if (typeof forwardedRef === 'function') forwardedRef(node);\n else if (forwardedRef) forwardedRef.current = node;\n },\n [forwardedRef]\n );\n\n function prefetchIt(): Promise<ResolvedEntry<ReactNode>> {\n setLoading(true);\n setError(undefined);\n failedRef.current = false;\n // Route guards(redirect/beforeLoad) run before the view resolves; the\n // stored entry carries the terminal location, so prefetch, preview and\n // commit all agree on the final target. preload() caches the entry at\n // the router level(keyed by pathname+search, TTL bounded), so repeated\n // prefetches of the same target share one resolution and the entry is\n // evicted once committed.\n const entryPromise = preload<Route, ReactNode>(router, to);\n entryRef.current = entryPromise;\n // The derived chain carries the loading/error/view state and handles\n // the rejection of the entry task, so a prefetched task that is never\n // committed does not surface as a global unhandledrejection. Failure is\n // tracked in `failedRef` instead of relying on the rejected task itself.\n entryPromise\n .then((entry) => entry.task)\n .then(\n (v) => setView(v),\n (e) => {\n setError(e);\n failedRef.current = true;\n }\n )\n .finally(() => setLoading(false));\n return entryPromise;\n }\n\n function handlePrefetch() {\n if (entryRef.current) return;\n prefetchIt();\n }\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n // A stored entry that already failed can never be committed\n // successfully, so resolve the target again before committing.\n const stored = entryRef.current;\n const entryPromise = !stored || failedRef.current ? prefetchIt() : stored;\n // The terminal location of the entry is committed, not the link target.\n entryPromise\n .then((entry) => commit(router, entry.task, entry.location))\n .catch(() => undefined)\n .finally(() => {\n entryRef.current = undefined;\n failedRef.current = false;\n });\n }\n\n // Reset every piece of prefetch state when the target changes, so a stale\n // error or preview from the previous target is not rendered for the new one.\n useEffect(() => {\n entryRef.current = undefined;\n failedRef.current = false;\n setLoading(false);\n setError(undefined);\n setView(undefined);\n }, [to, router]);\n\n useEffect(() => {\n if (prefetch === 'render') {\n handlePrefetch();\n return undefined;\n }\n if (prefetch !== 'viewport') return undefined;\n const el = anchorRef.current;\n if (!el || typeof IntersectionObserver === 'undefined') return undefined;\n // eslint-disable-next-line compat/compat -- guarded above at runtime\n const observer = new IntersectionObserver((entries) => {\n if (!entries.some((entry) => entry.isIntersecting)) return;\n observer.disconnect();\n handlePrefetch();\n });\n observer.observe(el);\n return () => observer.disconnect();\n // `location` and `handlePrefetch` are derived from these deps.\n }, [prefetch, to, router]);\n\n const linkContext = useMemo(\n () => ({loading, error, view}),\n [loading, error, view]\n );\n\n // Hover/focus are intent signals only; 'render', 'viewport' and 'none'\n // never prefetch on interaction.\n const intentHandlers =\n prefetch === 'intent'\n ? {onMouseEnter: handlePrefetch, onFocus: handlePrefetch}\n : undefined;\n\n const A = (as ?? 'a') as ElementType;\n\n return (\n <Context.Provider value={linkContext}>\n <A\n {...rest}\n {...intentHandlers}\n {...asProps}\n ref={setAnchorRef}\n href={createHref(router, to)}\n onClick={handleClick}\n >\n {children}\n </A>\n </Context.Provider>\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link).\nconst PrefetchLink = forwardRef(PrefetchLinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<LinkProps, A>\n ): ReactElement | null;\n (props: LinkProps): ReactElement | null;\n displayName?: string;\n};\n\nPrefetchLink.displayName = 'PrefetchLink';\n\nexport default PrefetchLink;\n","import {createPath} from 'history';\nimport type {HistoryState} from '@native-router/core';\nimport {useEffect, useRef} from 'react';\nimport {useRouter} from './Router';\n\n/** Saved scroll offset of one history stack slot. */\ntype ScrollPosition = {x: number; y: number};\n\ntype ScrollRestorationProps = {\n /**\n * Scroll a freshly pushed(or replaced) entry back to the top, like a full\n * page load. Set to false to keep the current offset across forward\n * navigations(e.g. feed-style \"load more\" pages). POP always restores the\n * saved offset, regardless of this flag.\n * @default true\n */\n resetOnPush?: boolean;\n};\n\n/**\n * Restore the window scroll position across history navigations.\n *\n * The router restores views from the in-memory `viewStack`: on back/forward\n * the view is reused without re-fetching its data, but the browser has\n * already left the old document position and a remounted DOM starts at the\n * top by default. Mount `<ScrollRestoration />` anywhere inside\n * {@link Router}(typically in the root layout) to fill that gap:\n *\n * - the scroll offset of every visited entry is remembered, keyed by the\n * absolute history index(`history.location.state.index` — the same key\n * `viewStack` is keyed by). Like `viewStack`, the map is in-memory and\n * session scoped: after a page reload there is nothing to restore and the\n * browser's own restoration takes over.\n * - `history.scrollRestoration` is taken over as `manual`(the browser's\n * own `auto` restoration would race the restore and pre-scroll while the\n * left entry's offset is still being read), making the component solely\n * responsible for restoration; the takeover is session scoped and not\n * reverted on unmount, like `viewStack`.\n * - POP restores the saved offset of the landed entry(`0,0` when none was\n * saved, e.g. forward-past-the-end or post-reload entries).\n * - PUSH and REPLACE scroll a fresh entry back to the top when\n * `resetOnPush` is set(default). Internal re-commits of the very same\n * entry(the core listener's POP sync, `refresh`, listen bootstrap) never\n * touch the scroll.\n *\n * Renders nothing. SSR safe: it only subscribes in an effect and only when\n * `window` exists.\n * @param props\n * @group Components\n */\nexport default function ScrollRestoration({\n resetOnPush = true\n}: ScrollRestorationProps) {\n const router = useRouter();\n // Positions survive effect re-runs(resetOnPush changes) on purpose.\n const positionsRef = useRef(new Map<number, ScrollPosition>());\n const lastIndexRef = useRef(-1);\n const lastPathRef = useRef('');\n\n useEffect(() => {\n if (typeof window === 'undefined') return undefined;\n\n // The browser's own `auto` restoration races this component's restore\n // (it can pre-scroll within the microtask window where the left entry's\n // offset is still being read), so take full control for the session.\n if (window.history.scrollRestoration) {\n window.history.scrollRestoration = 'manual';\n }\n\n const positions = positionsRef.current;\n const readIndex = (state: unknown) =>\n (state as HistoryState | undefined)?.index || 0;\n\n lastIndexRef.current = readIndex(router.history.location.state);\n lastPathRef.current = createPath(router.history.location);\n\n let scheduled = false;\n let sawPop = false;\n let active = true;\n\n const unlisten = router.history.listen(({action}) => {\n // The core listener re-commits a landed POP entry with an internal\n // REPLACE(stack serialization sync), and listener registration order\n // decides whether that REPLACE reaches us before or after the POP\n // itself. Collapse the whole synchronous event storm and decide once,\n // from the final history state, in a microtask — no layout has\n // scrolled yet at that point, so saving the left entry's offset\n // still reads the pre-navigation scroll.\n sawPop ||= action === 'POP';\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n if (!active) return;\n const popped = sawPop;\n sawPop = false;\n const {location} = router.history;\n const index = readIndex(location.state);\n const path = createPath(location);\n const lastIndex = lastIndexRef.current;\n\n if (index !== lastIndex) {\n // The entry we just left keeps its scroll offset.\n positions.set(lastIndex, {x: window.scrollX, y: window.scrollY});\n }\n\n if (popped) {\n const saved = positions.get(index) ?? {x: 0, y: 0};\n window.scrollTo(saved.x, saved.y);\n positions.set(index, saved);\n } else if (\n resetOnPush &&\n (index !== lastIndex || path !== lastPathRef.current)\n ) {\n // A fresh forward entry, or the current entry rewritten to a\n // different location(a replace navigation) — start at the top.\n window.scrollTo(0, 0);\n positions.set(index, {x: 0, y: 0});\n }\n // Anything else is an internal re-commit of the same entry: keep\n // the current scroll.\n\n lastIndexRef.current = index;\n lastPathRef.current = path;\n });\n });\n\n return () => {\n active = false;\n unlisten();\n };\n }, [router, resetOnPush]);\n\n return null;\n}\n","import {createHref, navigate} from '@native-router/core';\nimport {\n forwardRef,\n useRef,\n type ElementType,\n type MouseEvent,\n type ReactElement,\n type Ref\n} from 'react';\nimport type {AsLinkProps, TypedLinkProps} from '@@/types';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\n/**\n * Interpolate params into a path pattern: `:name` segments take a\n * string, `*name` wildcards a string array(joined with `/`), both\n * percent-encoded; everything else — including `\\` escapes — is static\n * text. The grammar matches the core matcher's(the ASCII identifier\n * scanner the type-level `ExtractPathParams` models).\n * @throws when a required param is missing or empty — the click-time\n * params check of {@link TypedLink}\n */\nfunction interpolatePath(\n pattern: string,\n params: Record<string, string | string[]>\n): string {\n return pattern.replace(\n /\\\\.|[:*]([A-Za-z_$][A-Za-z0-9_$]*)/g,\n (match, name?: string) => {\n if (name === undefined) return match;\n const value = params[name];\n if (value === undefined || value.length === 0) {\n throw new Error(\n `Missing param \"${name}\" for the path pattern \"${pattern}\"`\n );\n }\n return (Array.isArray(value) ? value : [value])\n .map(encodeURIComponent)\n .join('/');\n }\n );\n}\n\n/**\n * Link whose `to` is narrowed to a route table's path patterns and whose\n * `params` is checked against the exact pattern's param segments. Give\n * it the pattern union as its type argument:\n *\n * ```tsx\n * const routes = createRoutes({children: [{path: '/users/:id'}, ...]});\n *\n * <TypedLink<RoutePaths<typeof routes>> to=\"/users/:id\" params={{id: '7'}}>\n * User 7\n * </TypedLink>\n * ```\n *\n * A `to` outside the table, a missing required param or a wrong param\n * shape is a compile error; at click time the params are interpolated\n * into the pattern and a missing required param throws instead of\n * navigating(the type-level check's runtime backstop).\n *\n * Without the type argument the component degrades to a plain `Link`:\n * any path, params optional. Click interception follows {@link Link}\n * — only plain primary-button clicks are intercepted.\n *\n * An `as` component can be layered on top(`asProps`/flattened `as`-props\n * per {@link AsLinkProps}); give both type arguments to keep the pattern\n * narrowing: `<TypedLink<Paths, typeof MyLink> ... />`.\n * @group Components\n * @param props `to`(a pattern of the table), `params`(per the pattern)\n * and the usual anchor attributes\n */\n// The implementation works on the loose shape; the typed signature is\n// attached below so discriminated-union props need not be destructured\n// across the union.\nfunction TypedLinkImpl(\n {\n to,\n params,\n onClick,\n as,\n asProps,\n ...rest\n }: {\n to: string;\n params?: Record<string, string | string[]>;\n as?: ElementType;\n asProps?: Record<string, unknown>;\n } & Omit<TypedLinkProps, 'to' | 'params' | 'prefetch' | 'href'>,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const lockRef = useRef(false);\n\n // The href shows the interpolated target; when a required param is\n // missing the raw pattern stays and the click-time check below blocks\n // the navigation.\n let href: string = to;\n try {\n href = interpolatePath(to, params ?? {});\n } catch {\n // Programming error the types already flag; surfaced on click.\n }\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n\n if (lockRef.current) return;\n // Click-time params check per the pattern's param segments: a missing\n // required param throws instead of navigating.\n const target = interpolatePath(to, params ?? {});\n lockRef.current = true;\n navigate(router, target)\n .catch(() => undefined)\n .finally(() => {\n lockRef.current = false;\n });\n }\n\n const A = (as ?? 'a') as ElementType;\n return (\n <A\n {...rest}\n {...asProps}\n ref={ref}\n href={createHref(router, href)}\n onClick={handleClick}\n />\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link);\n// the tail keeps the pre-`as` discriminated-union shape.\nconst TypedLink = forwardRef(TypedLinkImpl) as {\n <Paths extends string = string, A extends ElementType = 'a'>(\n props: AsLinkProps<TypedLinkProps<Paths>, A>\n ): ReactElement | null;\n <Paths extends string = string>(\n props: TypedLinkProps<Paths>\n ): ReactElement | null;\n displayName?: string;\n};\n\nTypedLink.displayName = 'TypedLink';\n\nexport default TypedLink;\n","/**\n * Identity function with `satisfies` semantics: the table is checked\n * against `Route` while every `path` keeps its string-literal type, so\n * `RoutePaths<typeof routes>` can extract the full pattern union for\n * `TypedLink`. An `as Route` assertion does the opposite — it widens\n * every `path` to `string` and gives up the literals.\n *\n * ```tsx\n * const routes = createRoutes({\n * children: [\n * {path: '/', component: () => import('./Home')},\n * {path: '/users/:id', component: () => import('./UserProfile')}\n * ]\n * });\n * // type AppPaths = '/' | '/users/:id'\n * type AppPaths = RoutePaths<typeof routes>;\n * ```\n *\n * Zero runtime cost: the function returns its argument unchanged and\n * tree-shakes away.\n * @group Methods\n * @category Route\n * @param routes the route table, a route object or an array of them\n * @returns the very same route table, literal types preserved\n */\nexport function createRoutes(\n // The `const` modifier keeps every `path` a string literal(through\n // arbitrary nesting) while the parameter is still checked against\n // `Route` — the `satisfies` semantics an `as Route` assertion lacks:\n // the assertion widens every `path` to `string` instead.\n routes\n) {\n return routes;\n}\n","import {useCallback} from 'react';\nimport {\n commitReplace,\n navigate,\n parseSearchInput,\n parseSearchSync,\n resolveEntry,\n toLocation\n} from '@native-router/core';\nimport type {\n SearchInput,\n SearchOutputOf,\n StandardSchemaV1\n} from '@native-router/core';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './components/Router';\n\ntype SetSearchParams = (\n next: URLSearchParams | ((prev: URLSearchParams) => URLSearchParams),\n opts?: {replace?: boolean}\n) => Promise<void> | void;\n\n/**\n * Read and write the search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as the Router Component), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; a fresh `URLSearchParams` view is derived from that string\n * on each render.\n *\n * The setter navigates like any other route change: by default the new\n * search is pushed onto the history stack(mainstream react-router\n * semantics), pass `{replace: true}` to rewrite the current entry instead.\n * Since the search is part of the location, every write re-resolves the\n * matched route, so route `data` fetchers(see {@link useData}) observe the\n * new search on the next {@link useData} read.\n *\n * @group Hooks\n * @returns [searchParams, setSearchParams] - the current search params and\n * the setter(functional updates receive the live previous params); the\n * setter returns a `Promise<void>` that resolves once the navigation\n * commits, so callers may optionally `await` it\n */\nexport function useSearchParams(): [URLSearchParams, SetSearchParams] {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a URLSearchParams instance) to keep the\n // snapshot reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n const searchParams = new URLSearchParams(\n useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n );\n\n const setSearchParams = useCallback<SetSearchParams>(\n (next, opts) => {\n const {history} = router;\n const params =\n typeof next === 'function'\n ? // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n next(new URLSearchParams(history.location.search))\n : next;\n return setSearch(router, params.toString(), opts);\n },\n [router]\n );\n\n return [searchParams, setSearchParams];\n}\n\n/**\n * Write the search params of the current location through a schema, the\n * setter-side twin of `useSearch(schema)`: the next value is serialized\n * to a query string, degraded with `parseSearchInput` and validated by\n * the SAME schema before any navigation happens. A schema that rejects\n * the value throws its issues(`SearchError`) without touching the\n * location; the value the schema would default or coerce on the read\n * side never gets silently written.\n *\n * Synchronous schemas only(the `useSearch` flavor); an async `validate`\n * rejects without navigating.\n *\n * The navigation semantics follow `useSearchParams`' setter: push by\n * default, `{replace: true}` rewrites the current entry, guards run,\n * and the returned `Promise<void>` resolves once the navigation commits.\n *\n * @group Hooks\n * @param schema a Standard Schema validator of the search — must\n * validate synchronously\n * @returns the schema-aware setter; functional updates receive the live\n * previous params\n * @throws {SearchError} when `schema` rejects the next value, before\n * any navigation\n */\nexport function useSetSearch<S extends StandardSchemaV1>(\n schema: S\n): (\n next: SearchInput | ((prev: SearchInput) => SearchInput),\n opts?: {replace?: boolean}\n) => Promise<void> | void {\n const router = useRouter();\n\n return useCallback(\n (next, opts) => {\n const {history} = router;\n const input =\n typeof next === 'function'\n ? next(parseSearchInput(history.location.search))\n : next;\n // Validate the whole next value — not a diff — the same way a\n // navigation to the resulting URL would: parseSearchSync throws\n // SearchError with the schema's issues, and no navigation happens.\n const validated = parseSearchSync(schema, stringifySearch(input));\n // The schema output is authoritative: defaults applied and values\n // coerced to strings, so a partially-filled input still writes the\n // fully-defaulted query.\n return setSearch(\n router,\n stringifySearch(validated as Record<string, unknown>),\n opts\n );\n },\n [router, schema]\n );\n}\n\nfunction stringifySearch(input: Record<string, unknown>): string {\n return Object.entries(input)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) =>\n (Array.isArray(value) ? value : [value])\n .map(\n (v) => `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`\n )\n .join('&')\n )\n .join('&');\n}\n\nfunction setSearch(\n router: ReturnType<typeof useRouter>,\n qs: string,\n opts?: {replace?: boolean}\n): Promise<void> | void {\n const {history} = router;\n const {pathname, hash} = history.location;\n const to = pathname + (qs ? `?${qs}` : '') + hash;\n if (opts?.replace) {\n // Route guards run like any other navigation(align with the push\n // branch): the entry carries the terminal location, so a redirect\n // replaces the current entry with its final target.\n return resolveEntry(router, toLocation(router, to)).then((entry) =>\n commitReplace(router, entry.task, entry.location)\n );\n }\n return navigate(router, to);\n}\n\n/**\n * Read the parsed search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as {@link useSearchParams}), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; the parse itself runs on each render.\n *\n * Without a schema the hook degrades to the raw input object of\n * `parseSearchInput` — strings, arrays for repeated keys\n * (`{page: '2', tag: ['a', 'b']}`). With a schema — any zod/valibot/\n * arktype schema, see the route {@link Route.search search field} — the\n * returned object is the schema's parsed output, so coercion and defaults\n * apply, e.g. `useSearch(pageSchema).page` is a number.\n *\n * Prefer declaring the schema once on the route: its `data` loader then\n * receives a parsed `ctx.search` during resolve, and an invalid search\n * fails the navigation through the existing error channels instead of\n * throwing during render.\n *\n * @group Hooks\n * @param schema an optional Standard Schema validator of the search; it\n * must validate synchronously\n * @returns the parsed search params of the current location\n * @throws {SearchError} when `schema` rejects the current search\n */\nexport function useSearch<S extends StandardSchemaV1>(\n schema: S\n): SearchOutputOf<S>;\nexport function useSearch(): SearchInput;\nexport function useSearch(schema?: StandardSchemaV1): unknown {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a parsed object) to keep the snapshot\n // reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n const search = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n );\n\n return schema ? parseSearchSync(schema, search) : parseSearchInput(search);\n}\n","import {useEffect, useRef} from 'react';\nimport {setBlocker} from '@native-router/core';\nimport type {BlockerFn} from '@native-router/core';\nimport {useRouter} from './components/Router';\n\n/**\n * Block navigations away from the current page while the component is\n * mounted — the unsaved-changes guard.\n *\n * The predicate is the core `setBlocker` veto: `(to, from) => boolean`\n * over path strings(including search and hash), asked synchronously at\n * the head of every navigation and before a history POP lands. Return\n * `false` to veto: a vetoed navigation never starts and a vetoed POP is\n * rewound. `refresh` and guard redirects are never blocked; the effect\n * releases the blocker on unmount, so the guard lives exactly as long\n * as the guarding component.\n *\n * The predicate is stored in a ref and re-synced on every render, so a\n * navigation is always asked the latest closure — a `confirmed` flag it\n * captured works without re-registering anything. SSR-safe: nothing\n * here touches `window`, and the registration itself is an effect that\n * never runs on the server.\n *\n * @group Hooks\n * @param fn blocker predicate; `to` is the target path, `from` the\n * current path\n * @see {@link setBlocker}\n */\nexport function useBlocker(fn: BlockerFn): void {\n const router = useRouter();\n const fnRef = useRef(fn);\n // Always ask the latest closure: re-rendering with new state must not\n // require re-registering the blocker.\n fnRef.current = fn;\n useEffect(\n () => setBlocker(router, (to, from) => fnRef.current(to, from)),\n [router]\n );\n}\n"],"mappings":"+PAeA,SAAgB,EACd,EAQA,EACA,GAEA,QACG,EAAE,kBACU,IAAb,EAAE,QACD,EAAE,SACF,EAAE,SACF,EAAE,UACF,EAAE,QACQ,WAAX,GACW,YAAX,GACW,SAAX,IACE,GAAO,IAAI,MAAM,OAAO,SAAS,YAEvC,CCoDA,IAAM,GAAA,EAAO,EAAA,YA1Db,UACE,GAAC,EAAA,GAAI,EAAA,QAAI,EAAA,QAAS,KAAY,GAC9B,GAEA,MAAM,EAAS,EAAA,YACT,GAAA,EAAU,EAAA,SAAO,GA6BjB,EAAK,GAAM,KAIV,eAAgB,KAAgB,GAAe,EACtD,OACE,EAAA,EAAA,KAAC,EAAD,IACM,KACA,EACC,MACL,MAAA,EAAM,EAAA,YAAW,EAAQ,GACzB,QAtCJ,SAAqB,GAGnB,IAAU,GAMP,EACC,EACC,GAAS,QAAiC,EAAK,OAC/C,GAAS,KAA8B,EAAK,OAIjD,EAAE,iBAEE,EAAQ,UACZ,EAAQ,SAAU,GAClB,EAAA,EAAA,UAAS,EAAQ,GACd,MAAA,QACA,QAAA,KACC,EAAQ,SAAU,KAExB,EAcI,eAAc,GAGpB,GAiBA,EAAK,YAAc,OC/EnB,IAAM,EAAY,EAwFlB,IAAM,GAAA,EAAU,EAAA,YA7DhB,UACE,GACE,EAAA,IACA,GAAM,EAAA,cACN,GAAgB,EAAA,UAChB,EAAA,MACA,EAAA,YACA,EAAA,SACA,EAAA,GACA,EAAA,QACA,KACG,GAEL,GAEA,MAAM,EAAS,EAAA,YAGT,GAAA,EAAY,EAAA,aACf,GAA8B,EAAO,QAAQ,OAAA,IAAa,KAC3D,CAAC,IAEG,GAAA,EAAc,EAAA,aAAA,IACZ,EAAO,QAAQ,SAAS,SAC9B,CAAC,IAEG,GAAA,EAAU,EAAA,sBAAqB,EAAW,EAAa,GAEvD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D,OAAO,EACL,EACA,EAAgB,GAChB,IAGJ,CAAC,EAAQ,GAEb"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/components/link-behavior.ts","../src/components/Link.tsx","../src/components/NavLink.tsx","../src/components/PrefetchLink.tsx","../src/components/ScrollRestoration.tsx","../src/components/TypedLink.tsx","../src/create-routes.js","../src/use-search-params.ts","../src/use-blocker.ts"],"sourcesContent":["/**\n * Checks whether a click on an anchor should be intercepted and handled as an\n * in-app navigation, following the standard link interception semantics of\n * react-router/wouter: plain left clicks only.\n *\n * The browser keeps the default behavior whenever this returns `false`, so\n * modified clicks, middle clicks and links to other browsing contexts open in\n * a new tab/window as the user expects.\n *\n * @param e The click event to inspect.\n * @param target The anchor's `target` attribute, if any.\n * @param rel The anchor's `rel` attribute, if any.\n * @group Components\n */\n\nexport function shouldNavigate(\n e: {\n button: number;\n defaultPrevented: boolean;\n metaKey: boolean;\n ctrlKey: boolean;\n shiftKey: boolean;\n altKey: boolean;\n },\n target?: string,\n rel?: string\n): boolean {\n return (\n !e.defaultPrevented &&\n e.button === 0 &&\n !e.metaKey &&\n !e.ctrlKey &&\n !e.shiftKey &&\n !e.altKey &&\n target !== '_blank' &&\n target !== '_parent' &&\n target !== '_top' &&\n !(rel ?? '').split(/\\s+/).includes('external')\n );\n}\n","import {createHref, navigate} from '@native-router/core';\nimport type {AsLinkProps, LinkProps} from '@@/types';\nimport {\n forwardRef,\n useRef,\n type ElementType,\n type MouseEvent,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\n// The implementation works on the loose shape; the typed signature is\n// attached below so the `as` generic is not threaded through forwardRef's\n// typings(the same pattern TypedLink uses for its discriminated union).\ntype LinkImplProps = LinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n/**\n * Link for navigate in app.\n *\n * Pass an `as` component to render through it instead of the plain anchor:\n * the computed `href` and the navigation-aware click handling are injected,\n * the component's non-conflicting props are accepted directly on the link\n * and its conflicting ones go through `asProps`(see {@link AsLinkProps}).\n * The component should forward its ref and spread the rest props onto the\n * DOM element it renders.\n * @param props\n * @group Components\n */\nfunction LinkImpl(\n {to, as, asProps, onClick, ...rest}: LinkImplProps,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const lockRef = useRef(false);\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n\n if (lockRef.current) return;\n lockRef.current = true;\n navigate(router, to)\n .catch(() => undefined)\n .finally(() => {\n lockRef.current = false;\n });\n }\n\n const A = (as ?? 'a') as ElementType;\n // `aria-current` is NavLink's active-state injection(or a plain anchor\n // attribute on the others): a managed key, so it is injected after\n // asProps like href/onClick instead of traveling through the rest.\n const {'aria-current': ariaCurrent, ...anchorProps} = rest;\n return (\n <A\n {...anchorProps}\n {...asProps}\n ref={ref}\n href={createHref(router, to)}\n onClick={handleClick}\n aria-current={ariaCurrent}\n />\n );\n}\n\n// Two call signatures, generic first: call sites resolve through the `as`\n// generic, while the plain non-generic signature placed LAST is what\n// `ComponentProps<typeof Link>`-style helpers read — without it the\n// uninstantiated generic collapses to its `ElementType` constraint and the\n// ref becomes required `any`. The tail signature is exactly the pre-`as`\n// public shape. The displayName slot keeps the component name settable\n// despite the cast(the forwardRef wrapper shows its own name otherwise).\nconst Link = forwardRef(LinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<LinkProps, A>\n ): ReactElement | null;\n (props: LinkProps): ReactElement | null;\n displayName?: string;\n};\n\nLink.displayName = 'Link';\n\nexport default Link;\n","import {toLocation} from '@native-router/core';\nimport type {AsLinkProps, NavLinkProps, NavLinkState} from '@@/types';\nimport {\n forwardRef,\n useCallback,\n type ElementType,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './Router';\nimport Link from './Link';\n\ntype NavLinkImplProps = NavLinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n// Internal delegation to Link with the implementation-loose `as` shape;\n// the public generic typing lives on both components' public signatures.\nconst LooseLink = Link as (props: any) => ReactElement | null;\n\n/**\n * Link that knows whether its target matches the current location.\n *\n * Active rules(aligned with react-router's `NavLink`):\n *\n * - `target` is the pathname of `toLocation(router, to)`(baseUrl prepended),\n * `current` is `router.history.location.pathname`; both are lowercased\n * unless `caseSensitive` is set.\n * - `isExactActive`: `current === target`.\n * - `isActive`: `isExactActive` when `end` is set, otherwise `current` equals\n * `target` or starts with `target` plus a trailing `/`(so `to=\"/\"` is active\n * for every path).\n *\n * While active the anchor renders `aria-current={ariaCurrent ?? 'page'}` and\n * `className`/`style`/`children` receive the active state when given as\n * functions. Click behavior is delegated to {@link Link}, inheriting the\n * modified-click guard and the double-click lock.\n *\n * Pass an `as` component to render through it instead of the plain anchor\n * (see {@link AsLinkProps}): the active-state callbacks, the computed\n * `className`/`style` and the injected `aria-current` flow to it like any\n * other prop.\n * @param props\n * @group Components\n */\nfunction NavLinkImpl(\n {\n to,\n end = false,\n caseSensitive = false,\n className,\n style,\n ariaCurrent,\n children,\n as,\n asProps,\n ...rest\n }: NavLinkImplProps,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n // Subscribe to the history location so the active state stays in sync even\n // when rendered outside the routed view(e.g. a nav bar beside <View />).\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n const getSnapshot = useCallback(\n () => router.history.location.pathname,\n [router]\n );\n const current = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const target = toLocation(router, to).pathname;\n const [currentPath, targetPath] = caseSensitive\n ? [current, target]\n : [current.toLowerCase(), target.toLowerCase()];\n\n const isExactActive = currentPath === targetPath;\n // A root `to=\"/\"` normalizes to the \"/\" prefix and matches every path.\n const isActive =\n end || isExactActive\n ? isExactActive\n : currentPath.startsWith(\n targetPath.endsWith('/') ? targetPath : `${targetPath}/`\n );\n\n const state: NavLinkState = {isActive, isExactActive};\n\n return (\n <LooseLink\n to={to}\n {...rest}\n as={as}\n asProps={asProps}\n ref={ref}\n className={typeof className === 'function' ? className(state) : className}\n style={typeof style === 'function' ? style(state) : style}\n aria-current={isActive ? (ariaCurrent ?? 'page') : undefined}\n >\n {typeof children === 'function' ? children(state) : children}\n </LooseLink>\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link).\nconst NavLink = forwardRef(NavLinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<NavLinkProps, A>\n ): ReactElement | null;\n (props: NavLinkProps): ReactElement | null;\n displayName?: string;\n};\n\nNavLink.displayName = 'NavLink';\n\nexport default NavLink;\n","import {commit, createHref, preload} from '@native-router/core';\nimport type {ResolvedEntry} from '@native-router/core';\nimport type {AsLinkProps, LinkProps, Route} from '@@/types';\nimport {\n createContext,\n forwardRef,\n MouseEvent,\n ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ElementType,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\ntype PrefetchLinkContext = {loading: boolean; error?: Error; view?: ReactNode};\n\nconst Context = createContext<PrefetchLinkContext>({loading: false});\n\n/**\n * Get the prefetch context. Use for render a preview view.\n * @group Hooks\n */\nexport function usePrefetch() {\n return useContext(Context);\n}\n\ntype PrefetchLinkImplProps = LinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n/**\n * Link with prefetch support.\n *\n * The `prefetch` prop controls when the target view is resolved:\n * - `'intent'` (default): prefetch on hover or focus.\n * - `'render'`: prefetch as soon as the link mounts.\n * - `'viewport'`: prefetch when the link scrolls into the viewport.\n * - `'none'`: never prefetch; the target is resolved on click.\n *\n * Pass an `as` component to render through it instead of the plain anchor\n * (see {@link AsLinkProps}); every strategy keeps working. The `viewport`\n * strategy observes the DOM node the component forwards its ref to, so a\n * component that does not forward the ref down to a DOM element never\n * triggers a viewport prefetch.\n * @param props\n * @group Components\n */\nfunction PrefetchLinkImpl(\n {\n to,\n prefetch = 'intent',\n children,\n as,\n asProps,\n onClick,\n ...rest\n }: PrefetchLinkImplProps,\n forwardedRef: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const anchorRef = useRef<HTMLAnchorElement>(null);\n const entryRef = useRef<Promise<ResolvedEntry<ReactNode>> | undefined>(\n undefined\n );\n const failedRef = useRef(false);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error>();\n const [view, setView] = useState<ReactNode>();\n\n // Feed both the internal viewport-observation ref and the user's ref.\n const setAnchorRef = useCallback(\n (node: HTMLAnchorElement | null) => {\n anchorRef.current = node;\n if (typeof forwardedRef === 'function') forwardedRef(node);\n else if (forwardedRef) forwardedRef.current = node;\n },\n [forwardedRef]\n );\n\n function prefetchIt(): Promise<ResolvedEntry<ReactNode>> {\n setLoading(true);\n setError(undefined);\n failedRef.current = false;\n // Route guards(redirect/beforeLoad) run before the view resolves; the\n // stored entry carries the terminal location, so prefetch, preview and\n // commit all agree on the final target. preload() caches the entry at\n // the router level(keyed by pathname+search, TTL bounded), so repeated\n // prefetches of the same target share one resolution and the entry is\n // evicted once committed.\n const entryPromise = preload<Route, ReactNode>(router, to);\n entryRef.current = entryPromise;\n // The derived chain carries the loading/error/view state and handles\n // the rejection of the entry task, so a prefetched task that is never\n // committed does not surface as a global unhandledrejection. Failure is\n // tracked in `failedRef` instead of relying on the rejected task itself.\n entryPromise\n .then((entry) => entry.task)\n .then(\n (v) => setView(v),\n (e) => {\n setError(e);\n failedRef.current = true;\n }\n )\n .finally(() => setLoading(false));\n return entryPromise;\n }\n\n function handlePrefetch() {\n if (entryRef.current) return;\n prefetchIt();\n }\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n // A stored entry that already failed can never be committed\n // successfully, so resolve the target again before committing.\n const stored = entryRef.current;\n const entryPromise = !stored || failedRef.current ? prefetchIt() : stored;\n // The terminal location of the entry is committed, not the link target.\n entryPromise\n .then((entry) => commit(router, entry.task, entry.location))\n .catch(() => undefined)\n .finally(() => {\n entryRef.current = undefined;\n failedRef.current = false;\n });\n }\n\n // Reset every piece of prefetch state when the target changes, so a stale\n // error or preview from the previous target is not rendered for the new one.\n useEffect(() => {\n entryRef.current = undefined;\n failedRef.current = false;\n setLoading(false);\n setError(undefined);\n setView(undefined);\n }, [to, router]);\n\n useEffect(() => {\n if (prefetch === 'render') {\n handlePrefetch();\n return undefined;\n }\n if (prefetch !== 'viewport') return undefined;\n const el = anchorRef.current;\n if (!el || typeof IntersectionObserver === 'undefined') return undefined;\n // eslint-disable-next-line compat/compat -- guarded above at runtime\n const observer = new IntersectionObserver((entries) => {\n if (!entries.some((entry) => entry.isIntersecting)) return;\n observer.disconnect();\n handlePrefetch();\n });\n observer.observe(el);\n return () => observer.disconnect();\n // `location` and `handlePrefetch` are derived from these deps.\n }, [prefetch, to, router]);\n\n const linkContext = useMemo(\n () => ({loading, error, view}),\n [loading, error, view]\n );\n\n // Hover/focus are intent signals only; 'render', 'viewport' and 'none'\n // never prefetch on interaction.\n const intentHandlers =\n prefetch === 'intent'\n ? {onMouseEnter: handlePrefetch, onFocus: handlePrefetch}\n : undefined;\n\n const A = (as ?? 'a') as ElementType;\n\n return (\n <Context.Provider value={linkContext}>\n <A\n {...rest}\n {...intentHandlers}\n {...asProps}\n ref={setAnchorRef}\n href={createHref(router, to)}\n onClick={handleClick}\n >\n {children}\n </A>\n </Context.Provider>\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link).\nconst PrefetchLink = forwardRef(PrefetchLinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<LinkProps, A>\n ): ReactElement | null;\n (props: LinkProps): ReactElement | null;\n displayName?: string;\n};\n\nPrefetchLink.displayName = 'PrefetchLink';\n\nexport default PrefetchLink;\n","import {createPath} from 'history';\nimport type {HistoryState} from '@native-router/core';\nimport {useEffect, useRef} from 'react';\nimport {useRouter} from './Router';\n\n/** Saved scroll offset of one history stack slot. */\ntype ScrollPosition = {x: number; y: number};\n\ntype ScrollRestorationProps = {\n /**\n * Scroll a freshly pushed(or replaced) entry back to the top, like a full\n * page load. Set to false to keep the current offset across forward\n * navigations(e.g. feed-style \"load more\" pages). POP always restores the\n * saved offset, regardless of this flag.\n * @default true\n */\n resetOnPush?: boolean;\n};\n\n/**\n * Restore the window scroll position across history navigations.\n *\n * The router restores views from the in-memory `viewStack`: on back/forward\n * the view is reused without re-fetching its data, but the browser has\n * already left the old document position and a remounted DOM starts at the\n * top by default. Mount `<ScrollRestoration />` anywhere inside\n * {@link Router}(typically in the root layout) to fill that gap:\n *\n * - the scroll offset of every visited entry is remembered, keyed by the\n * absolute history index(`history.location.state.index` — the same key\n * `viewStack` is keyed by). Like `viewStack`, the map is in-memory and\n * session scoped: after a page reload there is nothing to restore and the\n * browser's own restoration takes over.\n * - `history.scrollRestoration` is taken over as `manual`(the browser's\n * own `auto` restoration would race the restore and pre-scroll while the\n * left entry's offset is still being read), making the component solely\n * responsible for restoration; the takeover is session scoped and not\n * reverted on unmount, like `viewStack`.\n * - POP restores the saved offset of the landed entry(`0,0` when none was\n * saved, e.g. forward-past-the-end or post-reload entries).\n * - PUSH and REPLACE scroll a fresh entry back to the top when\n * `resetOnPush` is set(default). Internal re-commits of the very same\n * entry(the core listener's POP sync, `refresh`, listen bootstrap) never\n * touch the scroll.\n *\n * Renders nothing. SSR safe: it only subscribes in an effect and only when\n * `window` exists.\n * @param props\n * @group Components\n */\nexport default function ScrollRestoration({\n resetOnPush = true\n}: ScrollRestorationProps) {\n const router = useRouter();\n // Positions survive effect re-runs(resetOnPush changes) on purpose.\n const positionsRef = useRef(new Map<number, ScrollPosition>());\n const lastIndexRef = useRef(-1);\n const lastPathRef = useRef('');\n\n useEffect(() => {\n if (typeof window === 'undefined') return undefined;\n\n // The browser's own `auto` restoration races this component's restore\n // (it can pre-scroll within the microtask window where the left entry's\n // offset is still being read), so take full control for the session.\n if (window.history.scrollRestoration) {\n window.history.scrollRestoration = 'manual';\n }\n\n const positions = positionsRef.current;\n const readIndex = (state: unknown) =>\n (state as HistoryState | undefined)?.index || 0;\n\n lastIndexRef.current = readIndex(router.history.location.state);\n lastPathRef.current = createPath(router.history.location);\n\n let scheduled = false;\n let sawPop = false;\n let active = true;\n\n const unlisten = router.history.listen(({action}) => {\n // The core listener re-commits a landed POP entry with an internal\n // REPLACE(stack serialization sync), and listener registration order\n // decides whether that REPLACE reaches us before or after the POP\n // itself. Collapse the whole synchronous event storm and decide once,\n // from the final history state, in a microtask — no layout has\n // scrolled yet at that point, so saving the left entry's offset\n // still reads the pre-navigation scroll.\n sawPop ||= action === 'POP';\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n if (!active) return;\n const popped = sawPop;\n sawPop = false;\n const {location} = router.history;\n const index = readIndex(location.state);\n const path = createPath(location);\n const lastIndex = lastIndexRef.current;\n\n if (index !== lastIndex) {\n // The entry we just left keeps its scroll offset.\n positions.set(lastIndex, {x: window.scrollX, y: window.scrollY});\n }\n\n if (popped) {\n const saved = positions.get(index) ?? {x: 0, y: 0};\n window.scrollTo(saved.x, saved.y);\n positions.set(index, saved);\n } else if (\n resetOnPush &&\n (index !== lastIndex || path !== lastPathRef.current)\n ) {\n // A fresh forward entry, or the current entry rewritten to a\n // different location(a replace navigation) — start at the top.\n window.scrollTo(0, 0);\n positions.set(index, {x: 0, y: 0});\n }\n // Anything else is an internal re-commit of the same entry: keep\n // the current scroll.\n\n lastIndexRef.current = index;\n lastPathRef.current = path;\n });\n });\n\n return () => {\n active = false;\n unlisten();\n };\n }, [router, resetOnPush]);\n\n return null;\n}\n","import {createHref, navigate} from '@native-router/core';\nimport {\n forwardRef,\n useRef,\n type ElementType,\n type MouseEvent,\n type ReactElement,\n type Ref\n} from 'react';\nimport type {AsLinkProps, TypedLinkProps} from '@@/types';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\n/**\n * Interpolate params into a path pattern: `:name` segments take a\n * string, `*name` wildcards a string array(joined with `/`), both\n * percent-encoded; everything else — including `\\` escapes — is static\n * text. The grammar matches the core matcher's(the ASCII identifier\n * scanner the type-level `ExtractPathParams` models).\n * @throws when a required param is missing or empty — the click-time\n * params check of {@link TypedLink}\n */\nfunction interpolatePath(\n pattern: string,\n params: Record<string, string | string[]>\n): string {\n return pattern.replace(\n /\\\\.|[:*]([A-Za-z_$][A-Za-z0-9_$]*)/g,\n (match, name?: string) => {\n if (name === undefined) return match;\n const value = params[name];\n if (value === undefined || value.length === 0) {\n throw new Error(\n `Missing param \"${name}\" for the path pattern \"${pattern}\"`\n );\n }\n return (Array.isArray(value) ? value : [value])\n .map(encodeURIComponent)\n .join('/');\n }\n );\n}\n\n/**\n * Link whose `to` is narrowed to a route table's path patterns and whose\n * `params` is checked against the exact pattern's param segments. Give\n * it the pattern union as its type argument:\n *\n * ```tsx\n * const routes = createRoutes({children: [{path: '/users/:id'}, ...]});\n *\n * <TypedLink<RoutePaths<typeof routes>> to=\"/users/:id\" params={{id: '7'}}>\n * User 7\n * </TypedLink>\n * ```\n *\n * A `to` outside the table, a missing required param or a wrong param\n * shape is a compile error; at click time the params are interpolated\n * into the pattern and a missing required param throws instead of\n * navigating(the type-level check's runtime backstop).\n *\n * Without the type argument the component degrades to a plain `Link`:\n * any path, params optional. Click interception follows {@link Link}\n * — only plain primary-button clicks are intercepted.\n *\n * An `as` component can be layered on top(`asProps`/flattened `as`-props\n * per {@link AsLinkProps}); give both type arguments to keep the pattern\n * narrowing: `<TypedLink<Paths, typeof MyLink> ... />`.\n * @group Components\n * @param props `to`(a pattern of the table), `params`(per the pattern)\n * and the usual anchor attributes\n */\n// The implementation works on the loose shape; the typed signature is\n// attached below so discriminated-union props need not be destructured\n// across the union.\nfunction TypedLinkImpl(\n {\n to,\n params,\n onClick,\n as,\n asProps,\n ...rest\n }: {\n to: string;\n params?: Record<string, string | string[]>;\n as?: ElementType;\n asProps?: Record<string, unknown>;\n } & Omit<TypedLinkProps, 'to' | 'params' | 'prefetch' | 'href'>,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const lockRef = useRef(false);\n\n // The href shows the interpolated target; when a required param is\n // missing the raw pattern stays and the click-time check below blocks\n // the navigation.\n let href: string = to;\n try {\n href = interpolatePath(to, params ?? {});\n } catch {\n // Programming error the types already flag; surfaced on click.\n }\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n\n if (lockRef.current) return;\n // Click-time params check per the pattern's param segments: a missing\n // required param throws instead of navigating.\n const target = interpolatePath(to, params ?? {});\n lockRef.current = true;\n navigate(router, target)\n .catch(() => undefined)\n .finally(() => {\n lockRef.current = false;\n });\n }\n\n const A = (as ?? 'a') as ElementType;\n return (\n <A\n {...rest}\n {...asProps}\n ref={ref}\n href={createHref(router, href)}\n onClick={handleClick}\n />\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link);\n// the tail keeps the pre-`as` discriminated-union shape.\nconst TypedLink = forwardRef(TypedLinkImpl) as {\n <Paths extends string = string, A extends ElementType = 'a'>(\n props: AsLinkProps<TypedLinkProps<Paths>, A>\n ): ReactElement | null;\n <Paths extends string = string>(\n props: TypedLinkProps<Paths>\n ): ReactElement | null;\n displayName?: string;\n};\n\nTypedLink.displayName = 'TypedLink';\n\nexport default TypedLink;\n","/**\n * Identity function with `satisfies` semantics: the table is checked\n * against `Route` while every `path` keeps its string-literal type, so\n * `RoutePaths<typeof routes>` can extract the full pattern union for\n * `TypedLink`. An `as Route` assertion does the opposite — it widens\n * every `path` to `string` and gives up the literals.\n *\n * ```tsx\n * const routes = createRoutes({\n * children: [\n * {path: '/', component: () => import('./Home')},\n * {path: '/users/:id', component: () => import('./UserProfile')}\n * ]\n * });\n * // type AppPaths = '/' | '/users/:id'\n * type AppPaths = RoutePaths<typeof routes>;\n * ```\n *\n * Zero runtime cost: the function returns its argument unchanged and\n * tree-shakes away.\n * @group Methods\n * @category Route\n * @param routes the route table, a route object or an array of them\n * @returns the very same route table, literal types preserved\n */\nexport function createRoutes(\n // The `const` modifier keeps every `path` a string literal(through\n // arbitrary nesting) while the parameter is still checked against\n // `Route` — the `satisfies` semantics an `as Route` assertion lacks:\n // the assertion widens every `path` to `string` instead.\n routes\n) {\n return routes;\n}\n","import {useCallback} from 'react';\nimport {\n commitReplace,\n navigate,\n parseSearchInput,\n parseSearchSync,\n resolveEntry,\n toLocation\n} from '@native-router/core';\nimport type {\n SearchInput,\n SearchOutputOf,\n StandardSchemaV1\n} from '@native-router/core';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './components/Router';\n\ntype SetSearchParams = (\n next: URLSearchParams | ((prev: URLSearchParams) => URLSearchParams),\n opts?: {replace?: boolean}\n) => Promise<void> | void;\n\n/**\n * Read and write the search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as the Router Component), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; a fresh `URLSearchParams` view is derived from that string\n * on each render.\n *\n * The setter navigates like any other route change: by default the new\n * search is pushed onto the history stack(mainstream react-router\n * semantics), pass `{replace: true}` to rewrite the current entry instead.\n * Since the search is part of the location, every write re-resolves the\n * matched route, so route `data` fetchers(see {@link useData}) observe the\n * new search on the next {@link useData} read.\n *\n * @group Hooks\n * @returns [searchParams, setSearchParams] - the current search params and\n * the setter(functional updates receive the live previous params); the\n * setter returns a `Promise<void>` that resolves once the navigation\n * commits, so callers may optionally `await` it\n */\nexport function useSearchParams(): [URLSearchParams, SetSearchParams] {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a URLSearchParams instance) to keep the\n // snapshot reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n const searchParams = new URLSearchParams(\n useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n );\n\n const setSearchParams = useCallback<SetSearchParams>(\n (next, opts) => {\n const {history} = router;\n const params =\n typeof next === 'function'\n ? // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n next(new URLSearchParams(history.location.search))\n : next;\n return setSearch(router, params.toString(), opts);\n },\n [router]\n );\n\n return [searchParams, setSearchParams];\n}\n\n/**\n * Write the search params of the current location through a schema, the\n * setter-side twin of `useSearch(schema)`: the next value is serialized\n * to a query string, degraded with `parseSearchInput` and validated by\n * the SAME schema before any navigation happens. A schema that rejects\n * the value throws its issues(`SearchError`) without touching the\n * location; the value the schema would default or coerce on the read\n * side never gets silently written.\n *\n * Synchronous schemas only(the `useSearch` flavor); an async `validate`\n * rejects without navigating.\n *\n * The navigation semantics follow `useSearchParams`' setter: push by\n * default, `{replace: true}` rewrites the current entry, guards run,\n * and the returned `Promise<void>` resolves once the navigation commits.\n *\n * @group Hooks\n * @param schema a Standard Schema validator of the search — must\n * validate synchronously\n * @returns the schema-aware setter; functional updates receive the live\n * previous params\n * @throws {SearchError} when `schema` rejects the next value, before\n * any navigation\n */\nexport function useSetSearch<S extends StandardSchemaV1>(\n schema: S\n): (\n next: SearchInput | ((prev: SearchInput) => SearchInput),\n opts?: {replace?: boolean}\n) => Promise<void> | void {\n const router = useRouter();\n\n return useCallback(\n (next, opts) => {\n const {history} = router;\n const input =\n typeof next === 'function'\n ? next(parseSearchInput(history.location.search))\n : next;\n // Validate the whole next value — not a diff — the same way a\n // navigation to the resulting URL would: parseSearchSync throws\n // SearchError with the schema's issues, and no navigation happens.\n const validated = parseSearchSync(schema, stringifySearch(input));\n // The schema output is authoritative: defaults applied and values\n // coerced to strings, so a partially-filled input still writes the\n // fully-defaulted query.\n return setSearch(\n router,\n stringifySearch(validated as Record<string, unknown>),\n opts\n );\n },\n [router, schema]\n );\n}\n\nfunction stringifySearch(input: Record<string, unknown>): string {\n return Object.entries(input)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) =>\n (Array.isArray(value) ? value : [value])\n .map(\n (v) => `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`\n )\n .join('&')\n )\n .join('&');\n}\n\nfunction setSearch(\n router: ReturnType<typeof useRouter>,\n qs: string,\n opts?: {replace?: boolean}\n): Promise<void> | void {\n const {history} = router;\n const {pathname, hash} = history.location;\n const to = pathname + (qs ? `?${qs}` : '') + hash;\n if (opts?.replace) {\n // Route guards run like any other navigation(align with the push\n // branch): the entry carries the terminal location, so a redirect\n // replaces the current entry with its final target.\n return resolveEntry(router, toLocation(router, to)).then((entry) =>\n commitReplace(router, entry.task, entry.location)\n );\n }\n return navigate(router, to);\n}\n\n/**\n * Read the parsed search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as {@link useSearchParams}), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; the parse itself runs on each render.\n *\n * Without a schema the hook degrades to the raw input object of\n * `parseSearchInput` — strings, arrays for repeated keys\n * (`{page: '2', tag: ['a', 'b']}`). With a schema — any zod/valibot/\n * arktype schema, see the route {@link Route.search search field} — the\n * returned object is the schema's parsed output, so coercion and defaults\n * apply, e.g. `useSearch(pageSchema).page` is a number.\n *\n * Prefer declaring the schema once on the route: its `data` loader then\n * receives a parsed `ctx.search` during resolve, and an invalid search\n * fails the navigation through the existing error channels instead of\n * throwing during render.\n *\n * @group Hooks\n * @param schema an optional Standard Schema validator of the search; it\n * must validate synchronously\n * @returns the parsed search params of the current location\n * @throws {SearchError} when `schema` rejects the current search\n */\nexport function useSearch<S extends StandardSchemaV1>(\n schema: S\n): SearchOutputOf<S>;\nexport function useSearch(): SearchInput;\nexport function useSearch(schema?: StandardSchemaV1): unknown {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a parsed object) to keep the snapshot\n // reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n const search = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n );\n\n return schema ? parseSearchSync(schema, search) : parseSearchInput(search);\n}\n","import {useEffect, useRef} from 'react';\nimport {setBlocker} from '@native-router/core';\nimport type {BlockerFn} from '@native-router/core';\nimport {useRouter} from './components/Router';\n\n/**\n * Block navigations away from the current page while the component is\n * mounted — the unsaved-changes guard.\n *\n * The predicate is the core `setBlocker` veto: `(to, from) => boolean`\n * over path strings(including search and hash), asked synchronously at\n * the head of every navigation and before a history POP lands. Return\n * `false` to veto: a vetoed navigation never starts and a vetoed POP is\n * rewound. `refresh` and guard redirects are never blocked; the effect\n * releases the blocker on unmount, so the guard lives exactly as long\n * as the guarding component.\n *\n * The predicate is stored in a ref and re-synced on every render, so a\n * navigation is always asked the latest closure — a `confirmed` flag it\n * captured works without re-registering anything. SSR-safe: nothing\n * here touches `window`, and the registration itself is an effect that\n * never runs on the server.\n *\n * @group Hooks\n * @param fn blocker predicate; `to` is the target path, `from` the\n * current path\n * @see {@link setBlocker}\n */\nexport function useBlocker(fn: BlockerFn): void {\n const router = useRouter();\n const fnRef = useRef(fn);\n // Always ask the latest closure: re-rendering with new state must not\n // require re-registering the blocker.\n fnRef.current = fn;\n useEffect(\n () => setBlocker(router, (to, from) => fnRef.current(to, from)),\n [router]\n );\n}\n"],"mappings":"kmBAeA,SAAgB,EACd,EAQA,EACA,GAEA,QACG,EAAE,kBACU,IAAb,EAAE,QACD,EAAE,SACF,EAAE,SACF,EAAE,UACF,EAAE,QACQ,WAAX,GACW,YAAX,GACW,SAAX,IACE,GAAO,IAAI,MAAM,OAAO,SAAS,YAEvC,CCoDA,IAAM,EAAO,EA1Db,UACE,GAAC,EAAA,GAAI,EAAA,QAAI,EAAA,QAAS,KAAY,GAC9B,GAEA,MAAM,EAAS,IACT,EAAU,GAAO,GA6BjB,EAAK,GAAM,KAIV,eAAgB,KAAgB,GAAe;AACtD,OACE,EAAC,EAAD,IACM,KACA,EACC,MACL,KAAM,EAAW,EAAQ,GACzB,QAtCJ,SAAqB,GAGnB,IAAU,GAMP,EACC,EACC,GAAS,QAAiC,EAAK,OAC/C,GAAS,KAA8B,EAAK,OAIjD,EAAE,iBAEE,EAAQ,UACZ,EAAQ,SAAU,EAClB,EAAS,EAAQ,GACd,MAAA,QACA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AAT,EACH,EAAK,EAAiB,EAAQ,SAAS,SACvC,EAIA,EAAY,EAAgB,EAAQ,EAAgB,IAI1D,OAAO,EACL,EACA,EAAgB,GAChB,IAGJ,CAAC,EAAQ,GAEb,CAEA,SAAS,EAAgB,GACvB,OAAO,OAAO,QAAQ,GACnB,OAAA,EAAQ,CAAG,KAAW,SACtB,IAAA,EAAM,EAAK,MACT,MAAM,QAAQ,GAAS,EAAQ,CAAC,IAC9B,IACE,GAAM,GAAG,mBAAmB,MAAQ,mBAAmB,OAAO,OAEhE,KAAK,MAET,KAAK,IACV,CAEA,SAAS,EACP,EACA,EACA,GAEA,MAAM,QAAC,GAAW,GACZ,SAAC,EAAA,KAAU,GAAQ,EAAQ,SAC3B,EAAK,GAAY,EAAK,IAAI,IAAO,IAAM,EAC7C,OAAI,GAAM,QAID,EAAa,EAAQ,EAAW,EAAQ,IAAK,KAAM,GACxD,EAAc,EAAQ,EAAM,KAAM,EAAM,WAGrC,EAAS,EAAQ,EAC1B,CAgCA,SAAgB,EAAU,GACxB,MAAM,EAAS,IAIT,EAAY,EACf,GAA8B,EAAO,QAAQ,OAAA,IAAa,KAC3D,CAAC,IAIG,EAAc,EAAA,IACZ,EAAO,QAAQ,SAAS,OAC9B,CAAC,IAGG,EAAoB,EAAA,IAAkB,GAAI,IAE1C,EAAS,EACb,EACA,EACA,GAGF,OAAO,EAAS,EAAgB,EAAQ,GAAU,EAAiB,EACrE,CCtMA,SAAgB,EAAW,GACzB,MAAM,EAAS,IACT,EAAQ,EAAO,GAGrB,EAAM,QAAU,EAChB,EAAA,IACQ,EAAW,EAAA,CAAS,EAAI,IAAS,EAAM,QAAQ,EAAI,IACzD,CAAC,GAEL,CHwHA,EAAU,YAAc"}
@@ -1,8 +0,0 @@
1
- import{Component as r,createContext as e,useCallback as n,useContext as t,useEffect as o,useMemo as i,useRef as a,useState as u}from"react";import{createBrowserHistory as c,createHashHistory as s,createMemoryHistory as l,createPath as d}from"history";import{Fragment as h,jsx as f,jsxs as v}from"react/jsx-runtime";import{create as m,getCurrentView as p,listen as g,match as y,mergeMatchedParams as w,parseSearch as x,parseSearchInput as P,resolve as b,setOptions as C,toLocation as A}from"@native-router/core";import{isString as E,splitProps as R,uniqId as S}from"@native-router/core/util";import{useSyncExternalStore as k}from"use-sync-external-store/shim";var K=e(null);function $(r){/* @__PURE__ */
2
- return f(K.Provider,{...r})}function H(){return t(K)}var I=e(null);function L(){const r=H(),e=t(I);return r??e}var V=e([void 0,{}]);function _(){return t(V)}function D(){return _()[1]}function M({children:r,name:e,data:n}){const t=D(),o=i(()=>[n,e?{...t,[e]:n}:t],[n,e,t]);/* @__PURE__ */
3
- return f(V.Provider,{value:o,children:r})}var U=e(void 0);function W(){return t(U)}function j(r){const[e,n]=_();return r?n[r]:e}var F=e(void 0);function J(){return t(F)}var N=class extends r{state={};static getDerivedStateFromError(r){return{error:r}}render(){const{error:r}=this.state;if(!r)return this.props.children;const{route:e,ctx:n,router:t}=this.props,o=e.errorComponent;if(o)/* @__PURE__ */return f(o,{error:r,ctx:{...n,phase:"render"}});const i=t.errorHandler?.(r);if(i instanceof Promise)throw i.catch(()=>{}),r;if(void 0!==i)return i;throw r}};function O(r,e){return z(r,e,(r,e)=>r?.(e))}var T=/* @__PURE__ */new WeakMap;function q(r,e){const n=new Array(r.length);return z(r,e,(r,e)=>Promise.resolve(r?.(e)).then(r=>n[e.index]=r)).then(r=>(T.set(r,n),r))}function z(r,{router:e,location:n,signal:t},o){return Promise.all(r.map(({route:i},a)=>{const u={matched:r,params:w(r,a),index:a,router:e,location:n,search:P(n.search),signal:t??(new AbortController).signal};return Promise.all([i.search?x(i.search,n.search).then(r=>(u.search=r,o(i.data,u))):o(i.data,u),function(){if(!i.component)return L;const r=i.component(u);return Promise.resolve(r).then(r=>"default"in r?r.default:r)}()]).then(([r,n])=>/* @__PURE__ */f(N,{route:i,ctx:u,router:e,children:/* @__PURE__ */f(M,{data:r,name:i.name,children:/* @__PURE__ */f(U.Provider,{value:u,children:/* @__PURE__ */f(n,{})})})},`${a}:${i.path??""}`),r=>{if(!i.errorComponent)throw r;/* @__PURE__ */
4
- return f(M,{data:void 0,name:i.name,children:/* @__PURE__ */f(U.Provider,{value:u,children:/* @__PURE__ */f(i.errorComponent,{error:r,ctx:u})})})})})).then(r=>r.reverse().reduce((r,e)=>/* @__PURE__ */f($,{value:r,children:e})))}var B=e(null);function G({router:r,children:e}){const o=a(p(r)),i=n(e=>g(r,r=>{o.current=r,e()}),[r]),u=n(()=>o.current,[]),c=n(()=>p(r),[r]),s=k(i,u,c),l=t(F),d=null==s&&"pending"===l?.status?function(r,e){const{resolving:n}=r,t=n?y(r,n.pathname):void 0;if(!t)return null;for(let o=t.length-1;o>=0;o--){const r=t[o].route.pendingComponent;if(r)/* @__PURE__ */return f(r,{},e)}return null}(r,l.key):null;/* @__PURE__ */
5
- return f(B.Provider,{value:r,children:void 0===e?s??d:/* @__PURE__ */f($,{value:s,children:/* @__PURE__ */f(I.Provider,{value:d,children:e})})})}function Q(r,e,{resolveView:n=O,...t}={}){return m(r,e,n,t)}function X({routes:r,children:e,...n},t){const[a,c]=R(n,["baseUrl","currentView"]),{baseUrl:s,currentView:l}=a,[d,h]=u(),v=i(()=>Q(r,t(),{...n,onLoadingChange(r){h(r&&{key:S(),status:r})}}),[r,t,s,l]);o(()=>{C(v,{...c,onLoadingChange(r){h(r&&{key:S(),status:r})}})},[v,c]);const m=i(()=>/* @__PURE__ */f(G,{router:v,children:e}),[v,e]);/* @__PURE__ */
6
- return f(F.Provider,{value:d,children:m})}function Y(r){return X(r,c)}function Z(r){return X(r,s)}function rr({initialEntries:r,initialIndex:e,...n}){return X(n,i(()=>()=>l({initialEntries:r,initialIndex:e}),[r,e]))}function er(){const r=t(B);if(!r)throw new Error("useRouter() must be used within a <Router> component");return r}var nr="_nativeRouterReactSSRData";function tr(r,e,n){return b(r,e).then(t=>{const o=function(r){return T.get(r)}(t),i=r.history.location.state?.index||0;/* @__PURE__ */
7
- return v(h,{children:[/* @__PURE__ */f(G,{router:r,children:t}),/* @__PURE__ */f("script",{...n?.scriptAttributes,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:`window.${n?.hydrateKey||nr} = ${a={data:o,location:e,index:i},JSON.stringify(a).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};`}})]});var a})}function or(r,e,{scriptAttributes:n,hydrateKey:t,...o}={}){const i=m(r,l({initialEntries:[e]}),q,o);return tr(i,E(e)?A(i,e):e,{scriptAttributes:n,hydrateKey:t})}function ir(r,e){const{data:n,location:t,index:o=0}=window[e?.hydrateKey||nr],i=c();i.replace(d(i.location),{index:o});const a=m(r,i,function(r){return(e,n)=>z(e,n,(e,n)=>r[n.index])}(n),e);return b(a,t).then(r=>({view:r,router:a}))}export{rr as a,er as c,j as d,J as f,H as h,Y as i,O as l,D as m,or as n,G as o,W as p,Z as r,Q as s,ir as t,L as u};
8
- //# sourceMappingURL=ssr-873l9jA-.js.map