clarusjs 0.8.0 → 0.8.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.
- package/dist/check/generate.d.ts +6 -0
- package/dist/check/generate.js +11 -1
- package/dist/cli/check.js +16 -6
- package/dist/runtime/dom.js +4 -1
- package/dist/runtime/fragments.d.ts +1 -1
- package/dist/runtime/fragments.js +10 -35
- package/dist/runtime/loader.js +4 -2
- package/dist/runtime/navigate.d.ts +38 -0
- package/dist/runtime/navigate.js +88 -0
- package/dist/runtime/navigation.d.ts +88 -0
- package/dist/runtime/navigation.js +165 -0
- package/dist/runtime/router.d.ts +8 -1
- package/dist/runtime/router.js +28 -39
- package/dist/server/handler.d.ts +8 -0
- package/dist/server/handler.js +36 -9
- package/dist/vite/aliases.d.ts +10 -0
- package/dist/vite/aliases.js +42 -0
- package/dist/vite/build.d.ts +2 -1
- package/dist/vite/build.js +3 -2
- package/dist/vite/plugin.d.ts +6 -0
- package/dist/vite/plugin.js +66 -18
- package/dist/vite/redirects.d.ts +10 -0
- package/dist/vite/redirects.js +41 -0
- package/package.json +15 -1
package/dist/check/generate.d.ts
CHANGED
|
@@ -25,3 +25,9 @@ export declare function viewsDeclaration(views: {
|
|
|
25
25
|
file: string;
|
|
26
26
|
source: string;
|
|
27
27
|
}[]): string;
|
|
28
|
+
/**
|
|
29
|
+
* .clarusjs/routes.d.ts: every page's route → its params, for href() from clarusjs/navigation. A page is any file
|
|
30
|
+
* under src/pages but scripts (.ts/.js, so .load.ts too), styles and data, and _-prefixed files (partials). Markdown
|
|
31
|
+
* and other page sources count, though check only type-checks .tscl pages (#142).
|
|
32
|
+
*/
|
|
33
|
+
export declare function routesDeclaration(files: string[]): string;
|
package/dist/check/generate.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { routeFromFile } from '../server/handler.js';
|
|
1
2
|
import { parse } from '../compiler/parse.js';
|
|
2
3
|
import { splitImports } from '../compiler/script.js';
|
|
3
4
|
export function generateTs(source, file, options = {}) {
|
|
@@ -48,7 +49,7 @@ export function generateTs(source, file, options = {}) {
|
|
|
48
49
|
emit('}\n');
|
|
49
50
|
let loaderSpan;
|
|
50
51
|
if (options.loader) {
|
|
51
|
-
emit('declare const __cl_loaded: Awaited<ReturnType<typeof __cl_load
|
|
52
|
+
emit('declare const __cl_loaded: Exclude<Awaited<ReturnType<typeof __cl_load>>, Response>\n');
|
|
52
53
|
const start = code.length;
|
|
53
54
|
point('const __cl_from_load: Partial<Inputs> = __cl_loaded', 0);
|
|
54
55
|
loaderSpan = [start, code.length];
|
|
@@ -212,3 +213,12 @@ export function viewsDeclaration(views) {
|
|
|
212
213
|
lines.push("declare module 'clarusjs/views' {", ' interface Views {', ...entries, ' }', '}', 'export {}', '');
|
|
213
214
|
return lines.join('\n');
|
|
214
215
|
}
|
|
216
|
+
export function routesDeclaration(files) {
|
|
217
|
+
const pages = files.filter((f) => f.startsWith('src/pages/') && !/\.(m?[jt]s|css|json)$/.test(f) && !/(^|\/)_[^/]*$/.test(f));
|
|
218
|
+
const routes = [...new Set(pages.map((f) => routeFromFile(`/${f}`)))].sort();
|
|
219
|
+
const entries = routes.map((route) => {
|
|
220
|
+
const keys = [...route.matchAll(/\[([^\]]+)\]/g)].map((m) => m[1]);
|
|
221
|
+
return ` ${JSON.stringify(route)}: ${keys.length ? `{ ${keys.map((k) => `${k}: string`).join('; ')} }` : '{}'}`;
|
|
222
|
+
});
|
|
223
|
+
return ['// Generated by clarusjs check: every page route → its params, for href() from clarusjs/navigation.', "declare module 'clarusjs/navigation' {", ' interface Routes {', ...entries, ' }', '}', 'export {}', ''].join('\n');
|
|
224
|
+
}
|
package/dist/cli/check.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { spawnSync } from 'node:child_process';
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { createRequire } from 'node:module';
|
|
4
4
|
import { basename, dirname, relative, resolve, sep } from 'node:path';
|
|
5
5
|
import { ClarusError } from '../compiler/errors.js';
|
|
6
|
-
import { generateTs, toSourceOffset, viewsDeclaration } from '../check/generate.js';
|
|
6
|
+
import { generateTs, routesDeclaration, toSourceOffset, viewsDeclaration } from '../check/generate.js';
|
|
7
7
|
import { findClarusFiles, reachableComponents } from '../vite/build.js';
|
|
8
|
+
import { projectAliases } from '../vite/aliases.js';
|
|
8
9
|
const VIRTUAL = '.clarusjs/virtual';
|
|
9
10
|
const posix = (path) => path.split(sep).join('/');
|
|
10
11
|
function packageInfo(file) {
|
|
@@ -52,7 +53,7 @@ export function check(options) {
|
|
|
52
53
|
const appRoot = realpathSync(root);
|
|
53
54
|
const paths = {};
|
|
54
55
|
const virtualOf = new Map();
|
|
55
|
-
const components = reachableComponents(root, findClarusFiles(resolve(root, 'src')), (p) => readFileSync(p, 'utf8'), ['.tscl']);
|
|
56
|
+
const components = reachableComponents(root, findClarusFiles(resolve(root, 'src')), (p) => readFileSync(p, 'utf8'), ['.tscl'], projectAliases(root));
|
|
56
57
|
for (const path of components.filter((p) => !p.startsWith(resolve(appRoot, 'src') + sep))) {
|
|
57
58
|
const pkg = packageInfo(path);
|
|
58
59
|
const vpath = resolve(virtualRoot, '_pkg', pkg.name, `${relative(pkg.dir, path)}.ts`);
|
|
@@ -80,12 +81,21 @@ export function check(options) {
|
|
|
80
81
|
catch { }
|
|
81
82
|
}
|
|
82
83
|
}
|
|
84
|
+
const fromCheck = (path) => { const rel = posix(relative(resolve(root, '.clarusjs'), path)); return rel.startsWith('.') ? rel : `./${rel}`; };
|
|
85
|
+
for (const alias of projectAliases(root)) {
|
|
86
|
+
const tail = alias.exact ? '' : '*';
|
|
87
|
+
const mirror = resolve(virtualRoot, relative(root, alias.replacement));
|
|
88
|
+
paths[alias.find + tail] = [fromCheck(alias.replacement) + (alias.exact ? '' : '/') + tail, fromCheck(mirror) + (alias.exact ? '' : '/') + tail].map((p) => p.replace(/\/\/\*$/, '/*'));
|
|
89
|
+
}
|
|
83
90
|
mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
|
|
84
91
|
const sources = findClarusFiles(resolve(root, 'src')).map((path) => ({ file: posix(relative(root, path)), source: readFileSync(path, 'utf8') }));
|
|
85
92
|
writeFileSync(resolve(root, '.clarusjs/views.d.ts'), viewsDeclaration(sources));
|
|
86
|
-
const
|
|
93
|
+
const walk = (dir) => (existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(resolve(dir, e.name)) : [resolve(dir, e.name)])) : []);
|
|
94
|
+
writeFileSync(resolve(root, '.clarusjs/routes.d.ts'), routesDeclaration(walk(resolve(root, 'src/pages')).map((path) => posix(relative(root, path)))));
|
|
95
|
+
const own = ['tsconfig.json', 'jsconfig.json'].find((name) => existsSync(resolve(root, name)));
|
|
96
|
+
const hasConfig = own !== undefined;
|
|
87
97
|
const config = {
|
|
88
|
-
...(hasConfig ? { extends:
|
|
98
|
+
...(hasConfig ? { extends: `../${own}` } : {}),
|
|
89
99
|
compilerOptions: {
|
|
90
100
|
...(hasConfig ? {} : { strict: true, target: 'ES2023', module: 'ESNext', moduleResolution: 'Bundler', lib: ['ES2023', 'DOM', 'DOM.Iterable'] }),
|
|
91
101
|
noEmit: true,
|
|
@@ -95,7 +105,7 @@ export function check(options) {
|
|
|
95
105
|
rootDirs: ['..', './virtual'],
|
|
96
106
|
paths,
|
|
97
107
|
},
|
|
98
|
-
include: ['../src', './virtual', './views.d.ts'],
|
|
108
|
+
include: ['../src', './virtual', './views.d.ts', './routes.d.ts'],
|
|
99
109
|
};
|
|
100
110
|
const configPath = resolve(root, '.clarusjs/tsconfig.check.json');
|
|
101
111
|
mkdirSync(dirname(configPath), { recursive: true });
|
package/dist/runtime/dom.js
CHANGED
|
@@ -188,7 +188,10 @@ export function forBlock(ctx, index, list, keyOf, row, empty) {
|
|
|
188
188
|
const keys = items.map((item, i) => {
|
|
189
189
|
let key = keyOf(item, i);
|
|
190
190
|
if (seen.has(key)) {
|
|
191
|
-
|
|
191
|
+
// Development only: Vite replaces import.meta.env.DEV, so a production build drops it (no ImportMeta
|
|
192
|
+
// declaration needed: consumers of this source typecheck without one).
|
|
193
|
+
if (import.meta.env?.DEV)
|
|
194
|
+
console.warn(`[clarusjs] @for: duplicate key ${String(key)}; rows with repeated keys are matched by position`);
|
|
192
195
|
key = `${String(key)}\u0000${i}`;
|
|
193
196
|
}
|
|
194
197
|
seen.add(key);
|
|
@@ -2,4 +2,4 @@ import './loader.ts';
|
|
|
2
2
|
/** '/guide/lists/' → '/guide/lists/index.frag.html', keeping the query. */
|
|
3
3
|
export declare function fragmentUrl(url: URL): string;
|
|
4
4
|
/** Fetch the page's fragment and swap it in. Throws when there is none (the caller then loads the page normally). */
|
|
5
|
-
export declare function swap(url: URL, get?: (url: string) => Promise<Response>, isCurrent?: () => boolean): Promise<void>;
|
|
5
|
+
export declare function swap(url: URL, get?: (url: string) => Promise<Response>, isCurrent?: () => Promise<boolean> | boolean): Promise<void>;
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// instead of reloading. Browser only. Each page's fragment is <path>/index.frag.html; elements marked
|
|
3
3
|
// data-cl-persist="key" are kept across swaps, and the island loader attaches whatever islands arrive.
|
|
4
4
|
import './loader.js';
|
|
5
|
+
import { takeOver } from './navigate.js';
|
|
5
6
|
/** '/guide/lists/' → '/guide/lists/index.frag.html', keeping the query. */
|
|
6
7
|
export function fragmentUrl(url) {
|
|
7
8
|
return `${url.pathname.replace(/\/+$/, '')}/index.frag.html${url.search}`;
|
|
@@ -9,15 +10,15 @@ export function fragmentUrl(url) {
|
|
|
9
10
|
const region = (doc) => doc.querySelector('[data-cl-swap]') ?? doc.body;
|
|
10
11
|
/** Fetch the page's fragment and swap it in. Throws when there is none (the caller then loads the page normally). */
|
|
11
12
|
export async function swap(url, get = fetch,
|
|
12
|
-
//
|
|
13
|
+
// Awaited right before the swap (where the in-between hooks run): false once a newer navigation has started,
|
|
14
|
+
// then this one must not touch the document.
|
|
13
15
|
isCurrent = () => true) {
|
|
14
16
|
const src = fragmentUrl(url);
|
|
15
17
|
const res = await get(src);
|
|
16
|
-
|
|
18
|
+
// Redirected: the page moved, and the address bar would keep the old URL. Failing loads the page normally.
|
|
19
|
+
if (!res.ok || res.redirected)
|
|
17
20
|
throw new Error(`${res.status}: ${src}`);
|
|
18
21
|
const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
|
|
19
|
-
if (!isCurrent())
|
|
20
|
-
return;
|
|
21
22
|
const next = region(doc);
|
|
22
23
|
const old = region(document);
|
|
23
24
|
// A body can only replace a body, and a marked region a marked region: otherwise load the page normally.
|
|
@@ -38,7 +39,7 @@ isCurrent = () => true) {
|
|
|
38
39
|
document.head.append(added);
|
|
39
40
|
}
|
|
40
41
|
await Promise.all(loading);
|
|
41
|
-
if (!isCurrent())
|
|
42
|
+
if (!(await isCurrent()))
|
|
42
43
|
return;
|
|
43
44
|
// Persisted elements move into the new page as they are, with their state and attached islands.
|
|
44
45
|
for (const old of document.querySelectorAll('[data-cl-persist]')) {
|
|
@@ -46,34 +47,8 @@ isCurrent = () => true) {
|
|
|
46
47
|
}
|
|
47
48
|
document.title = doc.title;
|
|
48
49
|
old.replaceWith(next);
|
|
49
|
-
|
|
50
|
+
// Attaches the new islands; the loader also releases those that left with the old region.
|
|
51
|
+
await globalThis.__clAttach?.(next, 1); // 1: navigated (bytes)
|
|
50
52
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
// (the reload of a failed URL is itself a navigation to it, which the fallback check lets through).
|
|
54
|
-
let latest = 0;
|
|
55
|
-
let fallback = '';
|
|
56
|
-
let swapping = false;
|
|
57
|
-
navigation?.addEventListener('navigate', (event) => {
|
|
58
|
-
const e = event;
|
|
59
|
-
// A #hash, and the page's own history.pushState/replaceState (same-document, not back/forward), are never a page
|
|
60
|
-
// load, except while a swap is still loading: they abort it, so this navigation has to show the new page instead.
|
|
61
|
-
if (!e.canIntercept || e.hashChange || (e.destination.sameDocument && e.navigationType !== 'traverse' && !swapping) || e.downloadRequest !== null || e.formData)
|
|
62
|
-
return;
|
|
63
|
-
const url = new URL(e.destination.url);
|
|
64
|
-
if (url.href === fallback)
|
|
65
|
-
return;
|
|
66
|
-
const id = ++latest;
|
|
67
|
-
const isCurrent = () => latest === id && !e.signal.aborted;
|
|
68
|
-
swapping = true;
|
|
69
|
-
e.intercept({
|
|
70
|
-
handler: () => swap(url, fetch, isCurrent).finally(() => { if (latest === id)
|
|
71
|
-
swapping = false; }).catch(() => {
|
|
72
|
-
if (!isCurrent())
|
|
73
|
-
return;
|
|
74
|
-
fallback = url.href;
|
|
75
|
-
// The URL is already committed: reload it (assign() would only move within the page when it has a #hash).
|
|
76
|
-
location.reload();
|
|
77
|
-
}),
|
|
78
|
-
});
|
|
79
|
-
});
|
|
53
|
+
// Every navigation the shared guard takes over.
|
|
54
|
+
takeOver(() => (url, isCurrent, signal) => swap(url, (src) => fetch(src, { signal }), isCurrent));
|
package/dist/runtime/loader.js
CHANGED
|
@@ -176,12 +176,14 @@ function arrive() {
|
|
|
176
176
|
setTimeout(() => { region.textContent = document.title; }, 50);
|
|
177
177
|
}
|
|
178
178
|
// Islands inserted later (an @if branch, a @for row, a re-rendered child) are attached through this hook. The router
|
|
179
|
-
// and fragment navigation pass navigated = true after replacing the page
|
|
179
|
+
// and fragment navigation pass navigated = true after replacing the page, and wait for the returned promise: the
|
|
180
|
+
// islands that attach right away are attached before afterSwap and afterNavigate run.
|
|
180
181
|
;
|
|
181
182
|
globalThis.__clAttach = (root, navigated) => {
|
|
182
|
-
|
|
183
|
+
const done = attachAll(root);
|
|
183
184
|
if (navigated)
|
|
184
185
|
arrive();
|
|
186
|
+
return done;
|
|
185
187
|
};
|
|
186
188
|
if (typeof document !== 'undefined') {
|
|
187
189
|
// Islands never affect layout. Installed on the document (not in <head>), so it survives head swaps by the client
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** `gate()` is awaited right before the page changes the document: false means stop (a newer navigation won). */
|
|
2
|
+
/** `signal`: aborts when the navigation does (pass it to the page's requests). */
|
|
3
|
+
export type Render = (url: URL, gate: () => Promise<boolean> | boolean, signal?: AbortSignal) => Promise<unknown>;
|
|
4
|
+
/** A navigation in progress, as the in-between hooks and the navigating store see it. */
|
|
5
|
+
export type Transition = {
|
|
6
|
+
from: URL;
|
|
7
|
+
to: URL;
|
|
8
|
+
type: string;
|
|
9
|
+
phase: 'loading' | 'swapping';
|
|
10
|
+
signal: AbortSignal;
|
|
11
|
+
};
|
|
12
|
+
type Pick = (url: URL) => Render | false | null | undefined;
|
|
13
|
+
type NavigateEvent = {
|
|
14
|
+
canIntercept: boolean;
|
|
15
|
+
hashChange: boolean;
|
|
16
|
+
downloadRequest: string | null;
|
|
17
|
+
formData: FormData | null;
|
|
18
|
+
destination: {
|
|
19
|
+
url: string;
|
|
20
|
+
sameDocument: boolean;
|
|
21
|
+
};
|
|
22
|
+
navigationType: string;
|
|
23
|
+
signal: AbortSignal;
|
|
24
|
+
intercept(options: {
|
|
25
|
+
handler(): Promise<void>;
|
|
26
|
+
precommitHandler?(): Promise<void>;
|
|
27
|
+
}): void;
|
|
28
|
+
};
|
|
29
|
+
/** The number of the latest navigation taken over (0 before any): only that one may change the document. */
|
|
30
|
+
export declare let latest: number;
|
|
31
|
+
/**
|
|
32
|
+
* Take over the navigations `pick` wants. A page loads one navigator (the router or fragments), so one picker.
|
|
33
|
+
* @see https://clarusjs.com/guide/client-routes
|
|
34
|
+
* @see https://clarusjs.com/guide/fragment-navigation
|
|
35
|
+
*/
|
|
36
|
+
export declare function takeOver(pick: Pick): void;
|
|
37
|
+
export declare function onNavigate(e: NavigateEvent, pick: Pick): void;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Which navigations clarusjs takes over, in one place for the fragment navigator and the client router. Browser
|
|
2
|
+
// only. Each passes a picker: given the URL, it returns how to render that page, or nothing to leave it alone.
|
|
3
|
+
/** The number of the latest navigation taken over (0 before any): only that one may change the document. */
|
|
4
|
+
export let latest = 0;
|
|
5
|
+
// A URL that failed to render loads normally, never taken over again (its reload is itself a navigation to it).
|
|
6
|
+
let fallback = '';
|
|
7
|
+
let swapping = false;
|
|
8
|
+
// The URL a held navigation is loading (not committed yet).
|
|
9
|
+
let held = '';
|
|
10
|
+
/**
|
|
11
|
+
* Take over the navigations `pick` wants. A page loads one navigator (the router or fragments), so one picker.
|
|
12
|
+
* @see https://clarusjs.com/guide/client-routes
|
|
13
|
+
* @see https://clarusjs.com/guide/fragment-navigation
|
|
14
|
+
*/
|
|
15
|
+
export function takeOver(pick) {
|
|
16
|
+
;
|
|
17
|
+
globalThis.navigation?.addEventListener('navigate', (e) => onNavigate(e, pick));
|
|
18
|
+
}
|
|
19
|
+
export function onNavigate(e, pick) {
|
|
20
|
+
// A #hash, and the page's own history.pushState/replaceState (same-document push or replace), are never a page
|
|
21
|
+
// load, except while a swap runs after its URL changed: they abort it, so this navigation shows the new page.
|
|
22
|
+
if (!e.canIntercept || e.hashChange || e.downloadRequest != null || e.formData)
|
|
23
|
+
return;
|
|
24
|
+
// Push and replace (same-document ones too: never reloads; back/forward is a traverse).
|
|
25
|
+
const hold = /^(p|rep)/.test(e.navigationType);
|
|
26
|
+
if (e.destination.sameDocument && hold && !swapping) {
|
|
27
|
+
// The page's own history change aborts a navigation whose URL is held: it goes on to its page right after.
|
|
28
|
+
if (held)
|
|
29
|
+
setTimeout(navigation.navigate.bind(navigation, held)); // it fired this event
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
const url = new URL(e.destination.url);
|
|
33
|
+
const render = url.href != fallback && pick(url);
|
|
34
|
+
if (!render)
|
|
35
|
+
return;
|
|
36
|
+
const id = ++latest;
|
|
37
|
+
const isCurrent = () => latest == id && !e.signal.aborted;
|
|
38
|
+
const t = { from: new URL(location.href), to: url, type: e.navigationType, phase: 'loading', signal: e.signal };
|
|
39
|
+
const data = document.documentElement.dataset;
|
|
40
|
+
// Each step: on <html data-cl-navigating> (for CSS), then to clarusjs/navigation when an island loaded it.
|
|
41
|
+
const step = async (s) => {
|
|
42
|
+
if (s != 'swapped')
|
|
43
|
+
s ? (data.clNavigating = t.phase = s) : delete data.clNavigating;
|
|
44
|
+
await globalThis.__clNav?.(s, t);
|
|
45
|
+
};
|
|
46
|
+
step('loading');
|
|
47
|
+
// Push and replace hold the URL while the page loads, where the browser can (precommitHandler; others ignore it and
|
|
48
|
+
// only run handler): it changes once the page is ready to swap in, so an abort before that leaves page and URL as
|
|
49
|
+
// they were. Back/forward and reloads change it at once. Until its URL changes, a held navigation leaves the page's
|
|
50
|
+
// own history changes alone (see above).
|
|
51
|
+
swapping = !hold;
|
|
52
|
+
held = hold ? url.href : '';
|
|
53
|
+
let ready;
|
|
54
|
+
let commit;
|
|
55
|
+
const atGate = new Promise((r) => (ready = r));
|
|
56
|
+
const onCommit = new Promise((r) => (commit = () => { swapping = true; held = ''; r(); }));
|
|
57
|
+
let running;
|
|
58
|
+
// Ends this attempt (unless a newer one started): also when it is cancelled before its handlers ever run. `held`
|
|
59
|
+
// clears a task later: a page's own history change aborts this attempt just before its event reaches us, and still
|
|
60
|
+
// has to find it (see above).
|
|
61
|
+
const end = () => { if (latest == id) {
|
|
62
|
+
swapping = false;
|
|
63
|
+
step();
|
|
64
|
+
setTimeout(() => latest == id && (held = ''));
|
|
65
|
+
} };
|
|
66
|
+
e.signal.onabort = end;
|
|
67
|
+
const work = () => (running = render(url, async () => {
|
|
68
|
+
if (!isCurrent())
|
|
69
|
+
return false;
|
|
70
|
+
ready();
|
|
71
|
+
await onCommit;
|
|
72
|
+
await step('swapping');
|
|
73
|
+
return isCurrent();
|
|
74
|
+
}, e.signal).then(() => isCurrent() && step('swapped')).catch((err) => {
|
|
75
|
+
if (!isCurrent())
|
|
76
|
+
return;
|
|
77
|
+
fallback = url.href;
|
|
78
|
+
// Loaded normally: a reload once the URL changed (assign() would only move within the page with a #hash), else
|
|
79
|
+
// the new URL. After the failure is reported, so starting that load doesn't turn it into a cancellation.
|
|
80
|
+
setTimeout(() => (location.href == url.href ? location.reload() : location.assign(url.href)));
|
|
81
|
+
throw err; // reported as navigateerror (onNavigateError)
|
|
82
|
+
}).finally(end));
|
|
83
|
+
e.intercept({
|
|
84
|
+
// Resolves when the page is ready to swap in; rejects with a failure before that (reported, URL unchanged).
|
|
85
|
+
precommitHandler: hold ? () => Promise.race([atGate, work()]) : undefined,
|
|
86
|
+
handler: () => (commit(), running ?? work()),
|
|
87
|
+
});
|
|
88
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { type Signal } from './signals.ts';
|
|
2
|
+
import type { Transition } from './navigate.ts';
|
|
3
|
+
export type { Transition };
|
|
4
|
+
/**
|
|
5
|
+
* The current page's URL, as a store: `let here = shared(currentUrl)` in an island's script. `null` on the server
|
|
6
|
+
* (what the server renders), so pass the page's path as a prop when the server HTML needs it.
|
|
7
|
+
* @see https://clarusjs.com/guide/fragment-navigation
|
|
8
|
+
*/
|
|
9
|
+
export declare const currentUrl: Signal<URL | null>;
|
|
10
|
+
/**
|
|
11
|
+
* Go to `to`, as a link click would: the page's navigator swaps or renders it. Resolves once the new page is shown,
|
|
12
|
+
* and also when the navigation is cancelled or a newer one replaces it (so check `currentUrl` when it matters);
|
|
13
|
+
* rejects when it fails.
|
|
14
|
+
* @see https://clarusjs.com/guide/fragment-navigation
|
|
15
|
+
* @see https://clarusjs.com/guide/client-routes
|
|
16
|
+
*/
|
|
17
|
+
export declare function navigate(to: string | URL, options?: {
|
|
18
|
+
replace?: boolean;
|
|
19
|
+
state?: unknown;
|
|
20
|
+
}): Promise<void>;
|
|
21
|
+
/**
|
|
22
|
+
* Stops the navigation in progress, like the browser's stop button: its requests are cancelled and, where the URL was
|
|
23
|
+
* held while loading (push and replace in browsers with precommit handlers), page and URL stay as they were. Hooks
|
|
24
|
+
* see it through `t.signal`. Like the stop button, it also stops the page's own loading (images still arriving).
|
|
25
|
+
* @see https://clarusjs.com/guide/navigation
|
|
26
|
+
*/
|
|
27
|
+
export declare function abort(): void;
|
|
28
|
+
/** Back one entry, like the browser's back button. */
|
|
29
|
+
export declare function back(): void;
|
|
30
|
+
/**
|
|
31
|
+
* Before any navigation (links, forms, back/forward, `navigate()`): `nav.cancel()` stops it, for example to keep
|
|
32
|
+
* unsaved work. Back/forward can only be cancelled where the browser allows it.
|
|
33
|
+
* @see https://clarusjs.com/guide/navigation
|
|
34
|
+
*/
|
|
35
|
+
export declare function beforeNavigate(fn: (to: URL, nav: {
|
|
36
|
+
type: string;
|
|
37
|
+
cancel(): void;
|
|
38
|
+
}) => void): void;
|
|
39
|
+
/**
|
|
40
|
+
* After a navigation within the page finished: the new page is in and its islands attached.
|
|
41
|
+
* @see https://clarusjs.com/guide/navigation
|
|
42
|
+
*/
|
|
43
|
+
export declare function afterNavigate(fn: (to: URL) => void): void;
|
|
44
|
+
/**
|
|
45
|
+
* A navigation failed (a fragment or a client page could not be loaded). The page then loads normally.
|
|
46
|
+
* @see https://clarusjs.com/guide/navigation
|
|
47
|
+
*/
|
|
48
|
+
export declare function onNavigateError(fn: (to: URL, error: unknown) => void): void;
|
|
49
|
+
/**
|
|
50
|
+
* The navigation in progress, as a store (`let nav = shared(navigating)`): `null` when idle, else where it goes and
|
|
51
|
+
* its phase, `'loading'` (the next page is fetched) or `'swapping'` (it replaces this one). For CSS alone,
|
|
52
|
+
* `<html data-cl-navigating>` carries the phase.
|
|
53
|
+
* @see https://clarusjs.com/guide/navigation
|
|
54
|
+
*/
|
|
55
|
+
export declare const navigating: Signal<Transition | null>;
|
|
56
|
+
/**
|
|
57
|
+
* Page changes run as view transitions where the browser has them (`document.startViewTransition`), so CSS
|
|
58
|
+
* `::view-transition-*` rules animate them; elsewhere they stay instant. Call it once, from any island's script.
|
|
59
|
+
* `beforeSwap` hooks run before the browser's snapshot, `afterSwap` hooks once the new page is in.
|
|
60
|
+
* @see https://clarusjs.com/guide/navigation
|
|
61
|
+
*/
|
|
62
|
+
export declare function viewTransitions(): void;
|
|
63
|
+
/**
|
|
64
|
+
* Runs once the next page is loaded, before it replaces this one (animate out, save state). Return a promise to
|
|
65
|
+
* make the navigation wait; `t.signal` aborts when a newer navigation takes over. A hook that throws makes the page
|
|
66
|
+
* load normally.
|
|
67
|
+
* @see https://clarusjs.com/guide/navigation
|
|
68
|
+
*/
|
|
69
|
+
export declare function beforeSwap(fn: (t: Transition) => unknown): void;
|
|
70
|
+
/**
|
|
71
|
+
* Runs once the new page is in and its islands attached (animate in, move focus). Return a promise to make the
|
|
72
|
+
* navigation wait for it.
|
|
73
|
+
* @see https://clarusjs.com/guide/navigation
|
|
74
|
+
*/
|
|
75
|
+
export declare function afterSwap(fn: (t: Transition) => unknown): void;
|
|
76
|
+
/** Route → params. Filled in by the generated .clarusjs/routes.d.ts (declaration merging; see `clarusjs check`). */
|
|
77
|
+
export interface Routes {
|
|
78
|
+
}
|
|
79
|
+
/** Without the generated routes any path is accepted; with them, only real routes. */
|
|
80
|
+
export type RouteName = [keyof Routes] extends [never] ? string : Extract<keyof Routes, string>;
|
|
81
|
+
type ParamsOf<R> = R extends keyof Routes ? Routes[R] : Record<string, string>;
|
|
82
|
+
/**
|
|
83
|
+
* A page's URL from its route, as its file names it, with the site's base: `href('/releases/[version]',
|
|
84
|
+
* { version: '0.8.0' })` is `'/releases/0.8.0'`. With .clarusjs/routes.d.ts (written by `clarusjs check`), a route
|
|
85
|
+
* that doesn't exist or a missing param is a type error. Params are encoded.
|
|
86
|
+
* @see https://clarusjs.com/guide/navigation
|
|
87
|
+
*/
|
|
88
|
+
export declare function href<R extends RouteName>(route: R, ...params: [keyof Routes] extends [never] ? [Record<string, string>?] : keyof ParamsOf<R> extends never ? [] : [ParamsOf<R>]): string;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// Moving between pages from islands: `import { navigate, back, currentUrl } from 'clarusjs/navigation'`.
|
|
2
|
+
// Navigations go through the Navigation API, so the page's navigator (fragments or the client router) takes them
|
|
3
|
+
// over exactly like a link click; without it they are normal page loads. Island scripts also run on the server,
|
|
4
|
+
// where this does nothing.
|
|
5
|
+
import { onDispose, state } from './signals.js';
|
|
6
|
+
const navigation = globalThis.navigation;
|
|
7
|
+
const browser = typeof document !== 'undefined';
|
|
8
|
+
/**
|
|
9
|
+
* The current page's URL, as a store: `let here = shared(currentUrl)` in an island's script. `null` on the server
|
|
10
|
+
* (what the server renders), so pass the page's path as a prop when the server HTML needs it.
|
|
11
|
+
* @see https://clarusjs.com/guide/fragment-navigation
|
|
12
|
+
*/
|
|
13
|
+
export const currentUrl = state(browser ? new URL(location.href) : null);
|
|
14
|
+
if (browser) {
|
|
15
|
+
const update = () => currentUrl.set(new URL(location.href));
|
|
16
|
+
// currententrychange covers links, back/forward and the page's own pushState/replaceState; without the
|
|
17
|
+
// Navigation API, only back/forward and #hash changes happen within a page.
|
|
18
|
+
if (navigation)
|
|
19
|
+
navigation.addEventListener('currententrychange', update);
|
|
20
|
+
else
|
|
21
|
+
for (const type of ['popstate', 'hashchange'])
|
|
22
|
+
addEventListener(type, update);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Go to `to`, as a link click would: the page's navigator swaps or renders it. Resolves once the new page is shown,
|
|
26
|
+
* and also when the navigation is cancelled or a newer one replaces it (so check `currentUrl` when it matters);
|
|
27
|
+
* rejects when it fails.
|
|
28
|
+
* @see https://clarusjs.com/guide/fragment-navigation
|
|
29
|
+
* @see https://clarusjs.com/guide/client-routes
|
|
30
|
+
*/
|
|
31
|
+
export async function navigate(to, options = {}) {
|
|
32
|
+
if (!browser)
|
|
33
|
+
return;
|
|
34
|
+
if (!navigation)
|
|
35
|
+
return options.replace ? location.replace(String(to)) : location.assign(String(to));
|
|
36
|
+
try {
|
|
37
|
+
await navigation.navigate(String(to), { history: options.replace ? 'replace' : 'auto', state: options.state }).finished;
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
if (err.name != 'AbortError')
|
|
41
|
+
throw err;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Stops the navigation in progress, like the browser's stop button: its requests are cancelled and, where the URL was
|
|
46
|
+
* held while loading (push and replace in browsers with precommit handlers), page and URL stay as they were. Hooks
|
|
47
|
+
* see it through `t.signal`. Like the stop button, it also stops the page's own loading (images still arriving).
|
|
48
|
+
* @see https://clarusjs.com/guide/navigation
|
|
49
|
+
*/
|
|
50
|
+
export function abort() {
|
|
51
|
+
if (browser)
|
|
52
|
+
stop();
|
|
53
|
+
}
|
|
54
|
+
/** Back one entry, like the browser's back button. */
|
|
55
|
+
export function back() {
|
|
56
|
+
if (browser)
|
|
57
|
+
history.back();
|
|
58
|
+
}
|
|
59
|
+
// A hook listens on the Navigation API for as long as the island that registered it (no-op without the API).
|
|
60
|
+
function hook(type, listener) {
|
|
61
|
+
if (!navigation)
|
|
62
|
+
return;
|
|
63
|
+
navigation.addEventListener(type, listener);
|
|
64
|
+
onDispose(() => navigation.removeEventListener(type, listener));
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Before any navigation (links, forms, back/forward, `navigate()`): `nav.cancel()` stops it, for example to keep
|
|
68
|
+
* unsaved work. Back/forward can only be cancelled where the browser allows it.
|
|
69
|
+
* @see https://clarusjs.com/guide/navigation
|
|
70
|
+
*/
|
|
71
|
+
export function beforeNavigate(fn) {
|
|
72
|
+
hook('navigate', (e) => fn(new URL(e.destination.url), { type: e.navigationType, cancel: () => e.preventDefault() }));
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* After a navigation within the page finished: the new page is in and its islands attached.
|
|
76
|
+
* @see https://clarusjs.com/guide/navigation
|
|
77
|
+
*/
|
|
78
|
+
export function afterNavigate(fn) {
|
|
79
|
+
hook('navigatesuccess', () => fn(new URL(location.href)));
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* A navigation failed (a fragment or a client page could not be loaded). The page then loads normally.
|
|
83
|
+
* @see https://clarusjs.com/guide/navigation
|
|
84
|
+
*/
|
|
85
|
+
export function onNavigateError(fn) {
|
|
86
|
+
// Where it was going: a navigation that failed before its URL changed (held while loading) never became current.
|
|
87
|
+
let to = '';
|
|
88
|
+
hook('navigate', (e) => { to = e.destination.url; });
|
|
89
|
+
hook('navigateerror', (e) => fn(new URL(to || location.href), e.error));
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The navigation in progress, as a store (`let nav = shared(navigating)`): `null` when idle, else where it goes and
|
|
93
|
+
* its phase, `'loading'` (the next page is fetched) or `'swapping'` (it replaces this one). For CSS alone,
|
|
94
|
+
* `<html data-cl-navigating>` carries the phase.
|
|
95
|
+
* @see https://clarusjs.com/guide/navigation
|
|
96
|
+
*/
|
|
97
|
+
export const navigating = state(null);
|
|
98
|
+
const before = [];
|
|
99
|
+
const after = [];
|
|
100
|
+
// The page's navigator (the router or fragments, a separate script) reports each step here and waits for it.
|
|
101
|
+
if (browser) {
|
|
102
|
+
;
|
|
103
|
+
globalThis.__clNav = async (step, t) => {
|
|
104
|
+
navigating.set(step ? { ...t } : null);
|
|
105
|
+
if (step != 'swapping')
|
|
106
|
+
done?.(); // the new page is in (or the navigation ended): the transition animates
|
|
107
|
+
const hooks = step == 'swapping' ? before : step == 'swapped' ? after : [];
|
|
108
|
+
// Each hook is awaited in turn; one whose island was released meanwhile (by an earlier hook) is skipped.
|
|
109
|
+
for (const hook of [...hooks])
|
|
110
|
+
if (hooks.includes(hook))
|
|
111
|
+
await hook(t);
|
|
112
|
+
// A view transition: the browser snapshots this page, then the swap (which waits for this) runs inside it.
|
|
113
|
+
const start = document.startViewTransition;
|
|
114
|
+
if (step == 'swapping' && transitions && start) {
|
|
115
|
+
await new Promise((snapshot) => start.call(document, () => { snapshot(); return new Promise((r) => (done = r)); }));
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
let transitions = false;
|
|
120
|
+
let done;
|
|
121
|
+
/**
|
|
122
|
+
* Page changes run as view transitions where the browser has them (`document.startViewTransition`), so CSS
|
|
123
|
+
* `::view-transition-*` rules animate them; elsewhere they stay instant. Call it once, from any island's script.
|
|
124
|
+
* `beforeSwap` hooks run before the browser's snapshot, `afterSwap` hooks once the new page is in.
|
|
125
|
+
* @see https://clarusjs.com/guide/navigation
|
|
126
|
+
*/
|
|
127
|
+
export function viewTransitions() {
|
|
128
|
+
transitions = true;
|
|
129
|
+
}
|
|
130
|
+
function inBetween(hooks, fn) {
|
|
131
|
+
if (!browser)
|
|
132
|
+
return;
|
|
133
|
+
hooks.push(fn);
|
|
134
|
+
onDispose(() => hooks.splice(hooks.indexOf(fn), 1));
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Runs once the next page is loaded, before it replaces this one (animate out, save state). Return a promise to
|
|
138
|
+
* make the navigation wait; `t.signal` aborts when a newer navigation takes over. A hook that throws makes the page
|
|
139
|
+
* load normally.
|
|
140
|
+
* @see https://clarusjs.com/guide/navigation
|
|
141
|
+
*/
|
|
142
|
+
export function beforeSwap(fn) {
|
|
143
|
+
inBetween(before, fn);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Runs once the new page is in and its islands attached (animate in, move focus). Return a promise to make the
|
|
147
|
+
* navigation wait for it.
|
|
148
|
+
* @see https://clarusjs.com/guide/navigation
|
|
149
|
+
*/
|
|
150
|
+
export function afterSwap(fn) {
|
|
151
|
+
inBetween(after, fn);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* A page's URL from its route, as its file names it, with the site's base: `href('/releases/[version]',
|
|
155
|
+
* { version: '0.8.0' })` is `'/releases/0.8.0'`. With .clarusjs/routes.d.ts (written by `clarusjs check`), a route
|
|
156
|
+
* that doesn't exist or a missing param is a type error. Params are encoded.
|
|
157
|
+
* @see https://clarusjs.com/guide/navigation
|
|
158
|
+
*/
|
|
159
|
+
export function href(route,
|
|
160
|
+
// Without the generated routes, params are optional; with them, required exactly when the route has some.
|
|
161
|
+
...params) {
|
|
162
|
+
const values = (params[0] ?? {});
|
|
163
|
+
const base = (import.meta.env?.BASE_URL ?? '/').replace(/\/$/, '');
|
|
164
|
+
return base + route.replace(/\[([^\]]+)\]/g, (_, key) => encodeURIComponent(values[key] ?? ''));
|
|
165
|
+
}
|
package/dist/runtime/router.d.ts
CHANGED
|
@@ -11,5 +11,12 @@ export declare function matchRoute(table: Entry[], pathname: string): {
|
|
|
11
11
|
params: Record<string, string>;
|
|
12
12
|
} | null;
|
|
13
13
|
/** Render the client route at `url` into the document. False when `url` is not a client route. */
|
|
14
|
-
export declare function show(url: URL, table: Entry[], isCurrent?: () => boolean, load?: (src: string) => Promise<Page>, get?: (url: string) => Promise<Response>): Promise<boolean>;
|
|
14
|
+
export declare function show(url: URL, table: Entry[], isCurrent?: () => Promise<boolean> | boolean, load?: (src: string) => Promise<Page>, get?: (url: string) => Promise<Response>): Promise<boolean>;
|
|
15
|
+
/**
|
|
16
|
+
* Puts a whole page in: its body, its own <html> attributes (lang, dir, …), its title (through `title`, else as
|
|
17
|
+
* written) and its inline head scripts (such as setting the theme before paint, run once as on a normal load); then
|
|
18
|
+
* attaches its islands (the loader also releases the old page's). The head stays. Resolves once the islands that
|
|
19
|
+
* attach right away are attached.
|
|
20
|
+
*/
|
|
21
|
+
export declare function swapIn(html: string, title?: (title: string) => string): Promise<void>;
|
|
15
22
|
export {};
|
package/dist/runtime/router.js
CHANGED
|
@@ -11,6 +11,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
11
11
|
// the island loader attach. Later navigations between client routes are intercepted with the Navigation API;
|
|
12
12
|
// browsers without it simply load pages normally.
|
|
13
13
|
import { parse } from './serialize.js';
|
|
14
|
+
import { latest, takeOver } from './navigate.js';
|
|
14
15
|
/** The route a path belongs to, with its decoded params. Same grammar as the server: whole [param] segments. */
|
|
15
16
|
export function matchRoute(table, pathname) {
|
|
16
17
|
const got = pathname.replace(/(.)\/+$/, '$1').split('/');
|
|
@@ -35,7 +36,8 @@ export function matchRoute(table, pathname) {
|
|
|
35
36
|
}
|
|
36
37
|
/** Render the client route at `url` into the document. False when `url` is not a client route. */
|
|
37
38
|
export async function show(url, table,
|
|
38
|
-
//
|
|
39
|
+
// Awaited right before the swap (where the in-between hooks run): false once a newer navigation has started,
|
|
40
|
+
// then this one must not touch the document.
|
|
39
41
|
isCurrent = () => true, load = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src)), get = fetch) {
|
|
40
42
|
const found = matchRoute(table, url.pathname);
|
|
41
43
|
if (!found)
|
|
@@ -49,61 +51,48 @@ isCurrent = () => true, load = (src) => import(__rewriteRelativeImportExtension(
|
|
|
49
51
|
return parse(await res.text());
|
|
50
52
|
}),
|
|
51
53
|
]);
|
|
52
|
-
if (!isCurrent())
|
|
54
|
+
if (!(await isCurrent()))
|
|
53
55
|
return false;
|
|
54
|
-
|
|
55
|
-
//
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
56
|
+
// The head stays (its stylesheets are every client page's, linked by the shell); the title gets the site's
|
|
57
|
+
// titleTemplate, from the shell (always set: '%s' without one).
|
|
58
|
+
await swapIn(page.render(props), (title) => document.getElementById('cl-routes').dataset.title.replace('%s', () => title));
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Puts a whole page in: its body, its own <html> attributes (lang, dir, …), its title (through `title`, else as
|
|
63
|
+
* written) and its inline head scripts (such as setting the theme before paint, run once as on a normal load); then
|
|
64
|
+
* attaches its islands (the loader also releases the old page's). The head stays. Resolves once the islands that
|
|
65
|
+
* attach right away are attached.
|
|
66
|
+
*/
|
|
67
|
+
export async function swapIn(html, title = (t) => t) {
|
|
68
|
+
const doc = new DOMParser().parseFromString(html, 'text/html');
|
|
59
69
|
const root = document.documentElement;
|
|
60
70
|
for (const { name } of [...root.attributes])
|
|
61
71
|
root.removeAttribute(name);
|
|
62
72
|
for (const { name, value } of [...doc.documentElement.attributes])
|
|
63
73
|
root.setAttribute(name, value);
|
|
74
|
+
document.title = title(doc.title); // before islands attach: the loader announces it
|
|
64
75
|
document.body.replaceWith(doc.body);
|
|
65
|
-
// The page's inline head scripts (such as setting the theme before paint) run once, as on a normal load.
|
|
66
76
|
for (const old of doc.head.querySelectorAll('script:not([src])')) {
|
|
67
77
|
const script = document.createElement('script');
|
|
68
78
|
script.textContent = old.textContent;
|
|
69
79
|
document.head.append(script);
|
|
70
80
|
script.remove();
|
|
71
81
|
}
|
|
72
|
-
|
|
73
|
-
;
|
|
74
|
-
globalThis.__clAttach?.(document.body, 1); // 1: navigated (bytes)
|
|
75
|
-
return true;
|
|
82
|
+
await globalThis.__clAttach?.(document.body, 1); // 1: navigated (bytes)
|
|
76
83
|
}
|
|
77
84
|
const routes = globalThis.document?.getElementById('cl-routes');
|
|
78
85
|
if (routes) {
|
|
79
86
|
const table = JSON.parse(routes.textContent);
|
|
80
|
-
//
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if (latest !== 1)
|
|
87
|
+
// The first render is current until a navigation is taken over.
|
|
88
|
+
show(new URL(location.href), table, () => !latest).catch((err) => {
|
|
89
|
+
if (latest)
|
|
84
90
|
return;
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
let fallback = '';
|
|
90
|
-
const navigation = globalThis.navigation;
|
|
91
|
-
navigation?.addEventListener('navigate', (event) => {
|
|
92
|
-
const e = event;
|
|
93
|
-
if (!e.canIntercept || e.hashChange || e.downloadRequest != null || e.formData)
|
|
94
|
-
return;
|
|
95
|
-
const url = new URL(e.destination.url);
|
|
96
|
-
if (url.href === fallback || !matchRoute(table, url.pathname))
|
|
97
|
-
return;
|
|
98
|
-
const id = ++latest;
|
|
99
|
-
const isCurrent = () => latest === id && !e.signal.aborted;
|
|
100
|
-
e.intercept({
|
|
101
|
-
handler: () => show(url, table, isCurrent).then(() => { }, () => {
|
|
102
|
-
if (!isCurrent())
|
|
103
|
-
return;
|
|
104
|
-
fallback = url.href;
|
|
105
|
-
location.reload(); // the URL is already committed; assign() would stay in the page with a #hash
|
|
106
|
-
}),
|
|
107
|
-
});
|
|
91
|
+
// The site's 404 or 500 page, at this same URL (its title as written); plain text when the site has none.
|
|
92
|
+
fetch(routes.dataset.base + (/^404/.test(err.message) ? 404 : 500))
|
|
93
|
+
.then((res) => (res.ok ? res.text() : Promise.reject()))
|
|
94
|
+
.then((html) => swapIn(html), () => { document.body.textContent = 'Could not load page.'; });
|
|
108
95
|
});
|
|
96
|
+
// Later navigations to client routes.
|
|
97
|
+
takeOver((url) => matchRoute(table, url.pathname) && ((url, isCurrent, signal) => show(url, table, isCurrent, undefined, (src) => fetch(src, { signal }))));
|
|
109
98
|
}
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -16,6 +16,12 @@ type DataModule = {
|
|
|
16
16
|
}): object | Promise<object>;
|
|
17
17
|
};
|
|
18
18
|
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.md' → '/about' (any page source) */
|
|
19
|
+
/**
|
|
20
|
+
* A redirect for a server page's `load()` to return: `return redirect('/login')`. 302 by default; 301 or 308 for
|
|
21
|
+
* a page that moved for good, 303 after a form, 307 to keep the method.
|
|
22
|
+
* @see https://clarusjs.com/guide/routing
|
|
23
|
+
*/
|
|
24
|
+
export declare function redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): Response;
|
|
19
25
|
export declare function routeFromFile(file: string): string;
|
|
20
26
|
export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
|
|
21
27
|
loaderUrl?: string;
|
|
@@ -38,6 +44,8 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
|
|
|
38
44
|
head?: HeadOptions;
|
|
39
45
|
/** The site's public address: canonical URLs and social cards (see head.ts). */
|
|
40
46
|
site?: SiteOptions;
|
|
47
|
+
/** Development: a failing page throws its error (the dev server shows it with its stack) instead of answering 500. */
|
|
48
|
+
dev?: boolean;
|
|
41
49
|
}): {
|
|
42
50
|
fetch(request: Request): Promise<Response>;
|
|
43
51
|
routes: string[];
|
package/dist/server/handler.js
CHANGED
|
@@ -17,6 +17,9 @@ function compile(path) {
|
|
|
17
17
|
}).join('/');
|
|
18
18
|
return { keys, regex: new RegExp(`^${source}$`) };
|
|
19
19
|
}
|
|
20
|
+
export function redirect(to, status = 302) {
|
|
21
|
+
return new Response(null, { status, headers: { location: to } });
|
|
22
|
+
}
|
|
20
23
|
export function routeFromFile(file) {
|
|
21
24
|
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.[^./]+$/, '').replace(/\/index$/, '');
|
|
22
25
|
return path || '/';
|
|
@@ -143,6 +146,22 @@ export function createHandler(pages, options = {}) {
|
|
|
143
146
|
return plain();
|
|
144
147
|
return new Response(head ? null : rootLinks(await page.text(), options.base ?? '/'), { status: 404, headers: page.headers });
|
|
145
148
|
};
|
|
149
|
+
const fail = async (message, err) => {
|
|
150
|
+
if (options.dev)
|
|
151
|
+
throw err ?? new Error(message);
|
|
152
|
+
const plain500 = failure(message);
|
|
153
|
+
if (wantsData || wantsFrag || trim(pathname) === '/500' || !routes.some((r) => r.path === '/500'))
|
|
154
|
+
return plain500;
|
|
155
|
+
try {
|
|
156
|
+
const page = await handler.fetch(new Request(new URL('/500', request.url), { method: request.method }));
|
|
157
|
+
if (page.status !== 200)
|
|
158
|
+
return plain500;
|
|
159
|
+
return new Response(head ? null : rootLinks(await page.text(), options.base ?? '/'), { status: 500, headers: page.headers });
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return plain500;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
146
165
|
const mode = found && modeFor(found.route.path, modes);
|
|
147
166
|
if (!found)
|
|
148
167
|
return notFound();
|
|
@@ -153,8 +172,8 @@ export function createHandler(pages, options = {}) {
|
|
|
153
172
|
const prefix = (options.base ?? '/').replace(/\/$/, '');
|
|
154
173
|
const table = routes.filter((r) => client[r.path]).map((r) => ({ p: (prefix + r.path).replace(/(.)\/$/, '$1'), r: client[r.path] }));
|
|
155
174
|
const shell = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
|
|
156
|
-
links(routes.filter((r) => client[r.path]).flatMap((r) => options.css?.[r.path] ?? [])) +
|
|
157
|
-
`<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes" data-title="${escape(options.head?.titleTemplate ?? '%s')}">${safeJson(JSON.stringify(table))}</script>` +
|
|
175
|
+
links(routes.filter((r) => client[r.path] || r.path === '/404' || r.path === '/500').flatMap((r) => options.css?.[r.path] ?? [])) +
|
|
176
|
+
`<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes" data-title="${escape(options.head?.titleTemplate ?? '%s')}" data-base="${escape(options.base ?? '/')}">${safeJson(JSON.stringify(table))}</script>` +
|
|
158
177
|
`<script type="module" src="${loaderUrl}"></script><script type="module" src="${options.routerUrl ?? '/cl-router.js'}"></script>` +
|
|
159
178
|
'</head><body><noscript>This page is rendered in the browser and needs JavaScript.</noscript></body></html>';
|
|
160
179
|
const { titleTemplate: _, ...siteHead } = options.head ?? {};
|
|
@@ -163,11 +182,11 @@ export function createHandler(pages, options = {}) {
|
|
|
163
182
|
page = completeHead(shell, maskComments, { ...siteHead, site: options.site, base: options.base }, { route: found.route.path, path: pagePath(pathname, false) });
|
|
164
183
|
}
|
|
165
184
|
catch (err) {
|
|
166
|
-
return
|
|
185
|
+
return fail(`${found.route.file}: ${err.message}`, err);
|
|
167
186
|
}
|
|
168
187
|
return new Response(head ? null : page, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
169
188
|
}
|
|
170
|
-
let props = found.params;
|
|
189
|
+
let props = found.route.path === '/500' ? { status: 500, ...found.params } : found.params;
|
|
171
190
|
const dataFile = found.route.file.replace(/\.[^./]+$/, '.load.ts');
|
|
172
191
|
const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
|
|
173
192
|
if (mod?.load) {
|
|
@@ -176,26 +195,34 @@ export function createHandler(pages, options = {}) {
|
|
|
176
195
|
loaded = await mod.load({ params: found.params, request });
|
|
177
196
|
}
|
|
178
197
|
catch (err) {
|
|
179
|
-
return
|
|
198
|
+
return fail(`${dataFile}: load() failed: ${err?.message ?? err}`, err);
|
|
180
199
|
}
|
|
200
|
+
if (loaded instanceof Response)
|
|
201
|
+
return loaded;
|
|
181
202
|
if (loaded === null || typeof loaded !== 'object' || Array.isArray(loaded)) {
|
|
182
|
-
return
|
|
203
|
+
return fail(`${dataFile}: load() must return an object of page inputs (or a Response, such as redirect()), got ${Array.isArray(loaded) ? 'an array' : loaded === null ? 'null' : typeof loaded}`);
|
|
183
204
|
}
|
|
184
205
|
;
|
|
185
206
|
globalThis.__clLoaderRan = true;
|
|
186
|
-
props = { ...
|
|
207
|
+
props = { ...props, ...loaded };
|
|
187
208
|
}
|
|
188
209
|
if (wantsData) {
|
|
189
210
|
return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
|
|
190
211
|
}
|
|
191
|
-
let html
|
|
212
|
+
let html;
|
|
213
|
+
try {
|
|
214
|
+
html = (await found.route.load()).render(props);
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
return fail(`${found.route.file}: render failed: ${err?.message ?? err}`, err);
|
|
218
|
+
}
|
|
192
219
|
if (!/<html[\s>]/i.test(maskComments(html)))
|
|
193
220
|
html = `<!doctype html><html><head><meta charset="utf-8"><title>clarusjs</title></head><body>${html}</body></html>`;
|
|
194
221
|
try {
|
|
195
222
|
html = completeHead(html, maskComments, { ...options.head, site: options.site, base: options.base }, { route: found.route.path, path: pagePath(pathname, wantsFrag) });
|
|
196
223
|
}
|
|
197
224
|
catch (err) {
|
|
198
|
-
return
|
|
225
|
+
return fail(`${found.route.file}: ${err.message}`, err);
|
|
199
226
|
}
|
|
200
227
|
if (wantsFrag) {
|
|
201
228
|
const fragment = toFragment(html).replace(/^(<title\b[^>]*>[\s\S]*?<\/title\s*>)/i, (t) => t + pageLinks(found.route));
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** `find` ending in '/' is a prefix; otherwise it matches itself, and (unless `exact`) itself followed by '/…'. */
|
|
2
|
+
export type Alias = {
|
|
3
|
+
find: string;
|
|
4
|
+
replacement: string;
|
|
5
|
+
exact?: boolean;
|
|
6
|
+
};
|
|
7
|
+
/** The project's aliases; `vite`: the Vite config's `resolve.alias` (an object or a list). */
|
|
8
|
+
export declare function projectAliases(root: string, vite?: unknown): Alias[];
|
|
9
|
+
/** Where `spec` points when an alias matches it (an absolute path), else undefined. */
|
|
10
|
+
export declare function resolveAlias(spec: string, aliases: Alias[]): string | undefined;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
function readJsonc(text) {
|
|
4
|
+
const bare = text.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '');
|
|
5
|
+
return JSON.parse(bare.replace(/,(\s*[}\]])/g, '$1'));
|
|
6
|
+
}
|
|
7
|
+
export function projectAliases(root, vite = []) {
|
|
8
|
+
const aliases = [{ find: '~/', replacement: resolve(root, 'src') + '/' }];
|
|
9
|
+
const config = ['tsconfig.json', 'jsconfig.json'].map((name) => resolve(root, name)).find(existsSync);
|
|
10
|
+
if (config) {
|
|
11
|
+
let options = {};
|
|
12
|
+
try {
|
|
13
|
+
options = readJsonc(readFileSync(config, 'utf8')).compilerOptions ?? {};
|
|
14
|
+
}
|
|
15
|
+
catch { }
|
|
16
|
+
const base = resolve(root, options.baseUrl ?? '.');
|
|
17
|
+
for (const [key, targets] of Object.entries(options.paths ?? {})) {
|
|
18
|
+
const target = targets?.[0];
|
|
19
|
+
if (!target)
|
|
20
|
+
continue;
|
|
21
|
+
if (key.endsWith('/*') && target.endsWith('/*'))
|
|
22
|
+
aliases.push({ find: key.slice(0, -1), replacement: resolve(base, target.slice(0, -2)) + '/' });
|
|
23
|
+
else if (!key.includes('*'))
|
|
24
|
+
aliases.push({ find: key, replacement: resolve(base, target), exact: true });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const list = Array.isArray(vite) ? vite : vite && typeof vite === 'object' ? Object.entries(vite).map(([find, replacement]) => ({ find, replacement })) : [];
|
|
28
|
+
for (const { find, replacement } of list) {
|
|
29
|
+
if (typeof find === 'string' && typeof replacement === 'string')
|
|
30
|
+
aliases.push({ find, replacement });
|
|
31
|
+
}
|
|
32
|
+
return aliases.sort((a, b) => b.find.length - a.find.length);
|
|
33
|
+
}
|
|
34
|
+
export function resolveAlias(spec, aliases) {
|
|
35
|
+
for (const { find, replacement, exact } of aliases) {
|
|
36
|
+
if (find.endsWith('/') ? spec.startsWith(find) : spec === find)
|
|
37
|
+
return spec === find ? replacement : replacement + spec.slice(find.length);
|
|
38
|
+
if (!exact && !find.endsWith('/') && spec.startsWith(find + '/'))
|
|
39
|
+
return replacement + spec.slice(find.length);
|
|
40
|
+
}
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
package/dist/vite/build.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Alias } from './aliases.ts';
|
|
1
2
|
/** Absolute paths of every component file under `srcDir` (`.tscl`, or any page source extension given). */
|
|
2
3
|
export declare function findClarusFiles(srcDir: string, extensions?: string[]): string[];
|
|
3
4
|
/**
|
|
@@ -27,4 +28,4 @@ export declare function packageOf(file: string): string | undefined;
|
|
|
27
28
|
* specifiers ('@clarusjs/theme-docs/layout.tscl', resolved as Node would from the app). Real paths, so a workspace
|
|
28
29
|
* package linked into node_modules is one file, not two.
|
|
29
30
|
*/
|
|
30
|
-
export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[]): string[];
|
|
31
|
+
export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[], aliases?: Alias[]): string[];
|
package/dist/vite/build.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { resolveAlias } from './aliases.js';
|
|
1
2
|
import { spawnSync } from 'node:child_process';
|
|
2
3
|
import { readdirSync, realpathSync } from 'node:fs';
|
|
3
4
|
import { createRequire } from 'node:module';
|
|
@@ -84,7 +85,7 @@ export async function prerender(serverEntry, outDir, manifestFile, only) {
|
|
|
84
85
|
export function packageOf(file) {
|
|
85
86
|
return /.*[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)[\\/]/.exec(file)?.[1].replace(/\\/g, '/');
|
|
86
87
|
}
|
|
87
|
-
export function reachableComponents(root, start, read, extensions) {
|
|
88
|
+
export function reachableComponents(root, start, read, extensions, aliases = []) {
|
|
88
89
|
const require = createRequire(resolve(root, 'package.json'));
|
|
89
90
|
const seen = new Set();
|
|
90
91
|
const queue = start.map((f) => realpathSync(f));
|
|
@@ -106,7 +107,7 @@ export function reachableComponents(root, start, read, extensions) {
|
|
|
106
107
|
continue;
|
|
107
108
|
let target;
|
|
108
109
|
try {
|
|
109
|
-
target = spec.startsWith('.') ? resolve(dirname(file), spec) : spec.startsWith('/') ? resolve(root, spec.slice(1)) : require.resolve(spec);
|
|
110
|
+
target = spec.startsWith('.') ? resolve(dirname(file), spec) : spec.startsWith('/') ? resolve(root, spec.slice(1)) : resolveAlias(spec, aliases) ?? require.resolve(spec);
|
|
110
111
|
target = realpathSync(target);
|
|
111
112
|
}
|
|
112
113
|
catch {
|
package/dist/vite/plugin.d.ts
CHANGED
|
@@ -24,6 +24,12 @@ export type ClarusOptions = {
|
|
|
24
24
|
anchors?: LinkLevel;
|
|
25
25
|
strict?: boolean;
|
|
26
26
|
};
|
|
27
|
+
/**
|
|
28
|
+
* Paths that moved: `{ '/old': '/new' }` (a site path or a full URL). The build writes a page at each old path that
|
|
29
|
+
* sends visitors on, and `_redirects` lines (a real 301 on Netlify and Cloudflare Pages); dev answers 301.
|
|
30
|
+
* @see https://clarusjs.com/guide/routing
|
|
31
|
+
*/
|
|
32
|
+
redirects?: Record<string, string>;
|
|
27
33
|
/**
|
|
28
34
|
* Every page's <head>: `titleTemplate` ('%s · Site') wraps the document title, `tags` are added unless the page has
|
|
29
35
|
* its own with the same key. Anything else: export `transformHead(head, page)` from src/head.ts.
|
package/dist/vite/plugin.js
CHANGED
|
@@ -19,6 +19,8 @@ export { gitDates } from './sitemap.js';
|
|
|
19
19
|
import { writeManifest } from './manifest.js';
|
|
20
20
|
import { writeNetlifyFunction } from './netlify.js';
|
|
21
21
|
import { checkLinks } from './links.js';
|
|
22
|
+
import { checkRedirects, redirectFor, writeRedirects } from './redirects.js';
|
|
23
|
+
import { projectAliases, resolveAlias } from './aliases.js';
|
|
22
24
|
import { gitDates, sitemapXml } from './sitemap.js';
|
|
23
25
|
import { checkModes, modeFor } from '../server/modes.js';
|
|
24
26
|
import { rootLinks, routeFromFile } from '../server/handler.js';
|
|
@@ -37,7 +39,7 @@ const NAV_ENTRY = 'cl-nav';
|
|
|
37
39
|
const STYLES_ENTRY = 'cl-styles';
|
|
38
40
|
const STYLES_FILE = '.clarusjs/styles.css';
|
|
39
41
|
const scopeFor = (root, file) => scopeId(relative(root, file).split(sep).join('/'));
|
|
40
|
-
function pageStylesheets(root, files) {
|
|
42
|
+
function pageStylesheets(root, files, aliases = []) {
|
|
41
43
|
const deps = new Map();
|
|
42
44
|
const require = createRequire(resolve(root, 'package.json'));
|
|
43
45
|
const packageFile = (spec) => { try {
|
|
@@ -59,9 +61,10 @@ function pageStylesheets(root, files) {
|
|
|
59
61
|
const path = from.replace(/\?.*$/, '');
|
|
60
62
|
return path.startsWith('/') ? resolve(root, `.${path}`) : resolve(dirname(file), path);
|
|
61
63
|
};
|
|
64
|
+
const bare = (from) => resolveAlias(from.replace(/\?.*$/, ''), aliases) ?? packageFile(from);
|
|
62
65
|
deps.set(file, {
|
|
63
|
-
css: parsed?.cssImports.map((c) => near(c.from)) ?? [],
|
|
64
|
-
components: parsed?.imports.map((imp) => (/^[./]/.test(imp.from) ? near(imp.from) :
|
|
66
|
+
css: parsed?.cssImports.map((c) => (/^[./]/.test(c.from) ? near(c.from) : bare(c.from))).filter((f) => !!f) ?? [],
|
|
67
|
+
components: parsed?.imports.map((imp) => (/^[./]/.test(imp.from) ? near(imp.from) : bare(imp.from))).filter((f) => !!f) ?? [],
|
|
65
68
|
});
|
|
66
69
|
}
|
|
67
70
|
return deps.get(file);
|
|
@@ -139,9 +142,10 @@ export default function clarusjs(options = {}) {
|
|
|
139
142
|
throw new Error('clarusjs: .tscl files are compiled directly; a source needs its own extension');
|
|
140
143
|
}
|
|
141
144
|
const extensions = ['.tscl', ...sources.map((src) => src.extension)];
|
|
145
|
+
let aliases = [];
|
|
142
146
|
const files = {
|
|
143
147
|
find: (dir) => findClarusFiles(dir, extensions).filter((f) => f.endsWith('.tscl') || f.includes(`${sep}src${sep}pages${sep}`)),
|
|
144
|
-
components: (appRoot) => reachableComponents(appRoot, files.find(resolve(appRoot, 'src')), (file) => files.read(file, appRoot), extensions),
|
|
148
|
+
components: (appRoot) => reachableComponents(appRoot, files.find(resolve(appRoot, 'src')), (file) => files.read(file, appRoot), extensions, aliases),
|
|
145
149
|
read: (file, appRoot) => {
|
|
146
150
|
const code = readFileSync(file, 'utf8');
|
|
147
151
|
const src = sources.find((x) => file.endsWith(x.extension));
|
|
@@ -183,12 +187,17 @@ export default function clarusjs(options = {}) {
|
|
|
183
187
|
return {
|
|
184
188
|
name: 'clarusjs',
|
|
185
189
|
config(userConfig, env) {
|
|
190
|
+
const projectRoot = resolve(userConfig.root ?? process.cwd());
|
|
191
|
+
aliases = projectAliases(projectRoot, userConfig.resolve?.alias);
|
|
192
|
+
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
193
|
+
const own = projectAliases(projectRoot).map((a) => ({ find: new RegExp(`^${escape(a.find)}${a.exact ? '$' : a.find.endsWith('/') ? '' : '(?=/|$)'}`), replacement: a.replacement }));
|
|
186
194
|
const config = {
|
|
187
195
|
appType: 'custom',
|
|
188
196
|
resolve: {
|
|
189
197
|
alias: [
|
|
190
198
|
{ find: 'clarusjs/runtime/server', replacement: here('../runtime/server') },
|
|
191
199
|
{ find: 'clarusjs/runtime', replacement: here('../runtime/index') },
|
|
200
|
+
...own,
|
|
192
201
|
],
|
|
193
202
|
},
|
|
194
203
|
};
|
|
@@ -223,7 +232,7 @@ export default function clarusjs(options = {}) {
|
|
|
223
232
|
input[NAV_ENTRY] = here('../runtime/fragments');
|
|
224
233
|
if (writeStyles(appRoot, files))
|
|
225
234
|
input[STYLES_ENTRY] = resolve(appRoot, STYLES_FILE);
|
|
226
|
-
for (const sheet of new Set([...pageStylesheets(appRoot, files).values()].flat())) {
|
|
235
|
+
for (const sheet of new Set([...pageStylesheets(appRoot, files, aliases).values()].flat())) {
|
|
227
236
|
if (!existsSync(sheet))
|
|
228
237
|
throw new Error(`clarusjs: imported stylesheet not found: ${relative(appRoot, sheet)}`);
|
|
229
238
|
input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3))}`] = sheet;
|
|
@@ -269,6 +278,7 @@ export default function clarusjs(options = {}) {
|
|
|
269
278
|
const { client, ssr } = builder.environments;
|
|
270
279
|
if (!client || !ssr)
|
|
271
280
|
return;
|
|
281
|
+
checkRedirects(options.redirects ?? {}, files.find(resolve(builder.config.root, 'src/pages')).map((f) => routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`)));
|
|
272
282
|
await builder.build(client);
|
|
273
283
|
await builder.build(ssr);
|
|
274
284
|
const entry = resolve(builder.config.root, SERVER_OUT, 'index.mjs');
|
|
@@ -289,6 +299,17 @@ export default function clarusjs(options = {}) {
|
|
|
289
299
|
writeFileSync(resolve(out, routeToFile('/404')), html);
|
|
290
300
|
writeFileSync(resolve(out, '404.html'), html);
|
|
291
301
|
}
|
|
302
|
+
if (pageRoutes.includes('/500') && !clientRoutes.includes('/500')) {
|
|
303
|
+
const html = rootLinks(readFileSync(resolve(out, routeToFile('/500')), 'utf8'), basePath(builder.config.base));
|
|
304
|
+
writeFileSync(resolve(out, routeToFile('/500')), html);
|
|
305
|
+
writeFileSync(resolve(out, '500.html'), html);
|
|
306
|
+
}
|
|
307
|
+
if (options.redirects) {
|
|
308
|
+
writeRedirects(out, options.redirects, basePath(builder.config.base).replace(/\/$/, ''), routes);
|
|
309
|
+
const moved = Object.keys(options.redirects).map((from) => (from.length > 1 ? from.replace(/\/+$/, '') : from));
|
|
310
|
+
pageRoutes.push(...moved);
|
|
311
|
+
clientRoutes.push(...moved);
|
|
312
|
+
}
|
|
292
313
|
const issues = checkLinks({
|
|
293
314
|
outDir: out,
|
|
294
315
|
routes: pageRoutes,
|
|
@@ -337,7 +358,7 @@ export default function clarusjs(options = {}) {
|
|
|
337
358
|
writeFileSync(file, html.replace(marker, ''));
|
|
338
359
|
return !!marker || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? ''));
|
|
339
360
|
};
|
|
340
|
-
const pages = pageRoutes.filter((page) => page !== '/404' && !clientRoutes.includes(page) && !optedOut(page) && !exclude.some((re) => re.test(page)))
|
|
361
|
+
const pages = pageRoutes.filter((page) => page !== '/404' && page !== '/500' && !clientRoutes.includes(page) && !optedOut(page) && !exclude.some((re) => re.test(page)))
|
|
341
362
|
.map((path) => ({ path, lastmod: dates.get(fileOf(path) ?? '') ?? epoch }));
|
|
342
363
|
writeFileSync(resolve(out, 'sitemap.xml'), sitemapXml(options.site.url, builder.config.base, pages));
|
|
343
364
|
}
|
|
@@ -348,16 +369,19 @@ export default function clarusjs(options = {}) {
|
|
|
348
369
|
if (options.adapter === 'netlify')
|
|
349
370
|
writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true);
|
|
350
371
|
},
|
|
351
|
-
resolveId(id) {
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
372
|
+
resolveId: { order: 'pre', handler(id, importer) {
|
|
373
|
+
if (/^\.\/navigate\.[jt]s$/.test(id) && importer && /[\\/]runtime[\\/](router|fragments)\.[jt]s$/.test(importer)) {
|
|
374
|
+
return `${here('../runtime/navigate')}?cl-copy=${/router\.[jt]s$/.test(importer) ? 'router' : 'nav'}`;
|
|
375
|
+
}
|
|
376
|
+
if (id === '/cl-loader.js')
|
|
377
|
+
return here('../runtime/loader');
|
|
378
|
+
if (id === '/cl-router.js')
|
|
379
|
+
return here('../runtime/router');
|
|
380
|
+
if (id === '/cl-nav.js')
|
|
381
|
+
return here('../runtime/fragments');
|
|
382
|
+
if (id === ENTRY)
|
|
383
|
+
return '\0' + ENTRY;
|
|
384
|
+
} },
|
|
361
385
|
load: { order: 'pre', handler(id) {
|
|
362
386
|
if (id !== '\0' + ENTRY) {
|
|
363
387
|
if (/[?&](raw|url|inline)\b/.test(id) || id.startsWith('\0'))
|
|
@@ -372,7 +396,7 @@ export default function clarusjs(options = {}) {
|
|
|
372
396
|
const routerUrl = urls?.get(ROUTER_ENTRY) ?? '/cl-router.js';
|
|
373
397
|
const navUrl = urls?.get(NAV_ENTRY) ?? '/cl-nav.js';
|
|
374
398
|
const css = {};
|
|
375
|
-
for (const [route, sheets] of pageStylesheets(root, files)) {
|
|
399
|
+
for (const [route, sheets] of pageStylesheets(root, files, aliases)) {
|
|
376
400
|
if (!sheets.length)
|
|
377
401
|
continue;
|
|
378
402
|
css[route] = sheets.map((sheet) => {
|
|
@@ -404,6 +428,7 @@ export default function clarusjs(options = {}) {
|
|
|
404
428
|
` client: ${JSON.stringify(client)},\n` +
|
|
405
429
|
` base: ${JSON.stringify(base)},\n` +
|
|
406
430
|
` fragments: ${options.fragments === true},\n` +
|
|
431
|
+
` dev: ${command === 'serve'},\n` +
|
|
407
432
|
` navUrl: ${JSON.stringify(navUrl)},\n` +
|
|
408
433
|
` stylesUrl: ${JSON.stringify(stylesUrl)},\n` +
|
|
409
434
|
` css: ${JSON.stringify(css)},\n` +
|
|
@@ -413,7 +438,7 @@ export default function clarusjs(options = {}) {
|
|
|
413
438
|
} },
|
|
414
439
|
transform: {
|
|
415
440
|
filter: { id: fileRe },
|
|
416
|
-
handler(raw, id) {
|
|
441
|
+
async handler(raw, id) {
|
|
417
442
|
const file = id.replace(/\?.*$/, '');
|
|
418
443
|
const src = sources.find((x) => file.endsWith(x.extension));
|
|
419
444
|
if (src && (/[?&](raw|url|inline)\b/.test(id) || !normalizePath(file).startsWith(normalizePath(resolve(root, 'src/pages')) + '/')))
|
|
@@ -432,6 +457,22 @@ export default function clarusjs(options = {}) {
|
|
|
432
457
|
if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
|
|
433
458
|
this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
|
|
434
459
|
}
|
|
460
|
+
let parsed;
|
|
461
|
+
try {
|
|
462
|
+
parsed = parse(code, file);
|
|
463
|
+
}
|
|
464
|
+
catch {
|
|
465
|
+
parsed = null;
|
|
466
|
+
}
|
|
467
|
+
for (const imp of parsed ? [...parsed.imports, ...parsed.dataImports, ...parsed.cssImports] : []) {
|
|
468
|
+
if (/^[./]/.test(imp.from) || /^[a-z]+:/i.test(imp.from))
|
|
469
|
+
continue;
|
|
470
|
+
if (await this.resolve(imp.from.replace(/\?.*$/, ''), id))
|
|
471
|
+
continue;
|
|
472
|
+
const before = code.slice(0, imp.start);
|
|
473
|
+
const line = before.split('\n').length;
|
|
474
|
+
this.error(`${rel}:${line}:${imp.start - before.lastIndexOf('\n')} cannot resolve '${imp.from}': no file, package or path alias (~/, tsconfig paths, resolve.alias) matches it`);
|
|
475
|
+
}
|
|
435
476
|
try {
|
|
436
477
|
const renderImports = renderQuery && this.environment.config.consumer !== 'server';
|
|
437
478
|
return { code: compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file) }).code, map: null, moduleType: 'js' };
|
|
@@ -502,6 +543,13 @@ export default function clarusjs(options = {}) {
|
|
|
502
543
|
const env = server.environments.ssr;
|
|
503
544
|
if (!isRunnableDevEnvironment(env))
|
|
504
545
|
return next();
|
|
546
|
+
if (options.redirects) {
|
|
547
|
+
const prefix = basePath(server.config.base).replace(/\/$/, '');
|
|
548
|
+
const pathname = new URL(req.url ?? '/', 'http://x').pathname;
|
|
549
|
+
const to = redirectFor(options.redirects, pathname.startsWith(prefix + '/') ? pathname.slice(prefix.length) : pathname, prefix);
|
|
550
|
+
if (to !== undefined)
|
|
551
|
+
return void res.writeHead(301, { location: to }).end();
|
|
552
|
+
}
|
|
505
553
|
const app = await env.runner.import(ENTRY);
|
|
506
554
|
const response = await app.default.fetch(toRequest(req));
|
|
507
555
|
if (response.status === 404 && !response.headers.get('content-type')?.startsWith('text/html'))
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Old paths start with /; none may be a page (`pages`: the site's routes, [param] segments matching any one). */
|
|
2
|
+
export declare function checkRedirects(redirects: Record<string, string>, pages?: string[]): void;
|
|
3
|
+
/** The redirect for a request path in dev (the base already removed), or undefined. */
|
|
4
|
+
export declare function redirectFor(redirects: Record<string, string>, pathname: string, prefix: string): string | undefined;
|
|
5
|
+
/**
|
|
6
|
+
* Writes each old path's page and the _redirects lines (after any the site's public/ already has). `built`: every
|
|
7
|
+
* route the build wrote (pages, data and fragment files); a redirect whose file would replace one of them, or land
|
|
8
|
+
* outside `out` (%2e%2e segments), fails before anything is written.
|
|
9
|
+
*/
|
|
10
|
+
export declare function writeRedirects(out: string, redirects: Record<string, string>, prefix: string, built?: string[]): void;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, resolve, sep } from 'node:path';
|
|
3
|
+
import { routeToFile } from './build.js';
|
|
4
|
+
const attr = (s) => s.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
|
5
|
+
export function checkRedirects(redirects, pages = []) {
|
|
6
|
+
const route = (r) => new RegExp(`^${r.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
|
|
7
|
+
for (const from of Object.keys(redirects)) {
|
|
8
|
+
if (!from.startsWith('/'))
|
|
9
|
+
throw new Error(`clarusjs: redirects['${from}']: paths start with /`);
|
|
10
|
+
if (pages.some((p) => route(p).test(trim(from))))
|
|
11
|
+
throw new Error(`clarusjs: redirects['${from}']: ${from} is a page; remove the page or the redirect`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
15
|
+
const target = (to, prefix) => (to.startsWith('/') ? prefix + to : to);
|
|
16
|
+
export function redirectFor(redirects, pathname, prefix) {
|
|
17
|
+
const to = Object.entries(redirects).find(([from]) => trim(from) === trim(pathname))?.[1];
|
|
18
|
+
return to === undefined ? undefined : target(to, prefix);
|
|
19
|
+
}
|
|
20
|
+
export function writeRedirects(out, redirects, prefix, built = []) {
|
|
21
|
+
const fileOf = (route) => resolve(out, routeToFile(route));
|
|
22
|
+
const taken = new Map(built.map((route) => [fileOf(route), route]));
|
|
23
|
+
for (const from of Object.keys(redirects)) {
|
|
24
|
+
const file = fileOf(from);
|
|
25
|
+
if (!file.startsWith(resolve(out) + sep))
|
|
26
|
+
throw new Error(`clarusjs: redirects['${from}'] is outside the site`);
|
|
27
|
+
if (taken.has(file))
|
|
28
|
+
throw new Error(`clarusjs: redirects['${from}'] would replace the page ${taken.get(file)}`);
|
|
29
|
+
}
|
|
30
|
+
const lines = [];
|
|
31
|
+
for (const [from, to] of Object.entries(redirects)) {
|
|
32
|
+
const url = attr(target(to, prefix));
|
|
33
|
+
const file = fileOf(from);
|
|
34
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
35
|
+
writeFileSync(file, `<!doctype html><html><head><meta charset="utf-8"><title>Moved</title><meta http-equiv="refresh" content="0; url=${url}"><link rel="canonical" href="${url}"><meta name="robots" content="noindex"></head><body><p>This page moved to <a href="${url}">${url}</a>.</p></body></html>\n`);
|
|
36
|
+
lines.push(`${prefix}${trim(from)} ${target(to, prefix)} 301\n`);
|
|
37
|
+
}
|
|
38
|
+
const file = resolve(out, '_redirects');
|
|
39
|
+
if (lines.length)
|
|
40
|
+
writeFileSync(file, (existsSync(file) ? readFileSync(file, 'utf8').replace(/\n?$/, '\n') : '') + lines.join(''));
|
|
41
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clarusjs",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"description": "Clear, compiled views: templates compiled to server HTML, with JavaScript only for interactive islands. SSR, SSG and CSR from one component model, built on Vite.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -28,6 +28,16 @@
|
|
|
28
28
|
"url": "https://github.com/forinda/clarusjs/issues"
|
|
29
29
|
},
|
|
30
30
|
"type": "module",
|
|
31
|
+
"sideEffects": [
|
|
32
|
+
"./src/runtime/loader.ts",
|
|
33
|
+
"./src/runtime/router.ts",
|
|
34
|
+
"./src/runtime/fragments.ts",
|
|
35
|
+
"./src/runtime/navigation.ts",
|
|
36
|
+
"./dist/runtime/loader.js",
|
|
37
|
+
"./dist/runtime/router.js",
|
|
38
|
+
"./dist/runtime/fragments.js",
|
|
39
|
+
"./dist/runtime/navigation.js"
|
|
40
|
+
],
|
|
31
41
|
"exports": {
|
|
32
42
|
"./compiler": {
|
|
33
43
|
"types": "./dist/compiler/index.d.ts",
|
|
@@ -37,6 +47,10 @@
|
|
|
37
47
|
"types": "./dist/runtime/index.d.ts",
|
|
38
48
|
"default": "./dist/runtime/index.js"
|
|
39
49
|
},
|
|
50
|
+
"./navigation": {
|
|
51
|
+
"types": "./dist/runtime/navigation.d.ts",
|
|
52
|
+
"default": "./dist/runtime/navigation.js"
|
|
53
|
+
},
|
|
40
54
|
"./runtime/server": {
|
|
41
55
|
"types": "./dist/runtime/server.d.ts",
|
|
42
56
|
"default": "./dist/runtime/server.js"
|