clarusjs 0.6.0 → 0.8.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/check/generate.js +1 -21
- package/dist/cli/check.js +44 -11
- package/dist/cli/explain.js +0 -1
- package/dist/cli/index.js +0 -1
- package/dist/compiler/emit-client.js +1 -11
- package/dist/compiler/emit-server.js +1 -2
- package/dist/compiler/errors.js +0 -1
- package/dist/compiler/html-expr.js +2 -7
- package/dist/compiler/index.d.ts +6 -0
- package/dist/compiler/index.js +45 -4
- package/dist/compiler/ir.d.ts +1 -0
- package/dist/compiler/ir.js +9 -14
- package/dist/compiler/parse.d.ts +10 -0
- package/dist/compiler/parse.js +48 -20
- package/dist/compiler/script.js +2 -31
- package/dist/compiler/shared.js +0 -5
- package/dist/runtime/fragments.js +23 -3
- package/dist/runtime/html.d.ts +2 -0
- package/dist/runtime/html.js +4 -0
- package/dist/runtime/loader.js +46 -3
- package/dist/runtime/router.d.ts +1 -1
- package/dist/runtime/router.js +23 -15
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/server.js +1 -1
- package/dist/server/handler.d.ts +15 -1
- package/dist/server/handler.js +61 -52
- package/dist/server/head.d.ts +36 -0
- package/dist/server/head.js +129 -0
- package/dist/server/manifest.js +0 -3
- package/dist/server/modes.js +0 -5
- package/dist/server/views.js +1 -8
- package/dist/vite/build.d.ts +10 -2
- package/dist/vite/build.js +44 -19
- package/dist/vite/links.d.ts +20 -0
- package/dist/vite/links.js +94 -0
- package/dist/vite/manifest.js +2 -10
- package/dist/vite/netlify.js +1 -7
- package/dist/vite/plugin.d.ts +55 -0
- package/dist/vite/plugin.js +282 -82
- package/dist/vite/sitemap.d.ts +11 -0
- package/dist/vite/sitemap.js +31 -0
- package/package.json +5 -3
package/dist/vite/plugin.js
CHANGED
|
@@ -6,24 +6,27 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
6
6
|
}
|
|
7
7
|
return path;
|
|
8
8
|
};
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
|
9
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { createRequire } from 'node:module';
|
|
12
11
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
13
12
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
14
|
-
import { isRunnableDevEnvironment } from 'vite';
|
|
15
|
-
import { compile, ClarusError } from '../compiler/index.js';
|
|
16
|
-
import {
|
|
13
|
+
import { isRunnableDevEnvironment, normalizePath } from 'vite';
|
|
14
|
+
import { compile, scopeId, ClarusError } from '../compiler/index.js';
|
|
15
|
+
import { parse } from '../compiler/parse.js';
|
|
16
|
+
import { findClarusFiles, packageOf as packageOfFile, prerender, reachableComponents, routeToFile } from './build.js';
|
|
17
|
+
export { packageOf } from './build.js';
|
|
18
|
+
export { gitDates } from './sitemap.js';
|
|
17
19
|
import { writeManifest } from './manifest.js';
|
|
18
20
|
import { writeNetlifyFunction } from './netlify.js';
|
|
21
|
+
import { checkLinks } from './links.js';
|
|
22
|
+
import { gitDates, sitemapXml } from './sitemap.js';
|
|
19
23
|
import { checkModes, modeFor } from '../server/modes.js';
|
|
20
|
-
import { routeFromFile } from '../server/handler.js';
|
|
24
|
+
import { rootLinks, routeFromFile } from '../server/handler.js';
|
|
25
|
+
import { basePath } from '../server/head.js';
|
|
21
26
|
import { sendResponse, toRequest } from './node.js';
|
|
22
|
-
// From src/ (workspace, tests) our siblings are .ts files; from the published dist/ they are .js.
|
|
23
27
|
const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
|
|
24
28
|
const here = (path) => fileURLToPath(new URL(path + ext, import.meta.url));
|
|
25
29
|
const ENTRY = 'virtual:clarusjs/server-entry';
|
|
26
|
-
/** Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. */
|
|
27
30
|
export function clientUrlFor(root, file) {
|
|
28
31
|
const rel = relative(root, file);
|
|
29
32
|
return rel.startsWith('..') || isAbsolute(rel) ? `/@fs${file}?import` : `/${rel}?import`;
|
|
@@ -31,17 +34,92 @@ export function clientUrlFor(root, file) {
|
|
|
31
34
|
const LOADER_ENTRY = 'cl-loader';
|
|
32
35
|
const ROUTER_ENTRY = 'cl-router';
|
|
33
36
|
const NAV_ENTRY = 'cl-nav';
|
|
34
|
-
|
|
37
|
+
const STYLES_ENTRY = 'cl-styles';
|
|
38
|
+
const STYLES_FILE = '.clarusjs/styles.css';
|
|
39
|
+
const scopeFor = (root, file) => scopeId(relative(root, file).split(sep).join('/'));
|
|
40
|
+
function pageStylesheets(root, files) {
|
|
41
|
+
const deps = new Map();
|
|
42
|
+
const require = createRequire(resolve(root, 'package.json'));
|
|
43
|
+
const packageFile = (spec) => { try {
|
|
44
|
+
return realpathSync(require.resolve(spec.replace(/\?.*$/, '')));
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return undefined;
|
|
48
|
+
} };
|
|
49
|
+
const read = (file) => {
|
|
50
|
+
if (!deps.has(file)) {
|
|
51
|
+
let parsed;
|
|
52
|
+
try {
|
|
53
|
+
parsed = parse(files.read(file, root), file);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
parsed = null;
|
|
57
|
+
}
|
|
58
|
+
const near = (from) => {
|
|
59
|
+
const path = from.replace(/\?.*$/, '');
|
|
60
|
+
return path.startsWith('/') ? resolve(root, `.${path}`) : resolve(dirname(file), path);
|
|
61
|
+
};
|
|
62
|
+
deps.set(file, {
|
|
63
|
+
css: parsed?.cssImports.map((c) => near(c.from)) ?? [],
|
|
64
|
+
components: parsed?.imports.map((imp) => (/^[./]/.test(imp.from) ? near(imp.from) : packageFile(imp.from))).filter((f) => !!f) ?? [],
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
return deps.get(file);
|
|
68
|
+
};
|
|
69
|
+
const collect = (file, out, seen) => {
|
|
70
|
+
if (seen.has(file))
|
|
71
|
+
return;
|
|
72
|
+
seen.add(file);
|
|
73
|
+
const { css, components } = read(file);
|
|
74
|
+
for (const c of components)
|
|
75
|
+
if (existsSync(c))
|
|
76
|
+
collect(c, out, seen);
|
|
77
|
+
for (const sheet of css)
|
|
78
|
+
if (!out.includes(sheet))
|
|
79
|
+
out.push(sheet);
|
|
80
|
+
};
|
|
81
|
+
const pages = new Map();
|
|
82
|
+
for (const file of files.find(resolve(root, 'src/pages'))) {
|
|
83
|
+
const out = [];
|
|
84
|
+
collect(file, out, new Set());
|
|
85
|
+
pages.set(routeFromFile(`/${relative(root, file).split(sep).join('/')}`), out);
|
|
86
|
+
}
|
|
87
|
+
return pages;
|
|
88
|
+
}
|
|
89
|
+
function writeStyles(root, files) {
|
|
90
|
+
let css = '';
|
|
91
|
+
const head = new Set();
|
|
92
|
+
const outDir = resolve(root, '.clarusjs');
|
|
93
|
+
for (const file of files.components(root)) {
|
|
94
|
+
try {
|
|
95
|
+
let out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file) }).css;
|
|
96
|
+
out = out.replace(/^(?:[ \t]*@(?:reference|import)\b[^;{]*;[ \t]*\n?)+/, (statements) => {
|
|
97
|
+
for (const statement of statements.split(';').map((x) => x.trim()).filter(Boolean)) {
|
|
98
|
+
head.add(statement.replace(/(["'])(\.{1,2}\/[^"']*)\1/, (_, q, spec) => {
|
|
99
|
+
const target = relative(outDir, resolve(file, '..', spec)).split(sep).join('/');
|
|
100
|
+
return q + (target.startsWith('.') ? target : `./${target}`) + q;
|
|
101
|
+
}) + ';');
|
|
102
|
+
}
|
|
103
|
+
return '';
|
|
104
|
+
});
|
|
105
|
+
if (out)
|
|
106
|
+
css += `/* ${relative(root, file).split(sep).join('/')} */\n${out}`;
|
|
107
|
+
}
|
|
108
|
+
catch { }
|
|
109
|
+
}
|
|
110
|
+
css = [...head].map((x) => `${x}\n`).join('') + css;
|
|
111
|
+
mkdirSync(outDir, { recursive: true });
|
|
112
|
+
writeFileSync(resolve(root, STYLES_FILE), css);
|
|
113
|
+
return css !== '';
|
|
114
|
+
}
|
|
35
115
|
const renderEntry = (name) => `render/${name}`;
|
|
36
116
|
const CLIENT_OUT = 'dist/client';
|
|
37
|
-
// Placeholder for a nested island's chunk URL in the client build, replaced once the bundle's file names are known.
|
|
38
117
|
const CHUNK_TOKEN = '__CLARUS_CHUNK__';
|
|
39
118
|
const SERVER_OUT = 'dist/server';
|
|
40
|
-
const entryName = (root, file) => relative(root, file).replace(/\.
|
|
41
|
-
|
|
42
|
-
function clientPages(appRoot, modes) {
|
|
119
|
+
const entryName = (root, file) => relative(root, file).split(sep).join('/').replace(/\.[^./\\]+$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3));
|
|
120
|
+
function clientPages(appRoot, modes, files) {
|
|
43
121
|
const pages = new Map();
|
|
44
|
-
for (const file of
|
|
122
|
+
for (const file of files.find(resolve(appRoot, 'src/pages'))) {
|
|
45
123
|
const route = routeFromFile(`/${relative(appRoot, file).split(sep).join('/')}`);
|
|
46
124
|
if (modeFor(route, modes) === 'client')
|
|
47
125
|
pages.set(route, file);
|
|
@@ -51,15 +129,36 @@ function clientPages(appRoot, modes) {
|
|
|
51
129
|
export default function clarusjs(options = {}) {
|
|
52
130
|
const modes = options.routes ?? {};
|
|
53
131
|
checkModes(modes);
|
|
132
|
+
const sources = options.sources ?? [];
|
|
133
|
+
if (options.site && !/^https?:\/\/[^/]/.test(options.site.url))
|
|
134
|
+
throw new Error(`clarusjs: site.url must be an absolute http(s) URL, got "${options.site.url}"`);
|
|
135
|
+
for (const src of sources) {
|
|
136
|
+
if (!/^\.[\w-]+$/.test(src.extension))
|
|
137
|
+
throw new Error(`clarusjs: a source extension must look like ".md", got "${src.extension}"`);
|
|
138
|
+
if (src.extension === '.tscl')
|
|
139
|
+
throw new Error('clarusjs: .tscl files are compiled directly; a source needs its own extension');
|
|
140
|
+
}
|
|
141
|
+
const extensions = ['.tscl', ...sources.map((src) => src.extension)];
|
|
142
|
+
const files = {
|
|
143
|
+
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),
|
|
145
|
+
read: (file, appRoot) => {
|
|
146
|
+
const code = readFileSync(file, 'utf8');
|
|
147
|
+
const src = sources.find((x) => file.endsWith(x.extension));
|
|
148
|
+
if (!src)
|
|
149
|
+
return code;
|
|
150
|
+
const rel = relative(appRoot, file).split(sep).join('/');
|
|
151
|
+
return src.toTscl(code, file, { route: rel.startsWith('src/pages/') ? routeFromFile(`/${rel}`) : '', root: appRoot, addDependency: () => { } });
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
const fileRe = new RegExp(`\\.(${extensions.map((e) => e.slice(1)).join('|')})(\\?|$)`);
|
|
155
|
+
const glob = (dir) => JSON.stringify(extensions.map((e) => `${dir}/**/*${e}`));
|
|
54
156
|
if (options.adapter !== undefined && options.adapter !== 'netlify') {
|
|
55
157
|
throw new Error(`clarusjs: adapter "${options.adapter}" is not supported; use 'netlify'`);
|
|
56
158
|
}
|
|
57
159
|
let root = process.cwd();
|
|
58
160
|
let command = 'serve';
|
|
59
161
|
let base = '/';
|
|
60
|
-
// `vite build` only: client entry name (see entryName) → public URL of its hashed chunk.
|
|
61
|
-
// Read from the client manifest on disk, because Vite resolves config (and so creates a new plugin instance) per
|
|
62
|
-
// environment: the server build cannot see state set during the client build.
|
|
63
162
|
let built;
|
|
64
163
|
const builtUrls = () => {
|
|
65
164
|
if (command !== 'build')
|
|
@@ -72,7 +171,6 @@ export default function clarusjs(options = {}) {
|
|
|
72
171
|
}
|
|
73
172
|
const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
|
|
74
173
|
built = new Map();
|
|
75
|
-
// By entry name, and by source key: names are sanitized ([id] → _id_), keys keep the real path.
|
|
76
174
|
for (const [key, chunk] of Object.entries(manifest)) {
|
|
77
175
|
if (!chunk.isEntry)
|
|
78
176
|
continue;
|
|
@@ -95,50 +193,59 @@ export default function clarusjs(options = {}) {
|
|
|
95
193
|
},
|
|
96
194
|
};
|
|
97
195
|
if (env.isPreview)
|
|
98
|
-
config.build = { outDir: CLIENT_OUT };
|
|
196
|
+
config.build = { outDir: CLIENT_OUT };
|
|
197
|
+
const shipping = new Set();
|
|
198
|
+
if (!env.isPreview) {
|
|
199
|
+
for (const file of files.components(resolve(userConfig.root ?? process.cwd()))) {
|
|
200
|
+
const name = packageOfFile(file);
|
|
201
|
+
if (name)
|
|
202
|
+
shipping.add(name);
|
|
203
|
+
}
|
|
204
|
+
if (shipping.size)
|
|
205
|
+
config.ssr = { noExternal: [...shipping] };
|
|
206
|
+
}
|
|
99
207
|
if (env.command !== 'build')
|
|
100
208
|
return config;
|
|
101
209
|
if (userConfig.base !== undefined && !userConfig.base.startsWith('/') && !/^https?:\/\//.test(userConfig.base)) {
|
|
102
|
-
// Pages live at different depths and islands are imported from the loader, so URLs must not be relative.
|
|
103
210
|
throw new Error(`clarusjs: relative base "${userConfig.base}" is not supported; use an absolute base such as "/" or "/docs/"`);
|
|
104
211
|
}
|
|
105
|
-
// Client entries: the island loader plus every stateful component. Stateless components never reach the client.
|
|
106
212
|
const appRoot = resolve(userConfig.root ?? process.cwd());
|
|
107
213
|
const input = { [LOADER_ENTRY]: here('../runtime/loader') };
|
|
108
|
-
|
|
109
|
-
|
|
214
|
+
const components = files.components(appRoot);
|
|
215
|
+
for (const file of components) {
|
|
216
|
+
if (compile(files.read(file, appRoot), { file, target: 'client' }).stateful)
|
|
110
217
|
input[entryName(appRoot, file)] = file;
|
|
111
218
|
}
|
|
112
|
-
|
|
113
|
-
const client = clientPages(appRoot, modes);
|
|
219
|
+
const client = clientPages(appRoot, modes, files);
|
|
114
220
|
if (client.size)
|
|
115
221
|
input[ROUTER_ENTRY] = here('../runtime/router');
|
|
116
222
|
if (options.fragments)
|
|
117
223
|
input[NAV_ENTRY] = here('../runtime/fragments');
|
|
224
|
+
if (writeStyles(appRoot, files))
|
|
225
|
+
input[STYLES_ENTRY] = resolve(appRoot, STYLES_FILE);
|
|
226
|
+
for (const sheet of new Set([...pageStylesheets(appRoot, files).values()].flat())) {
|
|
227
|
+
if (!existsSync(sheet))
|
|
228
|
+
throw new Error(`clarusjs: imported stylesheet not found: ${relative(appRoot, sheet)}`);
|
|
229
|
+
input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3))}`] = sheet;
|
|
230
|
+
}
|
|
118
231
|
for (const file of client.values())
|
|
119
232
|
input[renderEntry(entryName(appRoot, file))] = `${file}?render`;
|
|
120
233
|
config.builder = {};
|
|
121
234
|
config.environments = {
|
|
122
|
-
// Island chunks are loaded with import() and must keep their `attach` export.
|
|
123
235
|
client: { build: { outDir: CLIENT_OUT, manifest: true, rolldownOptions: { input, preserveEntrySignatures: 'exports-only' } } },
|
|
124
|
-
// Always .mjs, so Node loads it as ESM whatever the app's package.json says.
|
|
125
236
|
ssr: { build: { outDir: SERVER_OUT, rolldownOptions: { input: { index: ENTRY }, output: { entryFileNames: '[name].mjs' } } } },
|
|
126
237
|
};
|
|
127
238
|
return config;
|
|
128
239
|
},
|
|
129
|
-
// Each build re-reads the client manifest: a builder can run buildApp() more than once.
|
|
130
240
|
buildStart() { built = undefined; },
|
|
131
|
-
// Client build: nested islands rendered in the browser get their chunk's real URL.
|
|
132
241
|
generateBundle(_options, bundle) {
|
|
133
242
|
if (this.environment.config.consumer !== 'client' || command !== 'build')
|
|
134
243
|
return;
|
|
135
244
|
const byName = new Map();
|
|
136
|
-
// By sanitized name and by the raw entry name from the source path ([id] stays [id]).
|
|
137
245
|
for (const out of Object.values(bundle)) {
|
|
138
246
|
if (out.type !== 'chunk' || !out.isEntry)
|
|
139
247
|
continue;
|
|
140
248
|
byName.set(out.name, base + out.fileName);
|
|
141
|
-
// Only island chunks: a client page's ?render chunk would otherwise take its island's place.
|
|
142
249
|
if (out.facadeModuleId && !/[?&]render\b/.test(out.facadeModuleId))
|
|
143
250
|
byName.set(entryName(root, out.facadeModuleId.replace(/\?.*$/, '')), base + out.fileName);
|
|
144
251
|
}
|
|
@@ -158,7 +265,6 @@ export default function clarusjs(options = {}) {
|
|
|
158
265
|
command = config.command;
|
|
159
266
|
base = config.base;
|
|
160
267
|
},
|
|
161
|
-
// Order matters: the server build needs the client's hashed URLs, and prerendering needs the server build.
|
|
162
268
|
async buildApp(builder) {
|
|
163
269
|
const { client, ssr } = builder.environments;
|
|
164
270
|
if (!client || !ssr)
|
|
@@ -169,14 +275,76 @@ export default function clarusjs(options = {}) {
|
|
|
169
275
|
const out = resolve(builder.config.root, CLIENT_OUT);
|
|
170
276
|
const dist = dirname(out);
|
|
171
277
|
const manifestFile = resolve(dist, 'clarusjs-manifest.json');
|
|
172
|
-
rmSync(manifestFile, { force: true });
|
|
278
|
+
rmSync(manifestFile, { force: true });
|
|
173
279
|
const { routes, readers, loaded, server } = await prerender(entry, out, manifestFile);
|
|
174
280
|
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
175
|
-
// Pages that read the manifest saw none on the first pass: render them again now that it exists.
|
|
176
281
|
if (readers.length) {
|
|
177
282
|
await prerender(entry, out, manifestFile, readers);
|
|
178
283
|
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
179
284
|
}
|
|
285
|
+
const pageRoutes = routes.filter((r) => !/\/(__data\.json|index\.frag\.html)$/.test(r));
|
|
286
|
+
const clientRoutes = pageRoutes.filter((r) => routes.includes(r === '/' ? '/__data.json' : `${r}/__data.json`));
|
|
287
|
+
if (pageRoutes.includes('/404') && !clientRoutes.includes('/404')) {
|
|
288
|
+
const html = rootLinks(readFileSync(resolve(out, routeToFile('/404')), 'utf8'), basePath(builder.config.base));
|
|
289
|
+
writeFileSync(resolve(out, routeToFile('/404')), html);
|
|
290
|
+
writeFileSync(resolve(out, '404.html'), html);
|
|
291
|
+
}
|
|
292
|
+
const issues = checkLinks({
|
|
293
|
+
outDir: out,
|
|
294
|
+
routes: pageRoutes,
|
|
295
|
+
serverRoutes: server.map((x) => x.route),
|
|
296
|
+
clientRoutes,
|
|
297
|
+
base: builder.config.base,
|
|
298
|
+
site: options.site?.url,
|
|
299
|
+
});
|
|
300
|
+
const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn' };
|
|
301
|
+
const sourceOf = new Map(files.find(resolve(builder.config.root, 'src/pages')).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
|
|
302
|
+
const pattern = (route) => new RegExp(`^${route.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
|
|
303
|
+
const fileOf = (page) => sourceOf.get(page) ?? [...sourceOf].find(([route]) => pattern(route).test(page))?.[1];
|
|
304
|
+
const locate = (page, href) => {
|
|
305
|
+
const file = fileOf(page);
|
|
306
|
+
if (!file)
|
|
307
|
+
return page;
|
|
308
|
+
const rel = relative(builder.config.root, file).split(sep).join('/');
|
|
309
|
+
const line = readFileSync(file, 'utf8').split('\n').findIndex((l) => l.includes(href));
|
|
310
|
+
return line === -1 ? `${rel} (${page})` : `${rel}:${line + 1}`;
|
|
311
|
+
};
|
|
312
|
+
const errors = [];
|
|
313
|
+
for (const issue of issues) {
|
|
314
|
+
const level = levels[issue.kind];
|
|
315
|
+
if (level === 'off')
|
|
316
|
+
continue;
|
|
317
|
+
const text = `${locate(issue.page, issue.href)}: ${issue.message}`;
|
|
318
|
+
if (level === 'error' || options.links?.strict)
|
|
319
|
+
errors.push(text);
|
|
320
|
+
else
|
|
321
|
+
builder.config.logger.warn(`clarusjs: ${text}`);
|
|
322
|
+
}
|
|
323
|
+
if (errors.length)
|
|
324
|
+
throw new Error(`clarusjs: broken links:\n ${errors.join('\n ')}`);
|
|
325
|
+
if (options.site && options.sitemap !== false) {
|
|
326
|
+
const dates = gitDates(builder.config.root, 'src/pages');
|
|
327
|
+
const epoch = process.env.SOURCE_DATE_EPOCH ? Number(process.env.SOURCE_DATE_EPOCH) : undefined;
|
|
328
|
+
const exclude = (typeof options.sitemap === 'object' ? options.sitemap.exclude ?? [] : [])
|
|
329
|
+
.map((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*\*|\*/g, (s) => (s === '**' ? '.*' : '[^/]+'))}$`));
|
|
330
|
+
const optedOut = (page) => {
|
|
331
|
+
const file = resolve(out, routeToFile(page));
|
|
332
|
+
const html = readFileSync(file, 'utf8');
|
|
333
|
+
const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
|
|
334
|
+
const attr = (tag, name) => new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((v) => v !== undefined);
|
|
335
|
+
const marker = tags.find((tag) => attr(tag, 'name')?.toLowerCase() === 'sitemap' && attr(tag, 'content') === 'false');
|
|
336
|
+
if (marker)
|
|
337
|
+
writeFileSync(file, html.replace(marker, ''));
|
|
338
|
+
return !!marker || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? ''));
|
|
339
|
+
};
|
|
340
|
+
const pages = pageRoutes.filter((page) => page !== '/404' && !clientRoutes.includes(page) && !optedOut(page) && !exclude.some((re) => re.test(page)))
|
|
341
|
+
.map((path) => ({ path, lastmod: dates.get(fileOf(path) ?? '') ?? epoch }));
|
|
342
|
+
writeFileSync(resolve(out, 'sitemap.xml'), sitemapXml(options.site.url, builder.config.base, pages));
|
|
343
|
+
}
|
|
344
|
+
if (options.site && options.robots !== false && !existsSync(resolve(out, 'robots.txt'))) {
|
|
345
|
+
const sitemap = options.sitemap !== false ? `\nSitemap: ${new URL('sitemap.xml', new URL(builder.config.base, options.site.url.replace(/\/?$/, '/'))).href}\n` : '';
|
|
346
|
+
writeFileSync(resolve(out, 'robots.txt'), `User-agent: *\nAllow: /\n${sitemap}`);
|
|
347
|
+
}
|
|
180
348
|
if (options.adapter === 'netlify')
|
|
181
349
|
writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true);
|
|
182
350
|
},
|
|
@@ -190,51 +358,74 @@ export default function clarusjs(options = {}) {
|
|
|
190
358
|
if (id === ENTRY)
|
|
191
359
|
return '\0' + ENTRY;
|
|
192
360
|
},
|
|
193
|
-
load(id) {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
361
|
+
load: { order: 'pre', handler(id) {
|
|
362
|
+
if (id !== '\0' + ENTRY) {
|
|
363
|
+
if (/[?&](raw|url|inline)\b/.test(id) || id.startsWith('\0'))
|
|
364
|
+
return null;
|
|
365
|
+
const file = id.replace(/\?.*$/, '');
|
|
366
|
+
if (!sources.some((x) => file.endsWith(x.extension)) || !normalizePath(file).startsWith(normalizePath(resolve(root, 'src/pages')) + '/'))
|
|
367
|
+
return null;
|
|
368
|
+
return readFileSync(file, 'utf8');
|
|
369
|
+
}
|
|
370
|
+
const urls = builtUrls();
|
|
371
|
+
const loaderUrl = urls?.get(LOADER_ENTRY) ?? '/cl-loader.js';
|
|
372
|
+
const routerUrl = urls?.get(ROUTER_ENTRY) ?? '/cl-router.js';
|
|
373
|
+
const navUrl = urls?.get(NAV_ENTRY) ?? '/cl-nav.js';
|
|
374
|
+
const css = {};
|
|
375
|
+
for (const [route, sheets] of pageStylesheets(root, files)) {
|
|
376
|
+
if (!sheets.length)
|
|
377
|
+
continue;
|
|
378
|
+
css[route] = sheets.map((sheet) => {
|
|
379
|
+
const key = relative(root, sheet).split(sep).join('/');
|
|
380
|
+
const url = urls ? urls.get(key) : clientUrlFor(root, sheet).replace(/\?.*$/, '');
|
|
381
|
+
if (!url)
|
|
382
|
+
throw new Error(`clarusjs: no built stylesheet for ${key}`);
|
|
383
|
+
return url;
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
const stylesUrl = urls ? urls.get(STYLES_ENTRY) : writeStyles(root, files) ? `/${STYLES_FILE}` : undefined;
|
|
387
|
+
const client = {};
|
|
388
|
+
for (const [route, file] of clientPages(root, modes, files)) {
|
|
389
|
+
const key = `${relative(root, file).split(sep).join('/')}?render`;
|
|
390
|
+
const url = urls ? urls.get(key) : `${clientUrlFor(root, file).replace(/\?.*$/, '')}?render&import`;
|
|
391
|
+
if (!url)
|
|
392
|
+
throw new Error(`clarusjs: no client chunk for ${key}`);
|
|
393
|
+
client[route] = url;
|
|
394
|
+
}
|
|
395
|
+
return `import { createHandler } from ${JSON.stringify(here('../server/handler'))}\n` +
|
|
396
|
+
`import { registerViews, render } from ${JSON.stringify(here('../server/views'))}\n` +
|
|
397
|
+
`registerViews(import.meta.glob(${JSON.stringify(['/src/**/*.tscl', ...extensions.slice(1).map((e) => `/src/pages/**/*${e}`)])}))\n` +
|
|
398
|
+
`export { render }\n` +
|
|
399
|
+
`export default createHandler(import.meta.glob(${glob('/src/pages')}), {\n` +
|
|
400
|
+
` loaderUrl: ${JSON.stringify(loaderUrl)},\n` +
|
|
401
|
+
` data: import.meta.glob('/src/pages/**/*.load.ts'),\n` +
|
|
402
|
+
` modes: ${JSON.stringify(modes)},\n` +
|
|
403
|
+
` routerUrl: ${JSON.stringify(routerUrl)},\n` +
|
|
404
|
+
` client: ${JSON.stringify(client)},\n` +
|
|
405
|
+
` base: ${JSON.stringify(base)},\n` +
|
|
406
|
+
` fragments: ${options.fragments === true},\n` +
|
|
407
|
+
` navUrl: ${JSON.stringify(navUrl)},\n` +
|
|
408
|
+
` stylesUrl: ${JSON.stringify(stylesUrl)},\n` +
|
|
409
|
+
` css: ${JSON.stringify(css)},\n` +
|
|
410
|
+
` site: ${JSON.stringify(options.site)},\n` +
|
|
411
|
+
` head: { ...${JSON.stringify(options.head ?? {})}, transform: Object.values(import.meta.glob('/src/head.ts', { eager: true }))[0]?.transformHead },\n` +
|
|
412
|
+
`})\n`;
|
|
413
|
+
} },
|
|
225
414
|
transform: {
|
|
226
|
-
filter: { id:
|
|
227
|
-
handler(
|
|
415
|
+
filter: { id: fileRe },
|
|
416
|
+
handler(raw, id) {
|
|
228
417
|
const file = id.replace(/\?.*$/, '');
|
|
229
|
-
|
|
418
|
+
const src = sources.find((x) => file.endsWith(x.extension));
|
|
419
|
+
if (src && (/[?&](raw|url|inline)\b/.test(id) || !normalizePath(file).startsWith(normalizePath(resolve(root, 'src/pages')) + '/')))
|
|
420
|
+
return null;
|
|
421
|
+
const rel = relative(root, file).split(sep).join('/');
|
|
422
|
+
const code = src
|
|
423
|
+
? src.toTscl(raw, file, { route: rel.startsWith('src/pages/') ? routeFromFile(`/${rel}`) : '', root, addDependency: (dep) => this.addWatchFile(dep) })
|
|
424
|
+
: raw;
|
|
230
425
|
const renderQuery = /[?&]render\b/.test(id);
|
|
231
426
|
const target = this.environment.config.consumer === 'server' || renderQuery ? 'server' : 'client';
|
|
232
|
-
// ponytail: ?import makes Vite's dev transform middleware serve .tscl as JS for the loader's dynamic import; build output uses hashed chunk URLs from the client manifest (stage 3)
|
|
233
427
|
const consumer = this.environment.config.consumer;
|
|
234
|
-
// Server build: chunk URLs come from the client manifest. Client build (a ?render child): the chunk doesn't
|
|
235
|
-
// exist yet, so write a placeholder that generateBundle swaps for the real file name. Dev: the source URL.
|
|
236
428
|
const urls = consumer === 'server' ? builtUrls() : undefined;
|
|
237
|
-
// Built URLs by entry name, or by source key when the name was sanitized ([tag] → _tag_).
|
|
238
429
|
const clientUrl = urls
|
|
239
430
|
? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/'))
|
|
240
431
|
: command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
|
|
@@ -242,9 +433,8 @@ export default function clarusjs(options = {}) {
|
|
|
242
433
|
this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
|
|
243
434
|
}
|
|
244
435
|
try {
|
|
245
|
-
// A ?render module runs in the browser: its child components must be render modules too.
|
|
246
436
|
const renderImports = renderQuery && this.environment.config.consumer !== 'server';
|
|
247
|
-
return { code: compile(code, { file, target, clientUrl, renderImports }).code, map: null };
|
|
437
|
+
return { code: compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file) }).code, map: null, moduleType: 'js' };
|
|
248
438
|
}
|
|
249
439
|
catch (err) {
|
|
250
440
|
if (err instanceof ClarusError)
|
|
@@ -253,28 +443,25 @@ export default function clarusjs(options = {}) {
|
|
|
253
443
|
}
|
|
254
444
|
},
|
|
255
445
|
},
|
|
256
|
-
// The built site is static files: /guide/x is guide/x/index.html. appType 'custom' turns off Vite's own lookup.
|
|
257
446
|
configurePreviewServer(server) {
|
|
258
447
|
const outDir = resolve(server.config.root, server.config.build.outDir);
|
|
259
|
-
const base = server.config.base;
|
|
448
|
+
const base = server.config.base;
|
|
260
449
|
server.middlewares.use((req, _res, next) => {
|
|
261
450
|
let url;
|
|
262
451
|
try {
|
|
263
452
|
url = decodeURIComponent((req.url ?? '/').split('?')[0]);
|
|
264
453
|
}
|
|
265
454
|
catch {
|
|
266
|
-
return next();
|
|
455
|
+
return next();
|
|
267
456
|
}
|
|
268
457
|
const inBase = url === base.slice(0, -1) ? '/' : url.startsWith(base) ? '/' + url.slice(base.length) : undefined;
|
|
269
458
|
if (inBase !== undefined) {
|
|
270
|
-
// A built page wins; anything else (assets, /x.css) falls through to Vite's static files.
|
|
271
459
|
const file = resolve(outDir, `.${inBase.replace(/\/?$/, '/')}index.html`);
|
|
272
460
|
if (file.startsWith(outDir) && existsSync(file))
|
|
273
461
|
req.url = base + file.slice(outDir.length + 1).replace(/\\/g, '/');
|
|
274
462
|
}
|
|
275
463
|
next();
|
|
276
464
|
});
|
|
277
|
-
// Server routes go to the built handler, as they would in production; anything else that isn't a file is a 404.
|
|
278
465
|
return () => {
|
|
279
466
|
server.middlewares.use(async (req, res, next) => {
|
|
280
467
|
try {
|
|
@@ -293,9 +480,22 @@ export default function clarusjs(options = {}) {
|
|
|
293
480
|
next(err);
|
|
294
481
|
}
|
|
295
482
|
});
|
|
483
|
+
server.middlewares.use((req, res, next) => {
|
|
484
|
+
const page = resolve(outDir, '404.html');
|
|
485
|
+
if ((req.method !== 'GET' && req.method !== 'HEAD') || !existsSync(page))
|
|
486
|
+
return next();
|
|
487
|
+
res.statusCode = 404;
|
|
488
|
+
res.setHeader('content-type', 'text/html; charset=utf-8');
|
|
489
|
+
res.end(req.method === 'HEAD' ? undefined : readFileSync(page));
|
|
490
|
+
});
|
|
296
491
|
};
|
|
297
492
|
},
|
|
298
493
|
configureServer(server) {
|
|
494
|
+
const restyle = (file) => { if (fileRe.test(file))
|
|
495
|
+
writeStyles(server.config.root, files); };
|
|
496
|
+
server.watcher.on('change', restyle);
|
|
497
|
+
server.watcher.on('add', restyle);
|
|
498
|
+
server.watcher.on('unlink', restyle);
|
|
299
499
|
return () => {
|
|
300
500
|
server.middlewares.use(async (req, res, next) => {
|
|
301
501
|
try {
|
|
@@ -304,7 +504,7 @@ export default function clarusjs(options = {}) {
|
|
|
304
504
|
return next();
|
|
305
505
|
const app = await env.runner.import(ENTRY);
|
|
306
506
|
const response = await app.default.fetch(toRequest(req));
|
|
307
|
-
if (response.status === 404)
|
|
507
|
+
if (response.status === 404 && !response.headers.get('content-type')?.startsWith('text/html'))
|
|
308
508
|
return next();
|
|
309
509
|
await sendResponse(res, response);
|
|
310
510
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Newest commit time (unix seconds) of every file under `dir` that git knows, by absolute path. One `git log` lists
|
|
3
|
+
* commits newest first with the files each touched, so a file's first appearance is its last change. Not a git
|
|
4
|
+
* repository (or no git): an empty map.
|
|
5
|
+
*/
|
|
6
|
+
export declare function gitDates(root: string, dir: string): Map<string, number>;
|
|
7
|
+
/** The sitemap: one <url> per page, under the site URL and base; lastmod (unix seconds) as a date when known. */
|
|
8
|
+
export declare function sitemapXml(siteUrl: string, base: string, pages: {
|
|
9
|
+
path: string;
|
|
10
|
+
lastmod: number | undefined;
|
|
11
|
+
}[]): string;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
const xml = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
4
|
+
export function gitDates(root, dir) {
|
|
5
|
+
const dates = new Map();
|
|
6
|
+
let log;
|
|
7
|
+
try {
|
|
8
|
+
log = execFileSync('git', ['log', '--format=%x01%ct', '-z', '--name-only', '--relative', '--', dir], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 });
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return dates;
|
|
12
|
+
}
|
|
13
|
+
for (const commit of log.split('\x01').slice(1)) {
|
|
14
|
+
const [time, ...files] = commit.split('\0');
|
|
15
|
+
for (const file of files.map((f) => f.replace(/^\n/, '')).filter(Boolean)) {
|
|
16
|
+
const path = resolve(root, file);
|
|
17
|
+
if (!dates.has(path))
|
|
18
|
+
dates.set(path, Number(time));
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return dates;
|
|
22
|
+
}
|
|
23
|
+
export function sitemapXml(siteUrl, base, pages) {
|
|
24
|
+
const root = new URL(/^https?:\/\//i.test(base) ? new URL(base).pathname : base, siteUrl.replace(/\/?$/, '/'));
|
|
25
|
+
const urls = pages.map(({ path, lastmod }) => {
|
|
26
|
+
const loc = new URL(`./${path.slice(1)}`, root).href;
|
|
27
|
+
const date = lastmod === undefined ? '' : `<lastmod>${new Date(lastmod * 1000).toISOString().slice(0, 10)}</lastmod>`;
|
|
28
|
+
return `<url><loc>${xml(loc)}</loc>${date}</url>\n`;
|
|
29
|
+
});
|
|
30
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join('')}</urlset>\n`;
|
|
31
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clarusjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.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",
|
|
@@ -77,8 +77,10 @@
|
|
|
77
77
|
"vite": "^8.0.0"
|
|
78
78
|
},
|
|
79
79
|
"devDependencies": {
|
|
80
|
+
"@tailwindcss/vite": "^4.3.5",
|
|
80
81
|
"@types/node": "^26.6.6",
|
|
81
82
|
"happy-dom": "^21.0.4",
|
|
83
|
+
"tailwindcss": "^4.3.5",
|
|
82
84
|
"typescript": "^7.0.2",
|
|
83
85
|
"vite": "^8.3.8",
|
|
84
86
|
"vitest": "^5.1.1"
|
|
@@ -87,7 +89,7 @@
|
|
|
87
89
|
"access": "public"
|
|
88
90
|
},
|
|
89
91
|
"scripts": {
|
|
90
|
-
"build": "node -
|
|
92
|
+
"build": "node ../../scripts/build-package.mjs",
|
|
91
93
|
"test": "vitest run",
|
|
92
94
|
"typecheck": "tsc --noEmit"
|
|
93
95
|
}
|