clarusjs 0.6.0 → 0.7.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/README.md +2 -0
- package/dist/compiler/index.d.ts +6 -0
- package/dist/compiler/index.js +42 -3
- package/dist/compiler/parse.d.ts +9 -0
- package/dist/compiler/parse.js +32 -3
- package/dist/runtime/fragments.js +15 -0
- package/dist/runtime/loader.js +7 -1
- package/dist/runtime/router.js +15 -8
- package/dist/server/handler.d.ts +5 -1
- package/dist/server/handler.js +18 -9
- package/dist/server/views.js +1 -1
- package/dist/vite/build.d.ts +2 -2
- package/dist/vite/build.js +3 -3
- package/dist/vite/links.d.ts +18 -0
- package/dist/vite/links.js +93 -0
- package/dist/vite/plugin.d.ts +26 -0
- package/dist/vite/plugin.js +218 -44
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
|
|
7
7
|
<p align="center"><strong>Clear, compiled views.</strong></p>
|
|
8
8
|
|
|
9
|
+
<p align="center"><a href="https://clarusjs.com">Documentation</a> · <a href="https://clarusjs.com/guide/getting-started">Getting started</a> · <a href="https://www.npmjs.com/package/clarusjs">npm</a></p>
|
|
10
|
+
|
|
9
11
|
Write components in a familiar template language. clarusjs compiles them to plain server HTML and ships JavaScript
|
|
10
12
|
only for the parts that are interactive. Static sites, server rendering and client apps share one component model,
|
|
11
13
|
and you can always see where each line runs.
|
package/dist/compiler/index.d.ts
CHANGED
|
@@ -3,14 +3,20 @@ export { ClarusError } from './errors.ts';
|
|
|
3
3
|
* `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
|
|
4
4
|
* browser (a client route's page, or a component re-rendered inside an island).
|
|
5
5
|
*/
|
|
6
|
+
/** `scope`: the id that scopes this component's styles (default: from the file name). */
|
|
6
7
|
export type CompileOptions = {
|
|
7
8
|
file: string;
|
|
8
9
|
target: 'server' | 'client';
|
|
9
10
|
clientUrl?: string;
|
|
10
11
|
renderImports?: boolean;
|
|
12
|
+
scope?: string;
|
|
11
13
|
};
|
|
14
|
+
/** `css`: the component's stylesheet (scoped blocks wrapped in @scope, global ones as written); '' without <style>. */
|
|
12
15
|
export type CompileResult = {
|
|
13
16
|
code: string;
|
|
14
17
|
stateful: boolean;
|
|
18
|
+
css: string;
|
|
15
19
|
};
|
|
16
20
|
export declare function compile(source: string, options: CompileOptions): CompileResult;
|
|
21
|
+
/** 'src/components/card.tscl' → 'card-<short hash of the path>'. */
|
|
22
|
+
export declare function scopeId(file: string): string;
|
package/dist/compiler/index.js
CHANGED
|
@@ -5,10 +5,49 @@ import { lower } from './ir.js';
|
|
|
5
5
|
import { parse } from './parse.js';
|
|
6
6
|
export { ClarusError } from './errors.js';
|
|
7
7
|
export function compile(source, options) {
|
|
8
|
-
const
|
|
8
|
+
const parsed = parse(source, options.file);
|
|
9
|
+
let css = '';
|
|
10
|
+
if (parsed.styles.some((s) => !s.global)) {
|
|
11
|
+
// Native @scope: rules apply inside the component's top-level elements (style those with :scope) and stop at
|
|
12
|
+
// the next component's elements. The top-level elements are marked so the scope can find them.
|
|
13
|
+
const id = options.scope ?? scopeId(options.file);
|
|
14
|
+
const components = new Set(parsed.imports.map((imp) => imp.name));
|
|
15
|
+
markRoots(parsed.nodes, id, components);
|
|
16
|
+
for (const s of parsed.styles)
|
|
17
|
+
css += s.global ? s.css : `@scope ([data-cl-c="${id}"]) to ([data-cl-c]) {${s.css.replace(/\s*$/, '')}\n}\n`;
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
css = parsed.styles.map((s) => s.css).join('');
|
|
21
|
+
}
|
|
22
|
+
const ir = lower(parsed, options.file, source);
|
|
9
23
|
if (options.target === 'client')
|
|
10
|
-
return { code: emitClient(ir), stateful: ir.stateful };
|
|
24
|
+
return { code: emitClient(ir), stateful: ir.stateful, css };
|
|
11
25
|
if (ir.stateful && !options.clientUrl)
|
|
12
26
|
throw new Error(`[clarusjs] ${options.file}: clientUrl is required to compile a stateful component for the server`);
|
|
13
|
-
return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful };
|
|
27
|
+
return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful, css };
|
|
28
|
+
}
|
|
29
|
+
/** 'src/components/card.tscl' → 'card-<short hash of the path>'. */
|
|
30
|
+
export function scopeId(file) {
|
|
31
|
+
let h = 0x811c9dc5; // FNV-1a
|
|
32
|
+
for (let i = 0; i < file.length; i++)
|
|
33
|
+
h = Math.imul(h ^ file.charCodeAt(i), 0x01000193);
|
|
34
|
+
const name = (file.split(/[\\/]/).pop() ?? 'c').replace(/\.tscl$/, '').replace(/[^\w-]/g, '') || 'c';
|
|
35
|
+
return `${name}-${(h >>> 0).toString(36)}`;
|
|
36
|
+
}
|
|
37
|
+
/** The component's top-level HTML elements (also inside top-level @if/@for) get data-cl-c="id". */
|
|
38
|
+
function markRoots(nodes, id, components) {
|
|
39
|
+
for (const node of nodes) {
|
|
40
|
+
if (node.type === 'element' && !components.has(node.tag) && node.tag !== 'slot') {
|
|
41
|
+
node.attrs.push({ kind: 'static', name: 'data-cl-c', value: id, start: node.start });
|
|
42
|
+
}
|
|
43
|
+
else if (node.type === 'if') {
|
|
44
|
+
for (const b of node.branches)
|
|
45
|
+
markRoots(b.children, id, components);
|
|
46
|
+
}
|
|
47
|
+
else if (node.type === 'for') {
|
|
48
|
+
markRoots(node.children, id, components);
|
|
49
|
+
if (node.empty)
|
|
50
|
+
markRoots(node.empty, id, components);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
14
53
|
}
|
package/dist/compiler/parse.d.ts
CHANGED
|
@@ -101,6 +101,15 @@ export type ParsedFile = {
|
|
|
101
101
|
code: string;
|
|
102
102
|
start: number;
|
|
103
103
|
};
|
|
104
|
+
styles: {
|
|
105
|
+
css: string;
|
|
106
|
+
global: boolean;
|
|
107
|
+
start: number;
|
|
108
|
+
}[];
|
|
109
|
+
cssImports: {
|
|
110
|
+
from: string;
|
|
111
|
+
start: number;
|
|
112
|
+
}[];
|
|
104
113
|
nodes: TemplateNode[];
|
|
105
114
|
};
|
|
106
115
|
export declare function parse(source: string, file: string): ParsedFile;
|
package/dist/compiler/parse.js
CHANGED
|
@@ -5,8 +5,9 @@ const INPUT_RE = /^@input\s+([A-Za-z_$][\w$]*)\s*:\s*([^=\n]+?)\s*(?:=\s*(.+?))?
|
|
|
5
5
|
const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
|
|
6
6
|
const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s+from\s+(['"])(.+?)\2\s*$/d;
|
|
7
7
|
const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
|
|
8
|
+
const CSS_IMPORT_RE = /^@import\s+(['"])(.+?)\1\s*$/;
|
|
8
9
|
export function parse(source, file) {
|
|
9
|
-
const out = { inputs: [], imports: [], typeImports: [], dataImports: [], nodes: [] };
|
|
10
|
+
const out = { inputs: [], imports: [], typeImports: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
|
|
10
11
|
let i = 0;
|
|
11
12
|
const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
|
|
12
13
|
const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
|
|
@@ -32,6 +33,11 @@ export function parse(source, file) {
|
|
|
32
33
|
else
|
|
33
34
|
out.dataImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + line.indexOf(m[1], 7) });
|
|
34
35
|
}
|
|
36
|
+
else if ((m = CSS_IMPORT_RE.exec(line))) {
|
|
37
|
+
if (!/\.css(\?|$)/.test(m[2]))
|
|
38
|
+
fail(`@import without a name only takes a stylesheet (.css): "${m[2]}"`, i);
|
|
39
|
+
out.cssImports.push({ from: m[2], start: i });
|
|
40
|
+
}
|
|
35
41
|
else
|
|
36
42
|
fail(`unknown or malformed directive "${line.split(/\s/)[0]}"`, i);
|
|
37
43
|
i = end;
|
|
@@ -367,9 +373,21 @@ export function parse(source, file) {
|
|
|
367
373
|
fail(`unclosed <${tag}>`, start);
|
|
368
374
|
const selfClosing = source.startsWith('/>', i);
|
|
369
375
|
i += selfClosing ? 2 : 1;
|
|
370
|
-
if (tag === 'script') {
|
|
376
|
+
if (tag === 'script' && list.some((a) => a.name === 'inline')) {
|
|
377
|
+
// <script inline>: written out as is and run where it stands (e.g. in <head>, before the first paint).
|
|
378
|
+
const bound = list.find((a) => a.kind !== 'static');
|
|
379
|
+
if (bound)
|
|
380
|
+
fail('an inline script takes static attributes only', bound.start);
|
|
381
|
+
const end = source.indexOf('</script>', i);
|
|
382
|
+
if (end === -1)
|
|
383
|
+
fail('unclosed <script inline>', start);
|
|
384
|
+
const kids = selfClosing ? [] : [{ type: 'text', value: source.slice(i, end), start: i }];
|
|
385
|
+
nodes.push({ type: 'element', tag, attrs: list.filter((a) => a.name !== 'inline'), children: kids, start });
|
|
386
|
+
i = selfClosing ? i : end + '</script>'.length;
|
|
387
|
+
}
|
|
388
|
+
else if (tag === 'script') {
|
|
371
389
|
if (parent)
|
|
372
|
-
fail('<script> must be at the top level', start);
|
|
390
|
+
fail('<script> must be at the top level (a component script); add `inline` for a script that runs where it stands', start);
|
|
373
391
|
if (out.script)
|
|
374
392
|
fail('only one <script> block is allowed', start);
|
|
375
393
|
const end = source.indexOf('</script>', i);
|
|
@@ -378,6 +396,17 @@ export function parse(source, file) {
|
|
|
378
396
|
out.script = { code: source.slice(i, end), start: i };
|
|
379
397
|
i = end + '</script>'.length;
|
|
380
398
|
}
|
|
399
|
+
else if (tag === 'style' && !parent) {
|
|
400
|
+
// A top-level <style> is the component's stylesheet. One inside markup (a layout's <head>) stays HTML.
|
|
401
|
+
const end = source.indexOf('</style>', i);
|
|
402
|
+
if (end === -1)
|
|
403
|
+
fail('unclosed <style>', start);
|
|
404
|
+
const hole = source.slice(i, end).indexOf('{{');
|
|
405
|
+
if (hole !== -1)
|
|
406
|
+
fail('{{ }} holes are not supported in a component <style>: set a CSS custom property from the template instead (style="--x: {{ x }}")', i + hole);
|
|
407
|
+
out.styles.push({ css: source.slice(i, end), global: list.some((a) => a.name === 'global'), start: i });
|
|
408
|
+
i = end + '</style>'.length;
|
|
409
|
+
}
|
|
381
410
|
else if (list.some((a) => a.name === 'verbatim')) {
|
|
382
411
|
// Everything up to </tag> is text: no holes, tags or directives.
|
|
383
412
|
const attr = list.find((a) => a.name === 'verbatim');
|
|
@@ -25,6 +25,21 @@ isCurrent = () => true) {
|
|
|
25
25
|
throw new Error('different swap regions');
|
|
26
26
|
for (const title of next.querySelectorAll('title'))
|
|
27
27
|
title.remove(); // some parsers leave the leading <title> in the body
|
|
28
|
+
// The page's stylesheets: add the ones not loaded yet to <head>, and wait for them, so nothing shows unstyled.
|
|
29
|
+
const loading = [];
|
|
30
|
+
for (const link of doc.querySelectorAll('link[rel="stylesheet"]')) {
|
|
31
|
+
link.remove();
|
|
32
|
+
if (document.head.querySelector(`link[rel="stylesheet"][href="${CSS.escape(link.getAttribute('href'))}"]`))
|
|
33
|
+
continue;
|
|
34
|
+
const added = document.createElement('link');
|
|
35
|
+
added.rel = 'stylesheet';
|
|
36
|
+
added.href = link.getAttribute('href');
|
|
37
|
+
loading.push(new Promise((done) => { added.onload = added.onerror = done; }));
|
|
38
|
+
document.head.append(added);
|
|
39
|
+
}
|
|
40
|
+
await Promise.all(loading);
|
|
41
|
+
if (!isCurrent())
|
|
42
|
+
return;
|
|
28
43
|
// Persisted elements move into the new page as they are, with their state and attached islands.
|
|
29
44
|
for (const old of document.querySelectorAll('[data-cl-persist]')) {
|
|
30
45
|
next.querySelector(`[data-cl-persist="${CSS.escape(old.getAttribute('data-cl-persist'))}"]`)?.replaceWith(old);
|
package/dist/runtime/loader.js
CHANGED
|
@@ -146,5 +146,11 @@ export async function attachAll(root = document, load = lastLoad) {
|
|
|
146
146
|
// Islands inserted later (an @if branch, a @for row, a re-rendered child) are attached through this hook.
|
|
147
147
|
;
|
|
148
148
|
globalThis.__clAttach = (root) => void attachAll(root);
|
|
149
|
-
if (typeof document !== 'undefined')
|
|
149
|
+
if (typeof document !== 'undefined') {
|
|
150
|
+
// Islands never affect layout. Installed on the document (not in <head>), so it survives head swaps by the client
|
|
151
|
+
// router; the server also writes it as a <style> for the first paint.
|
|
152
|
+
const sheet = new CSSStyleSheet();
|
|
153
|
+
sheet.replaceSync('cl-island{display:contents}');
|
|
154
|
+
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
|
|
150
155
|
attachAll();
|
|
156
|
+
}
|
package/dist/runtime/router.js
CHANGED
|
@@ -45,24 +45,31 @@ isCurrent = () => true) {
|
|
|
45
45
|
load(found.r),
|
|
46
46
|
get(data).then(async (res) => {
|
|
47
47
|
if (!res.ok)
|
|
48
|
-
throw new Error(`${res.status
|
|
48
|
+
throw new Error(`${res.status} ${data}`);
|
|
49
49
|
return parse(await res.text());
|
|
50
50
|
}),
|
|
51
51
|
]);
|
|
52
52
|
if (!isCurrent())
|
|
53
53
|
return false;
|
|
54
54
|
const doc = new DOMParser().parseFromString(page.render(props), 'text/html');
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
doc.
|
|
58
|
-
// The page's <title> comes with its head; its own <html> attributes (lang, dir, …) replace the previous page's.
|
|
55
|
+
// The head stays (its stylesheets are every client page's, linked by the shell); the title and the page's own
|
|
56
|
+
// <html> attributes (lang, dir, …) are the new page's.
|
|
57
|
+
document.title = doc.title;
|
|
59
58
|
const root = document.documentElement;
|
|
60
59
|
for (const { name } of [...root.attributes])
|
|
61
60
|
root.removeAttribute(name);
|
|
62
61
|
for (const { name, value } of [...doc.documentElement.attributes])
|
|
63
62
|
root.setAttribute(name, value);
|
|
64
|
-
document.head.replaceWith(doc.head);
|
|
65
63
|
document.body.replaceWith(doc.body);
|
|
64
|
+
// The page's inline head scripts (such as setting the theme before paint) run once, as on a normal load.
|
|
65
|
+
for (const old of doc.head.querySelectorAll('script:not([src])')) {
|
|
66
|
+
const script = document.createElement('script');
|
|
67
|
+
script.textContent = old.textContent;
|
|
68
|
+
document.head.append(script);
|
|
69
|
+
script.remove();
|
|
70
|
+
}
|
|
71
|
+
// Attaches the new page's islands; the loader also releases the old page's.
|
|
72
|
+
;
|
|
66
73
|
globalThis.__clAttach?.(document.body);
|
|
67
74
|
return true;
|
|
68
75
|
}
|
|
@@ -74,7 +81,7 @@ if (routes) {
|
|
|
74
81
|
show(new URL(location.href), table, undefined, undefined, () => latest === 1).catch((err) => {
|
|
75
82
|
if (latest !== 1)
|
|
76
83
|
return;
|
|
77
|
-
document.body.textContent = err.message.startsWith('
|
|
84
|
+
document.body.textContent = err.message.startsWith('404') ? 'Page not found.' : 'Could not load page.';
|
|
78
85
|
});
|
|
79
86
|
// A URL that failed to render is loaded normally, never intercepted again (no retry loop). canIntercept is
|
|
80
87
|
// only true for same-origin navigations, so no origin check is needed.
|
|
@@ -82,7 +89,7 @@ if (routes) {
|
|
|
82
89
|
const navigation = globalThis.navigation;
|
|
83
90
|
navigation?.addEventListener('navigate', (event) => {
|
|
84
91
|
const e = event;
|
|
85
|
-
if (!e.canIntercept || e.hashChange || e.downloadRequest
|
|
92
|
+
if (!e.canIntercept || e.hashChange || e.downloadRequest != null || e.formData)
|
|
86
93
|
return;
|
|
87
94
|
const url = new URL(e.destination.url);
|
|
88
95
|
if (url.href === fallback || !matchRoute(table, url.pathname))
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ type DataModule = {
|
|
|
14
14
|
request: Request;
|
|
15
15
|
}): object | Promise<object>;
|
|
16
16
|
};
|
|
17
|
-
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.
|
|
17
|
+
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.md' → '/about' (any page source) */
|
|
18
18
|
export declare function routeFromFile(file: string): string;
|
|
19
19
|
export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
|
|
20
20
|
loaderUrl?: string;
|
|
@@ -29,6 +29,10 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
|
|
|
29
29
|
fragments?: boolean;
|
|
30
30
|
/** URL of the fragment navigation script (with fragments on, every static and server page loads it). */
|
|
31
31
|
navUrl?: string;
|
|
32
|
+
/** URL of the stylesheet with every component's <style>, linked from every page. */
|
|
33
|
+
stylesUrl?: string;
|
|
34
|
+
/** Stylesheets each page imports (directly or through its components), by route as its file names it. */
|
|
35
|
+
css?: Record<string, string[]>;
|
|
32
36
|
}): {
|
|
33
37
|
fetch(request: Request): Promise<Response>;
|
|
34
38
|
routes: string[];
|
package/dist/server/handler.js
CHANGED
|
@@ -18,9 +18,9 @@ function compile(path) {
|
|
|
18
18
|
}).join('/');
|
|
19
19
|
return { keys, regex: new RegExp(`^${source}$`) };
|
|
20
20
|
}
|
|
21
|
-
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.
|
|
21
|
+
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.md' → '/about' (any page source) */
|
|
22
22
|
export function routeFromFile(file) {
|
|
23
|
-
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.
|
|
23
|
+
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.[^./]+$/, '').replace(/\/index$/, '');
|
|
24
24
|
return path || '/';
|
|
25
25
|
}
|
|
26
26
|
export function createHandler(pages, options = {}) {
|
|
@@ -47,11 +47,14 @@ export function createHandler(pages, options = {}) {
|
|
|
47
47
|
}
|
|
48
48
|
return null;
|
|
49
49
|
}
|
|
50
|
+
// A page's stylesheet links: what it imports, then the component styles (so components can build on the base).
|
|
51
|
+
const links = (urls) => [...new Set([...urls, ...(options.stylesUrl ? [options.stylesUrl] : [])])].map((u) => `<link rel="stylesheet" href="${u}">`).join('');
|
|
52
|
+
const pageLinks = (route) => links(options.css?.[route.path] ?? []);
|
|
50
53
|
// entries() per route, asked once: prerendering and requests see the same list. null when there is none.
|
|
51
54
|
const entriesCache = new Map();
|
|
52
55
|
function entriesOf(route) {
|
|
53
56
|
if (!entriesCache.has(route)) {
|
|
54
|
-
const file = `/${route.file.replace(/\.
|
|
57
|
+
const file = `/${route.file.replace(/\.[^./]+$/, '.load.ts')}`;
|
|
55
58
|
entriesCache.set(route, (async () => {
|
|
56
59
|
const mod = data[file] ? await data[file]() : undefined;
|
|
57
60
|
return mod?.entries ? await mod.entries() : null;
|
|
@@ -79,7 +82,7 @@ export function createHandler(pages, options = {}) {
|
|
|
79
82
|
/** Whether a route (as its file names it) has a load(). */
|
|
80
83
|
async hasLoader(path) {
|
|
81
84
|
const route = routes.find((r) => r.path === path);
|
|
82
|
-
const file = route && `/${route.file.replace(/\.
|
|
85
|
+
const file = route && `/${route.file.replace(/\.[^./]+$/, '.load.ts')}`;
|
|
83
86
|
return Boolean(file && data[file] && typeof (await data[file]()).load === 'function');
|
|
84
87
|
},
|
|
85
88
|
/** Every concrete path to prerender: static routes as they are, dynamic ones from their entries(). */
|
|
@@ -102,7 +105,7 @@ export function createHandler(pages, options = {}) {
|
|
|
102
105
|
add(route.path);
|
|
103
106
|
continue;
|
|
104
107
|
}
|
|
105
|
-
const dataFile = route.file.replace(/\.
|
|
108
|
+
const dataFile = route.file.replace(/\.[^./]+$/, '.load.ts');
|
|
106
109
|
const list = await entriesOf(route);
|
|
107
110
|
if (!list)
|
|
108
111
|
throw new Error(`${route.path} is a dynamic route: export entries() from ${dataFile} to list the pages to prerender`);
|
|
@@ -164,13 +167,15 @@ export function createHandler(pages, options = {}) {
|
|
|
164
167
|
const prefix = (options.base ?? '/').replace(/\/$/, '');
|
|
165
168
|
const table = routes.filter((r) => client[r.path]).map((r) => ({ p: (prefix + r.path).replace(/(.)\/$/, '$1'), r: client[r.path] }));
|
|
166
169
|
const shell = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
|
|
170
|
+
// Every client page's stylesheets: the router keeps the head, so this is all they get.
|
|
171
|
+
links(routes.filter((r) => client[r.path]).flatMap((r) => options.css?.[r.path] ?? [])) +
|
|
167
172
|
`<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes">${safeJson(JSON.stringify(table))}</script>` +
|
|
168
173
|
`<script type="module" src="${loaderUrl}"></script><script type="module" src="${options.routerUrl ?? '/cl-router.js'}"></script>` +
|
|
169
174
|
'</head><body><noscript>This page is rendered in the browser and needs JavaScript.</noscript></body></html>';
|
|
170
175
|
return new Response(head ? null : shell, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
171
176
|
}
|
|
172
177
|
let props = found.params;
|
|
173
|
-
const dataFile = found.route.file.replace(/\.
|
|
178
|
+
const dataFile = found.route.file.replace(/\.[^./]+$/, '.load.ts');
|
|
174
179
|
const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
|
|
175
180
|
if (mod?.load) {
|
|
176
181
|
let loaded;
|
|
@@ -191,14 +196,18 @@ export function createHandler(pages, options = {}) {
|
|
|
191
196
|
return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
|
|
192
197
|
}
|
|
193
198
|
const html = (await found.route.load()).render(props);
|
|
194
|
-
if (wantsFrag)
|
|
195
|
-
|
|
199
|
+
if (wantsFrag) {
|
|
200
|
+
// The page's stylesheet links go right after its title, so fragment navigation can load any that are missing.
|
|
201
|
+
const fragment = toFragment(html).replace(/^(<title\b[^>]*>[\s\S]*?<\/title\s*>)/i, (t) => t + pageLinks(found.route));
|
|
202
|
+
return new Response(head ? null : fragment, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
203
|
+
}
|
|
196
204
|
const visible = maskComments(html);
|
|
197
205
|
const hasIslands = visible.includes('<cl-island ');
|
|
198
206
|
// Only pages with islands get a script, and only the loader; it fetches each island's own chunk. With fragment
|
|
199
207
|
// navigation every page gets the navigation script instead, which brings the loader for islands that arrive.
|
|
200
208
|
const nav = options.fragments === true;
|
|
201
|
-
const
|
|
209
|
+
const sheet = pageLinks(found.route);
|
|
210
|
+
const style = sheet + (hasIslands || nav ? '<style>cl-island{display:contents}</style>' : ''); // islands never affect layout
|
|
202
211
|
const script = nav
|
|
203
212
|
? `<script type="module" src="${options.navUrl ?? '/cl-nav.js'}"></script>`
|
|
204
213
|
: hasIslands ? `<script type="module" src="${loaderUrl}"></script>` : '';
|
package/dist/server/views.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// which types each name with that view's inputs.
|
|
4
4
|
/** '/src/components/pill.tscl' → 'components/pill' */
|
|
5
5
|
export function viewName(file) {
|
|
6
|
-
return file.replace(/^.*?\/src\//, '').replace(/\.
|
|
6
|
+
return file.replace(/^.*?\/src\//, '').replace(/\.[^./]+$/, '');
|
|
7
7
|
}
|
|
8
8
|
// On globalThis: the bundled server and an app's own `import 'clarusjs/views'` may be two copies of this module.
|
|
9
9
|
const store = globalThis;
|
package/dist/vite/build.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/** Absolute paths of every
|
|
2
|
-
export declare function findClarusFiles(srcDir: string): string[];
|
|
1
|
+
/** Absolute paths of every component file under `srcDir` (`.tscl`, or any page source extension given). */
|
|
2
|
+
export declare function findClarusFiles(srcDir: string, extensions?: string[]): string[];
|
|
3
3
|
/**
|
|
4
4
|
* '/' → 'index.html', '/about/team' → 'about/team/index.html', '/users/a%20b' → 'users/a b/index.html'.
|
|
5
5
|
* Segments are decoded because static hosts look files up by the decoded path. A decoded segment can't add a level:
|
package/dist/vite/build.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
import { spawnSync } from 'node:child_process';
|
|
3
3
|
import { readdirSync } from 'node:fs';
|
|
4
4
|
import { resolve } from 'node:path';
|
|
5
|
-
/** Absolute paths of every
|
|
6
|
-
export function findClarusFiles(srcDir) {
|
|
5
|
+
/** Absolute paths of every component file under `srcDir` (`.tscl`, or any page source extension given). */
|
|
6
|
+
export function findClarusFiles(srcDir, extensions = ['.tscl']) {
|
|
7
7
|
let entries;
|
|
8
8
|
try {
|
|
9
9
|
entries = readdirSync(srcDir, { recursive: true });
|
|
@@ -11,7 +11,7 @@ export function findClarusFiles(srcDir) {
|
|
|
11
11
|
catch {
|
|
12
12
|
return [];
|
|
13
13
|
}
|
|
14
|
-
return entries.filter((f) => f.endsWith(
|
|
14
|
+
return entries.filter((f) => extensions.some((ext) => f.endsWith(ext))).map((f) => resolve(srcDir, f)).sort();
|
|
15
15
|
}
|
|
16
16
|
/**
|
|
17
17
|
* '/' → 'index.html', '/about/team' → 'about/team/index.html', '/users/a%20b' → 'users/a b/index.html'.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type LinkIssue = {
|
|
2
|
+
kind: 'pages' | 'anchors';
|
|
3
|
+
page: string;
|
|
4
|
+
href: string;
|
|
5
|
+
message: string;
|
|
6
|
+
};
|
|
7
|
+
type Options = {
|
|
8
|
+
outDir: string;
|
|
9
|
+
/** Every built route (static pages and client shells), as URLs without the base. */
|
|
10
|
+
routes: string[];
|
|
11
|
+
/** Server routes as their files name them ('/account/[id]'): rendered per request, so any match counts. */
|
|
12
|
+
serverRoutes: string[];
|
|
13
|
+
/** Client routes render in the browser: their pages exist, but their anchors can't be checked at build. */
|
|
14
|
+
clientRoutes: string[];
|
|
15
|
+
base: string;
|
|
16
|
+
};
|
|
17
|
+
export declare function checkLinks(options: Options): LinkIssue[];
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Build-time link checking: once every page is built, links between pages and to #anchors are checked against
|
|
2
|
+
// what was actually written. Reads dist/client only; reporting and failing are up to the caller.
|
|
3
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
4
|
+
import { resolve } from 'node:path';
|
|
5
|
+
import { routeToFile } from './build.js';
|
|
6
|
+
// A stray % is kept as written, as routeToFile does, instead of failing the build with a URIError.
|
|
7
|
+
const decode = (s) => { try {
|
|
8
|
+
return decodeURIComponent(s);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return s;
|
|
12
|
+
} };
|
|
13
|
+
const isFile = (path) => { try {
|
|
14
|
+
return statSync(path).isFile();
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return false;
|
|
18
|
+
} };
|
|
19
|
+
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
20
|
+
/** Edit distance, for "did you mean". */
|
|
21
|
+
function distance(a, b) {
|
|
22
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
23
|
+
for (let i = 1; i <= a.length; i++) {
|
|
24
|
+
let prev = row[0];
|
|
25
|
+
row[0] = i;
|
|
26
|
+
for (let j = 1; j <= b.length; j++) {
|
|
27
|
+
const next = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
28
|
+
prev = row[j];
|
|
29
|
+
row[j] = next;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return row[b.length];
|
|
33
|
+
}
|
|
34
|
+
/** The closest candidate, if it is close enough to be a likely typo. */
|
|
35
|
+
function closest(target, candidates) {
|
|
36
|
+
let best;
|
|
37
|
+
let score = Infinity;
|
|
38
|
+
for (const c of candidates) {
|
|
39
|
+
const d = distance(target, c);
|
|
40
|
+
if (d < score) {
|
|
41
|
+
best = c;
|
|
42
|
+
score = d;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return best !== undefined && score <= Math.max(2, Math.floor(target.length / 3)) ? best : undefined;
|
|
46
|
+
}
|
|
47
|
+
const ids = (html) => new Set([...html.matchAll(/\s(?:id|name)="([^"]+)"/g)].map((m) => m[1]));
|
|
48
|
+
const hrefs = (html) => [...html.replace(/<!--[\s\S]*?-->/g, '').matchAll(/<a\b[^>]*?\shref="([^"]*)"/g)].map((m) => m[1].replace(/&/g, '&'));
|
|
49
|
+
export function checkLinks(options) {
|
|
50
|
+
const { outDir } = options;
|
|
51
|
+
// An absolute base (https://cdn.example.com/docs/) is compared by its path.
|
|
52
|
+
const base = /^https?:\/\//.test(options.base) ? new URL(options.base).pathname : options.base;
|
|
53
|
+
const routes = new Set(options.routes.map(trim));
|
|
54
|
+
const client = new Set(options.clientRoutes.map(trim));
|
|
55
|
+
const serverPatterns = options.serverRoutes.map((r) => new RegExp(`^${r.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`));
|
|
56
|
+
const html = new Map();
|
|
57
|
+
const read = (route) => {
|
|
58
|
+
if (!html.has(route)) {
|
|
59
|
+
const file = resolve(outDir, routeToFile(route));
|
|
60
|
+
html.set(route, existsSync(file) ? readFileSync(file, 'utf8') : '');
|
|
61
|
+
}
|
|
62
|
+
return html.get(route);
|
|
63
|
+
};
|
|
64
|
+
const issues = [];
|
|
65
|
+
for (const page of [...routes].filter((r) => !client.has(r))) {
|
|
66
|
+
for (const href of hrefs(read(page))) {
|
|
67
|
+
if (/^[a-z][\w+.-]*:|^\/\//i.test(href) || href === '')
|
|
68
|
+
continue; // external, mailto:, tel:, …
|
|
69
|
+
const url = new URL(href, `http://site${base}${page === '/' ? '' : page.slice(1) + '/'}`);
|
|
70
|
+
if (!url.pathname.startsWith(base) && `${url.pathname}/` !== base)
|
|
71
|
+
continue; // outside this site
|
|
72
|
+
let path = trim(decode(url.pathname.slice(base.length - 1)) || '/');
|
|
73
|
+
if (path.endsWith('/index.html'))
|
|
74
|
+
path = trim(path.slice(0, -'index.html'.length));
|
|
75
|
+
const anchor = decode(url.hash.slice(1));
|
|
76
|
+
const isPage = routes.has(path);
|
|
77
|
+
const exists = isPage || serverPatterns.some((re) => re.test(path)) || isFile(resolve(outDir, `.${path}`)); // a directory without a page is a 404
|
|
78
|
+
if (!exists) {
|
|
79
|
+
const guess = closest(path, routes);
|
|
80
|
+
issues.push({ kind: 'pages', page, href, message: `no page at ${path}${guess ? ` (did you mean ${guess}?)` : ''}` });
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (!anchor || !isPage || client.has(path))
|
|
84
|
+
continue;
|
|
85
|
+
const targets = ids(read(path));
|
|
86
|
+
if (targets.has(anchor))
|
|
87
|
+
continue;
|
|
88
|
+
const guess = closest(anchor, targets);
|
|
89
|
+
issues.push({ kind: 'anchors', page, href, message: `no #${anchor} on ${path}${guess ? ` (did you mean #${guess}?)` : ''}` });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return issues;
|
|
93
|
+
}
|
package/dist/vite/plugin.d.ts
CHANGED
|
@@ -9,5 +9,31 @@ export type ClarusOptions = {
|
|
|
9
9
|
adapter?: 'netlify';
|
|
10
10
|
/** Fragment navigation: each static and server page also answers at <path>/index.frag.html. */
|
|
11
11
|
fragments?: boolean;
|
|
12
|
+
/** Page sources for other file types, such as Markdown from @clarusjs/content: `sources: [markdown()]`. */
|
|
13
|
+
sources?: Source[];
|
|
14
|
+
/**
|
|
15
|
+
* Build-time link checking, after every page is built. `pages`: links to pages or files that don't exist (default
|
|
16
|
+
* 'error'). `anchors`: links to a #id the target page doesn't have (default 'warn'). `strict`: warnings fail too.
|
|
17
|
+
*/
|
|
18
|
+
links?: {
|
|
19
|
+
pages?: LinkLevel;
|
|
20
|
+
anchors?: LinkLevel;
|
|
21
|
+
strict?: boolean;
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
export type LinkLevel = 'error' | 'warn' | 'off';
|
|
25
|
+
/**
|
|
26
|
+
* A page source: files with another extension (such as Markdown) turned into .tscl text, then compiled like any
|
|
27
|
+
* page. `route` is the page's route when the file is under src/pages.
|
|
28
|
+
*/
|
|
29
|
+
export type Source = {
|
|
30
|
+
extension: string;
|
|
31
|
+
toTscl(code: string, file: string, context: SourceContext): string;
|
|
32
|
+
};
|
|
33
|
+
/** `root`: the app root. `addDependency(file)`: another file the output depends on (rebuilt when it changes in dev). */
|
|
34
|
+
export type SourceContext = {
|
|
35
|
+
route: string;
|
|
36
|
+
root: string;
|
|
37
|
+
addDependency(file: string): void;
|
|
12
38
|
};
|
|
13
39
|
export default function clarusjs(options?: ClarusOptions): Plugin;
|
package/dist/vite/plugin.js
CHANGED
|
@@ -8,14 +8,16 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
8
8
|
};
|
|
9
9
|
// The clarusjs Vite plugin: a thin adapter around the compiler.
|
|
10
10
|
// Server environment gets render(), client environment gets attach(). Dev requests go through the fetch handler.
|
|
11
|
-
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
12
12
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
13
13
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
14
|
-
import { isRunnableDevEnvironment } from 'vite';
|
|
15
|
-
import { compile, ClarusError } from '../compiler/index.js';
|
|
14
|
+
import { isRunnableDevEnvironment, normalizePath } from 'vite';
|
|
15
|
+
import { compile, scopeId, ClarusError } from '../compiler/index.js';
|
|
16
|
+
import { parse } from '../compiler/parse.js';
|
|
16
17
|
import { findClarusFiles, prerender } from './build.js';
|
|
17
18
|
import { writeManifest } from './manifest.js';
|
|
18
19
|
import { writeNetlifyFunction } from './netlify.js';
|
|
20
|
+
import { checkLinks } from './links.js';
|
|
19
21
|
import { checkModes, modeFor } from '../server/modes.js';
|
|
20
22
|
import { routeFromFile } from '../server/handler.js';
|
|
21
23
|
import { sendResponse, toRequest } from './node.js';
|
|
@@ -31,17 +33,84 @@ export function clientUrlFor(root, file) {
|
|
|
31
33
|
const LOADER_ENTRY = 'cl-loader';
|
|
32
34
|
const ROUTER_ENTRY = 'cl-router';
|
|
33
35
|
const NAV_ENTRY = 'cl-nav';
|
|
36
|
+
const STYLES_ENTRY = 'cl-styles';
|
|
37
|
+
// Every component's <style>, generated into one stylesheet (gitignored, like the rest of .clarusjs/).
|
|
38
|
+
const STYLES_FILE = '.clarusjs/styles.css';
|
|
39
|
+
/** Scope ids come from the path relative to the app root, so server, client and stylesheet always agree. */
|
|
40
|
+
const scopeFor = (root, file) => scopeId(relative(root, file).split(sep).join('/'));
|
|
41
|
+
/**
|
|
42
|
+
* Each page's stylesheets (absolute paths), from its own `@import './x.css'` and its components', transitively.
|
|
43
|
+
* Dependencies come first, so a layout's base CSS is linked before what the page adds.
|
|
44
|
+
*/
|
|
45
|
+
function pageStylesheets(root, files) {
|
|
46
|
+
const deps = new Map();
|
|
47
|
+
const read = (file) => {
|
|
48
|
+
if (!deps.has(file)) {
|
|
49
|
+
let parsed;
|
|
50
|
+
try {
|
|
51
|
+
parsed = parse(files.read(file, root), file);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
parsed = null;
|
|
55
|
+
} // errors surface on compile
|
|
56
|
+
// Relative to the file, or root-relative ('/src/layouts/docs.tscl', as Vite resolves it).
|
|
57
|
+
const near = (from) => {
|
|
58
|
+
const path = from.replace(/\?.*$/, '');
|
|
59
|
+
return path.startsWith('/') ? resolve(root, `.${path}`) : resolve(dirname(file), path);
|
|
60
|
+
};
|
|
61
|
+
deps.set(file, {
|
|
62
|
+
css: parsed?.cssImports.map((c) => near(c.from)) ?? [],
|
|
63
|
+
components: parsed?.imports.filter((imp) => /^[./]/.test(imp.from)).map((imp) => near(imp.from)) ?? [],
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return deps.get(file);
|
|
67
|
+
};
|
|
68
|
+
const collect = (file, out, seen) => {
|
|
69
|
+
if (seen.has(file))
|
|
70
|
+
return;
|
|
71
|
+
seen.add(file);
|
|
72
|
+
const { css, components } = read(file);
|
|
73
|
+
for (const c of components)
|
|
74
|
+
if (existsSync(c))
|
|
75
|
+
collect(c, out, seen);
|
|
76
|
+
for (const sheet of css)
|
|
77
|
+
if (!out.includes(sheet))
|
|
78
|
+
out.push(sheet);
|
|
79
|
+
};
|
|
80
|
+
const pages = new Map();
|
|
81
|
+
for (const file of files.find(resolve(root, 'src/pages'))) {
|
|
82
|
+
const out = [];
|
|
83
|
+
collect(file, out, new Set());
|
|
84
|
+
pages.set(routeFromFile(`/${relative(root, file).split(sep).join('/')}`), out);
|
|
85
|
+
}
|
|
86
|
+
return pages;
|
|
87
|
+
}
|
|
88
|
+
/** Write .clarusjs/styles.css from every component under src/; false when no component has a <style>. */
|
|
89
|
+
function writeStyles(root, files) {
|
|
90
|
+
let css = '';
|
|
91
|
+
for (const file of files.find(resolve(root, 'src'))) {
|
|
92
|
+
try {
|
|
93
|
+
const out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file) }).css;
|
|
94
|
+
if (out)
|
|
95
|
+
css += `/* ${relative(root, file).split(sep).join('/')} */\n${out}`;
|
|
96
|
+
}
|
|
97
|
+
catch { } // compile errors are reported when the component itself is compiled
|
|
98
|
+
}
|
|
99
|
+
mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
|
|
100
|
+
writeFileSync(resolve(root, STYLES_FILE), css);
|
|
101
|
+
return css !== '';
|
|
102
|
+
}
|
|
34
103
|
// Client entry name of a client-mode page's browser render module.
|
|
35
104
|
const renderEntry = (name) => `render/${name}`;
|
|
36
105
|
const CLIENT_OUT = 'dist/client';
|
|
37
106
|
// Placeholder for a nested island's chunk URL in the client build, replaced once the bundle's file names are known.
|
|
38
107
|
const CHUNK_TOKEN = '__CLARUS_CHUNK__';
|
|
39
108
|
const SERVER_OUT = 'dist/server';
|
|
40
|
-
const entryName = (root, file) => relative(root, file).replace(/\.
|
|
109
|
+
const entryName = (root, file) => relative(root, file).replace(/\.[^./\\]+$/, '');
|
|
41
110
|
/** Client-mode pages: route (as the file names it) → absolute file. */
|
|
42
|
-
function clientPages(appRoot, modes) {
|
|
111
|
+
function clientPages(appRoot, modes, files) {
|
|
43
112
|
const pages = new Map();
|
|
44
|
-
for (const file of
|
|
113
|
+
for (const file of files.find(resolve(appRoot, 'src/pages'))) {
|
|
45
114
|
const route = routeFromFile(`/${relative(appRoot, file).split(sep).join('/')}`);
|
|
46
115
|
if (modeFor(route, modes) === 'client')
|
|
47
116
|
pages.set(route, file);
|
|
@@ -51,6 +120,29 @@ function clientPages(appRoot, modes) {
|
|
|
51
120
|
export default function clarusjs(options = {}) {
|
|
52
121
|
const modes = options.routes ?? {};
|
|
53
122
|
checkModes(modes);
|
|
123
|
+
const sources = options.sources ?? [];
|
|
124
|
+
for (const src of sources) {
|
|
125
|
+
if (!/^\.[\w-]+$/.test(src.extension))
|
|
126
|
+
throw new Error(`clarusjs: a source extension must look like ".md", got "${src.extension}"`);
|
|
127
|
+
if (src.extension === '.tscl')
|
|
128
|
+
throw new Error('clarusjs: .tscl files are compiled directly; a source needs its own extension');
|
|
129
|
+
}
|
|
130
|
+
const extensions = ['.tscl', ...sources.map((src) => src.extension)];
|
|
131
|
+
// Component files of every kind, read as .tscl text (a source's output, or the file itself).
|
|
132
|
+
// Page sources only apply under src/pages: elsewhere (src/parts, …) their files are plain files, not components.
|
|
133
|
+
const files = {
|
|
134
|
+
find: (dir) => findClarusFiles(dir, extensions).filter((f) => f.endsWith('.tscl') || f.includes(`${sep}src${sep}pages${sep}`)),
|
|
135
|
+
read: (file, appRoot) => {
|
|
136
|
+
const code = readFileSync(file, 'utf8');
|
|
137
|
+
const src = sources.find((x) => file.endsWith(x.extension));
|
|
138
|
+
if (!src)
|
|
139
|
+
return code;
|
|
140
|
+
const rel = relative(appRoot, file).split(sep).join('/');
|
|
141
|
+
return src.toTscl(code, file, { route: rel.startsWith('src/pages/') ? routeFromFile(`/${rel}`) : '', root: appRoot, addDependency: () => { } });
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
const fileRe = new RegExp(`\\.(${extensions.map((e) => e.slice(1)).join('|')})(\\?|$)`);
|
|
145
|
+
const glob = (dir) => JSON.stringify(extensions.map((e) => `${dir}/**/*${e}`));
|
|
54
146
|
if (options.adapter !== undefined && options.adapter !== 'netlify') {
|
|
55
147
|
throw new Error(`clarusjs: adapter "${options.adapter}" is not supported; use 'netlify'`);
|
|
56
148
|
}
|
|
@@ -105,16 +197,24 @@ export default function clarusjs(options = {}) {
|
|
|
105
197
|
// Client entries: the island loader plus every stateful component. Stateless components never reach the client.
|
|
106
198
|
const appRoot = resolve(userConfig.root ?? process.cwd());
|
|
107
199
|
const input = { [LOADER_ENTRY]: here('../runtime/loader') };
|
|
108
|
-
for (const file of
|
|
109
|
-
if (compile(
|
|
200
|
+
for (const file of files.find(resolve(appRoot, 'src'))) {
|
|
201
|
+
if (compile(files.read(file, appRoot), { file, target: 'client' }).stateful)
|
|
110
202
|
input[entryName(appRoot, file)] = file;
|
|
111
203
|
}
|
|
112
204
|
// Client routes: the router, and each page's render function for the browser.
|
|
113
|
-
const client = clientPages(appRoot, modes);
|
|
205
|
+
const client = clientPages(appRoot, modes, files);
|
|
114
206
|
if (client.size)
|
|
115
207
|
input[ROUTER_ENTRY] = here('../runtime/router');
|
|
116
208
|
if (options.fragments)
|
|
117
209
|
input[NAV_ENTRY] = here('../runtime/fragments');
|
|
210
|
+
if (writeStyles(appRoot, files))
|
|
211
|
+
input[STYLES_ENTRY] = resolve(appRoot, STYLES_FILE);
|
|
212
|
+
// Stylesheets imported by pages and components: each goes through Vite's CSS pipeline as its own entry.
|
|
213
|
+
for (const sheet of new Set([...pageStylesheets(appRoot, files).values()].flat())) {
|
|
214
|
+
if (!existsSync(sheet))
|
|
215
|
+
throw new Error(`clarusjs: imported stylesheet not found: ${relative(appRoot, sheet)}`);
|
|
216
|
+
input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '')}`] = sheet;
|
|
217
|
+
}
|
|
118
218
|
for (const file of client.values())
|
|
119
219
|
input[renderEntry(entryName(appRoot, file))] = `${file}?render`;
|
|
120
220
|
config.builder = {};
|
|
@@ -177,6 +277,39 @@ export default function clarusjs(options = {}) {
|
|
|
177
277
|
await prerender(entry, out, manifestFile, readers);
|
|
178
278
|
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
179
279
|
}
|
|
280
|
+
// Links between pages and to anchors, checked against what was written.
|
|
281
|
+
const pageRoutes = routes.filter((r) => !/\/(__data\.json|index\.frag\.html)$/.test(r));
|
|
282
|
+
const issues = checkLinks({
|
|
283
|
+
outDir: out,
|
|
284
|
+
routes: pageRoutes,
|
|
285
|
+
serverRoutes: server.map((x) => x.route),
|
|
286
|
+
clientRoutes: pageRoutes.filter((r) => routes.includes(r === '/' ? '/__data.json' : `${r}/__data.json`)),
|
|
287
|
+
base: builder.config.base,
|
|
288
|
+
});
|
|
289
|
+
const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn' };
|
|
290
|
+
// Each problem names the page's source file, and the line where the link is written literally.
|
|
291
|
+
const sourceOf = new Map(files.find(resolve(builder.config.root, 'src/pages')).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
|
|
292
|
+
const locate = (page, href) => {
|
|
293
|
+
const file = sourceOf.get(page) ?? [...sourceOf].find(([route]) => new RegExp(`^${route.replace(/\[[^\]]+\]/g, '[^/]+')}$`).test(page))?.[1];
|
|
294
|
+
if (!file)
|
|
295
|
+
return page;
|
|
296
|
+
const rel = relative(builder.config.root, file).split(sep).join('/');
|
|
297
|
+
const line = readFileSync(file, 'utf8').split('\n').findIndex((l) => l.includes(href));
|
|
298
|
+
return line === -1 ? `${rel} (${page})` : `${rel}:${line + 1}`;
|
|
299
|
+
};
|
|
300
|
+
const errors = [];
|
|
301
|
+
for (const issue of issues) {
|
|
302
|
+
const level = levels[issue.kind];
|
|
303
|
+
if (level === 'off')
|
|
304
|
+
continue;
|
|
305
|
+
const text = `${locate(issue.page, issue.href)}: ${issue.message}`;
|
|
306
|
+
if (level === 'error' || options.links?.strict)
|
|
307
|
+
errors.push(text);
|
|
308
|
+
else
|
|
309
|
+
builder.config.logger.warn(`clarusjs: ${text}`);
|
|
310
|
+
}
|
|
311
|
+
if (errors.length)
|
|
312
|
+
throw new Error(`clarusjs: broken links:\n ${errors.join('\n ')}`);
|
|
180
313
|
if (options.adapter === 'netlify')
|
|
181
314
|
writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true);
|
|
182
315
|
},
|
|
@@ -190,42 +323,76 @@ export default function clarusjs(options = {}) {
|
|
|
190
323
|
if (id === ENTRY)
|
|
191
324
|
return '\0' + ENTRY;
|
|
192
325
|
},
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
326
|
+
// order 'pre': a page source's file is read as text before Vite's asset loader can claim it (.txt,
|
|
327
|
+
// assetsInclude), so the transform converts the original text, never a URL module.
|
|
328
|
+
load: { order: 'pre', handler(id) {
|
|
329
|
+
if (id !== '\0' + ENTRY) {
|
|
330
|
+
if (/[?&](raw|url|inline)\b/.test(id) || id.startsWith('\0'))
|
|
331
|
+
return null;
|
|
332
|
+
const file = id.replace(/\?.*$/, '');
|
|
333
|
+
if (!sources.some((x) => file.endsWith(x.extension)) || !normalizePath(file).startsWith(normalizePath(resolve(root, 'src/pages')) + '/'))
|
|
334
|
+
return null;
|
|
335
|
+
return readFileSync(file, 'utf8');
|
|
336
|
+
}
|
|
337
|
+
const urls = builtUrls();
|
|
338
|
+
const loaderUrl = urls?.get(LOADER_ENTRY) ?? '/cl-loader.js';
|
|
339
|
+
const routerUrl = urls?.get(ROUTER_ENTRY) ?? '/cl-router.js';
|
|
340
|
+
const navUrl = urls?.get(NAV_ENTRY) ?? '/cl-nav.js';
|
|
341
|
+
// Each page's imported stylesheets: built URLs (by source key), or the source served by Vite in dev.
|
|
342
|
+
const css = {};
|
|
343
|
+
for (const [route, sheets] of pageStylesheets(root, files)) {
|
|
344
|
+
if (!sheets.length)
|
|
345
|
+
continue;
|
|
346
|
+
css[route] = sheets.map((sheet) => {
|
|
347
|
+
const key = relative(root, sheet).split(sep).join('/');
|
|
348
|
+
const url = urls ? urls.get(key) : clientUrlFor(root, sheet).replace(/\?.*$/, '');
|
|
349
|
+
if (!url)
|
|
350
|
+
throw new Error(`clarusjs: no built stylesheet for ${key}`);
|
|
351
|
+
return url;
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
// Built: the hashed stylesheet, if any component has styles. Dev: the generated file, served by Vite.
|
|
355
|
+
const stylesUrl = urls ? urls.get(STYLES_ENTRY) : writeStyles(root, files) ? `/${STYLES_FILE}` : undefined;
|
|
356
|
+
// Built: hashed chunk URLs. Dev: the source, served as JS by Vite.
|
|
357
|
+
const client = {};
|
|
358
|
+
for (const [route, file] of clientPages(root, modes, files)) {
|
|
359
|
+
const key = `${relative(root, file).split(sep).join('/')}?render`;
|
|
360
|
+
const url = urls ? urls.get(key) : `${clientUrlFor(root, file).replace(/\?.*$/, '')}?render&import`;
|
|
361
|
+
if (!url)
|
|
362
|
+
throw new Error(`clarusjs: no client chunk for ${key}`);
|
|
363
|
+
client[route] = url;
|
|
364
|
+
}
|
|
365
|
+
return `import { createHandler } from ${JSON.stringify(here('../server/handler'))}\n` +
|
|
366
|
+
`import { registerViews, render } from ${JSON.stringify(here('../server/views'))}\n` +
|
|
367
|
+
// Every view under src/, for render(name, props) in server code. Also exported for apps that import the build.
|
|
368
|
+
`registerViews(import.meta.glob(${JSON.stringify(['/src/**/*.tscl', ...extensions.slice(1).map((e) => `/src/pages/**/*${e}`)])}))\n` +
|
|
369
|
+
`export { render }\n` +
|
|
370
|
+
`export default createHandler(import.meta.glob(${glob('/src/pages')}), {\n` +
|
|
371
|
+
` loaderUrl: ${JSON.stringify(loaderUrl)},\n` +
|
|
372
|
+
` data: import.meta.glob('/src/pages/**/*.load.ts'),\n` +
|
|
373
|
+
` modes: ${JSON.stringify(modes)},\n` +
|
|
374
|
+
` routerUrl: ${JSON.stringify(routerUrl)},\n` +
|
|
375
|
+
` client: ${JSON.stringify(client)},\n` +
|
|
376
|
+
` base: ${JSON.stringify(base)},\n` +
|
|
377
|
+
` fragments: ${options.fragments === true},\n` +
|
|
378
|
+
` navUrl: ${JSON.stringify(navUrl)},\n` +
|
|
379
|
+
` stylesUrl: ${JSON.stringify(stylesUrl)},\n` +
|
|
380
|
+
` css: ${JSON.stringify(css)},\n` +
|
|
381
|
+
`})\n`;
|
|
382
|
+
} },
|
|
225
383
|
transform: {
|
|
226
|
-
filter: { id:
|
|
227
|
-
handler(
|
|
384
|
+
filter: { id: fileRe },
|
|
385
|
+
handler(raw, id) {
|
|
228
386
|
const file = id.replace(/\?.*$/, '');
|
|
387
|
+
// A page source's file is compiled from the .tscl text it produces: only under src/pages, and never when it is
|
|
388
|
+
// imported as text or a URL (CHANGELOG.md?raw stays a string).
|
|
389
|
+
const src = sources.find((x) => file.endsWith(x.extension));
|
|
390
|
+
if (src && (/[?&](raw|url|inline)\b/.test(id) || !normalizePath(file).startsWith(normalizePath(resolve(root, 'src/pages')) + '/')))
|
|
391
|
+
return null;
|
|
392
|
+
const rel = relative(root, file).split(sep).join('/');
|
|
393
|
+
const code = src
|
|
394
|
+
? src.toTscl(raw, file, { route: rel.startsWith('src/pages/') ? routeFromFile(`/${rel}`) : '', root, addDependency: (dep) => this.addWatchFile(dep) })
|
|
395
|
+
: raw;
|
|
229
396
|
// ?render: a component's server render function, used in the browser to render children of islands.
|
|
230
397
|
const renderQuery = /[?&]render\b/.test(id);
|
|
231
398
|
const target = this.environment.config.consumer === 'server' || renderQuery ? 'server' : 'client';
|
|
@@ -244,7 +411,8 @@ export default function clarusjs(options = {}) {
|
|
|
244
411
|
try {
|
|
245
412
|
// A ?render module runs in the browser: its child components must be render modules too.
|
|
246
413
|
const renderImports = renderQuery && this.environment.config.consumer !== 'server';
|
|
247
|
-
|
|
414
|
+
// moduleType: a source extension may have its own built-in type in Rolldown (.txt is text); the output is JS.
|
|
415
|
+
return { code: compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file) }).code, map: null, moduleType: 'js' };
|
|
248
416
|
}
|
|
249
417
|
catch (err) {
|
|
250
418
|
if (err instanceof ClarusError)
|
|
@@ -296,6 +464,12 @@ export default function clarusjs(options = {}) {
|
|
|
296
464
|
};
|
|
297
465
|
},
|
|
298
466
|
configureServer(server) {
|
|
467
|
+
// Component styles change with their .tscl files: regenerate the stylesheet (Vite then updates the page's CSS).
|
|
468
|
+
const restyle = (file) => { if (fileRe.test(file))
|
|
469
|
+
writeStyles(server.config.root, files); };
|
|
470
|
+
server.watcher.on('change', restyle);
|
|
471
|
+
server.watcher.on('add', restyle);
|
|
472
|
+
server.watcher.on('unlink', restyle);
|
|
299
473
|
return () => {
|
|
300
474
|
server.middlewares.use(async (req, res, next) => {
|
|
301
475
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clarusjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
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": [
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"html-first",
|
|
19
19
|
"typescript"
|
|
20
20
|
],
|
|
21
|
-
"homepage": "https://
|
|
21
|
+
"homepage": "https://clarusjs.com",
|
|
22
22
|
"repository": {
|
|
23
23
|
"type": "git",
|
|
24
24
|
"url": "git+https://github.com/forinda/clarusjs.git",
|