clarusjs 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/check/generate.js +15 -8
- package/dist/cli/check.d.ts +7 -0
- package/dist/cli/check.js +14 -6
- package/dist/cli/explain.js +1 -1
- package/dist/cli/index.js +6 -3
- package/dist/cli/project.d.ts +7 -2
- package/dist/cli/project.js +4 -3
- package/dist/compiler/emit-client.d.ts +2 -1
- package/dist/compiler/emit-client.js +19 -7
- package/dist/compiler/emit-server.d.ts +1 -1
- package/dist/compiler/emit-server.js +4 -1
- package/dist/compiler/errors.d.ts +14 -1
- package/dist/compiler/html-expr.d.ts +21 -0
- package/dist/compiler/html-expr.js +24 -1
- package/dist/compiler/index.d.ts +23 -2
- package/dist/compiler/index.js +5 -3
- package/dist/compiler/ir.d.ts +6 -1
- package/dist/compiler/ir.js +104 -4
- package/dist/compiler/lint.d.ts +82 -0
- package/dist/compiler/lint.js +177 -0
- package/dist/compiler/parse.d.ts +34 -0
- package/dist/compiler/parse.js +11 -0
- package/dist/compiler/script.js +27 -0
- package/dist/fetch/index.d.ts +149 -0
- package/dist/fetch/index.js +312 -0
- package/dist/forms/index.d.ts +21 -2
- package/dist/forms/types.d.ts +20 -3
- package/dist/runtime/attrs.js +10 -2
- package/dist/runtime/dom.d.ts +15 -7
- package/dist/runtime/dom.js +33 -13
- package/dist/runtime/env.d.ts +8 -1
- package/dist/runtime/env.js +8 -1
- package/dist/runtime/hot.d.ts +2 -0
- package/dist/runtime/hot.js +51 -0
- package/dist/runtime/html.d.ts +9 -7
- package/dist/runtime/html.js +12 -7
- package/dist/runtime/navigate.d.ts +5 -0
- package/dist/runtime/navigation.d.ts +85 -13
- package/dist/runtime/navigation.js +77 -11
- package/dist/runtime/serialize.d.ts +1 -1
- package/dist/runtime/serialize.js +1 -1
- package/dist/runtime/server.d.ts +18 -1
- package/dist/runtime/server.js +42 -4
- package/dist/runtime/signals.d.ts +97 -4
- package/dist/runtime/signals.js +88 -4
- package/dist/server/handler.d.ts +115 -5
- package/dist/server/handler.js +233 -10
- package/dist/server/head.d.ts +4 -1
- package/dist/server/manifest.d.ts +14 -1
- package/dist/server/views.d.ts +64 -6
- package/dist/server/views.js +46 -0
- package/dist/vite/aliases.js +3 -3
- package/dist/vite/build.d.ts +2 -1
- package/dist/vite/build.js +1 -1
- package/dist/vite/manifest.d.ts +15 -0
- package/dist/vite/manifest.js +2 -2
- package/dist/vite/node.js +4 -1
- package/dist/vite/plugin.d.ts +47 -3
- package/dist/vite/plugin.js +197 -106
- package/dist/vite/sitemap.d.ts +1 -0
- package/package.json +5 -1
package/dist/vite/build.d.ts
CHANGED
|
@@ -19,9 +19,10 @@ export declare function prerender(serverEntry: string, outDir: string, manifestF
|
|
|
19
19
|
server: {
|
|
20
20
|
route: string;
|
|
21
21
|
loader: boolean;
|
|
22
|
+
cookies?: boolean;
|
|
22
23
|
}[];
|
|
23
24
|
}>;
|
|
24
|
-
/** The package a file belongs to, from its last node_modules segment (pnpm: node_modules/.pnpm/x@1/node_modules/x/…). */
|
|
25
|
+
/** The package a file belongs to, from its last node_modules segment (pnpm: node_modules/.pnpm/x@1/node_modules/x/…). @internal */
|
|
25
26
|
export declare function packageOf(file: string): string | undefined;
|
|
26
27
|
/**
|
|
27
28
|
* Component files reachable from `start` through @import lines: relative paths, root-relative ('/src/…') and package
|
package/dist/vite/build.js
CHANGED
|
@@ -72,7 +72,7 @@ export async function prerender(serverEntry, outDir, manifestFile, only) {
|
|
|
72
72
|
if (globalThis.__clLoaderRan) loaded.push(route)
|
|
73
73
|
}
|
|
74
74
|
const server = []
|
|
75
|
-
for (const route of handler.serverRoutes ?? []) server.push({ route, loader: await handler.hasLoader(route) })
|
|
75
|
+
for (const route of handler.serverRoutes ?? []) server.push({ route, loader: await handler.hasLoader(route), cookies: await handler.readsCookies?.(route) ?? false })
|
|
76
76
|
process.stdout.write(JSON.stringify({ routes, readers, loaded, server }))
|
|
77
77
|
`;
|
|
78
78
|
const args = ['--input-type=module', '-e', script, serverEntry, outDir, ...(only ? [JSON.stringify(only)] : [])];
|
package/dist/vite/manifest.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
export type Attach = 'load' | 'idle' | 'visible' | 'interaction';
|
|
2
|
+
/**
|
|
3
|
+
* An island on a page, in the manifest: its component, chunk, attach mode, how many, and its gzip size.
|
|
4
|
+
* @see https://clarusjs.com/reference/server#readmanifest
|
|
5
|
+
*/
|
|
2
6
|
export type IslandInfo = {
|
|
3
7
|
component: string;
|
|
4
8
|
src: string;
|
|
@@ -6,6 +10,10 @@ export type IslandInfo = {
|
|
|
6
10
|
count: number;
|
|
7
11
|
gzip: number;
|
|
8
12
|
};
|
|
13
|
+
/**
|
|
14
|
+
* A route in the manifest: its mode, islands, JavaScript and CSS.
|
|
15
|
+
* @see https://clarusjs.com/reference/server#readmanifest
|
|
16
|
+
*/
|
|
9
17
|
export type RouteInfo = {
|
|
10
18
|
/**
|
|
11
19
|
* 'static': prerendered at build. 'server': rendered per request by dist/server/index.mjs (its key is the route as
|
|
@@ -16,6 +24,8 @@ export type RouteInfo = {
|
|
|
16
24
|
html: string | null;
|
|
17
25
|
/** 'build': load() ran once, when the page was prerendered. 'request': it runs on every request. */
|
|
18
26
|
loader: 'build' | 'request' | null;
|
|
27
|
+
/** A server route whose load() reads cookies (from its source). */
|
|
28
|
+
cookies?: boolean;
|
|
19
29
|
islands: IslandInfo[];
|
|
20
30
|
/** Files relative to dist/client; gzip sizes in bytes. initialGzip is what loads with the page (attach="load"). */
|
|
21
31
|
js: {
|
|
@@ -25,6 +35,10 @@ export type RouteInfo = {
|
|
|
25
35
|
};
|
|
26
36
|
css: string[];
|
|
27
37
|
};
|
|
38
|
+
/**
|
|
39
|
+
* The built site's route manifest (`dist/clarusjs-manifest.json`).
|
|
40
|
+
* @see https://clarusjs.com/reference/server#readmanifest
|
|
41
|
+
*/
|
|
28
42
|
export type Manifest = {
|
|
29
43
|
version: 1;
|
|
30
44
|
routes: Record<string, RouteInfo>;
|
|
@@ -46,4 +60,5 @@ export declare function describeRoute(route: string, html: string, opts: {
|
|
|
46
60
|
export declare function writeManifest(distDir: string, routes: string[], base: string, loaded?: string[], server?: {
|
|
47
61
|
route: string;
|
|
48
62
|
loader: boolean;
|
|
63
|
+
cookies?: boolean;
|
|
49
64
|
}[]): Manifest;
|
package/dist/vite/manifest.js
CHANGED
|
@@ -70,8 +70,8 @@ export function writeManifest(distDir, routes, base, loaded = [], server = []) {
|
|
|
70
70
|
const ran = loaded.includes(route) || (isClient && loaded.includes(dataFile(route)));
|
|
71
71
|
manifest.routes[route] = describeRoute(route, readFileSync(resolve(client, routeToFile(route)), 'utf8'), { base, chunks, size, loaded: ran, client: isClient });
|
|
72
72
|
}
|
|
73
|
-
for (const { route, loader } of server) {
|
|
74
|
-
manifest.routes[route] = { mode: 'server', html: null, loader: loader ? 'request' : null, islands: [], js: { files: [], gzip: 0, initialGzip: 0 }, css: [] };
|
|
73
|
+
for (const { route, loader, cookies } of server) {
|
|
74
|
+
manifest.routes[route] = { mode: 'server', html: null, loader: loader ? 'request' : null, ...(cookies ? { cookies: true } : {}), islands: [], js: { files: [], gzip: 0, initialGzip: 0 }, css: [] };
|
|
75
75
|
}
|
|
76
76
|
writeFileSync(resolve(distDir, 'clarusjs-manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
77
77
|
return manifest;
|
package/dist/vite/node.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
1
2
|
export function toRequest(req) {
|
|
2
3
|
const headers = new Headers();
|
|
3
4
|
for (const [key, value] of Object.entries(req.headers)) {
|
|
@@ -6,7 +7,9 @@ export function toRequest(req) {
|
|
|
6
7
|
else if (value !== undefined)
|
|
7
8
|
headers.set(key, value);
|
|
8
9
|
}
|
|
9
|
-
|
|
10
|
+
const method = req.method ?? 'GET';
|
|
11
|
+
const body = method === 'GET' || method === 'HEAD' ? undefined : Readable.toWeb(req);
|
|
12
|
+
return new Request(`http://${req.headers.host ?? 'localhost'}${req.url ?? '/'}`, { method, headers, body, ...(body ? { duplex: 'half' } : {}) });
|
|
10
13
|
}
|
|
11
14
|
export async function sendResponse(res, response) {
|
|
12
15
|
res.statusCode = response.status;
|
package/dist/vite/plugin.d.ts
CHANGED
|
@@ -1,11 +1,20 @@
|
|
|
1
1
|
import { type Plugin } from 'vite';
|
|
2
|
+
import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
|
|
2
3
|
export { packageOf } from './build.ts';
|
|
3
4
|
/** Newest commit time (unix seconds) of every file under a folder, from one `git log` (themes use it for "last updated"). */
|
|
4
5
|
export { gitDates } from './sitemap.ts';
|
|
5
6
|
import { type ModeTable } from '../server/modes.ts';
|
|
6
7
|
import type { HeadTag, SiteOptions } from '../server/head.ts';
|
|
7
|
-
/**
|
|
8
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. Always with
|
|
10
|
+
* forward slashes (`/@fs/C:/libs/c.tscl` on Windows). `path`: the platform's (a parameter for tests). @internal
|
|
11
|
+
*/
|
|
12
|
+
export declare function clientUrlFor(root: string, file: string, path?: Pick<typeof import('node:path'), 'relative' | 'isAbsolute' | 'sep'>): string;
|
|
13
|
+
/**
|
|
14
|
+
* The Vite plugin's options: when routes render, the deploy adapter, fragment navigation, link checks, head tags, the
|
|
15
|
+
* site's address, sitemap and robots, redirects, and page sources.
|
|
16
|
+
* @see https://clarusjs.com/reference/vite-plugin#clarusjs
|
|
17
|
+
*/
|
|
9
18
|
export type ClarusOptions = {
|
|
10
19
|
/** When each route renders: { '/account/*': 'server' }. Routes default to 'static' (prerendered at build). */
|
|
11
20
|
routes?: ModeTable;
|
|
@@ -24,6 +33,16 @@ export type ClarusOptions = {
|
|
|
24
33
|
anchors?: LinkLevel;
|
|
25
34
|
strict?: boolean;
|
|
26
35
|
};
|
|
36
|
+
/**
|
|
37
|
+
* Template lint levels for `clarusjs check`: `{ 'img-alt': 'off', 'accessible-name': 'error' }`. Rules warn by default.
|
|
38
|
+
* @see https://clarusjs.com/guide/lint
|
|
39
|
+
*/
|
|
40
|
+
lint?: LintConfig;
|
|
41
|
+
/**
|
|
42
|
+
* The project's own lint rules, run by `clarusjs check` beside the built-in ones.
|
|
43
|
+
* @see https://clarusjs.com/guide/lint#writing-a-rule
|
|
44
|
+
*/
|
|
45
|
+
lintRules?: LintRuleDef[];
|
|
27
46
|
/**
|
|
28
47
|
* Paths that moved: `{ '/old': '/new' }` (a site path or a full URL). The build writes a page at each old path that
|
|
29
48
|
* sends visitors on, and `_redirects` lines (a real 301 on Netlify and Cloudflare Pages); dev answers 301.
|
|
@@ -54,21 +73,46 @@ export type ClarusOptions = {
|
|
|
54
73
|
};
|
|
55
74
|
/** With site.url, vite build writes robots.txt (allow all, and the sitemap), unless public/robots.txt exists. */
|
|
56
75
|
robots?: boolean;
|
|
76
|
+
/** Collapse whitespace in template text at build (default true). */
|
|
77
|
+
collapseWhitespace?: boolean;
|
|
78
|
+
/** At build, write .br and .gz next to dist/client's text files, for servers that serve them as is. Default false. */
|
|
79
|
+
compress?: boolean;
|
|
57
80
|
};
|
|
58
81
|
export type { HeadTag };
|
|
82
|
+
/**
|
|
83
|
+
* How a build reports a broken link: fail (`'error'`), print a warning, or skip the check.
|
|
84
|
+
* @see https://clarusjs.com/reference/vite-plugin#links
|
|
85
|
+
*/
|
|
59
86
|
export type LinkLevel = 'error' | 'warn' | 'off';
|
|
60
87
|
/**
|
|
61
88
|
* A page source: files with another extension (such as Markdown) turned into .tscl text, then compiled like any
|
|
62
89
|
* page. `route` is the page's route when the file is under src/pages.
|
|
90
|
+
* @see https://clarusjs.com/reference/vite-plugin#page-sources
|
|
63
91
|
*/
|
|
64
92
|
export type Source = {
|
|
65
93
|
extension: string;
|
|
66
94
|
toTscl(code: string, file: string, context: SourceContext): string;
|
|
67
95
|
};
|
|
68
|
-
/**
|
|
96
|
+
/** @see https://clarusjs.com/reference/vite-plugin#page-sources
|
|
97
|
+
* `root`: the app root. `addDependency(file)`: another file the output depends on (rebuilt when it changes in dev). */
|
|
69
98
|
export type SourceContext = {
|
|
70
99
|
route: string;
|
|
71
100
|
root: string;
|
|
72
101
|
addDependency(file: string): void;
|
|
73
102
|
};
|
|
103
|
+
/**
|
|
104
|
+
* The clarusjs Vite plugin: compiles `.tscl` files, serves pages in development, and on `vite build` builds the
|
|
105
|
+
* browser code, the server and the prerendered pages.
|
|
106
|
+
* @example
|
|
107
|
+
* ```ts
|
|
108
|
+
* // vite.config.ts
|
|
109
|
+
* import { defineConfig } from 'vite'
|
|
110
|
+
* import clarusjs from 'clarusjs/vite'
|
|
111
|
+
*
|
|
112
|
+
* export default defineConfig({
|
|
113
|
+
* plugins: [clarusjs({ routes: { '/account/*': 'server' }, fragments: true })],
|
|
114
|
+
* })
|
|
115
|
+
* ```
|
|
116
|
+
* @see https://clarusjs.com/reference/vite-plugin#clarusjs
|
|
117
|
+
*/
|
|
74
118
|
export default function clarusjs(options?: ClarusOptions): Plugin;
|
package/dist/vite/plugin.js
CHANGED
|
@@ -15,7 +15,8 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
15
15
|
}
|
|
16
16
|
return path;
|
|
17
17
|
};
|
|
18
|
-
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
18
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, watch as watchFs, writeFileSync } from 'node:fs';
|
|
19
|
+
import { brotliCompressSync, constants as zlibConstants, gzipSync } from 'node:zlib';
|
|
19
20
|
import { createRequire } from 'node:module';
|
|
20
21
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
21
22
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
@@ -38,17 +39,28 @@ import { sendResponse, toRequest } from './node.js';
|
|
|
38
39
|
const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
|
|
39
40
|
const here = (path) => fileURLToPath(new URL(path + ext, import.meta.url));
|
|
40
41
|
const ENTRY = 'virtual:clarusjs/server-entry';
|
|
41
|
-
export function clientUrlFor(root, file) {
|
|
42
|
-
const rel = relative(root, file);
|
|
43
|
-
|
|
42
|
+
export function clientUrlFor(root, file, path = { relative, isAbsolute, sep }) {
|
|
43
|
+
const rel = path.relative(root, file);
|
|
44
|
+
const slashes = (p) => p.split(path.sep).join('/');
|
|
45
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) {
|
|
46
|
+
const abs = slashes(file);
|
|
47
|
+
return `/@fs${abs.startsWith('/') ? '' : '/'}${abs}?import`;
|
|
48
|
+
}
|
|
49
|
+
return `/${slashes(rel)}?import`;
|
|
50
|
+
}
|
|
51
|
+
const real = (path) => { try {
|
|
52
|
+
return realpathSync.native(path);
|
|
44
53
|
}
|
|
54
|
+
catch {
|
|
55
|
+
return path;
|
|
56
|
+
} };
|
|
45
57
|
const LOADER_ENTRY = 'cl-loader';
|
|
46
58
|
const ROUTER_ENTRY = 'cl-router';
|
|
47
59
|
const NAV_ENTRY = 'cl-nav';
|
|
48
60
|
const STYLES_ENTRY = 'cl-styles';
|
|
49
61
|
const STYLES_FILE = '.clarusjs/styles.css';
|
|
50
62
|
const scopeFor = (root, file) => scopeId(relative(root, file).split(sep).join('/'));
|
|
51
|
-
function
|
|
63
|
+
function pageGraph(root, files, aliases = []) {
|
|
52
64
|
const deps = new Map();
|
|
53
65
|
const require = createRequire(resolve(root, 'package.json'));
|
|
54
66
|
const packageFile = (spec) => { try {
|
|
@@ -92,12 +104,20 @@ function pageStylesheets(root, files, aliases = []) {
|
|
|
92
104
|
};
|
|
93
105
|
const pages = new Map();
|
|
94
106
|
for (const file of files.find(resolve(root, 'src/pages'))) {
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
107
|
+
const css = [];
|
|
108
|
+
const seen = new Set();
|
|
109
|
+
collect(file, css, seen);
|
|
110
|
+
seen.delete(file);
|
|
111
|
+
pages.set(routeFromFile(`/${relative(root, file).split(sep).join('/')}`), { css, components: [...seen] });
|
|
98
112
|
}
|
|
99
113
|
return pages;
|
|
100
114
|
}
|
|
115
|
+
function componentLoaderOf(root, file) {
|
|
116
|
+
if (!file.endsWith('.tscl') || real(file).startsWith(real(resolve(root, 'src/pages')) + sep))
|
|
117
|
+
return undefined;
|
|
118
|
+
const loader = file.replace(/\.tscl$/, '.load.ts');
|
|
119
|
+
return existsSync(loader) ? loader : undefined;
|
|
120
|
+
}
|
|
101
121
|
function writeStyles(root, files) {
|
|
102
122
|
let css = '';
|
|
103
123
|
const head = new Set();
|
|
@@ -190,12 +210,14 @@ export default function clarusjs(options = {}) {
|
|
|
190
210
|
if (chunk.name)
|
|
191
211
|
built.set(chunk.name, base + chunk.file);
|
|
192
212
|
built.set(key, base + chunk.file);
|
|
213
|
+
const [file, query] = key.split('?');
|
|
214
|
+
built.set(real(resolve(root, file)) + (query ? `?${query}` : ''), base + chunk.file);
|
|
193
215
|
}
|
|
194
216
|
return built;
|
|
195
217
|
};
|
|
196
218
|
return {
|
|
197
219
|
name: 'clarusjs',
|
|
198
|
-
api: { sources },
|
|
220
|
+
api: { sources, lint: options.lint, lintRules: options.lintRules },
|
|
199
221
|
config(userConfig, env) {
|
|
200
222
|
const projectRoot = resolve(userConfig.root ?? process.cwd());
|
|
201
223
|
aliases = projectAliases(projectRoot, userConfig.resolve?.alias);
|
|
@@ -242,7 +264,7 @@ export default function clarusjs(options = {}) {
|
|
|
242
264
|
input[NAV_ENTRY] = here('../runtime/fragments');
|
|
243
265
|
if (writeStyles(appRoot, files))
|
|
244
266
|
input[STYLES_ENTRY] = resolve(appRoot, STYLES_FILE);
|
|
245
|
-
for (const sheet of new Set([...
|
|
267
|
+
for (const sheet of new Set([...pageGraph(appRoot, files, aliases).values()].flatMap((p) => p.css))) {
|
|
246
268
|
if (!existsSync(sheet))
|
|
247
269
|
throw new Error(`clarusjs: imported stylesheet not found: ${relative(appRoot, sheet)}`);
|
|
248
270
|
input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3))}`] = sheet;
|
|
@@ -288,96 +310,107 @@ export default function clarusjs(options = {}) {
|
|
|
288
310
|
const { client, ssr } = builder.environments;
|
|
289
311
|
if (!client || !ssr)
|
|
290
312
|
return;
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
const
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
313
|
+
const watching = !!client.config.build.watch;
|
|
314
|
+
if (watching)
|
|
315
|
+
client.config.build.watch = ssr.config.build.watch = null;
|
|
316
|
+
const once = async () => {
|
|
317
|
+
checkRedirects(options.redirects ?? {}, files.find(resolve(builder.config.root, 'src/pages')).map((f) => routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`)));
|
|
318
|
+
await builder.build(client);
|
|
319
|
+
await builder.build(ssr);
|
|
320
|
+
const entry = resolve(builder.config.root, SERVER_OUT, 'index.mjs');
|
|
321
|
+
const out = resolve(builder.config.root, CLIENT_OUT);
|
|
322
|
+
const dist = dirname(out);
|
|
323
|
+
const manifestFile = resolve(dist, 'clarusjs-manifest.json');
|
|
324
|
+
rmSync(manifestFile, { force: true });
|
|
325
|
+
const { routes, readers, loaded, server } = await prerender(entry, out, manifestFile);
|
|
303
326
|
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
const
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
const level = levels[issue.kind];
|
|
346
|
-
if (level === 'off')
|
|
347
|
-
continue;
|
|
348
|
-
const text = `${locate(issue.page, issue.href)}: ${issue.message}`;
|
|
349
|
-
if (level === 'error' || options.links?.strict)
|
|
350
|
-
errors.push(text);
|
|
351
|
-
else
|
|
352
|
-
builder.config.logger.warn(`clarusjs: ${text}`);
|
|
353
|
-
}
|
|
354
|
-
if (errors.length)
|
|
355
|
-
throw new Error(`clarusjs: broken links:\n ${errors.join('\n ')}`);
|
|
356
|
-
if (options.site && options.sitemap !== false) {
|
|
357
|
-
const dates = gitDates(builder.config.root, 'src/pages');
|
|
358
|
-
const epoch = process.env.SOURCE_DATE_EPOCH ? Number(process.env.SOURCE_DATE_EPOCH) : undefined;
|
|
359
|
-
const exclude = (typeof options.sitemap === 'object' ? options.sitemap.exclude ?? [] : [])
|
|
360
|
-
.map((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*\*|\*/g, (s) => (s === '**' ? '.*' : '[^/]+'))}$`));
|
|
361
|
-
const optedOut = (page) => {
|
|
362
|
-
const file = resolve(out, routeToFile(page));
|
|
363
|
-
const html = readFileSync(file, 'utf8');
|
|
364
|
-
const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
|
|
365
|
-
const attr = (tag, name) => new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((v) => v !== undefined);
|
|
366
|
-
const marker = tags.find((tag) => attr(tag, 'name')?.toLowerCase() === 'sitemap' && attr(tag, 'content') === 'false');
|
|
367
|
-
if (marker)
|
|
368
|
-
writeFileSync(file, html.replace(marker, ''));
|
|
369
|
-
return !!marker || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? ''));
|
|
327
|
+
if (readers.length) {
|
|
328
|
+
await prerender(entry, out, manifestFile, readers);
|
|
329
|
+
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
330
|
+
}
|
|
331
|
+
const pageRoutes = routes.filter((r) => !/\/(__data\.json|index\.frag\.html)$/.test(r));
|
|
332
|
+
const clientRoutes = pageRoutes.filter((r) => routes.includes(r === '/' ? '/__data.json' : `${r}/__data.json`));
|
|
333
|
+
if (pageRoutes.includes('/404') && !clientRoutes.includes('/404')) {
|
|
334
|
+
const html = rootLinks(readFileSync(resolve(out, routeToFile('/404')), 'utf8'), basePath(builder.config.base));
|
|
335
|
+
writeFileSync(resolve(out, routeToFile('/404')), html);
|
|
336
|
+
writeFileSync(resolve(out, '404.html'), html);
|
|
337
|
+
}
|
|
338
|
+
if (pageRoutes.includes('/500') && !clientRoutes.includes('/500')) {
|
|
339
|
+
const html = rootLinks(readFileSync(resolve(out, routeToFile('/500')), 'utf8'), basePath(builder.config.base));
|
|
340
|
+
writeFileSync(resolve(out, routeToFile('/500')), html);
|
|
341
|
+
writeFileSync(resolve(out, '500.html'), html);
|
|
342
|
+
}
|
|
343
|
+
if (options.redirects) {
|
|
344
|
+
writeRedirects(out, options.redirects, basePath(builder.config.base).replace(/\/$/, ''), routes);
|
|
345
|
+
const moved = Object.keys(options.redirects).map((from) => (from.length > 1 ? from.replace(/\/+$/, '') : from));
|
|
346
|
+
pageRoutes.push(...moved);
|
|
347
|
+
clientRoutes.push(...moved);
|
|
348
|
+
}
|
|
349
|
+
const issues = checkLinks({
|
|
350
|
+
outDir: out,
|
|
351
|
+
routes: pageRoutes,
|
|
352
|
+
serverRoutes: server.map((x) => x.route),
|
|
353
|
+
clientRoutes,
|
|
354
|
+
base: builder.config.base,
|
|
355
|
+
site: options.site?.url,
|
|
356
|
+
});
|
|
357
|
+
const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn' };
|
|
358
|
+
const sourceOf = new Map(files.find(resolve(builder.config.root, 'src/pages')).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
|
|
359
|
+
const pattern = (route) => new RegExp(`^${route.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
|
|
360
|
+
const fileOf = (page) => sourceOf.get(page) ?? [...sourceOf].find(([route]) => pattern(route).test(page))?.[1];
|
|
361
|
+
const locate = (page, href) => {
|
|
362
|
+
const file = fileOf(page);
|
|
363
|
+
if (!file)
|
|
364
|
+
return page;
|
|
365
|
+
const rel = relative(builder.config.root, file).split(sep).join('/');
|
|
366
|
+
const line = readFileSync(file, 'utf8').split('\n').findIndex((l) => l.includes(href));
|
|
367
|
+
return line === -1 ? `${rel} (${page})` : `${rel}:${line + 1}`;
|
|
370
368
|
};
|
|
371
|
-
const
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
369
|
+
const errors = [];
|
|
370
|
+
for (const issue of issues) {
|
|
371
|
+
const level = levels[issue.kind];
|
|
372
|
+
if (level === 'off')
|
|
373
|
+
continue;
|
|
374
|
+
const text = `${locate(issue.page, issue.href)}: ${issue.message}`;
|
|
375
|
+
if (level === 'error' || options.links?.strict)
|
|
376
|
+
errors.push(text);
|
|
377
|
+
else
|
|
378
|
+
builder.config.logger.warn(`clarusjs: ${text}`);
|
|
379
|
+
}
|
|
380
|
+
if (errors.length)
|
|
381
|
+
throw new Error(`clarusjs: broken links:\n ${errors.join('\n ')}`);
|
|
382
|
+
if (options.site && options.sitemap !== false) {
|
|
383
|
+
const dates = gitDates(builder.config.root, 'src/pages');
|
|
384
|
+
const epoch = process.env.SOURCE_DATE_EPOCH ? Number(process.env.SOURCE_DATE_EPOCH) : undefined;
|
|
385
|
+
const exclude = (typeof options.sitemap === 'object' ? options.sitemap.exclude ?? [] : [])
|
|
386
|
+
.map((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*\*|\*/g, (s) => (s === '**' ? '.*' : '[^/]+'))}$`));
|
|
387
|
+
const optedOut = (page) => {
|
|
388
|
+
const file = resolve(out, routeToFile(page));
|
|
389
|
+
const html = readFileSync(file, 'utf8');
|
|
390
|
+
const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
|
|
391
|
+
const attr = (tag, name) => new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((v) => v !== undefined);
|
|
392
|
+
const marker = tags.find((tag) => attr(tag, 'name')?.toLowerCase() === 'sitemap' && attr(tag, 'content') === 'false');
|
|
393
|
+
if (marker)
|
|
394
|
+
writeFileSync(file, html.replace(marker, ''));
|
|
395
|
+
return !!marker || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? ''));
|
|
396
|
+
};
|
|
397
|
+
const pages = pageRoutes.filter((page) => page !== '/404' && page !== '/500' && !clientRoutes.includes(page) && !optedOut(page) && !exclude.some((re) => re.test(page)))
|
|
398
|
+
.map((path) => ({ path, lastmod: dates.get(fileOf(path) ?? '') ?? epoch }));
|
|
399
|
+
writeFileSync(resolve(out, 'sitemap.xml'), sitemapXml(options.site.url, builder.config.base, pages));
|
|
400
|
+
}
|
|
401
|
+
if (options.site && options.robots !== false && !existsSync(resolve(out, 'robots.txt'))) {
|
|
402
|
+
const sitemap = options.sitemap !== false ? `\nSitemap: ${new URL('sitemap.xml', new URL(builder.config.base, options.site.url.replace(/\/?$/, '/'))).href}\n` : '';
|
|
403
|
+
writeFileSync(resolve(out, 'robots.txt'), `User-agent: *\nAllow: /\n${sitemap}`);
|
|
404
|
+
}
|
|
405
|
+
if (options.adapter === 'netlify')
|
|
406
|
+
writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true);
|
|
407
|
+
rmSync(resolve(out, '.vite'), { recursive: true, force: true });
|
|
408
|
+
if (options.compress)
|
|
409
|
+
precompress(out);
|
|
410
|
+
};
|
|
411
|
+
await once();
|
|
412
|
+
if (watching)
|
|
413
|
+
watchApp(builder, once);
|
|
381
414
|
},
|
|
382
415
|
resolveId: { order: 'pre', handler(id, importer) {
|
|
383
416
|
if (/^\.\/navigate\.[jt]s$/.test(id) && importer && /[\\/]runtime[\\/](router|fragments)\.[jt]s$/.test(importer)) {
|
|
@@ -389,6 +422,8 @@ export default function clarusjs(options = {}) {
|
|
|
389
422
|
return here('../runtime/router');
|
|
390
423
|
if (id === '/cl-nav.js')
|
|
391
424
|
return here('../runtime/fragments');
|
|
425
|
+
if (id === '/cl-hot.js')
|
|
426
|
+
return here('../runtime/hot');
|
|
392
427
|
if (id === ENTRY)
|
|
393
428
|
return '\0' + ENTRY;
|
|
394
429
|
} },
|
|
@@ -406,12 +441,19 @@ export default function clarusjs(options = {}) {
|
|
|
406
441
|
const routerUrl = urls?.get(ROUTER_ENTRY) ?? '/cl-router.js';
|
|
407
442
|
const navUrl = urls?.get(NAV_ENTRY) ?? '/cl-nav.js';
|
|
408
443
|
const css = {};
|
|
409
|
-
|
|
444
|
+
const graph = pageGraph(root, files, aliases);
|
|
445
|
+
const componentLoaders = {};
|
|
446
|
+
for (const [route, { components }] of graph) {
|
|
447
|
+
const loaders = components.map((c) => componentLoaderOf(root, c)).filter((f) => !!f && !relative(root, f).startsWith('..'));
|
|
448
|
+
if (loaders.length)
|
|
449
|
+
componentLoaders[route] = loaders.map((f) => `/${relative(root, f).split(sep).join('/')}`).sort();
|
|
450
|
+
}
|
|
451
|
+
for (const [route, { css: sheets }] of graph) {
|
|
410
452
|
if (!sheets.length)
|
|
411
453
|
continue;
|
|
412
454
|
css[route] = sheets.map((sheet) => {
|
|
413
455
|
const key = relative(root, sheet).split(sep).join('/');
|
|
414
|
-
const url = urls ? urls.get(key) : clientUrlFor(root, sheet).replace(/\?.*$/, '');
|
|
456
|
+
const url = urls ? urls.get(key) ?? urls.get(real(sheet)) : clientUrlFor(root, sheet).replace(/\?.*$/, '');
|
|
415
457
|
if (!url)
|
|
416
458
|
throw new Error(`clarusjs: no built stylesheet for ${key}`);
|
|
417
459
|
return url;
|
|
@@ -421,7 +463,7 @@ export default function clarusjs(options = {}) {
|
|
|
421
463
|
const client = {};
|
|
422
464
|
for (const [route, file] of clientPages(root, modes, files)) {
|
|
423
465
|
const key = `${relative(root, file).split(sep).join('/')}?render`;
|
|
424
|
-
const url = urls ? urls.get(key) : `${clientUrlFor(root, file).replace(/\?.*$/, '')}?render&import`;
|
|
466
|
+
const url = urls ? urls.get(key) ?? urls.get(`${real(file)}?render`) : `${clientUrlFor(root, file).replace(/\?.*$/, '')}?render&import`;
|
|
425
467
|
if (!url)
|
|
426
468
|
throw new Error(`clarusjs: no client chunk for ${key}`);
|
|
427
469
|
client[route] = url;
|
|
@@ -433,6 +475,9 @@ export default function clarusjs(options = {}) {
|
|
|
433
475
|
`export default createHandler(import.meta.glob(${glob('/src/pages')}), {\n` +
|
|
434
476
|
` loaderUrl: ${JSON.stringify(loaderUrl)},\n` +
|
|
435
477
|
` data: import.meta.glob('/src/pages/**/*.load.ts'),\n` +
|
|
478
|
+
` componentLoaders: ${JSON.stringify(componentLoaders)},\n` +
|
|
479
|
+
` componentData: import.meta.glob(['/src/**/*.load.ts', '!/src/pages/**']),\n` +
|
|
480
|
+
` endpoints: import.meta.glob(['/src/pages/**/*.ts', '!/src/pages/**/*.load.ts', '!/src/pages/**/*.d.ts']),\n` +
|
|
436
481
|
` modes: ${JSON.stringify(modes)},\n` +
|
|
437
482
|
` routerUrl: ${JSON.stringify(routerUrl)},\n` +
|
|
438
483
|
` client: ${JSON.stringify(client)},\n` +
|
|
@@ -444,6 +489,7 @@ export default function clarusjs(options = {}) {
|
|
|
444
489
|
` css: ${JSON.stringify(css)},\n` +
|
|
445
490
|
` site: ${JSON.stringify(options.site)},\n` +
|
|
446
491
|
` head: { ...${JSON.stringify(options.head ?? {})}, transform: Object.values(import.meta.glob('/src/head.ts', { eager: true }))[0]?.transformHead },\n` +
|
|
492
|
+
` hooks: Object.values(import.meta.glob('/src/server.ts', { eager: true }))[0],\n` +
|
|
447
493
|
`})\n`;
|
|
448
494
|
} },
|
|
449
495
|
transform: {
|
|
@@ -462,7 +508,7 @@ export default function clarusjs(options = {}) {
|
|
|
462
508
|
const consumer = this.environment.config.consumer;
|
|
463
509
|
const urls = consumer === 'server' ? builtUrls() : undefined;
|
|
464
510
|
const clientUrl = urls
|
|
465
|
-
? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/'))
|
|
511
|
+
? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/')) ?? urls.get(real(file))
|
|
466
512
|
: command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
|
|
467
513
|
if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
|
|
468
514
|
this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
|
|
@@ -485,7 +531,10 @@ export default function clarusjs(options = {}) {
|
|
|
485
531
|
}
|
|
486
532
|
try {
|
|
487
533
|
const renderImports = renderQuery && this.environment.config.consumer !== 'server';
|
|
488
|
-
const
|
|
534
|
+
const collapseWhitespace = command === 'build' && options.collapseWhitespace !== false;
|
|
535
|
+
const loader = componentLoaderOf(root, file) ? relative(root, file).split(sep).join('/') : undefined;
|
|
536
|
+
const hot = command === 'serve' && target === 'client' ? '/cl-hot.js' : undefined;
|
|
537
|
+
const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot });
|
|
489
538
|
if (consumer === 'server' && !renderQuery)
|
|
490
539
|
for (const w of out.warnings)
|
|
491
540
|
this.warn(w.message);
|
|
@@ -501,18 +550,20 @@ export default function clarusjs(options = {}) {
|
|
|
501
550
|
configurePreviewServer(server) {
|
|
502
551
|
const outDir = resolve(server.config.root, server.config.build.outDir);
|
|
503
552
|
const base = server.config.base;
|
|
504
|
-
server.middlewares.use((req,
|
|
553
|
+
server.middlewares.use((req, res, next) => {
|
|
505
554
|
let url;
|
|
506
555
|
try {
|
|
507
556
|
url = decodeURIComponent((req.url ?? '/').split('?')[0]);
|
|
508
557
|
}
|
|
509
558
|
catch {
|
|
510
|
-
|
|
559
|
+
res.statusCode = 400;
|
|
560
|
+
res.setHeader('content-type', 'text/plain; charset=utf-8');
|
|
561
|
+
return res.end('Bad Request: malformed URL');
|
|
511
562
|
}
|
|
512
563
|
const inBase = url === base.slice(0, -1) ? '/' : url.startsWith(base) ? '/' + url.slice(base.length) : undefined;
|
|
513
564
|
if (inBase !== undefined) {
|
|
514
565
|
const file = resolve(outDir, `.${inBase.replace(/\/?$/, '/')}index.html`);
|
|
515
|
-
if (file.startsWith(outDir) && existsSync(file))
|
|
566
|
+
if (file.startsWith(outDir + sep) && existsSync(file))
|
|
516
567
|
req.url = base + file.slice(outDir.length + 1).replace(/\\/g, '/');
|
|
517
568
|
}
|
|
518
569
|
next();
|
|
@@ -545,6 +596,13 @@ export default function clarusjs(options = {}) {
|
|
|
545
596
|
});
|
|
546
597
|
};
|
|
547
598
|
},
|
|
599
|
+
hotUpdate({ file, modules, server }) {
|
|
600
|
+
if (this.environment.name !== 'ssr' || !modules.length)
|
|
601
|
+
return;
|
|
602
|
+
if (server.environments.client.moduleGraph.getModulesByFile(file)?.size)
|
|
603
|
+
return;
|
|
604
|
+
server.environments.client.hot.send({ type: 'full-reload' });
|
|
605
|
+
},
|
|
548
606
|
configureServer(server) {
|
|
549
607
|
const restyle = (file) => { if (fileRe.test(file))
|
|
550
608
|
writeStyles(server.config.root, files); };
|
|
@@ -578,3 +636,36 @@ export default function clarusjs(options = {}) {
|
|
|
578
636
|
},
|
|
579
637
|
};
|
|
580
638
|
}
|
|
639
|
+
function precompress(dir) {
|
|
640
|
+
for (const name of readdirSync(dir, { recursive: true })) {
|
|
641
|
+
if (!/\.(html|js|css|svg|json|xml)$/.test(name))
|
|
642
|
+
continue;
|
|
643
|
+
const file = resolve(dir, name);
|
|
644
|
+
const data = readFileSync(file);
|
|
645
|
+
const br = brotliCompressSync(data, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 11, [zlibConstants.BROTLI_PARAM_SIZE_HINT]: data.length } });
|
|
646
|
+
const gz = gzipSync(data, { level: 9 });
|
|
647
|
+
if (br.length < data.length)
|
|
648
|
+
writeFileSync(file + '.br', br);
|
|
649
|
+
if (gz.length < data.length)
|
|
650
|
+
writeFileSync(file + '.gz', gz);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
function watchApp(builder, once) {
|
|
654
|
+
let timer;
|
|
655
|
+
let running = Promise.resolve();
|
|
656
|
+
const rebuild = () => {
|
|
657
|
+
clearTimeout(timer);
|
|
658
|
+
timer = setTimeout(() => {
|
|
659
|
+
running = running.then(once).then(() => builder.config.logger.info('clarusjs: rebuilt'), (err) => builder.config.logger.error(`clarusjs: rebuild failed: ${err?.message ?? err}`));
|
|
660
|
+
}, 100);
|
|
661
|
+
};
|
|
662
|
+
const watchers = ['src', 'public'].filter((d) => existsSync(resolve(builder.config.root, d))).map((d) => watchFs(resolve(builder.config.root, d), { recursive: true }, rebuild));
|
|
663
|
+
builder.clarusjsWatcher = {
|
|
664
|
+
async close() {
|
|
665
|
+
clearTimeout(timer);
|
|
666
|
+
for (const w of watchers)
|
|
667
|
+
w.close();
|
|
668
|
+
await running;
|
|
669
|
+
},
|
|
670
|
+
};
|
|
671
|
+
}
|