htmx-router 1.0.0-pre1 → 1.0.0-pre2

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 (66) hide show
  1. package/cli/config.d.ts +13 -0
  2. package/cli/config.js +11 -0
  3. package/cli/index.d.ts +2 -0
  4. package/cli/index.js +38 -0
  5. package/cookies.d.ts +29 -0
  6. package/cookies.js +80 -0
  7. package/css.d.ts +21 -0
  8. package/css.js +60 -0
  9. package/defer.d.ts +14 -0
  10. package/defer.js +80 -0
  11. package/endpoint.d.ts +20 -0
  12. package/endpoint.js +40 -0
  13. package/event-source.d.ts +26 -0
  14. package/event-source.js +116 -0
  15. package/index.d.ts +19 -0
  16. package/index.js +2 -0
  17. package/internal/client.d.ts +1 -0
  18. package/internal/client.js +14 -0
  19. package/internal/compile/manifest.d.ts +1 -0
  20. package/internal/compile/manifest.js +179 -0
  21. package/internal/component/defer.d.ts +4 -0
  22. package/internal/component/defer.js +19 -0
  23. package/internal/component/head.d.ts +5 -0
  24. package/internal/component/head.js +22 -0
  25. package/internal/component/index.d.ts +4 -0
  26. package/internal/component/index.js +4 -0
  27. package/internal/component/scripts.d.ts +4 -0
  28. package/internal/component/scripts.js +23 -0
  29. package/internal/mount.d.ts +10 -0
  30. package/internal/mount.js +88 -0
  31. package/internal/request/http.d.ts +10 -0
  32. package/internal/request/http.js +61 -0
  33. package/internal/request/index.d.ts +17 -0
  34. package/internal/request/index.js +8 -0
  35. package/internal/request/native.d.ts +9 -0
  36. package/internal/request/native.js +48 -0
  37. package/internal/router.d.ts +15 -0
  38. package/internal/router.js +24 -0
  39. package/internal/util.d.ts +4 -0
  40. package/internal/util.js +49 -0
  41. package/package.json +1 -1
  42. package/response.d.ts +13 -0
  43. package/response.js +46 -0
  44. package/router.d.ts +33 -0
  45. package/router.js +206 -0
  46. package/shell.d.ts +120 -0
  47. package/shell.js +261 -0
  48. package/util/parameters.d.ts +10 -0
  49. package/util/parameters.js +1 -0
  50. package/util/path-builder.d.ts +1 -0
  51. package/util/path-builder.js +45 -0
  52. package/util/route.d.ts +2 -0
  53. package/util/route.js +58 -0
  54. package/vite/bundle-splitter.d.ts +4 -0
  55. package/vite/bundle-splitter.js +26 -0
  56. package/vite/client-island.d.ts +4 -0
  57. package/vite/client-island.js +14 -0
  58. package/vite/index.d.ts +3 -0
  59. package/vite/index.js +3 -0
  60. package/vite/router.d.ts +2 -0
  61. package/vite/router.js +29 -0
  62. package/example/eventdim-react/package.json +0 -67
  63. package/example/eventdim-react/server.js +0 -90
  64. package/example/island-react/global.d.ts +0 -8
  65. package/example/island-react/package.json +0 -38
  66. package/example/island-react/server.js +0 -58
@@ -0,0 +1,179 @@
1
+ import { init, parse } from "es-module-lexer";
2
+ import { CutString, ServerOnlyWarning } from "../util.js";
3
+ ServerOnlyWarning("manifest-compiler");
4
+ export function CompileManifest(adapter, source, ssr) {
5
+ const imported = ParseImports(source);
6
+ if (ssr)
7
+ return BuildServerManifest(adapter, imported);
8
+ return BuildClientManifest(adapter, imported);
9
+ ;
10
+ }
11
+ await init; // ensure the webassembly module is ready
12
+ function ParseImports(source) {
13
+ const parsed = parse(source)[0];
14
+ const out = [];
15
+ for (const imported of parsed) {
16
+ if (imported.a !== -1)
17
+ continue;
18
+ if (imported.t !== 1)
19
+ continue;
20
+ const href = source.slice(imported.s, imported.e);
21
+ if (href === "htmx-router")
22
+ continue;
23
+ const front = source.slice(imported.ss, imported.s);
24
+ const start = front.indexOf("{");
25
+ if (start === -1) {
26
+ const middle = CutString(CutString(front, "import")[1], "from", -1)[0];
27
+ out.push({ mapping: ExtractName(middle), href });
28
+ continue;
29
+ }
30
+ const end = front.lastIndexOf("}");
31
+ const middle = front.slice(start + 1, end);
32
+ const segments = middle.split(",");
33
+ out.push({ mapping: segments.map(ExtractName), href });
34
+ }
35
+ return out;
36
+ }
37
+ function ExtractName(str) {
38
+ const parts = CutString(str, " as ");
39
+ if (parts[1].length !== 0)
40
+ return { name: parts[1].trim(), original: parts[0].trim() };
41
+ const name = parts[0].trim();
42
+ return { name, original: name };
43
+ }
44
+ function BuildServerManifest(type, imported) {
45
+ const names = new Array();
46
+ for (const imp of imported) {
47
+ if (Array.isArray(imp.mapping))
48
+ names.push(...imp.mapping.map(x => x.name));
49
+ else
50
+ names.push(imp.mapping.name);
51
+ }
52
+ let out = "/* eslint-disable @typescript-eslint/no-explicit-any */\n";
53
+ for (const imp of imported) {
54
+ out += "import ";
55
+ if (!Array.isArray(imp.mapping)) {
56
+ out += ImportNameSource(imp.mapping) + " ";
57
+ }
58
+ else {
59
+ let first = true;
60
+ out += "{ ";
61
+ for (const name of imp.mapping) {
62
+ if (first)
63
+ first = false;
64
+ else
65
+ out += ", ";
66
+ out += ImportNameSource(name);
67
+ }
68
+ out += " } ";
69
+ }
70
+ out += `from "${imp.href}";\n`;
71
+ }
72
+ out += `\nimport { StyleClass } from "htmx-router/css";\n`
73
+ + `const island = new StyleClass("i", ".this{display:contents;}\\n").name;\n\n`
74
+ + "type FirstArg<T> = T extends (arg: infer U, ...args: any[]) => any ? U : never;\n"
75
+ + "function mount(name: string, data: string, ssr?: JSX.Element) {\n"
76
+ + "\treturn (<>\n"
77
+ + `\t\t<div className={island}>{ssr}</div>\n`
78
+ + `\t\t${SafeScript(type, "`Router.mountAboveWith('${name}', ${data})`")}\n`
79
+ + "\t</>);\n"
80
+ + "}\n"
81
+ + "\n"
82
+ + "const Client = {\n";
83
+ for (const name of names) {
84
+ out += `\t${name}: function(props: FirstArg<typeof ${name}> & { children?: JSX.Element }) {\n`
85
+ + `\t\tconst { children, ...rest } = props;\n`
86
+ + `\t\treturn mount("${name}", JSON.stringify(rest), children);\n`
87
+ + `\t},\n`;
88
+ }
89
+ out += "}\nexport default Client;";
90
+ return out;
91
+ }
92
+ function ImportNameSource(name) {
93
+ if (name.original === name.name)
94
+ return name.name;
95
+ return `${name.original} as ${name.name}`;
96
+ }
97
+ function SafeScript(type, script) {
98
+ switch (type) {
99
+ case "react": return `<script dangerouslySetInnerHTML={{__html: ${script}}}></script>`;
100
+ default: return `<script>${script}</script>`;
101
+ }
102
+ }
103
+ function BuildClientManifest(type, imports) {
104
+ const bind = binding[type];
105
+ if (!bind)
106
+ throw new Error(`Unsupported client adapter ${type}`);
107
+ let out = "/* eslint-disable @typescript-eslint/no-explicit-any */\n\n";
108
+ out += "const client = {\n";
109
+ for (const imported of imports) {
110
+ if (Array.isArray(imported.mapping)) {
111
+ for (const map of imported.mapping) {
112
+ out += `\t${map.name}: async (element: HTMLElement, props: any) => {\n`
113
+ + `\t\tconst C = (await import("${imported.href}")).${map.original};\n`
114
+ + bind.mount
115
+ + `\n\t},\n`;
116
+ }
117
+ }
118
+ else {
119
+ out += `\t${imported.mapping.name}: async (element: HTMLElement, props: any) => {\n`
120
+ + `\t\tconst C = (await import("${imported.href}")).default;\n`
121
+ + bind.mount
122
+ + `\n\t},\n`;
123
+ }
124
+ }
125
+ out += "}\nexport default client;\n"
126
+ + "(window as any).CLIENT = client;\n\n";
127
+ out += bind.unmount;
128
+ out += cleanup;
129
+ return out;
130
+ }
131
+ const binding = {
132
+ react: {
133
+ mount: '\t\tconst d = await import("react-dom/client");\n'
134
+ + '\t\tconst r = d.createRoot(element);\n'
135
+ + '\t\tr.render(<C {...props} />);\n'
136
+ + '\t\tmounted.set(element, r);',
137
+ unmount: `
138
+ import type { Root } from "react-dom/client";
139
+ const mounted = new Map<HTMLElement, Root>();
140
+ function Unmount(node: HTMLElement, root: Root) {
141
+ mounted.delete(node);
142
+ root.unmount();
143
+ }`
144
+ }
145
+ };
146
+ const cleanup = `
147
+
148
+ const limbo = new Set<Node>();
149
+ let queued = false;
150
+ const observer = new MutationObserver((mutations) => {
151
+ for (const mut of mutations) {
152
+ for (const node of mut.removedNodes) limbo.add(node);
153
+ for (const node of mut.addedNodes) limbo.delete(node);
154
+ }
155
+
156
+ if (!queued) {
157
+ queueMicrotask(Cleanup);
158
+ queued = true;
159
+ }
160
+ });
161
+ observer.observe(document.body, { childList: true, subtree: true });
162
+
163
+ function Cleanup() {
164
+ queued = false;
165
+ for (const elm of limbo) CleanNode(elm);
166
+ limbo.clear();
167
+ }
168
+
169
+ function CleanNode(node: Node) {
170
+ if (node instanceof HTMLElement) {
171
+ const root = mounted.get(node);
172
+ if (root) {
173
+ console.info("unmounting", node);
174
+ Unmount(node, root);
175
+ }
176
+ }
177
+
178
+ for (const child of node.childNodes) CleanNode(child);
179
+ }`;
@@ -0,0 +1,4 @@
1
+ declare const _default: {
2
+ "*": string;
3
+ };
4
+ export default _default;
@@ -0,0 +1,19 @@
1
+ const generic = `import { Parameterized, ParameterShaper } from "htmx-router/util/parameters";
2
+ import { RenderFunction } from "htmx-router";
3
+ import { Deferral } from "htmx-router/dynamic";
4
+
5
+ export function Defer<T extends ParameterShaper>(props: {
6
+ params?: Parameterized<T>,
7
+ loader: RenderFunction<T>,
8
+ children?: JSX.Element
9
+ }): JSX.Element {
10
+ return <div
11
+ hx-get={Deferral(props.loader, props.params)}
12
+ hx-trigger="load"
13
+ hx-swap="outerHTML transition:true"
14
+ style={{ display: "contents" }}
15
+ >{props.children ? props.children : ""}</div>
16
+ }`;
17
+ export default {
18
+ "*": generic
19
+ };
@@ -0,0 +1,5 @@
1
+ declare const _default: {
2
+ "*": string;
3
+ react: string;
4
+ };
5
+ export default _default;
@@ -0,0 +1,22 @@
1
+ const generic = `import { RenderMetaDescriptor, ShellOptions } from "htmx-router/shell";
2
+
3
+ export function Head<T>(props: { options: ShellOptions<T>, children: JSX.Element }) {
4
+ return <head>
5
+ { RenderMetaDescriptor(props.options) as "safe" }
6
+ { props.children as "safe" }
7
+ </head>;
8
+ }`;
9
+ const react = `import { RenderMetaDescriptor, ShellOptions } from "htmx-router/shell";
10
+ import { renderToString } from 'react-dom/server';
11
+ import { ReactNode } from "react";
12
+
13
+ export function Head<T>(props: { options: ShellOptions<T>, children: ReactNode }) {
14
+ const body = RenderMetaDescriptor(props.options)
15
+ + renderToString(props.children);
16
+
17
+ return <head dangerouslySetInnerHTML={{ __html: body }}></head>;
18
+ }`;
19
+ export default {
20
+ "*": generic,
21
+ react
22
+ };
@@ -0,0 +1,4 @@
1
+ import defer from "./defer.js";
2
+ import scripts from "./scripts.js";
3
+ import head from "./head.js";
4
+ export { defer, head, scripts };
@@ -0,0 +1,4 @@
1
+ import defer from "./defer.js";
2
+ import scripts from "./scripts.js";
3
+ import head from "./head.js";
4
+ export { defer, head, scripts };
@@ -0,0 +1,4 @@
1
+ declare const _default: {
2
+ "*": string;
3
+ };
4
+ export default _default;
@@ -0,0 +1,23 @@
1
+ const generic = `import { GetClientEntryURL } from 'htmx-router/internal/client';
2
+ import { GetMountUrl } from 'htmx-router/internal/mount';
3
+ import { GetSheetUrl } from 'htmx-router/css';
4
+
5
+ let cache: JSX.Element | null = null;
6
+ const isProduction = process.env.NODE_ENV === "production";
7
+ const clientEntry = await GetClientEntryURL();
8
+ export function Scripts() {
9
+ if (cache) return cache;
10
+
11
+ const res = <>
12
+ <link href={GetSheetUrl()} rel="stylesheet"></link>
13
+ { isProduction ? "" : <script type="module" src="/@vite/client"></script> }
14
+ <script type="module" src={clientEntry}></script>
15
+ <script src={GetMountUrl()}></script>
16
+ </>;
17
+
18
+ if (isProduction) cache = res;
19
+ return res;
20
+ }`;
21
+ export default {
22
+ "*": generic
23
+ };
@@ -0,0 +1,10 @@
1
+ import { RouteContext } from "../index.js";
2
+ export declare function GetMountUrl(): string;
3
+ /**
4
+ * RouteTree mounting point
5
+ */
6
+ export declare const path = "_/mount/$hash";
7
+ export declare const parameters: {
8
+ hash: StringConstructor;
9
+ };
10
+ export declare function loader(ctx: RouteContext<typeof parameters>): Promise<Response | null>;
@@ -0,0 +1,88 @@
1
+ import { ServerOnlyWarning } from "./util.js";
2
+ ServerOnlyWarning("client-mounter");
3
+ import { CutString, QuickHash } from "./util.js";
4
+ // this function simply exists so it can be stringified and written into the client js bundle
5
+ function ClientMounter() {
6
+ const theme = {
7
+ get: () => {
8
+ return (localStorage.getItem("theme") || theme.infer());
9
+ },
10
+ infer: () => {
11
+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
12
+ const current = prefersDark ? 'dark' : 'light';
13
+ localStorage.setItem("theme", current);
14
+ return current;
15
+ },
16
+ apply: () => {
17
+ document.documentElement.setAttribute('data-theme', theme.get());
18
+ },
19
+ toggle: () => {
20
+ if (theme.get() === "dark")
21
+ localStorage.setItem("theme", "light");
22
+ else
23
+ localStorage.setItem("theme", "dark");
24
+ theme.apply();
25
+ return localStorage.getItem("theme");
26
+ }
27
+ };
28
+ window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
29
+ theme.infer();
30
+ theme.apply();
31
+ });
32
+ theme.apply();
33
+ const global = window;
34
+ const mountRequests = new Array();
35
+ function RequestMount(funcName, json) {
36
+ const elm = document.currentScript.previousElementSibling;
37
+ if (elm.hasAttribute("mounted"))
38
+ return;
39
+ mountRequests.push([funcName, elm, json]);
40
+ }
41
+ function Mount() {
42
+ if (mountRequests.length < 1)
43
+ return;
44
+ if (!global.CLIENT)
45
+ throw new Error("Client manifest missing");
46
+ for (const [funcName, element, json] of mountRequests) {
47
+ console.info("hydrating", funcName, "into", element);
48
+ const func = global.CLIENT[funcName];
49
+ if (!func)
50
+ throw new Error(`Component ${funcName} is missing from client manifest`);
51
+ func(element, json);
52
+ element.setAttribute("mounted", "yes");
53
+ }
54
+ mountRequests.length = 0;
55
+ }
56
+ document.addEventListener("DOMContentLoaded", Mount);
57
+ document.addEventListener("htmx:load", Mount);
58
+ return {
59
+ mountAboveWith: RequestMount,
60
+ theme
61
+ };
62
+ }
63
+ ;
64
+ const script = "window.Router = (function () {"
65
+ + CutString(ClientMounter.toString(), "{")[1]
66
+ + ")();";
67
+ const hash = QuickHash(script);
68
+ export function GetMountUrl() {
69
+ return `/_/mount/${hash}.js`;
70
+ }
71
+ /**
72
+ * RouteTree mounting point
73
+ */
74
+ export const path = "_/mount/$hash";
75
+ export const parameters = {
76
+ hash: String
77
+ };
78
+ export async function loader(ctx) {
79
+ if (!ctx.params.hash)
80
+ return null;
81
+ // const build = GetSheet();
82
+ if (!ctx.params.hash.startsWith(hash))
83
+ return null;
84
+ const headers = new Headers();
85
+ headers.set("Content-Type", "text/javascript");
86
+ headers.set("Cache-Control", "public, max-age=604800");
87
+ return new Response(script, { headers });
88
+ }
@@ -0,0 +1,10 @@
1
+ import type { IncomingMessage, ServerResponse } from "http";
2
+ import type { ViteDevServer } from "vite";
3
+ import type { GenericContext } from "../router.js";
4
+ type Config = {
5
+ build: Promise<any> | (() => Promise<Record<string, any>>);
6
+ viteDevServer: ViteDevServer | null;
7
+ render: GenericContext["render"];
8
+ };
9
+ export declare function createRequestHandler(config: Config): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
10
+ export {};
@@ -0,0 +1,61 @@
1
+ import { ServerOnlyWarning } from "../util.js";
2
+ ServerOnlyWarning("http-request");
3
+ import { Resolve } from "./native.js";
4
+ export function createRequestHandler(config) {
5
+ return async (req, res) => {
6
+ try {
7
+ const mod = typeof config.build === "function" ? await config.build() : await config.build;
8
+ const request = NativeRequest(req);
9
+ let { response, headers } = await Resolve(request, mod.tree, config);
10
+ res.writeHead(response.status, headers);
11
+ if (response.body instanceof ReadableStream) {
12
+ const reader = response.body.getReader();
13
+ while (true) {
14
+ const { done, value } = await reader.read();
15
+ if (done)
16
+ break;
17
+ res.write(value); // `value` is a Uint8Array.
18
+ }
19
+ res.end();
20
+ }
21
+ else {
22
+ const rendered = await response.text();
23
+ res.end(rendered);
24
+ }
25
+ }
26
+ catch (e) {
27
+ res.statusCode = 500;
28
+ if (e instanceof Error) {
29
+ console.error(e.stack);
30
+ config.viteDevServer?.ssrFixStacktrace(e);
31
+ res.end(e.stack);
32
+ }
33
+ else {
34
+ console.error(e);
35
+ res.end(String(e));
36
+ }
37
+ }
38
+ };
39
+ }
40
+ function NativeRequest(req) {
41
+ const ctrl = new AbortController();
42
+ const headers = new Headers(req.headers);
43
+ const url = new URL(`http://${headers.get('host')}${req.originalUrl || req.url}`);
44
+ req.once('aborted', () => ctrl.abort());
45
+ const bodied = req.method !== "GET" && req.method !== "HEAD";
46
+ const request = new Request(url, {
47
+ headers,
48
+ method: req.method,
49
+ body: bodied ? req : undefined,
50
+ signal: ctrl.signal,
51
+ referrer: headers.get("referrer") || undefined,
52
+ // @ts-ignore
53
+ duplex: bodied ? 'half' : undefined
54
+ });
55
+ if (!request.headers.has("X-Real-IP")) {
56
+ const info = req.socket.address();
57
+ if ("address" in info)
58
+ request.headers.set("X-Real-IP", info.address);
59
+ }
60
+ return request;
61
+ }
@@ -0,0 +1,17 @@
1
+ import type { ViteDevServer } from "vite";
2
+ import type { GenericContext } from "../router.js";
3
+ import type { RouteTree } from '../../router.js';
4
+ import * as native from "./native.js";
5
+ import * as http from "./http.js";
6
+ export type Config = {
7
+ build: Promise<any> | (() => Promise<Record<string, any>>);
8
+ viteDevServer: ViteDevServer | null;
9
+ render: GenericContext["render"];
10
+ };
11
+ export type RouterModule = {
12
+ tree: RouteTree;
13
+ };
14
+ export declare const createRequestHandler: {
15
+ http: typeof http.createRequestHandler;
16
+ native: typeof native.createRequestHandler;
17
+ };
@@ -0,0 +1,8 @@
1
+ import { ServerOnlyWarning } from "../util.js";
2
+ ServerOnlyWarning("request");
3
+ import * as native from "./native.js";
4
+ import * as http from "./http.js";
5
+ export const createRequestHandler = {
6
+ http: http.createRequestHandler,
7
+ native: native.createRequestHandler
8
+ };
@@ -0,0 +1,9 @@
1
+ import type { Config } from './index.js';
2
+ import type { RouteTree } from '../../router.js';
3
+ export declare function createRequestHandler(config: Config): (req: Request) => Promise<Response>;
4
+ export declare function Resolve(request: Request, tree: RouteTree, config: Config): Promise<{
5
+ response: Response;
6
+ headers: {
7
+ [key: string]: string | string[];
8
+ };
9
+ }>;
@@ -0,0 +1,48 @@
1
+ import { ServerOnlyWarning } from "../util.js";
2
+ ServerOnlyWarning("native-request");
3
+ import { GenericContext } from "../router.js";
4
+ export function createRequestHandler(config) {
5
+ return async (req) => {
6
+ try {
7
+ const mod = typeof config.build === "function" ? await config.build() : await config.build;
8
+ let { response } = await Resolve(req, mod.tree, config);
9
+ return response;
10
+ }
11
+ catch (e) {
12
+ if (e instanceof Error) {
13
+ console.error(e.stack);
14
+ config.viteDevServer?.ssrFixStacktrace(e);
15
+ return new Response(e.message + "\n" + e.stack, { status: 500, statusText: "Internal Server Error" });
16
+ }
17
+ else {
18
+ console.error(e);
19
+ return new Response(String(e), { status: 500, statusText: "Internal Server Error" });
20
+ }
21
+ }
22
+ };
23
+ }
24
+ export async function Resolve(request, tree, config) {
25
+ const url = new URL(request.url);
26
+ const ctx = new GenericContext(request, url, config.render);
27
+ const x = ctx.url.pathname.endsWith("/") ? ctx.url.pathname.slice(0, -1) : ctx.url.pathname;
28
+ const fragments = x.split("/").slice(1);
29
+ let response = await tree.resolve(fragments, ctx);
30
+ if (response === null)
31
+ response = new Response("No Route Found", { status: 404, statusText: "Not Found", headers: ctx.headers });
32
+ // Override with context headers
33
+ if (response.headers !== ctx.headers) {
34
+ for (const [key, value] of ctx.headers) {
35
+ if (response.headers.has(key))
36
+ continue;
37
+ response.headers.set(key, value);
38
+ }
39
+ }
40
+ // Merge cookie changes
41
+ const headers = Object.fromEntries(response.headers);
42
+ const cookies = ctx.cookie.export();
43
+ if (cookies.length > 0) {
44
+ headers['set-cookie'] = cookies;
45
+ response.headers.set("Set-Cookie", cookies[0]); // Response object doesn't support multi-header..[]
46
+ }
47
+ return { response, headers };
48
+ }
@@ -0,0 +1,15 @@
1
+ import { ParameterShaper } from '../util/parameters.js';
2
+ import { RouteContext } from "../router.js";
3
+ import { Cookies } from '../cookies.js';
4
+ export declare class GenericContext {
5
+ request: Request;
6
+ headers: Headers;
7
+ cookie: Cookies;
8
+ params: {
9
+ [key: string]: string;
10
+ };
11
+ url: URL;
12
+ render: (res: JSX.Element) => Response;
13
+ constructor(request: GenericContext["request"], url: GenericContext["url"], renderer: GenericContext["render"]);
14
+ shape<T extends ParameterShaper>(shape: T): RouteContext<T>;
15
+ }
@@ -0,0 +1,24 @@
1
+ import { ServerOnlyWarning } from "./util.js";
2
+ ServerOnlyWarning("internal/router");
3
+ import { RouteContext } from "../router.js";
4
+ import { Cookies } from '../cookies.js';
5
+ export class GenericContext {
6
+ request;
7
+ headers; // response headers
8
+ cookie;
9
+ params;
10
+ url;
11
+ render;
12
+ constructor(request, url, renderer) {
13
+ this.cookie = new Cookies(request.headers.get("cookie"));
14
+ this.headers = new Headers();
15
+ this.request = request;
16
+ this.params = {};
17
+ this.url = url;
18
+ this.render = renderer;
19
+ this.headers.set("x-powered-by", "htmx-router");
20
+ }
21
+ shape(shape) {
22
+ return new RouteContext(this, this.params, shape);
23
+ }
24
+ }
@@ -0,0 +1,4 @@
1
+ export declare function QuickHash(input: string): string;
2
+ export declare function CutString(str: string, pivot: string, offset?: number): [string, string];
3
+ export declare function Singleton<T>(name: string, cb: () => T): T;
4
+ export declare function ServerOnlyWarning(context: string): void;
@@ -0,0 +1,49 @@
1
+ export function QuickHash(input) {
2
+ let hash = 0;
3
+ for (let i = 0; i < input.length; i++) {
4
+ hash = (hash * 31 + input.charCodeAt(i)) >>> 0;
5
+ }
6
+ return hash.toString(36).slice(0, 5);
7
+ }
8
+ export function CutString(str, pivot, offset = 1) {
9
+ if (offset > 0) {
10
+ let cursor = 0;
11
+ while (offset !== 0) {
12
+ const i = str.indexOf(pivot, cursor);
13
+ if (i === -1)
14
+ return [str, ""];
15
+ cursor = i + 1;
16
+ offset--;
17
+ }
18
+ cursor--;
19
+ return [str.slice(0, cursor), str.slice(cursor + pivot.length)];
20
+ }
21
+ if (offset < 0) {
22
+ let cursor = str.length;
23
+ while (offset !== 0) {
24
+ const i = str.lastIndexOf(pivot, cursor);
25
+ if (i === -1)
26
+ return [str, ""];
27
+ cursor = i - 1;
28
+ offset++;
29
+ }
30
+ cursor++;
31
+ return [str.slice(0, cursor), str.slice(cursor + pivot.length)];
32
+ }
33
+ return [str, ""];
34
+ }
35
+ export function Singleton(name, cb) {
36
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
+ const g = globalThis;
38
+ g.__singletons ??= {};
39
+ g.__singletons[name] ??= cb();
40
+ return g.__singletons[name];
41
+ }
42
+ export function ServerOnlyWarning(context) {
43
+ if (typeof process !== "undefined")
44
+ return;
45
+ if (typeof document == "undefined")
46
+ return;
47
+ console.warn(`Warn: Server-side only htmx-router feature ${context} has leaked to client code`);
48
+ console.log(typeof document, typeof process);
49
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "htmx-router",
3
- "version": "1.0.0-pre1",
3
+ "version": "1.0.0-pre2",
4
4
  "description": "A lightweight SSR framework with server+client islands",
5
5
  "keywords": [
6
6
  "htmx", "router", "client islands", "ssr", "vite"
package/response.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export declare function text(text: string, init?: ResponseInit): Response;
2
+ export type TypedResponse<T> = Omit<Response, "json"> & {
3
+ json(): Promise<T>;
4
+ };
5
+ export type TypedJson<U extends TypedResponse<any>> = U extends TypedResponse<infer T> ? T : never;
6
+ export declare function json<T>(data: T, init?: ResponseInit): TypedResponse<T>;
7
+ export declare function redirect(url: string, init?: ResponseInit & {
8
+ clientOnly?: boolean;
9
+ }): Response;
10
+ export declare function revalidate(init?: ResponseInit): Response;
11
+ export declare function refresh(init?: ResponseInit & {
12
+ clientOnly?: boolean;
13
+ }): Response;