@luwiostack/router 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -521,8 +521,8 @@ page), not requirements: omit either and it falls back to `default` too.
521
521
  **matched** route (e.g. a loader that couldn't find its resource) — every kind of "not found" ends
522
522
  up on the same real, translated, linkable 404 page. Define it as a normal route.
523
523
  - **403** — a guard throws `context.router.forbidden()`, a locale-aware redirect to
524
- `statusPages[403]`. The target lives in config, so the guard never repeats it; pass `query` to
525
- carry a return URL.
524
+ `statusPages[403]`. The target lives in config, so the guard never repeats it. It adds the
525
+ requested page as `?referrer=`, so sign-in can [send the user back](#back-to-the-referrer).
526
526
  - **Any other status** (`503`, `429`, …) — a dedicated page for a `beforeLoad`/`loader` failure whose
527
527
  thrown value carries that `status` (an `HttpError` from `@luwiostack/http`, or anything else shaped
528
528
  like one: `{ status: 503, … }`).
@@ -573,11 +573,9 @@ createRoute({
573
573
  .alias(Locale.new({ languageOrLocale: 'en-BE' }), '404')
574
574
  .alias(Locale.new({ languageOrLocale: 'nl-BE' }), '404')
575
575
 
576
- // a guard — 403 → sign-in, carrying the return URL
577
- beforeLoad: ({ context, location }) => {
578
- if (!getSession()) {
579
- throw context.router.forbidden({ query: { redirect: (location as { href: string }).href } })
580
- }
576
+ // a guard — 403 → sign-in, adding ?referrer= so sign-in can send the user back
577
+ beforeLoad: ({ context }) => {
578
+ if (!getSession()) throw context.router.forbidden()
581
579
  }
582
580
 
583
581
  // the 500 route — just like the 404 route, a normal aliased page
@@ -628,6 +626,124 @@ has no dedicated entry) to be a **registered** route, else the build throws. `ro
628
626
  reports an excluded route as **not** mounted — a 403 guard is not
629
627
  something you link to.
630
628
 
629
+ ### Back to the referrer
630
+
631
+ The typical case: a signed-out visitor opens `/nl-BE/bestellingen/42`, a guard sends them to
632
+ sign-in, and after signing in they should land on order 42, not on a generic start page. That takes
633
+ two steps:
634
+
635
+ 1. **Add the referrer** where you send them away. `forbidden()` does this for you; anywhere else,
636
+ pass `referrer: true`.
637
+ 2. **Go to the referrer** when they're done: `canGoToReferrer() ? goToReferrer() : …`
638
+
639
+ `forbidden()` adds the page being loaded, which in a guard is the page the user was trying to reach.
640
+ For any other detour, add it yourself with `referrer: true` on `href`, `navigate` or `redirect`:
641
+
642
+ ```tsx
643
+ // 1. ADD — routes/auth.route.tsx: forbidden() adds the page the user asked for, by default.
644
+ export default createRoute({
645
+ id: 'auth',
646
+ layout: true,
647
+ beforeLoad: ({ context }) => {
648
+ // /nl-BE/bestellingen/42 → /nl-BE/aanmelden?referrer=%2Fnl-BE%2Fbestellingen%2F42
649
+ if (!getSession()) throw context.router.forbidden() // forbidden({ referrer: false }) to leave it out
650
+ },
651
+ })
652
+
653
+ // Anywhere else, ask for it with referrer: true — on any link, navigate or redirect, navigate or redirect: "edit your address, then come back here".
654
+ <a href={router.href({ id: 'address.edit', referrer: true })}>Edit address</a>
655
+ ```
656
+
657
+ On the other side, it works like `canGoBack()` / `goBack()`, except it follows `?referrer=` instead
658
+ of browser history. `canGoToReferrer()` tells you whether there's somewhere safe to go,
659
+ `goToReferrer()` goes there, and what to do otherwise is up to you. `referrer()` gives you the route
660
+ itself, for a `beforeLoad` redirect:
661
+
662
+ ```tsx
663
+ // 2. GO — routes/sign-in.route.tsx: after signing in, go to the referrer. Where there's none, you decide.
664
+ function SignIn() {
665
+ const { router } = useRouter()
666
+
667
+ async function onSignedIn() {
668
+ router.canGoToReferrer()
669
+ ? await router.goToReferrer({ replace: true }) // back to '/nl-BE/bestellingen/42'
670
+ : await router.navigate({ id: 'dashboard', replace: true })
671
+ }
672
+ // …form that calls onSignedIn()
673
+ }
674
+
675
+ // In a beforeLoad you throw a redirect instead: referrer() gives you the route, or undefined.
676
+ export default createRoute({
677
+ id: 'signIn',
678
+ component: SignIn,
679
+ beforeLoad: ({ context }) => {
680
+ const back = context.router.referrer()
681
+ if (getSession()) throw context.router.redirect(back ?? { id: 'dashboard' })
682
+ },
683
+ // …title, description
684
+ })
685
+ ```
686
+
687
+ `?referrer=` is untrusted, because anyone can link to `/aanmelden?referrer=https://evil.example`. So
688
+ it's checked every time it's read, and there is no referrer unless all of these hold:
689
+
690
+ - **It's on this site.** A root-relative path, not another origin, `//evil.example` or a backslash
691
+ trick.
692
+ - **It's a page.** The router itself matches the path to one of your routes. Unknown paths, excluded
693
+ routes and paths behind a 403 guard don't count.
694
+ - **It isn't a loop.** Not the current route, and not a status page.
695
+
696
+ The route has no `locale`, so it opens in the *active* one: someone who switched to French on the
697
+ sign-in page goes back to `/fr-BE/commandes/42`. It keeps its own locale only when the page doesn't
698
+ exist in the active one. It reads the raw query string, so the sign-in route doesn't need `referrer`
699
+ in its `validateSearch`. It's not the browser's `document.referrer`, which a client-side navigation
700
+ never updates.
701
+
702
+ #### Through an OAuth round trip
703
+
704
+ Signing in with an identity provider leaves your site, and the provider sends the user back to a
705
+ fixed callback URL that only carries what you put in `state`. So stash the referrer in `state` on the
706
+ way out, and on the callback hand it to the same methods with `from`:
707
+
708
+ ```tsx
709
+ // OAuth: the provider only sends back what you put in `state`, so the referrer travels there.
710
+
711
+ // 1. Sign-in page, before leaving for the provider: stash the CHECKED referrer as an href.
712
+ function signInWithProvider() {
713
+ const back = router.referrer() // undefined when there's nothing safe to go back to
714
+ const state = encodeState({ nonce: newNonce(), referrer: back && router.href(back) })
715
+ window.location.assign(`${provider}/authorize?client_id=…&state=${state}`)
716
+ }
717
+
718
+ // 2. routes/auth-callback.route.tsx: /auth/callback?code=…&state=…
719
+ export default createRoute({
720
+ id: 'authCallback',
721
+ loader: async ({ context, search }) => {
722
+ const { nonce, referrer } = decodeState(search.state) // verifying state is your app's job
723
+ await exchangeCode(search.code, nonce)
724
+
725
+ // `from` checks the value from state exactly like ?referrer= — anyone can craft a callback URL.
726
+ // In a loader you redirect rather than navigate, so take the route itself; where there's none, you decide.
727
+ const back = context.router.referrer({ from: referrer })
728
+ throw context.router.redirect({ ...(back ?? { id: 'dashboard' }), replace: true })
729
+ },
730
+ // …title, description
731
+ })
732
+ ```
733
+
734
+ - **Stash the checked href**, `router.href(router.referrer())`, not the raw `?referrer=`. It's smaller,
735
+ and it's already a page on your site.
736
+ - **Check it again on the callback.** A valid nonce proves the callback belongs to your sign-in, not
737
+ that what's inside `state` is safe. `from` runs it through the same checks as `?referrer=`.
738
+ - **Once you pass `from`, the URL isn't read.** `from: undefined`, when `state` had no referrer, means
739
+ there is none.
740
+ - **Mind the callback's locale.** The referrer opens in the active locale, which on the callback is
741
+ the callback route's. If your provider only accepts one fixed redirect URL, put the user's locale
742
+ in `state` too and pass it along: `redirect({ ...back, locale: state.locale })`.
743
+
744
+ Encoding, signing and verifying `state` stays with your app or OAuth library; the router only checks
745
+ the referrer that comes out of it.
746
+
631
747
  ### Legacy redirects
632
748
 
633
749
  When URLs change (renamed locale codes, a moved page), old bookmarks and indexed links shouldn't
@@ -709,6 +825,9 @@ and every generated link stay unprefixed while you're in the default locale.
709
825
  | `createRouter(registry, config)` | Expand a registry into a TanStack `Router`. |
710
826
  | `useRouter()` | `{ router }` — `href`/`path`/`absolute`/`navigate`/`redirect`/`notFound`/`forbidden`, plus `locale`, `routeId`, `locales`, `has`, `availableLocales`. |
711
827
  | `router.redirect` / `.notFound` / `.forbidden` | Locale-aware, throwable results for `beforeLoad` / `loader` — redirect by route id, notFound, or forbidden (→ `statusPages[403]`). Also on `context.router`. |
828
+ | `referrer: true` | On `href` / `navigate` / `redirect`: add the current page (in a guard, the page being loaded) as `?referrer=`. `forbidden()` adds it by default; `referrer: false` leaves it out. See [Back to the referrer](#back-to-the-referrer). |
829
+ | `router.canGoToReferrer({ from? })` / `router.goToReferrer({ from?, replace? })` | Like `canGoBack()` / `goBack()`, but for `?referrer=` instead of history: whether there's a safe page to go back to, and go there (a no-op when there isn't). |
830
+ | `router.referrer({ from? })` | The referrer as `{ id, params, query?, hash?, locale? }` in the active locale, or `undefined` unless it's a page on this site the router serves (and not the current route or a status page). `from` checks a value that arrived another way, like an OAuth `state`. See [Through an OAuth round trip](#through-an-oauth-round-trip). |
712
831
  | `useRouteFailure()` | `{ status, error? } \| undefined` — the failure that redirected to the current `statusPages` page. See [Not found, forbidden & error](#not-found-forbidden--error-404--403--5xx). |
713
832
  | `RouterProvider` / `Outlet` | Re-exported from the bundled TanStack Router. Mount the tree / render children. |
714
833
  | `HeadContent` / `Scripts` | Re-exported from the bundled TanStack Router. Render a route's `head()` tags / body scripts. |
package/dist/index.cjs CHANGED
@@ -7048,8 +7048,20 @@ function setRouterMeta(router, meta) {
7048
7048
  function getRouterMeta(router) {
7049
7049
  return store.get(router);
7050
7050
  }
7051
+ const tags = /* @__PURE__ */ new WeakMap();
7052
+ /** Tag a built route with the route id + locale it came from. Called by {@link createRouter}. */
7053
+ function tagRoute(route, tag) {
7054
+ tags.set(route, tag);
7055
+ }
7056
+ /** The route id + locale a built route came from, or `undefined` for a synthetic route. */
7057
+ function getRouteTag(route) {
7058
+ return route ? tags.get(route) : void 0;
7059
+ }
7051
7060
  //#endregion
7052
7061
  //#region src/use-router.ts
7062
+ /** The query param the referrer travels in. */
7063
+ const REFERRER = "referrer";
7064
+ const SAME_ORIGIN = "http://same-origin.invalid";
7053
7065
  const fillSegment = (seg, params, id) => {
7054
7066
  if (seg === "$") return params["*"] ?? "";
7055
7067
  if (!seg.startsWith("$")) return seg;
@@ -7136,53 +7148,66 @@ function routerApi(input) {
7136
7148
  const { registry, config, mounted, active, activeId, getTanstack } = input;
7137
7149
  const toLocale = (l) => l == null ? active : typeof l !== "string" ? l : config.locales.find((x) => x.code === l) ?? _luwiostack_locale.Locale.new({ languageOrLocale: l });
7138
7150
  const path = ({ id, locale, params }) => routePath(registry, config, id, toLocale(locale), params);
7139
- const href = ({ id, locale, params, query, hash }) => path({
7151
+ const latest = () => getTanstack()?.latestLocation;
7152
+ const withReferrer = (query, referrer) => {
7153
+ const current = referrer ? latest()?.href : void 0;
7154
+ return current === void 0 ? query : {
7155
+ ...query,
7156
+ [REFERRER]: current
7157
+ };
7158
+ };
7159
+ const href = ({ id, locale, params, query, hash, referrer }) => path({
7140
7160
  id,
7141
7161
  locale,
7142
7162
  params
7143
- }) + suffix(query, hash);
7163
+ }) + suffix(withReferrer(query, referrer), hash);
7144
7164
  const absolute = ({ baseUrl, ...rest }) => resolveOrigin(config, baseUrl) + href(rest);
7145
7165
  const liveRouter = () => {
7146
7166
  const t = getTanstack();
7147
7167
  if (!t) throw new Error("router: navigation is unavailable in this context (no live router yet).");
7148
7168
  return t;
7149
7169
  };
7150
- const navigate = async ({ id, from, params, query, hash, locale, replace, state, target }) => {
7170
+ const navigate = async ({ id, from, params, query, hash, locale, replace, state, target, referrer }) => {
7151
7171
  if (target === "_blank") {
7152
7172
  if (typeof window !== "undefined") window.open(absolute({
7153
7173
  id,
7154
7174
  locale,
7155
7175
  params,
7156
7176
  query,
7157
- hash
7177
+ hash,
7178
+ referrer
7158
7179
  }), "_blank");
7159
7180
  return;
7160
7181
  }
7182
+ const search = withReferrer(query, referrer);
7161
7183
  await liveRouter().navigate({
7162
7184
  to: path({
7163
7185
  id,
7164
7186
  locale,
7165
7187
  params
7166
7188
  }),
7167
- search: query ? cleanSearch(query) : void 0,
7189
+ search: search ? cleanSearch(search) : void 0,
7168
7190
  hash,
7169
7191
  replace,
7170
7192
  state,
7171
7193
  from
7172
7194
  });
7173
7195
  };
7174
- const buildRedirect = (opts) => redirect({
7175
- to: path({
7176
- id: opts.id,
7177
- locale: opts.locale,
7178
- params: opts.params
7179
- }),
7180
- search: opts.query ? cleanSearch(opts.query) : void 0,
7181
- hash: opts.hash,
7182
- replace: opts.replace,
7183
- ...opts.statusCode != null ? { statusCode: opts.statusCode } : {},
7184
- ...opts.state ? { state: opts.state } : {}
7185
- });
7196
+ const buildRedirect = (opts) => {
7197
+ const search = withReferrer(opts.query, opts.referrer);
7198
+ return redirect({
7199
+ to: path({
7200
+ id: opts.id,
7201
+ locale: opts.locale,
7202
+ params: opts.params
7203
+ }),
7204
+ search: search ? cleanSearch(search) : void 0,
7205
+ hash: opts.hash,
7206
+ replace: opts.replace,
7207
+ ...opts.statusCode != null ? { statusCode: opts.statusCode } : {},
7208
+ ...opts.state ? { state: opts.state } : {}
7209
+ });
7210
+ };
7186
7211
  const redirect$1 = (params) => buildRedirect(params);
7187
7212
  const notFound$1 = (options) => notFound(options);
7188
7213
  const forbidden = (params) => buildRedirect({
@@ -7193,8 +7218,38 @@ function routerApi(input) {
7193
7218
  hash: params?.hash,
7194
7219
  replace: params?.replace,
7195
7220
  statusCode: params?.statusCode ?? 403,
7196
- state: { status: 403 }
7221
+ state: { status: 403 },
7222
+ referrer: params?.referrer ?? true
7197
7223
  });
7224
+ const referrer = (options) => {
7225
+ const raw = options && "from" in options ? options.from : new URLSearchParams(latest()?.searchStr ?? "").get(REFERRER);
7226
+ if (typeof raw !== "string" || !raw.startsWith("/") || /^\/[/\\]/.test(raw)) return void 0;
7227
+ let url;
7228
+ try {
7229
+ url = new URL(raw, SAME_ORIGIN);
7230
+ } catch {
7231
+ return;
7232
+ }
7233
+ if (url.origin !== SAME_ORIGIN) return void 0;
7234
+ const live = getTanstack();
7235
+ if (!live) return void 0;
7236
+ const [, rawParams, foundRoute] = live.getMatchedRoutes(url.pathname);
7237
+ const tag = getRouteTag(foundRoute);
7238
+ if (!tag) return void 0;
7239
+ if (tag.id === activeId || Object.values(config.statusPages).includes(tag.id)) return void 0;
7240
+ const { _splat: _, ...params } = rawParams;
7241
+ url.searchParams.delete(REFERRER);
7242
+ const query = Object.fromEntries(url.searchParams);
7243
+ const hash = url.hash.slice(1);
7244
+ const inActive = availableLocales(registry, config, tag.id).some((l) => l.code === active.code);
7245
+ return {
7246
+ id: tag.id,
7247
+ params,
7248
+ ...Object.keys(query).length > 0 ? { query } : {},
7249
+ ...hash ? { hash } : {},
7250
+ ...inActive ? {} : { locale: tag.locale }
7251
+ };
7252
+ };
7198
7253
  return {
7199
7254
  locale: active,
7200
7255
  routeId: activeId,
@@ -7212,6 +7267,15 @@ function routerApi(input) {
7212
7267
  redirect: redirect$1,
7213
7268
  notFound: notFound$1,
7214
7269
  forbidden,
7270
+ referrer,
7271
+ canGoToReferrer: (options) => referrer(options) !== void 0,
7272
+ goToReferrer: async ({ replace, ...options } = {}) => {
7273
+ const target = referrer(options);
7274
+ if (target) await navigate({
7275
+ ...target,
7276
+ replace
7277
+ });
7278
+ },
7215
7279
  reload: () => liveRouter().invalidate(),
7216
7280
  goBack: async () => {
7217
7281
  liveRouter().history.back();
@@ -7423,6 +7487,10 @@ function createRouter(registry, config) {
7423
7487
  ...userLoader ? { loader: guardLoadPhase(userLoader, apiCtx, locale) } : {},
7424
7488
  ...head ? { head } : {}
7425
7489
  });
7490
+ if (!b.layout) tagRoute(route, {
7491
+ id: b.id,
7492
+ locale
7493
+ });
7426
7494
  const children = build(b.id, route);
7427
7495
  return children.length ? route.addChildren(children) : route;
7428
7496
  });