@teyik0/furin 0.1.0-alpha.12 → 0.1.0-alpha.13

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,187 @@
1
+ import type { HeadOptions, MetaDescriptor } from "../client.ts";
2
+
3
+ export function extractTitle(meta?: MetaDescriptor[]): string | undefined {
4
+ if (!meta) {
5
+ return;
6
+ }
7
+ for (const entry of meta) {
8
+ if ("title" in entry) {
9
+ return (entry as { title: string }).title;
10
+ }
11
+ }
12
+ return;
13
+ }
14
+
15
+ export function isMetaTag(entry: MetaDescriptor): boolean {
16
+ return !(
17
+ "title" in entry ||
18
+ "charSet" in entry ||
19
+ "script:ld+json" in entry ||
20
+ "tagName" in entry
21
+ );
22
+ }
23
+
24
+ export function escapeHtml(str: string): string {
25
+ return str
26
+ .replace(/&/g, "&")
27
+ .replace(/</g, "&lt;")
28
+ .replace(/>/g, "&gt;")
29
+ .replace(/"/g, "&quot;")
30
+ .replace(/'/g, "&#039;");
31
+ }
32
+
33
+ export function safeJson(value: unknown): string {
34
+ return JSON.stringify(value)
35
+ .replace(/</g, "\\u003c")
36
+ .replace(/>/g, "\\u003e")
37
+ .replace(/\u2028/g, "\\u2028")
38
+ .replace(/\u2029/g, "\\u2029");
39
+ }
40
+
41
+ export function renderAttrs(obj: Record<string, string | undefined>): string {
42
+ return Object.entries(obj)
43
+ .filter(([, v]) => v !== undefined)
44
+ .map(([k, v]) => `${k}="${escapeHtml(String(v))}"`)
45
+ .join(" ");
46
+ }
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // Head injection helpers
50
+ // ---------------------------------------------------------------------------
51
+
52
+ export function buildMetaParts(meta: MetaDescriptor[]): string[] {
53
+ const parts: string[] = [];
54
+ const title = extractTitle(meta);
55
+ if (title) {
56
+ parts.push(`<title>${escapeHtml(title)}</title>`);
57
+ }
58
+ for (const m of meta) {
59
+ if (isMetaTag(m)) {
60
+ parts.push(`<meta ${renderAttrs(m as Record<string, string>)} />`);
61
+ }
62
+ if ("script:ld+json" in m) {
63
+ parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
64
+ }
65
+ }
66
+ return parts;
67
+ }
68
+
69
+ export function buildLinkParts(links: NonNullable<HeadOptions["links"]>): string[] {
70
+ return links.map((link) => `<link ${renderAttrs(link)} />`);
71
+ }
72
+
73
+ export function buildScriptParts(scripts: NonNullable<HeadOptions["scripts"]>): string[] {
74
+ return scripts.map((script) => {
75
+ const { children, ...rest } = script;
76
+ const attrs = renderAttrs(rest as Record<string, string | undefined>);
77
+ if (children) {
78
+ return `<script ${attrs}>${children}</script>`;
79
+ }
80
+ return `<script ${attrs}></script>`;
81
+ });
82
+ }
83
+
84
+ export function buildStyleParts(styles: NonNullable<HeadOptions["styles"]>): string[] {
85
+ return styles.map((style) => {
86
+ const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
87
+ return `<style${typeAttr}>${style.children}</style>`;
88
+ });
89
+ }
90
+
91
+ /**
92
+ * Builds the string to inject into the <!--ssr-head--> placeholder.
93
+ * Handles title, meta tags, links, inline scripts, and inline styles from
94
+ * the page's `head()` function. CSS is handled by Bun (imported in user files).
95
+ */
96
+ export function buildHeadInjection(headData: HeadOptions | undefined): string {
97
+ const parts: string[] = [];
98
+
99
+ if (headData?.meta) {
100
+ parts.push(...buildMetaParts(headData.meta));
101
+ }
102
+
103
+ if (headData?.links) {
104
+ parts.push(...buildLinkParts(headData.links));
105
+ }
106
+
107
+ if (headData?.scripts) {
108
+ parts.push(...buildScriptParts(headData.scripts));
109
+ }
110
+
111
+ if (headData?.styles) {
112
+ parts.push(...buildStyleParts(headData.styles));
113
+ }
114
+
115
+ return parts.length > 0 ? `\n ${parts.join("\n ")}\n` : "";
116
+ }
117
+
118
+ /**
119
+ * Inline script that synchronously applies the persisted theme class to <html>
120
+ * before the first paint, preventing a flash of unstyled content (FOUC).
121
+ * Reads the `furin-theme` key from localStorage; defaults to "dark" on error.
122
+ */
123
+ const THEME_INIT_SCRIPT =
124
+ `<script>try{var __t=localStorage.getItem("furin-theme");` +
125
+ `document.documentElement.classList.add(__t==="light"?"light":"dark")}` +
126
+ `catch(e){document.documentElement.classList.add("dark")}</script>`;
127
+
128
+ export function generateIndexHtml(): string {
129
+ return `<!DOCTYPE html>
130
+ <html lang="en">
131
+ <head>
132
+ <meta charset="UTF-8">
133
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
134
+ ${THEME_INIT_SCRIPT}
135
+ <!--ssr-head-->
136
+ </head>
137
+ <body>
138
+ <div id="root"><!--ssr-outlet--></div>
139
+ <script type="module" src="./_hydrate.tsx"></script>
140
+ </body>
141
+ </html>
142
+ `;
143
+ }
144
+
145
+ /**
146
+ * Generates the production SSR template (index.html) with hashed asset paths.
147
+ * Called after Bun.build() completes so we can inject the correct entry chunk
148
+ * and CSS paths derived from result.outputs.
149
+ *
150
+ * @param buildId - Short hash identifying this specific build. Injected as a
151
+ * `<meta name="furin-build-id">` tag so the client can detect stale deploys.
152
+ * @param faviconHref - Absolute href for the favicon (e.g. "/furin/favicon.ico").
153
+ * When provided, a `<link rel="icon">` tag is injected so browsers can locate
154
+ * the favicon even when the site is served from a sub-path.
155
+ */
156
+ export function generateProdIndexHtml(
157
+ entryChunk: string,
158
+ cssChunks: string[],
159
+ buildId?: string,
160
+ faviconHref?: string
161
+ ): string {
162
+ const cssLinks = cssChunks
163
+ .map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`)
164
+ .join("\n");
165
+ const scriptTag = `<script type="module" crossorigin src="${entryChunk}"></script>`;
166
+ const buildIdMeta = buildId
167
+ ? ` <meta name="furin-build-id" content="${escapeHtml(buildId)}">\n`
168
+ : "";
169
+ const faviconLink = faviconHref
170
+ ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">\n`
171
+ : "";
172
+
173
+ return `<!DOCTYPE html>
174
+ <html lang="en">
175
+ <head>
176
+ <meta charset="UTF-8">
177
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
178
+ ${THEME_INIT_SCRIPT}
179
+ ${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
180
+ </head>
181
+ <body>
182
+ <div id="root"><!--ssr-outlet--></div>
183
+ ${scriptTag}
184
+ </body>
185
+ </html>
186
+ `;
187
+ }
@@ -312,7 +312,8 @@ export interface CacheEntry {
312
312
  }
313
313
  /** @internal Exported for unit testing only. */
314
314
  export declare function shouldRefetch(entry: CacheEntry): boolean;
315
- /** Strips trailing slashes from a pathname or href. Root `/` is preserved. */
315
+ /** Strips trailing slashes from a pathname or href. Root `/` is preserved.
316
+ * Query strings and hashes are preserved and re-attached after normalization. */
316
317
  export declare function normalizeHref(href: string): string;
317
318
  /**
318
319
  * Classification of a fetch response during SPA navigation. Returned by the
package/dist/router.js CHANGED
@@ -1387,7 +1387,7 @@ function computeLinkView({
1387
1387
  const logicalHrefWithoutHash = buildHref(to, search, undefined);
1388
1388
  const isAbsolute = logicalHref.startsWith("http://") || logicalHref.startsWith("https://") || logicalHref.startsWith("//");
1389
1389
  const href = isAbsolute ? logicalHref : router.basePath + logicalHref;
1390
- const isActive = router.currentHref === logicalHrefWithoutHash;
1390
+ const isActive = !isAbsolute && router.currentHref === normalizeHref(logicalHrefWithoutHash);
1391
1391
  const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
1392
1392
  const extraProps = {
1393
1393
  ...inactiveProps && !isActive ? inactiveProps() : {},
@@ -1990,6 +1990,14 @@ function useRouter() {
1990
1990
  defaultPreloadStaleTime: 30000
1991
1991
  };
1992
1992
  }
1993
+ function normalizeHref(href) {
1994
+ const url = new URL(href, "http://localhost");
1995
+ let pathname = url.pathname;
1996
+ if (pathname !== "/") {
1997
+ pathname = pathname.replace(/\/+$/g, "");
1998
+ }
1999
+ return pathname + url.search + url.hash;
2000
+ }
1993
2001
 
1994
2002
  // src/render/element.tsx
1995
2003
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
@@ -2218,7 +2226,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
2218
2226
  }
2219
2227
  const ssrContext = {
2220
2228
  basePath: basePath ?? "",
2221
- currentHref: ctx.path,
2229
+ currentHref: normalizeHref(ctx.path),
2222
2230
  navigate: () => Promise.resolve(),
2223
2231
  prefetch: () => {},
2224
2232
  invalidatePrefetch: () => {},