@xyd-js/host 0.1.0-build.158

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 xyd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ export default function DebugNull() {
2
+ return null
3
+ }
@@ -0,0 +1,69 @@
1
+ import {PageURL, Settings, Sidebar} from "@xyd-js/core";
2
+
3
+ export function docPaths(navigation: Settings['navigation']) {
4
+ if (!navigation?.sidebar) return [];
5
+
6
+ const paths: string[] = [];
7
+
8
+ if (globalThis.__xydHasIndexPage) {
9
+ paths.push("/")
10
+ }
11
+
12
+ // Process each sidebar group
13
+ navigation?.sidebar.forEach(sidebarGroup => {
14
+ if (typeof sidebarGroup === "string") {
15
+ paths.push(sidebarGroup.startsWith("/") ? sidebarGroup : `/${sidebarGroup}`)
16
+ return
17
+ }
18
+
19
+ // Add the route of the sidebar group
20
+ if ('route' in sidebarGroup) {
21
+ const route = sidebarGroup.route;
22
+ if (route) {
23
+ paths.push(`/${route}`);
24
+ }
25
+ }
26
+
27
+ // Process items in the sidebar group
28
+ if ("pages" in sidebarGroup && sidebarGroup.pages?.length) {
29
+ processSidebarItems(sidebarGroup.pages);
30
+ }
31
+ });
32
+
33
+ // Helper function to process sidebar items recursively
34
+ function processSidebarItems(items: Sidebar[] | PageURL[]) {
35
+ items.forEach(item => {
36
+ if (typeof item === 'string') {
37
+ paths.push(`/${item}`);
38
+ return
39
+ }
40
+
41
+ // Add the route of the sidebar group
42
+ if ('route' in item) {
43
+ const route = item.route;
44
+ if (route) {
45
+ paths.push(`/${route}`);
46
+ }
47
+ }
48
+
49
+ // If item has pages, process them
50
+ if ("pages" in item && item.pages?.length) {
51
+ item.pages.forEach((page) => {
52
+ if (typeof page === 'string') {
53
+ // Add the page path
54
+ paths.push(`/${page}`);
55
+ } else {
56
+ if ("virtual" in page) {
57
+ paths.push(`/${page.page}`);
58
+ } else {
59
+ // Recursively process nested pages
60
+ processSidebarItems([page]);
61
+ }
62
+ }
63
+ });
64
+ }
65
+ });
66
+ }
67
+
68
+ return paths;
69
+ }
@@ -0,0 +1,58 @@
1
+ import { startTransition, StrictMode } from "react";
2
+ import { hydrateRoot } from "react-dom/client";
3
+ import { HydratedRouter } from "react-router/dom";
4
+
5
+ // TODO: !!! BETTER !!! - needed cuz issues with rerender in react-router hash change
6
+ (() => {
7
+ var _wr = function (type: 'pushState' | 'replaceState') {
8
+ var orig = history[type];
9
+ return function (data: any, unused: string, url?: string | URL | null) {
10
+ var rv = orig.call(history, data, unused, url);
11
+ var e = new Event(type);
12
+ (e as any).arguments = arguments;
13
+ window.dispatchEvent(e);
14
+ return rv;
15
+ };
16
+ };
17
+ history.replaceState = _wr('replaceState')
18
+ })()
19
+
20
+ console.log(`+-----------------------------------------------------------------------------------------------------------------------------+
21
+ | |
22
+ | dddddddd |
23
+ | /////// d::::::d |
24
+ | /:::::/ d::::::d >>>>>>> |
25
+ | /:::::/ d::::::d >:::::> |
26
+ | /:::::/ d::::::d >:::::> |
27
+ | /:::::/ xxxxxxx xxxxxxx yyyyyyy yyyyyyy ddddddddd:::::d >:::::> |
28
+ | /:::::/ x:::::x x:::::x y:::::y y:::::y dd::::::::::::::d >:::::> |
29
+ | /:::::/ x:::::x x:::::x y:::::y y:::::y d::::::::::::::::d >:::::> |
30
+ | /:::::/ x:::::xx:::::x y:::::y y:::::y d:::::::ddddd:::::d >:::::>|
31
+ | /:::::/ x::::::::::x y:::::y y:::::y d::::::d d:::::d >:::::> |
32
+ | /:::::/ x::::::::x y:::::y y:::::y d:::::d d:::::d >:::::> |
33
+ | /:::::/ x::::::::x y:::::y:::::y d:::::d d:::::d >:::::> |
34
+ | /:::::/ x::::::::::x y:::::::::y d:::::d d:::::d >:::::> |
35
+ | /:::::/ x:::::xx:::::x y:::::::y d::::::ddddd::::::dd >:::::> |
36
+ | /:::::/ x:::::x x:::::x y:::::y d:::::::::::::::::d >>>>>>> |
37
+ | /:::::/ x:::::x x:::::x y:::::y d:::::::::ddd::::d |
38
+ |/////// xxxxxxx xxxxxxx y:::::y ddddddddd ddddd |
39
+ | y:::::y |
40
+ | y:::::y |
41
+ | y:::::y |
42
+ | y:::::y |
43
+ | yyyyyyy |
44
+ | |
45
+ | |
46
+ | Check out https://github.com/livesession/xyd |
47
+ +-----------------------------------------------------------------------------------------------------------------------------+
48
+ `)
49
+
50
+
51
+ startTransition(() => {
52
+ hydrateRoot(
53
+ document,
54
+ <StrictMode>
55
+ <HydratedRouter />
56
+ </StrictMode>
57
+ );
58
+ });
@@ -0,0 +1,68 @@
1
+ import { PassThrough } from "node:stream";
2
+
3
+ import type { AppLoadContext, EntryContext } from "react-router";
4
+ import { createReadableStreamFromReadable } from "@react-router/node";
5
+ import { ServerRouter } from "react-router";
6
+ import { isbot } from "isbot";
7
+ import type { RenderToPipeableStreamOptions } from "react-dom/server";
8
+ import { renderToPipeableStream } from "react-dom/server";
9
+
10
+ export const streamTimeout = 5_000;
11
+
12
+ export default function handleRequest(
13
+ request: Request,
14
+ responseStatusCode: number,
15
+ responseHeaders: Headers,
16
+ routerContext: EntryContext,
17
+ loadContext: AppLoadContext
18
+ ) {
19
+ return new Promise((resolve, reject) => {
20
+ let shellRendered = false;
21
+ let userAgent = request.headers.get("user-agent");
22
+
23
+ // Ensure requests from bots and SPA Mode renders wait for all content to load before responding
24
+ // https://react.dev/reference/react-dom/server/renderToPipeableStream#waiting-for-all-content-to-load-for-crawlers-and-static-generation
25
+ let readyOption: keyof RenderToPipeableStreamOptions =
26
+ (userAgent && isbot(userAgent)) || routerContext.isSpaMode
27
+ ? "onAllReady"
28
+ : "onShellReady";
29
+
30
+ const { pipe, abort } = renderToPipeableStream(
31
+ <ServerRouter context={routerContext} url={request.url} />,
32
+ {
33
+ [readyOption]() {
34
+ shellRendered = true;
35
+ const body = new PassThrough();
36
+ const stream = createReadableStreamFromReadable(body);
37
+
38
+ responseHeaders.set("Content-Type", "text/html");
39
+
40
+ resolve(
41
+ new Response(stream, {
42
+ headers: responseHeaders,
43
+ status: responseStatusCode,
44
+ })
45
+ );
46
+
47
+ pipe(body);
48
+ },
49
+ onShellError(error: unknown) {
50
+ reject(error);
51
+ },
52
+ onError(error: unknown) {
53
+ responseStatusCode = 500;
54
+ // Log streaming rendering errors from inside the shell. Don't log
55
+ // errors encountered during initial shell rendering since they'll
56
+ // reject and get logged in handleDocumentRequest.
57
+ if (shellRendered) {
58
+ console.error(error);
59
+ }
60
+ },
61
+ }
62
+ );
63
+
64
+ // Abort the rendering stream after the `streamTimeout` so it has tine to
65
+ // flush down the rejected boundaries
66
+ setTimeout(abort, streamTimeout + 1000);
67
+ });
68
+ }
@@ -0,0 +1,86 @@
1
+ import path from "node:path";
2
+
3
+ import { RouteConfigEntry, index } from "@react-router/dev/routes";
4
+
5
+ import { Settings, SidebarNavigation } from "@xyd-js/core";
6
+ import { layout, route } from "@react-router/dev/routes";
7
+
8
+ type Route = {
9
+ id: string
10
+ path: string
11
+ }
12
+
13
+ // Helper function to recursively extract route definitions from nested pages
14
+ export function pathRoutes(basePath: string, navigation: Settings['navigation']) {
15
+ if (!navigation?.sidebar) return [];
16
+
17
+ const routes: Route[] = [];
18
+
19
+ // Process each sidebar group
20
+ extractNestedRoutes(navigation.sidebar || [], routes)
21
+
22
+ if (!routes.length) {
23
+ const rrRoutes: RouteConfigEntry[] = []
24
+ if (globalThis.__xydHasIndexPage) {
25
+ rrRoutes.push(
26
+ index(path.join(basePath, "src/pages/page.tsx"))
27
+ )
28
+ } else {
29
+ rrRoutes.push(
30
+ route("/*", path.join(basePath, "src/pages/page.tsx"))
31
+ )
32
+ }
33
+
34
+ return [
35
+ layout(path.join(basePath, "src/pages/layout.tsx"), [
36
+ ...rrRoutes
37
+ ])
38
+ ]
39
+ }
40
+
41
+ const rrRoutes: RouteConfigEntry[] = []
42
+ if (globalThis.__xydHasIndexPage) {
43
+ rrRoutes.push(
44
+ layout(path.join(basePath, "src/pages/layout.tsx"), { id: `layout:index` }, [
45
+ index(path.join(basePath, "src/pages/page.tsx"))
46
+ ])
47
+ )
48
+ }
49
+
50
+ return [
51
+ ...rrRoutes,
52
+ ...routes.map(r => {
53
+ return layout(path.join(basePath, "src/pages/layout.tsx"), { id: `layout:${r.id}` }, [
54
+ route(r.path, path.join(basePath, "src/pages/page.tsx"), { id: r.id })
55
+ ])
56
+ })
57
+ ]
58
+ }
59
+
60
+
61
+ function extractNestedRoutes(
62
+ sidebarItems: SidebarNavigation,
63
+ routes: Route[],
64
+ parentRoute?: string,
65
+ ) {
66
+ sidebarItems.forEach(item => {
67
+ if (item && typeof item === "object") {
68
+ let route = ""
69
+
70
+ // Only extract routes from items that have a "route" property
71
+ if ('route' in item && item.route) {
72
+ route = item.route
73
+ const routeMatch = item.route.startsWith("/") ? item.route : `/${item.route}`;
74
+ routes.push({ id: routeMatch, path: routeMatch + "/*" });
75
+ }
76
+
77
+ // Recursively process nested pages within this route
78
+ if (item.pages && Array.isArray(item.pages)) {
79
+ extractNestedRoutes(item.pages as SidebarNavigation, routes, route || parentRoute)
80
+ }
81
+ } else if (!parentRoute) {
82
+ const page = item.startsWith("/") ? item : `/${item}`;
83
+ routes.push({ id: page, path: page });
84
+ }
85
+ });
86
+ }
package/app/public.ts ADDED
@@ -0,0 +1,43 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs/promises";
3
+
4
+ import { redirect } from "react-router";
5
+
6
+ const MIME_TYPES: Record<string, string> = {
7
+ '.html': 'text/html',
8
+ '.css': 'text/css',
9
+ '.js': 'text/javascript',
10
+ '.json': 'application/json',
11
+ '.png': 'image/png',
12
+ '.jpg': 'image/jpeg',
13
+ '.jpeg': 'image/jpeg',
14
+ '.webp': 'image/webp',
15
+ '.gif': 'image/gif',
16
+ '.svg': 'image/svg+xml',
17
+ '.ico': 'image/x-icon',
18
+ '.txt': 'text/plain',
19
+ };
20
+
21
+ const BINARY_FILE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.gif', '.ico', '.webp'];
22
+
23
+ export async function loader({ params }: any) {
24
+ const filePath = path.join(process.cwd(), "public", params["*"])
25
+
26
+ try {
27
+ await fs.access(filePath)
28
+ } catch (e) {
29
+ return redirect("/404")
30
+ }
31
+
32
+ const ext = path.extname(filePath).toLowerCase();
33
+ const isBinaryFile = BINARY_FILE_EXTENSIONS.includes(ext);
34
+ const fileContent = await fs.readFile(filePath, isBinaryFile ? null : 'utf-8');
35
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
36
+
37
+ return new Response(fileContent, {
38
+ status: 200,
39
+ headers: {
40
+ 'Content-Type': contentType,
41
+ },
42
+ });
43
+ }
package/app/raw.ts ADDED
@@ -0,0 +1,31 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs/promises";
3
+
4
+ import { redirect } from "react-router";
5
+
6
+ const MIME_TYPES: Record<string, string> = {
7
+ '.md': 'text/markdown',
8
+ '.mdx': 'text/markdown',
9
+ };
10
+
11
+ // TODO: !!! FINISH !!!
12
+ export async function loader({ params }: any) {
13
+ const filePath = path.join(process.cwd(), "/docs/guides/quickstart.md")
14
+
15
+ try {
16
+ await fs.access(filePath)
17
+ } catch (e) {
18
+ return redirect("/404")
19
+ }
20
+
21
+ const ext = path.extname(filePath).toLowerCase();
22
+ const fileContent = await fs.readFile(filePath, 'utf-8');
23
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
24
+
25
+ return new Response(fileContent, {
26
+ status: 200,
27
+ headers: {
28
+ 'Content-Type': contentType,
29
+ },
30
+ });
31
+ }
package/app/robots.ts ADDED
@@ -0,0 +1,18 @@
1
+ export async function loader({ request }: { request: Request }) {
2
+ const baseUrl = __xydSettings?.seo?.domain || new URL(request.url).origin;
3
+
4
+ // Generate robots.txt content
5
+ const content = `# https://www.robotstxt.org/robotstxt.html
6
+ User-agent: *
7
+ Allow: /
8
+
9
+ # Sitemap
10
+ Sitemap: ${baseUrl}/sitemap.xml`;
11
+
12
+ return new Response(content, {
13
+ headers: {
14
+ 'Content-Type': 'text/plain',
15
+ 'Cache-Control': 'public, max-age=3600'
16
+ }
17
+ });
18
+ }