clarusjs 0.7.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.
Files changed (41) hide show
  1. package/dist/check/generate.js +1 -21
  2. package/dist/cli/check.js +44 -11
  3. package/dist/cli/explain.js +0 -1
  4. package/dist/cli/index.js +0 -1
  5. package/dist/compiler/emit-client.js +1 -11
  6. package/dist/compiler/emit-server.js +1 -2
  7. package/dist/compiler/errors.js +0 -1
  8. package/dist/compiler/html-expr.js +2 -7
  9. package/dist/compiler/index.js +10 -8
  10. package/dist/compiler/ir.d.ts +1 -0
  11. package/dist/compiler/ir.js +9 -14
  12. package/dist/compiler/parse.d.ts +1 -0
  13. package/dist/compiler/parse.js +18 -19
  14. package/dist/compiler/script.js +2 -31
  15. package/dist/compiler/shared.js +0 -5
  16. package/dist/runtime/fragments.js +8 -3
  17. package/dist/runtime/html.d.ts +2 -0
  18. package/dist/runtime/html.js +4 -0
  19. package/dist/runtime/loader.js +39 -2
  20. package/dist/runtime/router.d.ts +1 -1
  21. package/dist/runtime/router.js +9 -8
  22. package/dist/runtime/server.d.ts +1 -1
  23. package/dist/runtime/server.js +1 -1
  24. package/dist/server/handler.d.ts +10 -0
  25. package/dist/server/handler.js +48 -48
  26. package/dist/server/head.d.ts +36 -0
  27. package/dist/server/head.js +129 -0
  28. package/dist/server/manifest.js +0 -3
  29. package/dist/server/modes.js +0 -5
  30. package/dist/server/views.js +0 -7
  31. package/dist/vite/build.d.ts +8 -0
  32. package/dist/vite/build.js +42 -17
  33. package/dist/vite/links.d.ts +2 -0
  34. package/dist/vite/links.js +11 -10
  35. package/dist/vite/manifest.js +2 -10
  36. package/dist/vite/netlify.js +1 -7
  37. package/dist/vite/plugin.d.ts +29 -0
  38. package/dist/vite/plugin.js +99 -73
  39. package/dist/vite/sitemap.d.ts +11 -0
  40. package/dist/vite/sitemap.js +31 -0
  41. package/package.json +4 -2
@@ -1,9 +1,6 @@
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
1
  import { existsSync, readFileSync, statSync } from 'node:fs';
4
2
  import { resolve } from 'node:path';
5
3
  import { routeToFile } from './build.js';
6
- // A stray % is kept as written, as routeToFile does, instead of failing the build with a URIError.
7
4
  const decode = (s) => { try {
8
5
  return decodeURIComponent(s);
9
6
  }
@@ -17,7 +14,6 @@ catch {
17
14
  return false;
18
15
  } };
19
16
  const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
20
- /** Edit distance, for "did you mean". */
21
17
  function distance(a, b) {
22
18
  const row = Array.from({ length: b.length + 1 }, (_, i) => i);
23
19
  for (let i = 1; i <= a.length; i++) {
@@ -31,7 +27,6 @@ function distance(a, b) {
31
27
  }
32
28
  return row[b.length];
33
29
  }
34
- /** The closest candidate, if it is close enough to be a likely typo. */
35
30
  function closest(target, candidates) {
36
31
  let best;
37
32
  let score = Infinity;
@@ -48,8 +43,8 @@ const ids = (html) => new Set([...html.matchAll(/\s(?:id|name)="([^"]+)"/g)].map
48
43
  const hrefs = (html) => [...html.replace(/<!--[\s\S]*?-->/g, '').matchAll(/<a\b[^>]*?\shref="([^"]*)"/g)].map((m) => m[1].replace(/&amp;/g, '&'));
49
44
  export function checkLinks(options) {
50
45
  const { outDir } = options;
51
- // An absolute base (https://cdn.example.com/docs/) is compared by its path.
52
46
  const base = /^https?:\/\//.test(options.base) ? new URL(options.base).pathname : options.base;
47
+ const siteRoot = options.site ? new URL(base, options.site.replace(/\/?$/, '/')) : undefined;
53
48
  const routes = new Set(options.routes.map(trim));
54
49
  const client = new Set(options.clientRoutes.map(trim));
55
50
  const serverPatterns = options.serverRoutes.map((r) => new RegExp(`^${r.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`));
@@ -63,18 +58,24 @@ export function checkLinks(options) {
63
58
  };
64
59
  const issues = [];
65
60
  for (const page of [...routes].filter((r) => !client.has(r))) {
66
- for (const href of hrefs(read(page))) {
61
+ for (let href of hrefs(read(page))) {
62
+ if (siteRoot && /^https?:/i.test(href)) {
63
+ const u = new URL(href);
64
+ if (u.origin === siteRoot.origin && (u.pathname.startsWith(siteRoot.pathname) || `${u.pathname}/` === siteRoot.pathname)) {
65
+ href = base + u.pathname.slice(Math.min(u.pathname.length, siteRoot.pathname.length)) + u.search + u.hash;
66
+ }
67
+ }
67
68
  if (/^[a-z][\w+.-]*:|^\/\//i.test(href) || href === '')
68
- continue; // external, mailto:, tel:, …
69
+ continue;
69
70
  const url = new URL(href, `http://site${base}${page === '/' ? '' : page.slice(1) + '/'}`);
70
71
  if (!url.pathname.startsWith(base) && `${url.pathname}/` !== base)
71
- continue; // outside this site
72
+ continue;
72
73
  let path = trim(decode(url.pathname.slice(base.length - 1)) || '/');
73
74
  if (path.endsWith('/index.html'))
74
75
  path = trim(path.slice(0, -'index.html'.length));
75
76
  const anchor = decode(url.hash.slice(1));
76
77
  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
+ const exists = isPage || serverPatterns.some((re) => re.test(path)) || isFile(resolve(outDir, `.${path}`));
78
79
  if (!exists) {
79
80
  const guess = closest(path, routes);
80
81
  issues.push({ kind: 'pages', page, href, message: `no page at ${path}${guess ? ` (did you mean ${guess}?)` : ''}` });
@@ -1,5 +1,3 @@
1
- // The route manifest: after `vite build`, what each page ships, read back from its prerendered HTML.
2
- // dist/clarusjs-manifest.json is what `clarusjs explain` prints. Written outside dist/client, so it isn't served.
3
1
  import { readFileSync, writeFileSync } from 'node:fs';
4
2
  import { resolve } from 'node:path';
5
3
  import { gzipSync } from 'node:zlib';
@@ -11,12 +9,10 @@ const attrsOf = (tag) => {
11
9
  out[m[1]] = m[2].replace(/&amp;/g, '&');
12
10
  return out;
13
11
  };
14
- /** What one prerendered page ships. `size` returns a built file's gzip size. */
15
12
  export function describeRoute(route, html, opts) {
16
13
  const local = (url) => (url.startsWith(opts.base) ? url.slice(opts.base.length) : url.replace(/^\//, ''));
17
14
  const byFile = new Map(Object.values(opts.chunks).map((c) => [c.file, c]));
18
15
  const keyFile = new Map(Object.entries(opts.chunks).map(([k, c]) => [k, c.file]));
19
- // A chunk and everything it imports, in load order.
20
16
  const closure = (file, into) => {
21
17
  if (into.includes(file))
22
18
  return;
@@ -41,8 +37,7 @@ export function describeRoute(route, html, opts) {
41
37
  closure(local(m[1]), all);
42
38
  closure(local(m[1]), initial);
43
39
  }
44
- // A client route also loads its page's render module, named in the shell's route table.
45
- const table = /<script type="application\/json" id="cl-routes">(.*?)<\/script>/.exec(html)?.[1];
40
+ const table = /<script type="application\/json" id="cl-routes"[^>]*>(.*?)<\/script>/.exec(html)?.[1];
46
41
  const render = opts.client && table ? matchRoute(JSON.parse(table), route)?.r : undefined;
47
42
  if (render) {
48
43
  closure(local(render), all);
@@ -57,7 +52,6 @@ export function describeRoute(route, html, opts) {
57
52
  const css = [...html.matchAll(/<link\b[^>]*rel="stylesheet"[^>]*>/g)].map((m) => attrsOf(m[0]).href).filter(Boolean);
58
53
  return { mode: opts.client ? 'client' : 'static', html: routeToFile(route), loader: opts.loaded ? 'build' : null, islands, js: { files: all, gzip: sum(all), initialGzip: sum(initial) }, css };
59
54
  }
60
- /** Describe every prerendered route and write `<distDir>/clarusjs-manifest.json`. */
61
55
  export function writeManifest(distDir, routes, base, loaded = [], server = []) {
62
56
  const client = resolve(distDir, 'client');
63
57
  const chunks = JSON.parse(readFileSync(resolve(client, '.vite/manifest.json'), 'utf8'));
@@ -71,13 +65,11 @@ export function writeManifest(distDir, routes, base, loaded = [], server = []) {
71
65
  const dataFile = (route) => (route === '/' ? '/__data.json' : `${route}/__data.json`);
72
66
  for (const route of routes) {
73
67
  if (route.endsWith('/__data.json') || route.endsWith('/index.frag.html'))
74
- continue; // data and fragments, not pages
68
+ continue;
75
69
  const isClient = routes.includes(dataFile(route));
76
- // A client route's loader runs when its data file is written.
77
70
  const ran = loaded.includes(route) || (isClient && loaded.includes(dataFile(route)));
78
71
  manifest.routes[route] = describeRoute(route, readFileSync(resolve(client, routeToFile(route)), 'utf8'), { base, chunks, size, loaded: ran, client: isClient });
79
72
  }
80
- // Server routes have no HTML at build time: what they ship is decided per request.
81
73
  for (const { route, loader } of server) {
82
74
  manifest.routes[route] = { mode: 'server', html: null, loader: loader ? 'request' : null, islands: [], js: { files: [], gzip: 0, initialGzip: 0 }, css: [] };
83
75
  }
@@ -1,14 +1,10 @@
1
- // Netlify adapter: server routes run as one Netlify Function (Frameworks API) calling the same fetch handler.
2
- // Static routes stay files; preferStatic makes Netlify serve those first.
3
1
  import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
4
2
  import { dirname, relative, resolve, sep } from 'node:path';
5
3
  const FUNCTION = '.netlify/v1/functions/clarusjs-server.mjs';
6
- /** '/account/[id]' → ['/account/:id', '/account/:id/'] (Netlify paths use URLPattern syntax). */
7
4
  export function netlifyPaths(route, fragments = false) {
8
5
  const segments = route.split('/');
9
6
  const keyOf = (seg) => /^\[([A-Za-z_$][\w$]*)\]$/.exec(seg)?.[1];
10
7
  const valid = (key) => /^[A-Za-z_]\w*$/.test(key);
11
- // Names already valid in URLPattern are kept; others get p0, p1, … that aren't taken (URLPattern rejects duplicates).
12
8
  const taken = new Set(segments.map(keyOf).filter((k) => k !== undefined && valid(k)));
13
9
  let n = 0;
14
10
  const fresh = () => {
@@ -21,15 +17,13 @@ export function netlifyPaths(route, fragments = false) {
21
17
  const key = keyOf(seg);
22
18
  if (key !== undefined)
23
19
  return `:${valid(key) ? key : fresh()}`;
24
- return seg.replace(/[:*?+(){}\\]/g, '\\$&'); // literal text, not pattern syntax
20
+ return seg.replace(/[:*?+(){}\\]/g, '\\$&');
25
21
  }).join('/');
26
22
  const paths = path === '/' || path === '' ? ['/'] : [path, `${path}/`];
27
- // The page's fragment, for fragment navigation, comes from the same function.
28
23
  if (fragments)
29
24
  paths.push(path === '/' || path === '' ? '/index.frag.html' : `${path}/index.frag.html`);
30
25
  return paths;
31
26
  }
32
- /** Write (or, without server routes, remove) the function in `<root>/.netlify/v1/functions`. */
33
27
  export function writeNetlifyFunction(root, serverEntry, serverRoutes, fragments = false) {
34
28
  const file = resolve(root, FUNCTION);
35
29
  if (!serverRoutes.length) {
@@ -1,5 +1,9 @@
1
1
  import { type Plugin } from 'vite';
2
+ export { packageOf } from './build.ts';
3
+ /** Newest commit time (unix seconds) of every file under a folder, from one `git log` (themes use it for "last updated"). */
4
+ export { gitDates } from './sitemap.ts';
2
5
  import { type ModeTable } from '../server/modes.ts';
6
+ import type { HeadTag, SiteOptions } from '../server/head.ts';
3
7
  /** Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. */
4
8
  export declare function clientUrlFor(root: string, file: string): string;
5
9
  export type ClarusOptions = {
@@ -20,7 +24,32 @@ export type ClarusOptions = {
20
24
  anchors?: LinkLevel;
21
25
  strict?: boolean;
22
26
  };
27
+ /**
28
+ * Every page's <head>: `titleTemplate` ('%s · Site') wraps the document title, `tags` are added unless the page has
29
+ * its own with the same key. Anything else: export `transformHead(head, page)` from src/head.ts.
30
+ */
31
+ head?: {
32
+ titleTemplate?: string;
33
+ tags?: HeadTag[];
34
+ jsonLd?: object | object[];
35
+ };
36
+ /**
37
+ * The site's public address. Every page gets a canonical URL and social cards (Open Graph, Twitter) from its title,
38
+ * description and an image (the page's og:image, or `image`); absolute links to the site are link-checked.
39
+ */
40
+ site?: SiteOptions;
41
+ /**
42
+ * With site.url, vite build writes sitemap.xml (static pages, dated from git). false: no sitemap. `exclude`: paths
43
+ * left out ('/legal', '/tags/*' one segment, '/drafts/**' any depth). A page opts out itself with
44
+ * <cl-head><meta name="sitemap" content="false"></cl-head> (removed from the built page) or noindex.
45
+ */
46
+ sitemap?: boolean | {
47
+ exclude?: string[];
48
+ };
49
+ /** With site.url, vite build writes robots.txt (allow all, and the sitemap), unless public/robots.txt exists. */
50
+ robots?: boolean;
23
51
  };
52
+ export type { HeadTag };
24
53
  export type LinkLevel = 'error' | 'warn' | 'off';
25
54
  /**
26
55
  * A page source: files with another extension (such as Markdown) turned into .tscl text, then compiled like any
@@ -6,26 +6,27 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
6
6
  }
7
7
  return path;
8
8
  };
9
- // The clarusjs Vite plugin: a thin adapter around the compiler.
10
- // Server environment gets render(), client environment gets attach(). Dev requests go through the fetch handler.
11
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } 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
13
  import { isRunnableDevEnvironment, normalizePath } from 'vite';
15
14
  import { compile, scopeId, ClarusError } from '../compiler/index.js';
16
15
  import { parse } from '../compiler/parse.js';
17
- import { findClarusFiles, prerender } from './build.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';
18
19
  import { writeManifest } from './manifest.js';
19
20
  import { writeNetlifyFunction } from './netlify.js';
20
21
  import { checkLinks } from './links.js';
22
+ import { gitDates, sitemapXml } from './sitemap.js';
21
23
  import { checkModes, modeFor } from '../server/modes.js';
22
- import { routeFromFile } from '../server/handler.js';
24
+ import { rootLinks, routeFromFile } from '../server/handler.js';
25
+ import { basePath } from '../server/head.js';
23
26
  import { sendResponse, toRequest } from './node.js';
24
- // From src/ (workspace, tests) our siblings are .ts files; from the published dist/ they are .js.
25
27
  const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
26
28
  const here = (path) => fileURLToPath(new URL(path + ext, import.meta.url));
27
29
  const ENTRY = 'virtual:clarusjs/server-entry';
28
- /** Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. */
29
30
  export function clientUrlFor(root, file) {
30
31
  const rel = relative(root, file);
31
32
  return rel.startsWith('..') || isAbsolute(rel) ? `/@fs${file}?import` : `/${rel}?import`;
@@ -34,16 +35,17 @@ const LOADER_ENTRY = 'cl-loader';
34
35
  const ROUTER_ENTRY = 'cl-router';
35
36
  const NAV_ENTRY = 'cl-nav';
36
37
  const STYLES_ENTRY = 'cl-styles';
37
- // Every component's <style>, generated into one stylesheet (gitignored, like the rest of .clarusjs/).
38
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
39
  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
40
  function pageStylesheets(root, files) {
46
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
+ } };
47
49
  const read = (file) => {
48
50
  if (!deps.has(file)) {
49
51
  let parsed;
@@ -52,15 +54,14 @@ function pageStylesheets(root, files) {
52
54
  }
53
55
  catch {
54
56
  parsed = null;
55
- } // errors surface on compile
56
- // Relative to the file, or root-relative ('/src/layouts/docs.tscl', as Vite resolves it).
57
+ }
57
58
  const near = (from) => {
58
59
  const path = from.replace(/\?.*$/, '');
59
60
  return path.startsWith('/') ? resolve(root, `.${path}`) : resolve(dirname(file), path);
60
61
  };
61
62
  deps.set(file, {
62
63
  css: parsed?.cssImports.map((c) => near(c.from)) ?? [],
63
- components: parsed?.imports.filter((imp) => /^[./]/.test(imp.from)).map((imp) => near(imp.from)) ?? [],
64
+ components: parsed?.imports.map((imp) => (/^[./]/.test(imp.from) ? near(imp.from) : packageFile(imp.from))).filter((f) => !!f) ?? [],
64
65
  });
65
66
  }
66
67
  return deps.get(file);
@@ -85,29 +86,37 @@ function pageStylesheets(root, files) {
85
86
  }
86
87
  return pages;
87
88
  }
88
- /** Write .clarusjs/styles.css from every component under src/; false when no component has a <style>. */
89
89
  function writeStyles(root, files) {
90
90
  let css = '';
91
- for (const file of files.find(resolve(root, 'src'))) {
91
+ const head = new Set();
92
+ const outDir = resolve(root, '.clarusjs');
93
+ for (const file of files.components(root)) {
92
94
  try {
93
- const out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file) }).css;
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
+ });
94
105
  if (out)
95
106
  css += `/* ${relative(root, file).split(sep).join('/')} */\n${out}`;
96
107
  }
97
- catch { } // compile errors are reported when the component itself is compiled
108
+ catch { }
98
109
  }
99
- mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
110
+ css = [...head].map((x) => `${x}\n`).join('') + css;
111
+ mkdirSync(outDir, { recursive: true });
100
112
  writeFileSync(resolve(root, STYLES_FILE), css);
101
113
  return css !== '';
102
114
  }
103
- // Client entry name of a client-mode page's browser render module.
104
115
  const renderEntry = (name) => `render/${name}`;
105
116
  const CLIENT_OUT = 'dist/client';
106
- // Placeholder for a nested island's chunk URL in the client build, replaced once the bundle's file names are known.
107
117
  const CHUNK_TOKEN = '__CLARUS_CHUNK__';
108
118
  const SERVER_OUT = 'dist/server';
109
- const entryName = (root, file) => relative(root, file).replace(/\.[^./\\]+$/, '');
110
- /** Client-mode pages: route (as the file names it) → absolute file. */
119
+ const entryName = (root, file) => relative(root, file).split(sep).join('/').replace(/\.[^./\\]+$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3));
111
120
  function clientPages(appRoot, modes, files) {
112
121
  const pages = new Map();
113
122
  for (const file of files.find(resolve(appRoot, 'src/pages'))) {
@@ -121,6 +130,8 @@ export default function clarusjs(options = {}) {
121
130
  const modes = options.routes ?? {};
122
131
  checkModes(modes);
123
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}"`);
124
135
  for (const src of sources) {
125
136
  if (!/^\.[\w-]+$/.test(src.extension))
126
137
  throw new Error(`clarusjs: a source extension must look like ".md", got "${src.extension}"`);
@@ -128,10 +139,9 @@ export default function clarusjs(options = {}) {
128
139
  throw new Error('clarusjs: .tscl files are compiled directly; a source needs its own extension');
129
140
  }
130
141
  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
142
  const files = {
134
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),
135
145
  read: (file, appRoot) => {
136
146
  const code = readFileSync(file, 'utf8');
137
147
  const src = sources.find((x) => file.endsWith(x.extension));
@@ -149,9 +159,6 @@ export default function clarusjs(options = {}) {
149
159
  let root = process.cwd();
150
160
  let command = 'serve';
151
161
  let base = '/';
152
- // `vite build` only: client entry name (see entryName) → public URL of its hashed chunk.
153
- // Read from the client manifest on disk, because Vite resolves config (and so creates a new plugin instance) per
154
- // environment: the server build cannot see state set during the client build.
155
162
  let built;
156
163
  const builtUrls = () => {
157
164
  if (command !== 'build')
@@ -164,7 +171,6 @@ export default function clarusjs(options = {}) {
164
171
  }
165
172
  const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
166
173
  built = new Map();
167
- // By entry name, and by source key: names are sanitized ([id] → _id_), keys keep the real path.
168
174
  for (const [key, chunk] of Object.entries(manifest)) {
169
175
  if (!chunk.isEntry)
170
176
  continue;
@@ -187,21 +193,29 @@ export default function clarusjs(options = {}) {
187
193
  },
188
194
  };
189
195
  if (env.isPreview)
190
- config.build = { outDir: CLIENT_OUT }; // preview serves the static site
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
+ }
191
207
  if (env.command !== 'build')
192
208
  return config;
193
209
  if (userConfig.base !== undefined && !userConfig.base.startsWith('/') && !/^https?:\/\//.test(userConfig.base)) {
194
- // Pages live at different depths and islands are imported from the loader, so URLs must not be relative.
195
210
  throw new Error(`clarusjs: relative base "${userConfig.base}" is not supported; use an absolute base such as "/" or "/docs/"`);
196
211
  }
197
- // Client entries: the island loader plus every stateful component. Stateless components never reach the client.
198
212
  const appRoot = resolve(userConfig.root ?? process.cwd());
199
213
  const input = { [LOADER_ENTRY]: here('../runtime/loader') };
200
- for (const file of files.find(resolve(appRoot, 'src'))) {
214
+ const components = files.components(appRoot);
215
+ for (const file of components) {
201
216
  if (compile(files.read(file, appRoot), { file, target: 'client' }).stateful)
202
217
  input[entryName(appRoot, file)] = file;
203
218
  }
204
- // Client routes: the router, and each page's render function for the browser.
205
219
  const client = clientPages(appRoot, modes, files);
206
220
  if (client.size)
207
221
  input[ROUTER_ENTRY] = here('../runtime/router');
@@ -209,36 +223,29 @@ export default function clarusjs(options = {}) {
209
223
  input[NAV_ENTRY] = here('../runtime/fragments');
210
224
  if (writeStyles(appRoot, files))
211
225
  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
226
  for (const sheet of new Set([...pageStylesheets(appRoot, files).values()].flat())) {
214
227
  if (!existsSync(sheet))
215
228
  throw new Error(`clarusjs: imported stylesheet not found: ${relative(appRoot, sheet)}`);
216
- input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '')}`] = sheet;
229
+ input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3))}`] = sheet;
217
230
  }
218
231
  for (const file of client.values())
219
232
  input[renderEntry(entryName(appRoot, file))] = `${file}?render`;
220
233
  config.builder = {};
221
234
  config.environments = {
222
- // Island chunks are loaded with import() and must keep their `attach` export.
223
235
  client: { build: { outDir: CLIENT_OUT, manifest: true, rolldownOptions: { input, preserveEntrySignatures: 'exports-only' } } },
224
- // Always .mjs, so Node loads it as ESM whatever the app's package.json says.
225
236
  ssr: { build: { outDir: SERVER_OUT, rolldownOptions: { input: { index: ENTRY }, output: { entryFileNames: '[name].mjs' } } } },
226
237
  };
227
238
  return config;
228
239
  },
229
- // Each build re-reads the client manifest: a builder can run buildApp() more than once.
230
240
  buildStart() { built = undefined; },
231
- // Client build: nested islands rendered in the browser get their chunk's real URL.
232
241
  generateBundle(_options, bundle) {
233
242
  if (this.environment.config.consumer !== 'client' || command !== 'build')
234
243
  return;
235
244
  const byName = new Map();
236
- // By sanitized name and by the raw entry name from the source path ([id] stays [id]).
237
245
  for (const out of Object.values(bundle)) {
238
246
  if (out.type !== 'chunk' || !out.isEntry)
239
247
  continue;
240
248
  byName.set(out.name, base + out.fileName);
241
- // Only island chunks: a client page's ?render chunk would otherwise take its island's place.
242
249
  if (out.facadeModuleId && !/[?&]render\b/.test(out.facadeModuleId))
243
250
  byName.set(entryName(root, out.facadeModuleId.replace(/\?.*$/, '')), base + out.fileName);
244
251
  }
@@ -258,7 +265,6 @@ export default function clarusjs(options = {}) {
258
265
  command = config.command;
259
266
  base = config.base;
260
267
  },
261
- // Order matters: the server build needs the client's hashed URLs, and prerendering needs the server build.
262
268
  async buildApp(builder) {
263
269
  const { client, ssr } = builder.environments;
264
270
  if (!client || !ssr)
@@ -269,28 +275,34 @@ export default function clarusjs(options = {}) {
269
275
  const out = resolve(builder.config.root, CLIENT_OUT);
270
276
  const dist = dirname(out);
271
277
  const manifestFile = resolve(dist, 'clarusjs-manifest.json');
272
- rmSync(manifestFile, { force: true }); // a page reading the manifest must never see the previous build's
278
+ rmSync(manifestFile, { force: true });
273
279
  const { routes, readers, loaded, server } = await prerender(entry, out, manifestFile);
274
280
  writeManifest(dist, routes, builder.config.base, loaded, server);
275
- // Pages that read the manifest saw none on the first pass: render them again now that it exists.
276
281
  if (readers.length) {
277
282
  await prerender(entry, out, manifestFile, readers);
278
283
  writeManifest(dist, routes, builder.config.base, loaded, server);
279
284
  }
280
- // Links between pages and to anchors, checked against what was written.
281
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
+ }
282
292
  const issues = checkLinks({
283
293
  outDir: out,
284
294
  routes: pageRoutes,
285
295
  serverRoutes: server.map((x) => x.route),
286
- clientRoutes: pageRoutes.filter((r) => routes.includes(r === '/' ? '/__data.json' : `${r}/__data.json`)),
296
+ clientRoutes,
287
297
  base: builder.config.base,
298
+ site: options.site?.url,
288
299
  });
289
300
  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
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];
292
304
  const locate = (page, href) => {
293
- const file = sourceOf.get(page) ?? [...sourceOf].find(([route]) => new RegExp(`^${route.replace(/\[[^\]]+\]/g, '[^/]+')}$`).test(page))?.[1];
305
+ const file = fileOf(page);
294
306
  if (!file)
295
307
  return page;
296
308
  const rel = relative(builder.config.root, file).split(sep).join('/');
@@ -310,6 +322,29 @@ export default function clarusjs(options = {}) {
310
322
  }
311
323
  if (errors.length)
312
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
+ }
313
348
  if (options.adapter === 'netlify')
314
349
  writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true);
315
350
  },
@@ -323,8 +358,6 @@ export default function clarusjs(options = {}) {
323
358
  if (id === ENTRY)
324
359
  return '\0' + ENTRY;
325
360
  },
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
361
  load: { order: 'pre', handler(id) {
329
362
  if (id !== '\0' + ENTRY) {
330
363
  if (/[?&](raw|url|inline)\b/.test(id) || id.startsWith('\0'))
@@ -338,7 +371,6 @@ export default function clarusjs(options = {}) {
338
371
  const loaderUrl = urls?.get(LOADER_ENTRY) ?? '/cl-loader.js';
339
372
  const routerUrl = urls?.get(ROUTER_ENTRY) ?? '/cl-router.js';
340
373
  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
374
  const css = {};
343
375
  for (const [route, sheets] of pageStylesheets(root, files)) {
344
376
  if (!sheets.length)
@@ -351,9 +383,7 @@ export default function clarusjs(options = {}) {
351
383
  return url;
352
384
  });
353
385
  }
354
- // Built: the hashed stylesheet, if any component has styles. Dev: the generated file, served by Vite.
355
386
  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
387
  const client = {};
358
388
  for (const [route, file] of clientPages(root, modes, files)) {
359
389
  const key = `${relative(root, file).split(sep).join('/')}?render`;
@@ -364,7 +394,6 @@ export default function clarusjs(options = {}) {
364
394
  }
365
395
  return `import { createHandler } from ${JSON.stringify(here('../server/handler'))}\n` +
366
396
  `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
397
  `registerViews(import.meta.glob(${JSON.stringify(['/src/**/*.tscl', ...extensions.slice(1).map((e) => `/src/pages/**/*${e}`)])}))\n` +
369
398
  `export { render }\n` +
370
399
  `export default createHandler(import.meta.glob(${glob('/src/pages')}), {\n` +
@@ -378,14 +407,14 @@ export default function clarusjs(options = {}) {
378
407
  ` navUrl: ${JSON.stringify(navUrl)},\n` +
379
408
  ` stylesUrl: ${JSON.stringify(stylesUrl)},\n` +
380
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` +
381
412
  `})\n`;
382
413
  } },
383
414
  transform: {
384
415
  filter: { id: fileRe },
385
416
  handler(raw, id) {
386
417
  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
418
  const src = sources.find((x) => file.endsWith(x.extension));
390
419
  if (src && (/[?&](raw|url|inline)\b/.test(id) || !normalizePath(file).startsWith(normalizePath(resolve(root, 'src/pages')) + '/')))
391
420
  return null;
@@ -393,15 +422,10 @@ export default function clarusjs(options = {}) {
393
422
  const code = src
394
423
  ? src.toTscl(raw, file, { route: rel.startsWith('src/pages/') ? routeFromFile(`/${rel}`) : '', root, addDependency: (dep) => this.addWatchFile(dep) })
395
424
  : raw;
396
- // ?render: a component's server render function, used in the browser to render children of islands.
397
425
  const renderQuery = /[?&]render\b/.test(id);
398
426
  const target = this.environment.config.consumer === 'server' || renderQuery ? 'server' : 'client';
399
- // 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)
400
427
  const consumer = this.environment.config.consumer;
401
- // Server build: chunk URLs come from the client manifest. Client build (a ?render child): the chunk doesn't
402
- // exist yet, so write a placeholder that generateBundle swaps for the real file name. Dev: the source URL.
403
428
  const urls = consumer === 'server' ? builtUrls() : undefined;
404
- // Built URLs by entry name, or by source key when the name was sanitized ([tag] → _tag_).
405
429
  const clientUrl = urls
406
430
  ? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/'))
407
431
  : command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
@@ -409,9 +433,7 @@ export default function clarusjs(options = {}) {
409
433
  this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
410
434
  }
411
435
  try {
412
- // A ?render module runs in the browser: its child components must be render modules too.
413
436
  const renderImports = renderQuery && this.environment.config.consumer !== 'server';
414
- // moduleType: a source extension may have its own built-in type in Rolldown (.txt is text); the output is JS.
415
437
  return { code: compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file) }).code, map: null, moduleType: 'js' };
416
438
  }
417
439
  catch (err) {
@@ -421,28 +443,25 @@ export default function clarusjs(options = {}) {
421
443
  }
422
444
  },
423
445
  },
424
- // The built site is static files: /guide/x is guide/x/index.html. appType 'custom' turns off Vite's own lookup.
425
446
  configurePreviewServer(server) {
426
447
  const outDir = resolve(server.config.root, server.config.build.outDir);
427
- const base = server.config.base; // e.g. '/' or '/docs/'; Vite strips it after this middleware
448
+ const base = server.config.base;
428
449
  server.middlewares.use((req, _res, next) => {
429
450
  let url;
430
451
  try {
431
452
  url = decodeURIComponent((req.url ?? '/').split('?')[0]);
432
453
  }
433
454
  catch {
434
- return next(); // a malformed %-escape names no built page
455
+ return next();
435
456
  }
436
457
  const inBase = url === base.slice(0, -1) ? '/' : url.startsWith(base) ? '/' + url.slice(base.length) : undefined;
437
458
  if (inBase !== undefined) {
438
- // A built page wins; anything else (assets, /x.css) falls through to Vite's static files.
439
459
  const file = resolve(outDir, `.${inBase.replace(/\/?$/, '/')}index.html`);
440
460
  if (file.startsWith(outDir) && existsSync(file))
441
461
  req.url = base + file.slice(outDir.length + 1).replace(/\\/g, '/');
442
462
  }
443
463
  next();
444
464
  });
445
- // Server routes go to the built handler, as they would in production; anything else that isn't a file is a 404.
446
465
  return () => {
447
466
  server.middlewares.use(async (req, res, next) => {
448
467
  try {
@@ -461,10 +480,17 @@ export default function clarusjs(options = {}) {
461
480
  next(err);
462
481
  }
463
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
+ });
464
491
  };
465
492
  },
466
493
  configureServer(server) {
467
- // Component styles change with their .tscl files: regenerate the stylesheet (Vite then updates the page's CSS).
468
494
  const restyle = (file) => { if (fileRe.test(file))
469
495
  writeStyles(server.config.root, files); };
470
496
  server.watcher.on('change', restyle);
@@ -478,7 +504,7 @@ export default function clarusjs(options = {}) {
478
504
  return next();
479
505
  const app = await env.runner.import(ENTRY);
480
506
  const response = await app.default.fetch(toRequest(req));
481
- if (response.status === 404)
507
+ if (response.status === 404 && !response.headers.get('content-type')?.startsWith('text/html'))
482
508
  return next();
483
509
  await sendResponse(res, response);
484
510
  }