@renr/parcel-rsc-router 0.1.0-alpha.0 → 0.1.0-alpha.1

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.
@@ -0,0 +1,25 @@
1
+ import { RouteData, RoutePath } from "./types.js";
2
+ import React, { HTMLAttributeAnchorTarget } from "react";
3
+
4
+ //#region src/Link.d.ts
5
+ declare function Link({
6
+ to,
7
+ children,
8
+ hash,
9
+ onClick,
10
+ target,
11
+ search,
12
+ routes,
13
+ ...props
14
+ }: {
15
+ to: RoutePath;
16
+ hash?: string;
17
+ search?: Record<string, string>;
18
+ children: React.ReactNode;
19
+ onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;
20
+ target?: HTMLAttributeAnchorTarget;
21
+ routes: RouteData[];
22
+ } & React.AnchorHTMLAttributes<HTMLAnchorElement>): React.JSX.Element;
23
+ //#endregion
24
+ export { Link };
25
+ //# sourceMappingURL=Link.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Link.d.ts","names":[],"sources":["../../src/Link.tsx"],"sourcesContent":[],"mappings":";;;;iBAMgB,IAAA;;;;;;;;;AAMd;MAII;EAVU,IAAA,CAAA,EAAI,MAAA;EAClB,MAAA,CAAA,EAWS,MAXT,CAAA,MAAA,EAAA,MAAA,CAAA;EACA,QAAA,EAWU,KAAA,CAAM,SAXhB;EACA,OAAA,CAAA,EAAA,CAAA,CAAA,EAWc,KAAA,CAAM,UAXpB,CAW+B,iBAX/B,CAAA,EAAA,GAAA,IAAA;EACA,MAAA,CAAA,EAWS,yBAXT;EACA,MAAA,EAYQ,SAZR,EAAA;CACA,GAYE,KAAA,CAAM,oBAZR,CAY6B,iBAZ7B,CAAA,CAAA,EAY+C,KAAA,CAAA,GAAA,CAAA,OAZ/C"}
@@ -0,0 +1,28 @@
1
+ "use client";
2
+
3
+
4
+ import { navigate } from "./rsc.js";
5
+ import React from "react";
6
+
7
+ //#region src/Link.tsx
8
+ function Link({ to, children, hash, onClick, target, search, routes,...props }) {
9
+ const href = `${to}${hash ? `#${hash}` : ""}${search ? `?${new URLSearchParams(search)}` : ""}`;
10
+ console.log("Link href", href);
11
+ return /* @__PURE__ */ React.createElement("a", {
12
+ href,
13
+ onClick: (e) => {
14
+ if (onClick) onClick(e);
15
+ if ((!target || target === "_self") && e.button === 0 && !e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey && !e.defaultPrevented) {
16
+ e.preventDefault();
17
+ navigate(href, routes, () => {
18
+ window.history.pushState(null, "", href);
19
+ });
20
+ }
21
+ },
22
+ ...props
23
+ }, children);
24
+ }
25
+
26
+ //#endregion
27
+ export { Link };
28
+ //# sourceMappingURL=Link.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Link.js","names":[],"sources":["../../src/Link.tsx"],"sourcesContent":["\"use client\";\n\nimport React, { type HTMLAttributeAnchorTarget } from \"react\";\nimport { RouteData, RoutePath } from \"./types.js\";\nimport { navigate } from \"./rsc.js\";\n\nexport function Link({\n to,\n children,\n hash,\n onClick,\n target,\n search,\n routes,\n ...props\n}: {\n to: RoutePath;\n hash?: string;\n search?: Record<string, string>;\n children: React.ReactNode;\n onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;\n target?: HTMLAttributeAnchorTarget;\n // TODO we will get routes from context, but for now we pass it in\n routes: RouteData[];\n} & React.AnchorHTMLAttributes<HTMLAnchorElement>) {\n const href = `${to}${hash ? `#${hash}` : \"\"}${search ? `?${new URLSearchParams(search)}` : \"\"}`;\n console.log(\"Link href\", href);\n return (\n <a\n href={href}\n onClick={(e) => {\n if (onClick) {\n onClick(e);\n }\n\n if (\n (!target || target === \"_self\") &&\n e.button === 0 && // left clicks only\n !e.metaKey && // open in new tab (mac)\n !e.ctrlKey && // open in new tab (windows)\n !e.altKey && // download\n !e.shiftKey &&\n !e.defaultPrevented\n ) {\n // Intercept link clicks to perform RSC navigation.\n e.preventDefault();\n\n void navigate(href, routes, () => {\n // add to history on a successful navigation\n window.history.pushState(null, \"\", href);\n });\n }\n }}\n {...props}\n >\n {children}\n </a>\n );\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,KAAK,EACnB,IACA,UACA,MACA,SACA,QACA,QACA,OACA,GAAG,SAU8C;CACjD,MAAM,OAAO,GAAG,KAAK,OAAO,IAAI,SAAS,KAAK,SAAS,IAAI,IAAI,gBAAgB,OAAO,KAAK;AAC3F,SAAQ,IAAI,aAAa,KAAK;AAC9B,QACE,oCAAC;EACO;EACN,UAAU,MAAM;AACd,OAAI,QACF,SAAQ,EAAE;AAGZ,QACG,CAAC,UAAU,WAAW,YACvB,EAAE,WAAW,KACb,CAAC,EAAE,WACH,CAAC,EAAE,WACH,CAAC,EAAE,UACH,CAAC,EAAE,YACH,CAAC,EAAE,kBACH;AAEA,MAAE,gBAAgB;AAElB,IAAK,SAAS,MAAM,cAAc;AAEhC,YAAO,QAAQ,UAAU,MAAM,IAAI,KAAK;MACxC;;;EAGN,GAAI;IAEH,SACC"}
@@ -0,0 +1,11 @@
1
+ "use client-entry";
2
+
3
+
4
+ import { hydrate } from "@parcel/rsc/client";
5
+
6
+ //#region src/client-entry.ts
7
+ const updateRoot = hydrate({});
8
+
9
+ //#endregion
10
+ export { updateRoot };
11
+ //# sourceMappingURL=client-entry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-entry.js","names":["updateRoot: ReturnType<typeof hydrate>"],"sources":["../../src/client-entry.ts"],"sourcesContent":["\"use client-entry\";\n\nimport { hydrate } from \"@parcel/rsc/client\";\n\n//TODO https://github.com/microsoft/TypeScript/issues/42873#issuecomment-1416128545\nexport const updateRoot: ReturnType<typeof hydrate> = hydrate({\n // TODO - can't build due to reading window\n // onHmrReload() {},\n});\n"],"mappings":";;;;;;AAKA,MAAaA,aAAyC,QAAQ,EAG7D,CAAC"}
@@ -0,0 +1,3 @@
1
+ import { App, RouteData, RouteNode, RoutePath } from "./types.js";
2
+ import { Link } from "./Link.js";
3
+ export { type App, Link, type RouteData, type RouteNode, type RoutePath };
@@ -0,0 +1,3 @@
1
+ import { Link } from "./Link.js";
2
+
3
+ export { Link };
@@ -0,0 +1,54 @@
1
+ "use client";
2
+
3
+
4
+ import { updateRoot } from "./client-entry.js";
5
+ import { getPathData } from "./util.js";
6
+ import { createElement } from "react";
7
+ import { fetchRSC } from "@parcel/rsc/client";
8
+
9
+ //#region src/rsc.ts
10
+ async function navigate(pathname, routes, onPush, { push = true } = {}) {
11
+ console.log("client navigating to:", pathname);
12
+ let shouldPush = push;
13
+ const path = getPathData(pathname, routes);
14
+ if (!path) {
15
+ console.warn(`No route found for ${pathname}`);
16
+ if (routes.some((r) => r.path === "/404")) navigate("/404", routes, () => {
17
+ onPush(pathname);
18
+ });
19
+ else updateRoot(createElement("h1", null, "404 Not Found"));
20
+ return;
21
+ }
22
+ if (path.url === location.pathname) shouldPush = false;
23
+ try {
24
+ updateRoot(await fetchRSCWithPreloadCache(path.rsc), () => {
25
+ if (shouldPush) onPush(path.url);
26
+ });
27
+ } catch (e) {
28
+ console.log(`Error fetching ${path.path} RSC`, e);
29
+ }
30
+ }
31
+ async function fetchRSCWithPreloadCache(url, options) {
32
+ if (fetchCache.has(url)) {
33
+ console.log("Cache hit", url);
34
+ return fetchCache.get(url);
35
+ }
36
+ const promise = fetchRSC(url, options);
37
+ fetchCache.set(url, promise);
38
+ while (fetchCache.size > 5) {
39
+ const firstKey = fetchCache.keys().next().value;
40
+ if (!firstKey) break;
41
+ fetchCache.delete(firstKey);
42
+ }
43
+ return promise.then((data) => {
44
+ return data;
45
+ }).catch((error) => {
46
+ fetchCache.delete(url);
47
+ throw error;
48
+ });
49
+ }
50
+ const fetchCache = /* @__PURE__ */ new Map();
51
+
52
+ //#endregion
53
+ export { navigate };
54
+ //# sourceMappingURL=rsc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rsc.js","names":[],"sources":["../../src/rsc.ts"],"sourcesContent":["\"use client\";\n\nimport { type RSCRequestInit, fetchRSC } from \"@parcel/rsc/client\";\nimport { type ReactNode, createElement } from \"react\";\nimport { updateRoot } from \"./client-entry.js\";\nimport { getPathData } from \"./util.js\";\nimport { RouteData } from \"./types.js\";\n\n// fetch and push an rsc route\nexport async function navigate(\n pathname: string,\n routes: RouteData[],\n /** callback for a successful navigation (use this to update the history) */\n onPush: (url: string) => void,\n { push = true }: { push?: boolean } = {}\n) {\n console.log(\"client navigating to:\", pathname);\n\n let shouldPush = push;\n\n const path = getPathData(pathname, routes);\n\n if (!path) {\n console.warn(`No route found for ${pathname}`);\n\n if (routes.some((r) => r.path === \"/404\")) {\n // we have a 404 page, navigate there\n void navigate(\"/404\", routes, () => {\n // show the original not found path (rather than 404) in the URL\n onPush(pathname);\n });\n } else {\n // render a fallback 404\n updateRoot(createElement(\"h1\", null, \"404 Not Found\"));\n }\n return;\n }\n\n // Don't add to history if we're already on this page\n if (path.url === location.pathname) {\n shouldPush = false;\n }\n\n try {\n const root = await fetchRSCWithPreloadCache<ReactNode>(path.rsc);\n\n updateRoot(root, () => {\n if (shouldPush) {\n onPush(path.url);\n }\n });\n\n // after a successful navigation, we can clear the cache\n // note everything is static currently, we don't need to clear the cache\n // fetchCache.clear();\n } catch (e) {\n console.log(`Error fetching ${path.path} RSC`, e);\n }\n}\n\nasync function fetchRSCWithPreloadCache<T>(\n url: string | URL | Request,\n options?: RSCRequestInit\n): Promise<T> {\n if (fetchCache.has(url)) {\n console.log(\"Cache hit\", url);\n\n return fetchCache.get(url) as Promise<T>;\n }\n\n const promise = fetchRSC<T>(url, options);\n\n fetchCache.set(url, promise);\n\n // keep the cache small, removing the oldest entries\n while (fetchCache.size > 5) {\n const firstKey = fetchCache.keys().next().value;\n\n if (!firstKey) {\n break;\n }\n\n fetchCache.delete(firstKey);\n }\n\n return promise\n .then((data) => {\n return data;\n })\n .catch((error) => {\n fetchCache.delete(url);\n\n throw error;\n });\n}\n\nexport const fetchCache = new Map<string | URL | Request, Promise<unknown>>();\n\nexport async function prefetch(\n pathname: string,\n routes: RouteData[],\n signal?: AbortSignal\n) {\n const path = getPathData(pathname, routes);\n\n if (!path) {\n return;\n }\n\n try {\n await fetchRSCWithPreloadCache<ReactNode>(path.rsc, { signal });\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error fetching ${pathname} RSC`, error);\n\n return;\n }\n\n // don't throw if the signal is aborted - this is expected\n if (signal?.aborted) {\n console.log(signal.reason);\n\n return;\n }\n }\n}\n"],"mappings":";;;;;;;;;AASA,eAAsB,SACpB,UACA,QAEA,QACA,EAAE,OAAO,SAA6B,EAAE,EACxC;AACA,SAAQ,IAAI,yBAAyB,SAAS;CAE9C,IAAI,aAAa;CAEjB,MAAM,OAAO,YAAY,UAAU,OAAO;AAE1C,KAAI,CAAC,MAAM;AACT,UAAQ,KAAK,sBAAsB,WAAW;AAE9C,MAAI,OAAO,MAAM,MAAM,EAAE,SAAS,OAAO,CAEvC,CAAK,SAAS,QAAQ,cAAc;AAElC,UAAO,SAAS;IAChB;MAGF,YAAW,cAAc,MAAM,MAAM,gBAAgB,CAAC;AAExD;;AAIF,KAAI,KAAK,QAAQ,SAAS,SACxB,cAAa;AAGf,KAAI;AAGF,aAFa,MAAM,yBAAoC,KAAK,IAAI,QAEzC;AACrB,OAAI,WACF,QAAO,KAAK,IAAI;IAElB;UAKK,GAAG;AACV,UAAQ,IAAI,kBAAkB,KAAK,KAAK,OAAO,EAAE;;;AAIrD,eAAe,yBACb,KACA,SACY;AACZ,KAAI,WAAW,IAAI,IAAI,EAAE;AACvB,UAAQ,IAAI,aAAa,IAAI;AAE7B,SAAO,WAAW,IAAI,IAAI;;CAG5B,MAAM,UAAU,SAAY,KAAK,QAAQ;AAEzC,YAAW,IAAI,KAAK,QAAQ;AAG5B,QAAO,WAAW,OAAO,GAAG;EAC1B,MAAM,WAAW,WAAW,MAAM,CAAC,MAAM,CAAC;AAE1C,MAAI,CAAC,SACH;AAGF,aAAW,OAAO,SAAS;;AAG7B,QAAO,QACJ,MAAM,SAAS;AACd,SAAO;GACP,CACD,OAAO,UAAU;AAChB,aAAW,OAAO,IAAI;AAEtB,QAAM;GACN;;AAGN,MAAa,6BAAa,IAAI,KAA+C"}
@@ -0,0 +1,17 @@
1
+ //#region src/types.d.ts
2
+ declare namespace App {
3
+ interface Routes {}
4
+ }
5
+ type RoutePath = keyof App.Routes extends never ? string : keyof App.Routes;
6
+ type RouteData = Omit<RouteNode, "children">;
7
+ type RoutePathToSlug<T extends string> = T extends `/` ? "index" : T extends `${infer _Prefix}/${infer Slug}` ? RoutePathToSlug<Slug> : T;
8
+ interface RouteNode {
9
+ children: RouteNode[];
10
+ path: RoutePath;
11
+ slug: RoutePathToSlug<RoutePath>;
12
+ rsc: `${string}.rsc`;
13
+ html: `${string}.html`;
14
+ }
15
+ //#endregion
16
+ export { App, RouteData, RouteNode, RoutePath };
17
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../../src/types.ts"],"sourcesContent":[],"mappings":";kBAAiB,GAAA;EAAA,UAAG,MAAA,CAAA,CAIR;AAIZ;AAEK,KANO,SAAA,GAMQ,MANU,GAAA,CAAI,MAMd,SAAA,KAAA,GAAA,MAAA,GAAA,MAJV,GAAA,CAAI,MAIM;AAAqB,KAF7B,SAAA,GAAY,IAEiB,CAFZ,SAEY,EAAA,UAAA,CAAA;KAApC,eAED,CAAA,UAAA,MAAA,CAAA,GAFqC,CAErC,SAAA,GAAA,GAAA,OAAA,GAAA,CAAA,SAAA,GAAA,KAAA,QAAA,IAAA,KAAA,KAAA,EAAA,GACE,eADF,CACkB,IADlB,CAAA,GAEE,CAFF;AACkB,UAGL,SAAA,CAHK;EAAhB,QAAA,EAIM,SAJN,EAAA;EACA,IAAA,EAIE,SAJF;EAAC,IAAA,EAKC,eALD,CAKiB,SALjB,CAAA;EAEU,GAAA,EAAA,GAAA,MAAS,MAAA;EACd,IAAA,EAAA,GAAA,MAAA,OAAA"}
@@ -0,0 +1,23 @@
1
+ "use client";
2
+
3
+
4
+ //#region src/util.ts
5
+ const normalizeRoutePath = (path) => {
6
+ for (const suffix of ["/", "/index"]) if (path.endsWith(suffix)) return path.slice(0, -suffix.length) || "/";
7
+ return path;
8
+ };
9
+ function getPathData(pathname, routes) {
10
+ const normalizedPath = normalizeRoutePath(pathname.startsWith("/") ? pathname : `/${pathname}`);
11
+ const routePathName = normalizeRoutePath(new URL(pathname, window.location.origin).pathname);
12
+ const route = routes.find((route$1) => route$1.path === routePathName);
13
+ if (!route) return null;
14
+ return {
15
+ ...route,
16
+ rsc: route.rsc,
17
+ url: normalizedPath
18
+ };
19
+ }
20
+
21
+ //#endregion
22
+ export { getPathData };
23
+ //# sourceMappingURL=util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.js","names":["route"],"sources":["../../src/util.ts"],"sourcesContent":["\"use client\";\nimport { RouteData } from \"./types.js\";\n\n// remove trailing slashes and index from the path\nexport const normalizeRoutePath = (path: string) => {\n for (const suffix of [\"/\", \"/index\"]) {\n if (path.endsWith(suffix)) {\n return path.slice(0, -suffix.length) || \"/\";\n }\n }\n\n return path;\n};\n\n// convert a path back to a route path\nexport const denormalizeRoutePath = (path: string) => {\n if (path === \"/\") {\n return \"index\";\n }\n\n if (path.startsWith(\"/\")) {\n return path.substring(1);\n }\n\n return path;\n};\n\nexport function getPathData(pathname: string, routes: RouteData[]) {\n const path = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n\n // path for the URL (including query string/hash)\n const normalizedPath = normalizeRoutePath(path);\n\n // we want the pathname without the query string/hash to match the route\n const url = new URL(pathname, window.location.origin);\n\n const routePathName = normalizeRoutePath(url.pathname);\n\n const route = routes.find((route) => route.path === routePathName);\n\n if (!route) {\n return null;\n }\n\n return {\n ...route,\n rsc: route.rsc,\n url: normalizedPath,\n };\n}\n"],"mappings":";;;;AAIA,MAAa,sBAAsB,SAAiB;AAClD,MAAK,MAAM,UAAU,CAAC,KAAK,SAAS,CAClC,KAAI,KAAK,SAAS,OAAO,CACvB,QAAO,KAAK,MAAM,GAAG,CAAC,OAAO,OAAO,IAAI;AAI5C,QAAO;;AAgBT,SAAgB,YAAY,UAAkB,QAAqB;CAIjE,MAAM,iBAAiB,mBAHV,SAAS,WAAW,IAAI,GAAG,WAAW,IAAI,WAGR;CAK/C,MAAM,gBAAgB,mBAFV,IAAI,IAAI,UAAU,OAAO,SAAS,OAAO,CAER,SAAS;CAEtD,MAAM,QAAQ,OAAO,MAAM,YAAUA,QAAM,SAAS,cAAc;AAElE,KAAI,CAAC,MACH,QAAO;AAGT,QAAO;EACL,GAAG;EACH,KAAK,MAAM;EACX,KAAK;EACN"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@renr/parcel-rsc-router",
3
- "version": "0.1.0-alpha.0",
3
+ "version": "0.1.0-alpha.1",
4
4
  "author": "Ren Rizzolo",
5
5
  "license": "MIT",
6
6
  "description": "Parcel rsc router",
@@ -15,11 +15,22 @@
15
15
  "type": "module",
16
16
  "main": "./src/index.ts",
17
17
  "files": [
18
- "src",
19
18
  "dist"
20
19
  ],
21
20
  "exports": {
22
- ".": "./src/index.ts"
21
+ "default": {
22
+ "types": "./dist/esm/index.d.ts",
23
+ "default": "./dist/esm/index.js"
24
+ }
25
+ },
26
+ "peerDependencies": {
27
+ "react": "^19",
28
+ "@parcel/rsc": "^2"
29
+ },
30
+ "devDependencies": {
31
+ "react": "^19.2.0",
32
+ "@types/react": "^19.2.2",
33
+ "@parcel/rsc": "^2.16.1"
23
34
  },
24
35
  "sideEffects": false,
25
36
  "publishConfig": {
package/src/index.ts CHANGED
@@ -1 +1,2 @@
1
1
  export type { RouteNode, RouteData, RoutePath, App } from "./types.js";
2
+ export { Link } from "./Link.js";
package/dist/index.js DELETED
@@ -1 +0,0 @@
1
- export { };
package/src/types.ts DELETED
@@ -1,22 +0,0 @@
1
- export namespace App {
2
- export interface Routes extends Record<string, RouteData> {}
3
- }
4
-
5
- // narrow the interface to have string keys only
6
- export type RoutePath = Exclude<keyof App.Routes, number>;
7
-
8
- export type RouteData = Omit<RouteNode, "children">;
9
-
10
- type RoutePathToSlug<T extends string> = T extends `/`
11
- ? "index"
12
- : T extends `${infer _Prefix}/${infer Slug}`
13
- ? RoutePathToSlug<Slug>
14
- : T;
15
-
16
- export interface RouteNode {
17
- children: RouteNode[];
18
- path: RoutePath;
19
- slug: RoutePathToSlug<RoutePath>;
20
- rsc: `${string}.rsc`;
21
- html: `${string}.html`;
22
- }