clarusjs 0.10.0 → 0.12.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/dist/cli/check.d.ts +7 -0
- package/dist/cli/check.js +14 -6
- package/dist/cli/explain.js +1 -1
- package/dist/cli/index.js +6 -3
- package/dist/cli/project.d.ts +7 -2
- package/dist/cli/project.js +4 -3
- package/dist/compiler/emit-client.d.ts +2 -1
- package/dist/compiler/emit-client.js +9 -2
- package/dist/compiler/emit-server.d.ts +1 -1
- package/dist/compiler/emit-server.js +4 -1
- package/dist/compiler/index.d.ts +3 -0
- package/dist/compiler/index.js +3 -2
- package/dist/compiler/ir.js +11 -5
- package/dist/compiler/lint.d.ts +82 -0
- package/dist/compiler/lint.js +177 -0
- package/dist/compiler/script.d.ts +10 -0
- package/dist/compiler/script.js +61 -0
- package/dist/forms/index.js +4 -1
- package/dist/runtime/hot.d.ts +2 -0
- package/dist/runtime/hot.js +51 -0
- package/dist/runtime/server.d.ts +10 -0
- package/dist/runtime/server.js +22 -0
- package/dist/server/handler.d.ts +101 -4
- package/dist/server/handler.js +232 -9
- package/dist/vite/aliases.js +3 -3
- package/dist/vite/build.d.ts +1 -0
- package/dist/vite/build.js +1 -1
- package/dist/vite/manifest.d.ts +3 -0
- package/dist/vite/manifest.js +2 -2
- package/dist/vite/node.js +4 -1
- package/dist/vite/plugin.d.ts +18 -2
- package/dist/vite/plugin.js +204 -107
- package/package.json +1 -1
package/dist/forms/index.js
CHANGED
|
@@ -154,7 +154,10 @@ export function form(values, options = {}) {
|
|
|
154
154
|
step.toggleAttribute('data-cl-current', step.id === id);
|
|
155
155
|
}
|
|
156
156
|
if (push && location.hash !== `#${id}`)
|
|
157
|
-
|
|
157
|
+
try {
|
|
158
|
+
history.pushState(null, '', `#${id}`);
|
|
159
|
+
}
|
|
160
|
+
catch { }
|
|
158
161
|
refresh();
|
|
159
162
|
}
|
|
160
163
|
const hashStep = () => {
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Island HMR (#53), dev only: a compiled island module that changed calls swap() with its new URL. The page is
|
|
2
|
+
// rendered again by the dev server, each of that component's islands gets its new HTML and the new module, and its
|
|
3
|
+
// state (and that of islands nested in it) carries over by name. Anything that doesn't line up is a full reload.
|
|
4
|
+
// Never part of a build: only dev client modules import it (the plugin's `hot` compile option).
|
|
5
|
+
import { parse, stringify } from './serialize.js';
|
|
6
|
+
/** Swap the islands of the component at `url` (the new module's URL, `…?import&t=…`) in place. */
|
|
7
|
+
export async function swap(url) {
|
|
8
|
+
const next = new URL(url, location.href);
|
|
9
|
+
const pathOf = (el) => new URL(el.getAttribute('src') ?? '', location.href).pathname;
|
|
10
|
+
// The outermost islands of this component: one nested in another is swapped with it.
|
|
11
|
+
const mine = (root) => [...root.querySelectorAll('cl-island')].filter((el) => pathOf(el) === next.pathname && !el.parentElement?.closest(`cl-island[src="${CSS.escape(el.getAttribute('src'))}"]`));
|
|
12
|
+
const old = mine(document);
|
|
13
|
+
if (!old.length)
|
|
14
|
+
return;
|
|
15
|
+
try {
|
|
16
|
+
const res = await fetch(location.href, { headers: { accept: 'text/html' } });
|
|
17
|
+
if (!res.ok)
|
|
18
|
+
throw new Error(`${res.status}`);
|
|
19
|
+
const fresh = mine(new DOMParser().parseFromString(await res.text(), 'text/html'));
|
|
20
|
+
if (fresh.length !== old.length)
|
|
21
|
+
throw new Error('the islands moved');
|
|
22
|
+
old.forEach((el, i) => {
|
|
23
|
+
// The island's own attributes (props a parent island may have changed, attach mode), the new markup and module.
|
|
24
|
+
const swapped = el.cloneNode(false);
|
|
25
|
+
swapped.removeAttribute('data-cl-ready');
|
|
26
|
+
swapped.removeAttribute('data-cl-error');
|
|
27
|
+
swapped.setAttribute('src', next.pathname + next.search);
|
|
28
|
+
swapped.replaceChildren(...[...fresh[i].childNodes].map((n) => document.importNode(n, true)));
|
|
29
|
+
swapped.setAttribute('s', fresh[i].getAttribute('s') ?? '{}');
|
|
30
|
+
// State: what the server rendered with, then what the running version had, island by island in page order.
|
|
31
|
+
const before = [el, ...el.querySelectorAll('cl-island')];
|
|
32
|
+
const after = [swapped, ...swapped.querySelectorAll('cl-island')];
|
|
33
|
+
if (before.length === after.length) {
|
|
34
|
+
before.forEach((b, j) => {
|
|
35
|
+
const state = pathOf(b) === pathOf(after[j]) ? b.__cl_hot?.() : undefined;
|
|
36
|
+
if (state)
|
|
37
|
+
after[j].setAttribute('s', stringify({ ...parse(after[j].getAttribute('s') ?? '{}'), ...state }));
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
el.replaceWith(swapped);
|
|
41
|
+
});
|
|
42
|
+
// The loader disposes the replaced islands (no longer in the page) and attaches the new ones.
|
|
43
|
+
await globalThis.__clAttach?.(document);
|
|
44
|
+
if (document.querySelector('cl-island[data-cl-error]'))
|
|
45
|
+
throw new Error('the new version failed to attach');
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
console.warn('[clarusjs] reloading: the changed island could not be swapped in place', err);
|
|
49
|
+
location.reload();
|
|
50
|
+
}
|
|
51
|
+
}
|
package/dist/runtime/server.d.ts
CHANGED
|
@@ -14,3 +14,13 @@ export declare const attr: typeof attrHtml;
|
|
|
14
14
|
* @internal clarusjs's own server code calls this; apps don't.
|
|
15
15
|
*/
|
|
16
16
|
export declare function toBrowser(value: unknown, path?: string, seen?: Set<object>): string;
|
|
17
|
+
/**
|
|
18
|
+
* The data a component's loader returned for the page being rendered (#97), or nothing outside such a render. Read by
|
|
19
|
+
* compiled components that have a loader. @internal
|
|
20
|
+
*/
|
|
21
|
+
export declare function loaded(key: string): object;
|
|
22
|
+
/**
|
|
23
|
+
* Render with component loaders' results available to `loaded()`. Rendering is synchronous, so one render's data never
|
|
24
|
+
* reaches another's; the previous data is restored afterwards, even when the render throws. @internal
|
|
25
|
+
*/
|
|
26
|
+
export declare function withLoaded<T>(data: Map<string, object>, render: () => T): T;
|
package/dist/runtime/server.js
CHANGED
|
@@ -31,3 +31,25 @@ export function toBrowser(value, path = '', seen = new Set()) {
|
|
|
31
31
|
}
|
|
32
32
|
return path ? '' : stringify(value);
|
|
33
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* The data a component's loader returned for the page being rendered (#97), or nothing outside such a render. Read by
|
|
36
|
+
* compiled components that have a loader. @internal
|
|
37
|
+
*/
|
|
38
|
+
export function loaded(key) {
|
|
39
|
+
return globalThis.__clLoaded?.get(key) ?? {};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Render with component loaders' results available to `loaded()`. Rendering is synchronous, so one render's data never
|
|
43
|
+
* reaches another's; the previous data is restored afterwards, even when the render throws. @internal
|
|
44
|
+
*/
|
|
45
|
+
export function withLoaded(data, render) {
|
|
46
|
+
const scope = globalThis;
|
|
47
|
+
const outer = scope.__clLoaded;
|
|
48
|
+
scope.__clLoaded = data;
|
|
49
|
+
try {
|
|
50
|
+
return render();
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
scope.__clLoaded = outer;
|
|
54
|
+
}
|
|
55
|
+
}
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -10,11 +10,97 @@ type Params = Record<string, string>;
|
|
|
10
10
|
*/
|
|
11
11
|
type DataModule = {
|
|
12
12
|
entries?(): Params[] | Promise<Params[]>;
|
|
13
|
-
load?(context:
|
|
14
|
-
params: Params;
|
|
15
|
-
request: Request;
|
|
16
|
-
}): object | Promise<object>;
|
|
13
|
+
load?(context: LoadContext): object | Promise<object>;
|
|
17
14
|
};
|
|
15
|
+
/**
|
|
16
|
+
* Data a request carries from `handle()` (src/server.ts) to every `load()`, such as the signed-in user. Declare what
|
|
17
|
+
* it holds once, and every loader is checked against it:
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* // src/server.ts
|
|
21
|
+
* declare module 'clarusjs/server' {
|
|
22
|
+
* interface Locals { user?: { id: string; name: string } }
|
|
23
|
+
* }
|
|
24
|
+
* ```
|
|
25
|
+
* @see https://clarusjs.com/reference/server#locals
|
|
26
|
+
*/
|
|
27
|
+
export interface Locals {
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Options for `cookies.set()`. Defaults: `path: '/'`, `httpOnly: true`, `sameSite: 'lax'`, and `secure: true` except
|
|
31
|
+
* in the Vite dev server (so development over plain http works everywhere).
|
|
32
|
+
* @see https://clarusjs.com/reference/server#cookies
|
|
33
|
+
*/
|
|
34
|
+
export type CookieOptions = {
|
|
35
|
+
path?: string;
|
|
36
|
+
domain?: string;
|
|
37
|
+
maxAge?: number;
|
|
38
|
+
expires?: Date;
|
|
39
|
+
httpOnly?: boolean;
|
|
40
|
+
secure?: boolean;
|
|
41
|
+
sameSite?: 'lax' | 'strict' | 'none';
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* A request's cookies: read from its `Cookie` header; what's set or deleted goes on the answer as `Set-Cookie`.
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* export function load({ cookies }: LoadContext) {
|
|
48
|
+
* cookies.set('visited', 'yes', { maxAge: 60 * 60 * 24 })
|
|
49
|
+
* return { theme: cookies.get('theme') ?? 'light' }
|
|
50
|
+
* }
|
|
51
|
+
* ```
|
|
52
|
+
* @see https://clarusjs.com/reference/server#cookies
|
|
53
|
+
*/
|
|
54
|
+
export type Cookies = {
|
|
55
|
+
get(name: string): string | undefined;
|
|
56
|
+
getAll(): Record<string, string>;
|
|
57
|
+
set(name: string, value: string, options?: CookieOptions): void;
|
|
58
|
+
delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* What a page's `load()` gets: its route params, the request, its cookies and the locals `handle()` filled.
|
|
62
|
+
* @see https://clarusjs.com/reference/server#loadcontext
|
|
63
|
+
*/
|
|
64
|
+
export type LoadContext = {
|
|
65
|
+
params: Params;
|
|
66
|
+
request: Request;
|
|
67
|
+
cookies: Cookies;
|
|
68
|
+
locals: Locals;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* `handle()` in src/server.ts: runs once per request before any page loads, to resolve the session into `locals`.
|
|
72
|
+
* Returning a Response (such as `redirect('/login')`) answers the request instead.
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* // src/server.ts
|
|
76
|
+
* import type { Handle } from 'clarusjs/server'
|
|
77
|
+
* export const handle: Handle = async ({ cookies, locals }) => {
|
|
78
|
+
* const id = cookies.get('session')
|
|
79
|
+
* if (id) locals.user = await sessions.get(id)
|
|
80
|
+
* }
|
|
81
|
+
* ```
|
|
82
|
+
* @see https://clarusjs.com/reference/server#handle
|
|
83
|
+
*/
|
|
84
|
+
export type Handle = (context: {
|
|
85
|
+
request: Request;
|
|
86
|
+
cookies: Cookies;
|
|
87
|
+
locals: Locals;
|
|
88
|
+
}) => void | Response | Promise<void | Response>;
|
|
89
|
+
/**
|
|
90
|
+
* An endpoint's handler (`export function GET(…)` in src/pages/api/items.ts): the request, its route params, cookies
|
|
91
|
+
* and locals; returns the Response.
|
|
92
|
+
* @example
|
|
93
|
+
* ```ts
|
|
94
|
+
* // src/pages/api/items.ts
|
|
95
|
+
* import type { RequestHandler } from 'clarusjs/server'
|
|
96
|
+
* export const GET: RequestHandler = ({ locals }) => Response.json(listItemsFor(locals.user))
|
|
97
|
+
* export const POST: RequestHandler = async ({ request }) => Response.json(await save(await request.json()), { status: 201 })
|
|
98
|
+
* ```
|
|
99
|
+
* @see https://clarusjs.com/reference/server#endpoints
|
|
100
|
+
*/
|
|
101
|
+
export type RequestHandler = (context: LoadContext) => Response | Promise<Response>;
|
|
102
|
+
/** An endpoint module: one handler per HTTP method it answers. @internal */
|
|
103
|
+
export type EndpointModule = Partial<Record<'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS', RequestHandler>>;
|
|
18
104
|
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.md' → '/about' (any page source) */
|
|
19
105
|
/**
|
|
20
106
|
* A redirect for a server page's `load()` to return: `return redirect('/login')`. 302 by default; 301 or 308 for
|
|
@@ -57,12 +143,23 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
|
|
|
57
143
|
site?: SiteOptions;
|
|
58
144
|
/** Development: a failing page throws its error (the dev server shows it with its stack) instead of answering 500. */
|
|
59
145
|
dev?: boolean;
|
|
146
|
+
/** src/server.ts: its `handle()` runs once per request, before any page loads. */
|
|
147
|
+
hooks?: {
|
|
148
|
+
handle?: Handle;
|
|
149
|
+
};
|
|
150
|
+
/** Component loaders (#97): each route's (as its file names it) loader files, by Vite path ('/src/x.load.ts'). */
|
|
151
|
+
componentLoaders?: Record<string, string[]>;
|
|
152
|
+
/** The component loader modules, by Vite path. */
|
|
153
|
+
componentData?: Record<string, () => Promise<DataModule>>;
|
|
154
|
+
/** Endpoints: .ts files under src/pages (not .load.ts) exporting GET, POST, … handlers. */
|
|
155
|
+
endpoints?: Record<string, () => Promise<EndpointModule>>;
|
|
60
156
|
}): {
|
|
61
157
|
fetch(request: Request): Promise<Response>;
|
|
62
158
|
routes: string[];
|
|
63
159
|
serverRoutes: string[];
|
|
64
160
|
paths(): Promise<string[]>;
|
|
65
161
|
hasLoader(route: string): Promise<boolean>;
|
|
162
|
+
readsCookies(route: string): Promise<boolean>;
|
|
66
163
|
isServerPath(pathname: string): boolean;
|
|
67
164
|
};
|
|
68
165
|
/**
|
package/dist/server/handler.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { modeFor } from './modes.js';
|
|
2
|
-
import { toBrowser } from '../runtime/server.js';
|
|
2
|
+
import { toBrowser, withLoaded } from '../runtime/server.js';
|
|
3
3
|
import { completeHead } from './head.js';
|
|
4
4
|
import { escape } from '../runtime/html.js';
|
|
5
5
|
const DATA = '__data.json';
|
|
@@ -28,6 +28,23 @@ export function createHandler(pages, options = {}) {
|
|
|
28
28
|
const routes = Object.entries(pages)
|
|
29
29
|
.map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
|
|
30
30
|
.sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
|
|
31
|
+
const endpointRoutes = Object.entries(options.endpoints ?? {})
|
|
32
|
+
.map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
|
|
33
|
+
.sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
|
|
34
|
+
const matchEndpoint = (pathname) => {
|
|
35
|
+
for (const route of endpointRoutes) {
|
|
36
|
+
const m = route.regex.exec(pathname);
|
|
37
|
+
if (!m)
|
|
38
|
+
continue;
|
|
39
|
+
try {
|
|
40
|
+
return { route, params: Object.fromEntries(route.keys.map((k, i) => [k, decodeURIComponent(m[i + 1])])) };
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
};
|
|
31
48
|
const data = options.data ?? {};
|
|
32
49
|
const modes = options.modes ?? {};
|
|
33
50
|
const loaderUrl = options.loaderUrl ?? '/cl-loader.js';
|
|
@@ -66,12 +83,18 @@ export function createHandler(pages, options = {}) {
|
|
|
66
83
|
}
|
|
67
84
|
const handler = {
|
|
68
85
|
routes: routes.map((r) => r.path).sort(),
|
|
69
|
-
serverRoutes: routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path).sort(),
|
|
86
|
+
serverRoutes: [...routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path), ...endpointRoutes.map((r) => r.path)].sort(),
|
|
70
87
|
isServerPath(pathname) {
|
|
71
88
|
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
72
89
|
const owner = options.fragments && pathname.endsWith(`/${FRAG}`) ? match(trim(pathname.slice(0, -FRAG.length - 1) || '/')) : null;
|
|
73
90
|
const found = owner ?? match(trim(pathname));
|
|
74
|
-
return Boolean(found
|
|
91
|
+
return Boolean(found ? modeFor(found.route.path, modes) === 'server' : matchEndpoint(trim(pathname)));
|
|
92
|
+
},
|
|
93
|
+
async readsCookies(route) {
|
|
94
|
+
const found = routes.find((r) => r.path === route);
|
|
95
|
+
const dataFile = found && `/${found.file.replace(/\.[^./]+$/, '.load.ts')}`;
|
|
96
|
+
const mod = dataFile && data[dataFile] ? await data[dataFile]() : undefined;
|
|
97
|
+
return !!mod?.load && /\bcookies\b/.test(String(mod.load));
|
|
75
98
|
},
|
|
76
99
|
async hasLoader(path) {
|
|
77
100
|
const route = routes.find((r) => r.path === path);
|
|
@@ -115,6 +138,37 @@ export function createHandler(pages, options = {}) {
|
|
|
115
138
|
return out.sort();
|
|
116
139
|
},
|
|
117
140
|
async fetch(request) {
|
|
141
|
+
const jar = cookieJar(request, options.dev === true);
|
|
142
|
+
const locals = {};
|
|
143
|
+
if (options.hooks?.handle) {
|
|
144
|
+
let early;
|
|
145
|
+
try {
|
|
146
|
+
early = await options.hooks.handle({ request, cookies: jar.cookies, locals });
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
if (options.dev)
|
|
150
|
+
throw err;
|
|
151
|
+
console.error(`clarusjs: src/server.ts: handle() failed: ${err?.message ?? err}`);
|
|
152
|
+
return jar.apply(failure('src/server.ts: handle() failed'));
|
|
153
|
+
}
|
|
154
|
+
if (early instanceof Response)
|
|
155
|
+
return jar.apply(early);
|
|
156
|
+
}
|
|
157
|
+
return jar.apply(await answer(request, jar.cookies, locals));
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
async function answer(request, cookies, locals) {
|
|
161
|
+
if (endpointRoutes.length) {
|
|
162
|
+
const path = new URL(request.url).pathname;
|
|
163
|
+
const trimmed = path.length > 1 ? path.replace(/\/+$/, '') : path;
|
|
164
|
+
const found = !match(trimmed) && matchEndpoint(trimmed);
|
|
165
|
+
if (found) {
|
|
166
|
+
const response = await callEndpoint(found.route.file, await found.route.load(), { request, params: found.params, cookies, locals }, options);
|
|
167
|
+
if (response)
|
|
168
|
+
return response;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
{
|
|
118
172
|
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
119
173
|
return new Response('Method Not Allowed', { status: 405 });
|
|
120
174
|
const pathname = new URL(request.url).pathname;
|
|
@@ -167,6 +221,10 @@ export function createHandler(pages, options = {}) {
|
|
|
167
221
|
return notFound();
|
|
168
222
|
if (mode !== 'server' && found.route.keys.length && !(await listed(found.route, found.params)))
|
|
169
223
|
return notFound();
|
|
224
|
+
const componentFiles = options.componentLoaders?.[found.route.path] ?? [];
|
|
225
|
+
if (mode === 'client' && componentFiles.length) {
|
|
226
|
+
return fail(`${found.route.file}: component loaders don't run in client routes yet (${componentFiles.map((f) => f.replace(/^\//, '')).join(', ')}); make the route 'static' or 'server'`);
|
|
227
|
+
}
|
|
170
228
|
if (mode === 'client' && !wantsData) {
|
|
171
229
|
const client = options.client ?? {};
|
|
172
230
|
const prefix = (options.base ?? '/').replace(/\/$/, '');
|
|
@@ -192,7 +250,8 @@ export function createHandler(pages, options = {}) {
|
|
|
192
250
|
if (mod?.load) {
|
|
193
251
|
let loaded;
|
|
194
252
|
try {
|
|
195
|
-
|
|
253
|
+
const once = modeFor(found.route.path, modes) !== 'server';
|
|
254
|
+
loaded = await mod.load({ params: found.params, locals, ...(once ? builtOnce(found.route.path, request) : { request, cookies }) });
|
|
196
255
|
}
|
|
197
256
|
catch (err) {
|
|
198
257
|
return fail(`${dataFile}: load() failed: ${err?.message ?? err}`, err);
|
|
@@ -209,9 +268,35 @@ export function createHandler(pages, options = {}) {
|
|
|
209
268
|
if (wantsData) {
|
|
210
269
|
return new Response(head ? null : safeJson(toBrowser(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
|
|
211
270
|
}
|
|
271
|
+
let componentData = new Map();
|
|
272
|
+
if (componentFiles.length) {
|
|
273
|
+
const once = mode !== 'server';
|
|
274
|
+
const context = { params: found.params, locals, ...(once ? builtOnce(found.route.path, request) : { request, cookies }) };
|
|
275
|
+
try {
|
|
276
|
+
componentData = new Map(await Promise.all(componentFiles.map(async (file) => {
|
|
277
|
+
const name = file.replace(/^\//, '');
|
|
278
|
+
const mod = await options.componentData?.[file]?.();
|
|
279
|
+
let value;
|
|
280
|
+
try {
|
|
281
|
+
value = await mod?.load?.(context);
|
|
282
|
+
}
|
|
283
|
+
catch (err) {
|
|
284
|
+
throw Object.assign(new Error(`${name}: load() failed: ${err?.message ?? err}`), { cause: err });
|
|
285
|
+
}
|
|
286
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value) || value instanceof Response) {
|
|
287
|
+
throw new Error(`${name}: load() must return an object of the component's inputs, got ${value instanceof Response ? 'a Response' : Array.isArray(value) ? 'an array' : value === null ? 'null' : typeof value}`);
|
|
288
|
+
}
|
|
289
|
+
return [name.replace(/\.load\.ts$/, '.tscl'), value];
|
|
290
|
+
})));
|
|
291
|
+
}
|
|
292
|
+
catch (err) {
|
|
293
|
+
return fail(err.message, err);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
212
296
|
let html;
|
|
213
297
|
try {
|
|
214
|
-
|
|
298
|
+
const module = await found.route.load();
|
|
299
|
+
html = withLoaded(componentData, () => module.render(props));
|
|
215
300
|
}
|
|
216
301
|
catch (err) {
|
|
217
302
|
return fail(`${found.route.file}: render failed: ${err?.message ?? err}`, err);
|
|
@@ -238,8 +323,8 @@ export function createHandler(pages, options = {}) {
|
|
|
238
323
|
: hasIslands ? `<script type="module" src="${loaderUrl}"></script>` : '';
|
|
239
324
|
const body = fullDocument(html, style, script);
|
|
240
325
|
return new Response(head ? null : body, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
241
|
-
}
|
|
242
|
-
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
243
328
|
return handler;
|
|
244
329
|
}
|
|
245
330
|
function pagePath(pathname, fragment) {
|
|
@@ -281,10 +366,12 @@ export function toFragment(html) {
|
|
|
281
366
|
return titleHtml + html.slice(open.index, close) + '</body>';
|
|
282
367
|
}
|
|
283
368
|
function maskComments(html) {
|
|
284
|
-
return html
|
|
369
|
+
return html
|
|
370
|
+
.replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length))
|
|
371
|
+
.replace(/(<(script|style)\b[^>]*>)([\s\S]*?)(<\/\2\s*>)/gi, (_, open, _tag, body, close) => open + ' '.repeat(body.length) + close);
|
|
285
372
|
}
|
|
286
373
|
function fullDocument(html, style, script) {
|
|
287
|
-
let out = /^\s*<!doctype/i.test(html) ? html : `<!doctype html>${html}`;
|
|
374
|
+
let out = /^\s*<!doctype/i.test(maskComments(html)) ? html : `<!doctype html>${html}`;
|
|
288
375
|
if (style) {
|
|
289
376
|
const head = maskComments(out).search(/<\/head>/i);
|
|
290
377
|
out = head === -1 ? out + style : out.slice(0, head) + style + out.slice(head);
|
|
@@ -304,3 +391,139 @@ export function rootLinks(html, base) {
|
|
|
304
391
|
return `${attr}${(resolved.pathname + resolved.search + resolved.hash).replace(/&/g, '&')}"`;
|
|
305
392
|
});
|
|
306
393
|
}
|
|
394
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
395
|
+
function cookieJar(request, dev) {
|
|
396
|
+
const incoming = new Map();
|
|
397
|
+
for (const part of (request.headers.get('cookie') ?? '').split(';')) {
|
|
398
|
+
const at = part.indexOf('=');
|
|
399
|
+
if (at < 1)
|
|
400
|
+
continue;
|
|
401
|
+
const name = part.slice(0, at).trim();
|
|
402
|
+
const raw = part.slice(at + 1).trim().replace(/^"(.*)"$/, '$1');
|
|
403
|
+
let value = raw;
|
|
404
|
+
try {
|
|
405
|
+
value = decodeURIComponent(raw);
|
|
406
|
+
}
|
|
407
|
+
catch { }
|
|
408
|
+
if (!incoming.has(name))
|
|
409
|
+
incoming.set(name, value);
|
|
410
|
+
}
|
|
411
|
+
const current = new Map(incoming);
|
|
412
|
+
const out = new Map();
|
|
413
|
+
const write = (name, value, o) => {
|
|
414
|
+
if (!TOKEN.test(name))
|
|
415
|
+
throw new Error(`cookies.set: ${JSON.stringify(name)} isn't a valid cookie name`);
|
|
416
|
+
const path = o.path ?? '/';
|
|
417
|
+
let header = `${name}=${encodeURIComponent(value)}; Path=${path}`;
|
|
418
|
+
if (o.domain)
|
|
419
|
+
header += `; Domain=${o.domain}`;
|
|
420
|
+
if (o.maxAge !== undefined)
|
|
421
|
+
header += `; Max-Age=${Math.floor(o.maxAge)}`;
|
|
422
|
+
if (o.expires)
|
|
423
|
+
header += `; Expires=${o.expires.toUTCString()}`;
|
|
424
|
+
if (o.httpOnly ?? true)
|
|
425
|
+
header += '; HttpOnly';
|
|
426
|
+
header += `; SameSite=${{ lax: 'Lax', strict: 'Strict', none: 'None' }[o.sameSite ?? 'lax']}`;
|
|
427
|
+
if (o.secure ?? !dev)
|
|
428
|
+
header += '; Secure';
|
|
429
|
+
out.set(`${name};${path};${o.domain ?? ''}`, header);
|
|
430
|
+
};
|
|
431
|
+
return {
|
|
432
|
+
cookies: {
|
|
433
|
+
get: (name) => current.get(name),
|
|
434
|
+
getAll: () => Object.fromEntries(current),
|
|
435
|
+
set(name, value, options = {}) {
|
|
436
|
+
write(name, value, options);
|
|
437
|
+
current.set(name, value);
|
|
438
|
+
},
|
|
439
|
+
delete(name, options = {}) {
|
|
440
|
+
write(name, '', { ...options, maxAge: undefined });
|
|
441
|
+
const key = `${name};${options.path ?? '/'};${options.domain ?? ''}`;
|
|
442
|
+
out.set(key, out.get(key) + '; Max-Age=0');
|
|
443
|
+
current.delete(name);
|
|
444
|
+
},
|
|
445
|
+
},
|
|
446
|
+
apply(response) {
|
|
447
|
+
if (!out.size)
|
|
448
|
+
return response;
|
|
449
|
+
const headers = new Headers(response.headers);
|
|
450
|
+
for (const header of out.values())
|
|
451
|
+
headers.append('set-cookie', header);
|
|
452
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
453
|
+
},
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
function builtOnce(route, request) {
|
|
457
|
+
const refuse = (what) => () => { throw new Error(`${route} reads ${what}, but static routes are built once for everyone: make it 'server' (routes in vite.config.ts)`); };
|
|
458
|
+
const cookies = { get: refuse('cookies'), getAll: refuse('cookies'), set: refuse('cookies'), delete: refuse('cookies') };
|
|
459
|
+
const headers = new Proxy(request.headers, { get: refuse("the request's headers") });
|
|
460
|
+
const proxied = new Proxy(request, {
|
|
461
|
+
get(target, key) {
|
|
462
|
+
if (key === 'headers')
|
|
463
|
+
return headers;
|
|
464
|
+
const value = Reflect.get(target, key, target);
|
|
465
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
466
|
+
},
|
|
467
|
+
});
|
|
468
|
+
return { request: proxied, cookies };
|
|
469
|
+
}
|
|
470
|
+
const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
471
|
+
const WRITES = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
472
|
+
async function callEndpoint(file, mod, context, options) {
|
|
473
|
+
const exported = METHODS.filter((m) => typeof mod[m] === 'function');
|
|
474
|
+
if (!exported.length)
|
|
475
|
+
return undefined;
|
|
476
|
+
const { request } = context;
|
|
477
|
+
const method = request.method.toUpperCase();
|
|
478
|
+
const fn = mod[method] ?? (method === 'HEAD' ? mod.GET : undefined);
|
|
479
|
+
if (!fn) {
|
|
480
|
+
const allow = [...new Set(exported.flatMap((m) => (m === 'GET' ? ['GET', 'HEAD'] : [m])))].sort();
|
|
481
|
+
return new Response('Method Not Allowed', { status: 405, headers: { allow: allow.join(', '), 'content-type': 'text/plain; charset=utf-8' } });
|
|
482
|
+
}
|
|
483
|
+
if (WRITES.has(method) && !sameOrigin(request, options.site?.url)) {
|
|
484
|
+
return new Response('Forbidden: cross-site request', { status: 403, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
485
|
+
}
|
|
486
|
+
let response;
|
|
487
|
+
try {
|
|
488
|
+
response = await fn(context);
|
|
489
|
+
}
|
|
490
|
+
catch (err) {
|
|
491
|
+
if (options.dev)
|
|
492
|
+
throw err;
|
|
493
|
+
console.error(`clarusjs: ${file}: ${method} failed: ${err?.message ?? err}`);
|
|
494
|
+
return failure(`${file}: ${method} failed`);
|
|
495
|
+
}
|
|
496
|
+
if (!(response instanceof Response)) {
|
|
497
|
+
const message = `${file}: ${method} must return a Response (got ${response === null ? 'null' : typeof response})`;
|
|
498
|
+
if (options.dev)
|
|
499
|
+
throw new Error(message);
|
|
500
|
+
console.error(`clarusjs: ${message}`);
|
|
501
|
+
return failure(message);
|
|
502
|
+
}
|
|
503
|
+
return method === 'HEAD' ? new Response(null, { status: response.status, statusText: response.statusText, headers: response.headers }) : response;
|
|
504
|
+
}
|
|
505
|
+
function sameOrigin(request, site) {
|
|
506
|
+
if (request.headers.get('sec-fetch-site') === 'cross-site')
|
|
507
|
+
return false;
|
|
508
|
+
let origin = request.headers.get('origin');
|
|
509
|
+
if (origin === 'null')
|
|
510
|
+
return false;
|
|
511
|
+
if (!origin) {
|
|
512
|
+
const referer = request.headers.get('referer');
|
|
513
|
+
try {
|
|
514
|
+
origin = referer ? new URL(referer).origin : null;
|
|
515
|
+
}
|
|
516
|
+
catch {
|
|
517
|
+
origin = null;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
if (!origin)
|
|
521
|
+
return !request.headers.has('cookie');
|
|
522
|
+
const allowed = [new URL(request.url).origin];
|
|
523
|
+
if (site)
|
|
524
|
+
try {
|
|
525
|
+
allowed.push(new URL(site).origin);
|
|
526
|
+
}
|
|
527
|
+
catch { }
|
|
528
|
+
return allowed.includes(origin);
|
|
529
|
+
}
|
package/dist/vite/aliases.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
-
import { resolve } from 'node:path';
|
|
2
|
+
import { normalize, resolve } from 'node:path';
|
|
3
3
|
function readJsonc(text) {
|
|
4
4
|
const bare = text.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '');
|
|
5
5
|
return JSON.parse(bare.replace(/,(\s*[}\]])/g, '$1'));
|
|
@@ -34,9 +34,9 @@ export function projectAliases(root, vite = []) {
|
|
|
34
34
|
export function resolveAlias(spec, aliases) {
|
|
35
35
|
for (const { find, replacement, exact } of aliases) {
|
|
36
36
|
if (find.endsWith('/') ? spec.startsWith(find) : spec === find)
|
|
37
|
-
return spec === find ? replacement : replacement + spec.slice(find.length);
|
|
37
|
+
return normalize(spec === find ? replacement : replacement + spec.slice(find.length));
|
|
38
38
|
if (!exact && !find.endsWith('/') && spec.startsWith(find + '/'))
|
|
39
|
-
return replacement + spec.slice(find.length);
|
|
39
|
+
return normalize(replacement + spec.slice(find.length));
|
|
40
40
|
}
|
|
41
41
|
return undefined;
|
|
42
42
|
}
|
package/dist/vite/build.d.ts
CHANGED
|
@@ -19,6 +19,7 @@ export declare function prerender(serverEntry: string, outDir: string, manifestF
|
|
|
19
19
|
server: {
|
|
20
20
|
route: string;
|
|
21
21
|
loader: boolean;
|
|
22
|
+
cookies?: boolean;
|
|
22
23
|
}[];
|
|
23
24
|
}>;
|
|
24
25
|
/** The package a file belongs to, from its last node_modules segment (pnpm: node_modules/.pnpm/x@1/node_modules/x/…). @internal */
|
package/dist/vite/build.js
CHANGED
|
@@ -72,7 +72,7 @@ export async function prerender(serverEntry, outDir, manifestFile, only) {
|
|
|
72
72
|
if (globalThis.__clLoaderRan) loaded.push(route)
|
|
73
73
|
}
|
|
74
74
|
const server = []
|
|
75
|
-
for (const route of handler.serverRoutes ?? []) server.push({ route, loader: await handler.hasLoader(route) })
|
|
75
|
+
for (const route of handler.serverRoutes ?? []) server.push({ route, loader: await handler.hasLoader(route), cookies: await handler.readsCookies?.(route) ?? false })
|
|
76
76
|
process.stdout.write(JSON.stringify({ routes, readers, loaded, server }))
|
|
77
77
|
`;
|
|
78
78
|
const args = ['--input-type=module', '-e', script, serverEntry, outDir, ...(only ? [JSON.stringify(only)] : [])];
|
package/dist/vite/manifest.d.ts
CHANGED
|
@@ -24,6 +24,8 @@ export type RouteInfo = {
|
|
|
24
24
|
html: string | null;
|
|
25
25
|
/** 'build': load() ran once, when the page was prerendered. 'request': it runs on every request. */
|
|
26
26
|
loader: 'build' | 'request' | null;
|
|
27
|
+
/** A server route whose load() reads cookies (from its source). */
|
|
28
|
+
cookies?: boolean;
|
|
27
29
|
islands: IslandInfo[];
|
|
28
30
|
/** Files relative to dist/client; gzip sizes in bytes. initialGzip is what loads with the page (attach="load"). */
|
|
29
31
|
js: {
|
|
@@ -58,4 +60,5 @@ export declare function describeRoute(route: string, html: string, opts: {
|
|
|
58
60
|
export declare function writeManifest(distDir: string, routes: string[], base: string, loaded?: string[], server?: {
|
|
59
61
|
route: string;
|
|
60
62
|
loader: boolean;
|
|
63
|
+
cookies?: boolean;
|
|
61
64
|
}[]): Manifest;
|
package/dist/vite/manifest.js
CHANGED
|
@@ -70,8 +70,8 @@ export function writeManifest(distDir, routes, base, loaded = [], server = []) {
|
|
|
70
70
|
const ran = loaded.includes(route) || (isClient && loaded.includes(dataFile(route)));
|
|
71
71
|
manifest.routes[route] = describeRoute(route, readFileSync(resolve(client, routeToFile(route)), 'utf8'), { base, chunks, size, loaded: ran, client: isClient });
|
|
72
72
|
}
|
|
73
|
-
for (const { route, loader } of server) {
|
|
74
|
-
manifest.routes[route] = { mode: 'server', html: null, loader: loader ? 'request' : null, islands: [], js: { files: [], gzip: 0, initialGzip: 0 }, css: [] };
|
|
73
|
+
for (const { route, loader, cookies } of server) {
|
|
74
|
+
manifest.routes[route] = { mode: 'server', html: null, loader: loader ? 'request' : null, ...(cookies ? { cookies: true } : {}), islands: [], js: { files: [], gzip: 0, initialGzip: 0 }, css: [] };
|
|
75
75
|
}
|
|
76
76
|
writeFileSync(resolve(distDir, 'clarusjs-manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
77
77
|
return manifest;
|
package/dist/vite/node.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
1
2
|
export function toRequest(req) {
|
|
2
3
|
const headers = new Headers();
|
|
3
4
|
for (const [key, value] of Object.entries(req.headers)) {
|
|
@@ -6,7 +7,9 @@ export function toRequest(req) {
|
|
|
6
7
|
else if (value !== undefined)
|
|
7
8
|
headers.set(key, value);
|
|
8
9
|
}
|
|
9
|
-
|
|
10
|
+
const method = req.method ?? 'GET';
|
|
11
|
+
const body = method === 'GET' || method === 'HEAD' ? undefined : Readable.toWeb(req);
|
|
12
|
+
return new Request(`http://${req.headers.host ?? 'localhost'}${req.url ?? '/'}`, { method, headers, body, ...(body ? { duplex: 'half' } : {}) });
|
|
10
13
|
}
|
|
11
14
|
export async function sendResponse(res, response) {
|
|
12
15
|
res.statusCode = response.status;
|