clarusjs 0.20.0 → 0.21.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 (49) hide show
  1. package/README.md +1 -1
  2. package/dist/check/generate.js +10 -4
  3. package/dist/cli/migrate.js +33 -9
  4. package/dist/compiler/emit-client.js +4 -3
  5. package/dist/compiler/emit-server.js +3 -1
  6. package/dist/compiler/factories.d.ts +4 -2
  7. package/dist/compiler/factories.js +116 -15
  8. package/dist/compiler/html-expr.d.ts +4 -0
  9. package/dist/compiler/html-expr.js +5 -1
  10. package/dist/compiler/index.js +6 -7
  11. package/dist/compiler/ir.d.ts +2 -0
  12. package/dist/compiler/ir.js +3 -5
  13. package/dist/compiler/parse.js +33 -13
  14. package/dist/compiler/script.d.ts +5 -0
  15. package/dist/compiler/script.js +14 -2
  16. package/dist/forms/index.js +26 -5
  17. package/dist/runtime/context.d.ts +16 -8
  18. package/dist/runtime/fragments.js +6 -2
  19. package/dist/runtime/index.d.ts +1 -1
  20. package/dist/runtime/navigate.js +2 -1
  21. package/dist/runtime/signals.d.ts +11 -6
  22. package/dist/runtime/signals.js +12 -3
  23. package/dist/vite/base-clash.d.ts +9 -0
  24. package/dist/vite/base-clash.js +54 -0
  25. package/dist/vite/build-app.d.ts +5 -0
  26. package/dist/vite/build-app.js +185 -0
  27. package/dist/vite/dev-server.d.ts +5 -0
  28. package/dist/vite/dev-server.js +67 -0
  29. package/dist/vite/graph.d.ts +45 -0
  30. package/dist/vite/graph.js +125 -0
  31. package/dist/vite/hmr.d.ts +19 -0
  32. package/dist/vite/hmr.js +53 -0
  33. package/dist/vite/links.d.ts +2 -0
  34. package/dist/vite/links.js +2 -0
  35. package/dist/vite/options.d.ts +147 -0
  36. package/dist/vite/options.js +1 -0
  37. package/dist/vite/output.d.ts +25 -0
  38. package/dist/vite/output.js +49 -0
  39. package/dist/vite/plugin.d.ts +4 -150
  40. package/dist/vite/plugin.js +45 -624
  41. package/dist/vite/preview.d.ts +3 -0
  42. package/dist/vite/preview.js +100 -0
  43. package/dist/vite/server-entry.d.ts +18 -0
  44. package/dist/vite/server-entry.js +83 -0
  45. package/dist/vite/shared.d.ts +34 -0
  46. package/dist/vite/shared.js +47 -0
  47. package/dist/vite/styles.d.ts +16 -0
  48. package/dist/vite/styles.js +56 -0
  49. package/package.json +1 -1
@@ -0,0 +1,45 @@
1
+ import { type ComponentNames } from '../compiler/components.ts';
2
+ import type { RouteParts } from './manifest.ts';
3
+ import { type Alias } from './aliases.ts';
4
+ import { type ModeTable } from '../server/modes.ts';
5
+ /** How the plugin finds and reads component files: .tscl, plus the extensions of its page sources. */
6
+ export type Files = {
7
+ find(dir: string): string[];
8
+ /** The page files under src/pages: not the + files (layouts). */
9
+ pages(root: string): string[];
10
+ /** A page's folder and config layouts (#456), for compile(); undefined for other files. */
11
+ layouts(file: string, root: string): string[] | undefined;
12
+ /** The automatic component names (#458), for compile(); undefined when off. */
13
+ names(root: string): ComponentNames | undefined;
14
+ read(file: string, root: string): string;
15
+ /** Every component of the app: those under src/, and every .tscl their @imports reach, in packages too. */
16
+ components(root: string): string[];
17
+ };
18
+ /**
19
+ * Each page's stylesheets (absolute paths), from its own `@import './x.css'` and its components', transitively.
20
+ * Dependencies come first, so a layout's base CSS is linked before what the page adds.
21
+ */
22
+ export declare function pageGraph(root: string, files: Files, aliases?: Alias[]): Map<string, {
23
+ css: string[];
24
+ components: string[];
25
+ }>;
26
+ /** A page's folder and config layouts as root paths, outermost first; none with `@layout none`. */
27
+ export declare function pageLayouts(root: string, file: string, files: Files): string[];
28
+ /** Each page's layouts and guards (#472), for the route manifest: what `clarusjs explain` lists. Paths from the root. */
29
+ export declare function routeParts(root: string, files: Files): RouteParts[];
30
+ /**
31
+ * A page's layouts (#456), outermost first, as root paths: the config layouts whose patterns take its route, then each
32
+ * +layout.tscl from src/pages down to its folder. None for a file that isn't a page.
33
+ */
34
+ export declare function layoutsFor(root: string, file: string, config: {
35
+ layout: string;
36
+ include?: string[];
37
+ exclude?: string[];
38
+ }[]): string[] | undefined;
39
+ /**
40
+ * A component's loader (#97): a .load.ts next to a .tscl outside src/pages (there it's the page's data), or none. A
41
+ * folder layout's is its +layout.load.ts (#472).
42
+ */
43
+ export declare function componentLoaderOf(root: string, file: string): string | undefined;
44
+ /** Client-mode pages: route (as the file names it) → absolute file. */
45
+ export declare function clientPages(appRoot: string, modes: ModeTable, files: Files): Map<string, string>;
@@ -0,0 +1,125 @@
1
+ import { existsSync, realpathSync } from 'node:fs';
2
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { parse } from '../compiler/parse.js';
4
+ import { autoImport } from '../compiler/components.js';
5
+ import { resolvePackage } from './build.js';
6
+ import { resolveAlias } from './aliases.js';
7
+ import { modeFor, routeMatches } from '../server/modes.js';
8
+ import { isPageFile, routeFromFile } from '../server/handler.js';
9
+ import { real } from './shared.js';
10
+ const parsedForGraph = new Map();
11
+ export function pageGraph(root, files, aliases = []) {
12
+ const deps = new Map();
13
+ const names = files.names(root);
14
+ const namesKey = JSON.stringify(names ?? null);
15
+ const read = (file) => {
16
+ if (!deps.has(file)) {
17
+ let parsed;
18
+ try {
19
+ const text = files.read(file, root);
20
+ const known = parsedForGraph.get(file);
21
+ if (known?.text === text && known.names === namesKey)
22
+ parsed = known.parsed;
23
+ else {
24
+ parsed = parse(text, file);
25
+ if (names)
26
+ autoImport(parsed, names, file, text);
27
+ parsedForGraph.set(file, { text, names: namesKey, parsed });
28
+ }
29
+ }
30
+ catch {
31
+ parsed = null;
32
+ }
33
+ const near = (from) => {
34
+ const path = from.replace(/\?.*$/, '');
35
+ return path.startsWith('/') ? resolve(root, `.${path}`) : resolve(dirname(file), path);
36
+ };
37
+ const packageFile = (spec) => { const found = resolvePackage(root, file, spec); return found && realpathSync(found); };
38
+ const bare = (from) => resolveAlias(from.replace(/\?.*$/, ''), aliases) ?? packageFile(from.replace(/\?.*$/, ''));
39
+ deps.set(file, {
40
+ css: parsed?.cssImports.map((c) => (/^[./]/.test(c.from) ? near(c.from) : bare(c.from))).filter((f) => !!f) ?? [],
41
+ components: parsed?.imports.map((imp) => (/^[./]/.test(imp.from) ? near(imp.from) : bare(imp.from))).filter((f) => !!f) ?? [],
42
+ });
43
+ }
44
+ return deps.get(file);
45
+ };
46
+ const collect = (file, out, seen) => {
47
+ if (seen.has(file))
48
+ return;
49
+ seen.add(file);
50
+ const { css, components } = read(file);
51
+ for (const c of components)
52
+ if (existsSync(c))
53
+ collect(c, out, seen);
54
+ for (const sheet of css)
55
+ if (!out.includes(sheet))
56
+ out.push(sheet);
57
+ };
58
+ const pages = new Map();
59
+ for (const file of files.pages(root)) {
60
+ const css = [];
61
+ const seen = new Set();
62
+ for (const layout of pageLayouts(root, file, files))
63
+ collect(resolve(root, `.${layout}`), css, seen);
64
+ collect(file, css, seen);
65
+ seen.delete(file);
66
+ pages.set(routeFromFile(`/${relative(root, file).split(sep).join('/')}`), { css, components: [...seen] });
67
+ }
68
+ return pages;
69
+ }
70
+ export function pageLayouts(root, file, files) {
71
+ const layouts = files.layouts(file, root) ?? [];
72
+ try {
73
+ return layouts.length && parse(files.read(file, root), file).layout === 'none' ? [] : layouts;
74
+ }
75
+ catch {
76
+ return layouts;
77
+ }
78
+ }
79
+ export function routeParts(root, files) {
80
+ return files.pages(root).map((file) => {
81
+ const rel = relative(root, file).split(sep).join('/');
82
+ const folders = rel.replace(/^src\/pages\//, '').split('/').slice(0, -1);
83
+ const guards = [];
84
+ for (let i = 0; i <= folders.length; i++) {
85
+ const guard = ['src/pages', ...folders.slice(0, i), '+guard.ts'].join('/');
86
+ if (existsSync(resolve(root, guard)))
87
+ guards.push(guard);
88
+ }
89
+ return { route: routeFromFile(`/${rel}`), layouts: pageLayouts(root, file, files).map((l) => l.replace(/^\//, '')), guards };
90
+ });
91
+ }
92
+ export function layoutsFor(root, file, config) {
93
+ const pages = resolve(root, 'src/pages');
94
+ const rel = relative(pages, file);
95
+ if (rel.startsWith('..') || isAbsolute(rel) || !isPageFile(file.split(sep).join('/')))
96
+ return undefined;
97
+ const route = routeFromFile(`/src/pages/${rel.split(sep).join('/')}`);
98
+ const out = config
99
+ .filter((l) => (l.include ?? ['/*']).some((p) => routeMatches(route, p)) && !(l.exclude ?? []).some((p) => routeMatches(route, p)))
100
+ .map((l) => l.layout);
101
+ const folders = dirname(rel) === '.' ? [] : dirname(rel).split(sep);
102
+ for (let i = 0; i <= folders.length; i++) {
103
+ const layout = resolve(pages, ...folders.slice(0, i), '+layout.tscl');
104
+ if (existsSync(layout))
105
+ out.push(`/${relative(root, layout).split(sep).join('/')}`);
106
+ }
107
+ return out;
108
+ }
109
+ export function componentLoaderOf(root, file) {
110
+ if (!file.endsWith('.tscl'))
111
+ return undefined;
112
+ if (real(file).startsWith(real(resolve(root, 'src/pages')) + sep) && !file.endsWith(`${sep}+layout.tscl`) && !file.endsWith('/+layout.tscl'))
113
+ return undefined;
114
+ const loader = file.replace(/\.tscl$/, '.load.ts');
115
+ return existsSync(loader) ? loader : undefined;
116
+ }
117
+ export function clientPages(appRoot, modes, files) {
118
+ const pages = new Map();
119
+ for (const file of files.pages(appRoot)) {
120
+ const route = routeFromFile(`/${relative(appRoot, file).split(sep).join('/')}`);
121
+ if (modeFor(route, modes) === 'client')
122
+ pages.set(route, file);
123
+ }
124
+ return pages;
125
+ }
@@ -0,0 +1,19 @@
1
+ import { type EnvironmentModuleNode, type HotUpdateOptions } from 'vite';
2
+ export type StyleEdits = {
3
+ /** A component compiled from this source: the baseline its next edit is compared with. */
4
+ compiled(file: string, source: string): void;
5
+ /** Did the file's latest edit change only the CSS inside its <style> blocks? Asked once per edit by each environment. */
6
+ styleOnly(file: string): boolean;
7
+ /** Did it gain its first <style>, or lose its last? The pages' stylesheet links change, so the page reloads. */
8
+ linksChanged(file: string): boolean;
9
+ };
10
+ /** Tells an edit that only changed a component's styles from one that changed its markup. */
11
+ export declare function styleEdits(): StyleEdits;
12
+ /**
13
+ * The plugin's hotUpdate, for the environment `environment`. A change only the server's modules see (a page, a layout,
14
+ * a stateless component, a loader) is a full reload: the browser has nothing to update. Changes the browser has loaded
15
+ * go through its own HMR (islands swap in place). Loaded means a module it imported (with an id): a stylesheet that only
16
+ * watches the file (Tailwind scanning a template for classes) puts a file-only entry in the browser's graph, and updates
17
+ * the CSS but not the markup.
18
+ */
19
+ export declare function hotUpdate(environment: string, { file, modules, server }: HotUpdateOptions, isComponent: (file: string) => boolean, edits: StyleEdits): EnvironmentModuleNode[] | void;
@@ -0,0 +1,53 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { isRunnableDevEnvironment } from 'vite';
3
+ import { ENTRY } from './shared.js';
4
+ export function styleEdits() {
5
+ const compiledSource = new Map();
6
+ const verdicts = new Map();
7
+ const parts = (text) => text.split(/(<script\b[\s\S]*?<\/script>)/i);
8
+ const withoutStyles = (text) => parts(text).map((p, i) => (i % 2 ? p : p.replace(/<style[\s>][\s\S]*?<\/style>/gi, ''))).join('');
9
+ const hasStyle = (text) => parts(text).some((p, i) => !(i % 2) && /<style[\s>]/i.test(p));
10
+ const verdict = (file) => {
11
+ let text;
12
+ try {
13
+ text = readFileSync(file, 'utf8');
14
+ }
15
+ catch {
16
+ return { styleOnly: false, linksChanged: false };
17
+ }
18
+ const known = verdicts.get(file);
19
+ if (known?.text === text)
20
+ return known;
21
+ const before = compiledSource.get(file);
22
+ const linksChanged = before !== undefined && hasStyle(before) !== hasStyle(text);
23
+ const styleOnly = before !== undefined && !linksChanged && hasStyle(text) && withoutStyles(before) === withoutStyles(text);
24
+ const result = { text, styleOnly, linksChanged };
25
+ verdicts.set(file, result);
26
+ return result;
27
+ };
28
+ return {
29
+ compiled: (file, source) => { compiledSource.set(file, source); },
30
+ styleOnly: (file) => verdict(file).styleOnly,
31
+ linksChanged: (file) => verdict(file).linksChanged,
32
+ };
33
+ }
34
+ export function hotUpdate(environment, { file, modules, server }, isComponent, edits) {
35
+ if (isComponent(file) && edits.styleOnly(file))
36
+ return environment === 'client' ? modules.filter((m) => !(m.id && m.type === 'js')) : [];
37
+ if (environment !== 'ssr' || !modules.length)
38
+ return;
39
+ const entry = '\0' + ENTRY;
40
+ const env = server.environments.ssr;
41
+ const mod = env.moduleGraph.getModuleById(entry);
42
+ if (mod)
43
+ env.moduleGraph.invalidateModule(mod);
44
+ if (isRunnableDevEnvironment(env)) {
45
+ const evaluated = env.runner.evaluatedModules.getModuleById(entry);
46
+ if (evaluated)
47
+ env.runner.evaluatedModules.invalidateModule(evaluated);
48
+ }
49
+ const island = [...(server.environments.client.moduleGraph.getModulesByFile(file) ?? [])].some((m) => m.id && m.type === 'js');
50
+ if (island && !(isComponent(file) && edits.linksChanged(file)))
51
+ return;
52
+ server.environments.client.hot.send({ type: 'full-reload' });
53
+ }
@@ -15,6 +15,8 @@ type Options = {
15
15
  base: string;
16
16
  /** site.url: absolute links to the site itself are checked like internal ones. */
17
17
  site?: string;
18
+ /** Path prefixes another build serves ('/v1/'), without the base: links into them, as resolved, go unchecked. */
19
+ ignore?: string[];
18
20
  };
19
21
  export declare function checkLinks(options: Options): LinkIssue[];
20
22
  export {};
@@ -80,6 +80,8 @@ export function checkLinks(options) {
80
80
  let path = trim(decode(url.pathname.slice(base.length - 1)) || '/');
81
81
  if (path.endsWith('/index.html'))
82
82
  path = trim(path.slice(0, -'index.html'.length));
83
+ if (options.ignore?.some((p) => path.startsWith(p) || `${path}/` === p))
84
+ continue;
83
85
  const anchor = decode(url.hash.slice(1));
84
86
  const isPage = routes.has(path);
85
87
  const exists = isPage || serverPatterns.some((re) => re.test(path)) || isFile(resolve(outDir, `.${path}`));
@@ -0,0 +1,147 @@
1
+ import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
2
+ import type { LibraryOption } from './libraries.ts';
3
+ import type { EnvOption } from './env.ts';
4
+ import type { HeadTag, SiteOptions } from '../server/head.ts';
5
+ import type { ModeTable } from '../server/modes.ts';
6
+ import type { HeaderRules } from './headers.ts';
7
+ /**
8
+ * The Vite plugin's options: when routes render, the deploy adapter, fragment navigation, link checks, head tags, the
9
+ * site's address, sitemap and robots, redirects, and page sources.
10
+ * @see https://clarusjs.com/reference/vite-plugin#clarusjs
11
+ */
12
+ export type ClarusOptions = {
13
+ /** When each route renders: { '/account/*': 'server' }. Routes default to 'static' (prerendered at build). */
14
+ routes?: ModeTable;
15
+ /**
16
+ * Layouts by route (#456), outermost first, around the folder layouts (`+layout.tscl`): `{ layout: '/src/layouts/site.tscl',
17
+ * include: ['/*'], exclude: ['/embed/*'] }` (patterns as in `routes`; include defaults to every route). A page with
18
+ * `@layout none` gets none.
19
+ */
20
+ layouts?: {
21
+ layout: string;
22
+ include?: string[];
23
+ exclude?: string[];
24
+ }[];
25
+ /**
26
+ * Automatic component imports (#458): a kebab-case file under these folders is used by its name, without @import
27
+ * (`src/components/forms/text-field.tscl` → `<forms-text-field>`, or `<text-field>` when no other has that name).
28
+ * Defaults: `{ dirs: ['src/components', 'src/layouts'], auto: true }`. `libraries`: installed component libraries whose
29
+ * components are used the same way (`libraries: ['@clarusjs/ui-primitives']` → `<ui-dialog>`), each described by its
30
+ * package.json; your own components win over theirs.
31
+ */
32
+ components?: {
33
+ dirs?: string[];
34
+ auto?: boolean;
35
+ libraries?: LibraryOption[];
36
+ };
37
+ /**
38
+ * Where server routes deploy. 'netlify': a Netlify Function (Frameworks API) next to the static files. 'vercel': the
39
+ * Build Output API in .vercel/output (static files, one Node function, routes), with the server bundled.
40
+ * 'cloudflare': a worker in dist/client/_worker.js/ and _routes.json (Pages, or a Worker with static assets).
41
+ * @see https://clarusjs.com/guide/deploy
42
+ */
43
+ adapter?: 'netlify' | 'vercel' | 'cloudflare';
44
+ /** Fragment navigation: each static and server page also answers at <path>/index.frag.html. */
45
+ fragments?: boolean;
46
+ /** Page sources for other file types, such as Markdown from @clarusjs/content: `sources: [markdown()]`. */
47
+ sources?: Source[];
48
+ /**
49
+ * Build-time link checking, after every page is built. `pages`: links to pages or files that don't exist (default
50
+ * 'error'). `anchors`: links to a #id the target page doesn't have (default 'warn'). `strict`: warnings fail too.
51
+ * `ignore`: path prefixes another build serves, left unchecked (archived docs: `['/v1/']`), written without the base.
52
+ * Other plugins add theirs with `api.clarusLinksIgnore()` (the docs theme's archived versions).
53
+ */
54
+ links?: {
55
+ pages?: LinkLevel;
56
+ anchors?: LinkLevel;
57
+ outside?: LinkLevel;
58
+ strict?: boolean;
59
+ ignore?: string[];
60
+ };
61
+ /**
62
+ * Template lint levels for `clarusjs check`: `{ 'img-alt': 'off', 'accessible-name': 'error' }`. Rules warn by default.
63
+ * @see https://clarusjs.com/guide/lint
64
+ */
65
+ lint?: LintConfig;
66
+ /**
67
+ * The project's own lint rules, run by `clarusjs check` beside the built-in ones.
68
+ * @see https://clarusjs.com/guide/lint#writing-a-rule
69
+ */
70
+ lintRules?: LintRuleDef[];
71
+ /**
72
+ * Paths that moved: `{ '/old': '/new' }` (a site path or a full URL). The build writes a page at each old path that
73
+ * sends visitors on, and `_redirects` lines (a real 301 on Netlify and Cloudflare Pages); dev answers 301.
74
+ * @see https://clarusjs.com/guide/routing
75
+ */
76
+ redirects?: Record<string, string>;
77
+ /**
78
+ * Response headers by path pattern (`*` anything, `:name` one segment): `{ '/*': { 'X-Frame-Options': 'DENY' } }`.
79
+ * The build writes them to `_headers` (read as is by Netlify and Cloudflare Pages; applied by `clarusjs serve` and
80
+ * vite preview), after `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin` and
81
+ * immutable caching for hashed assets. A name set by several matching patterns gets their values joined. `false`: no
82
+ * `_headers` written.
83
+ * @see https://clarusjs.com/guide/deploy#headers
84
+ */
85
+ headers?: HeaderRules | false;
86
+ /**
87
+ * The environment variables the site needs: `{ server: ['DATABASE_URL'], browser: ['VITE_API_URL'] }`. `vite build`
88
+ * fails naming any that is missing (dev warns), and `.clarusjs/env.d.ts` types them as strings. Browser ones start
89
+ * with Vite's prefix (VITE_). Server code reads every .env variable from process.env, whether named here or not.
90
+ * @see https://clarusjs.com/guide/environment-variables
91
+ */
92
+ env?: EnvOption;
93
+ /**
94
+ * Every page's <head>: `titleTemplate` ('%s · Site') wraps the document title, `tags` are added unless the page has
95
+ * its own with the same key. Anything else: export `transformHead(head, page)` from src/head.ts.
96
+ */
97
+ head?: {
98
+ titleTemplate?: string;
99
+ tags?: HeadTag[];
100
+ jsonLd?: object | object[];
101
+ };
102
+ /**
103
+ * The site's public address. Every page gets a canonical URL and social cards (Open Graph, Twitter) from its title,
104
+ * description and an image (the page's og:image, or `image`); absolute links to the site are link-checked.
105
+ */
106
+ site?: SiteOptions;
107
+ /**
108
+ * With site.url, vite build writes sitemap.xml (static pages, dated from git). false: no sitemap. `exclude`: paths
109
+ * left out ('/legal', '/tags/*' one segment, '/drafts/**' any depth). A page opts out itself with
110
+ * <cl-head><meta name="sitemap" content="false"></cl-head> (removed from the built page) or noindex, and sets its
111
+ * own date with <meta name="sitemap:lastmod" content="2026-11-01">. Each page's images (not alt="", not data:) are
112
+ * listed with Google's image extension; `images: false` leaves them out. `include`: paths the build can't list (server
113
+ * and client routes), or a function returning them (async, to read them from a database at build time).
114
+ */
115
+ sitemap?: boolean | {
116
+ exclude?: string[];
117
+ images?: boolean;
118
+ include?: string[] | (() => string[] | Promise<string[]>);
119
+ };
120
+ /** With site.url, vite build writes robots.txt (allow all, and the sitemap), unless public/robots.txt exists. */
121
+ robots?: boolean;
122
+ /** Collapse whitespace in template text at build (default true). */
123
+ collapseWhitespace?: boolean;
124
+ /** At build, write .br and .gz next to dist/client's text files, for servers that serve them as is. Default false. */
125
+ compress?: boolean;
126
+ };
127
+ /**
128
+ * How a build reports a broken link: fail (`'error'`), print a warning, or skip the check.
129
+ * @see https://clarusjs.com/reference/vite-plugin#links
130
+ */
131
+ export type LinkLevel = 'error' | 'warn' | 'off';
132
+ /**
133
+ * A page source: files with another extension (such as Markdown) turned into .tscl text, then compiled like any
134
+ * page. `route` is the page's route when the file is under src/pages.
135
+ * @see https://clarusjs.com/reference/vite-plugin#page-sources
136
+ */
137
+ export type Source = {
138
+ extension: string;
139
+ toTscl(code: string, file: string, context: SourceContext): string;
140
+ };
141
+ /** @see https://clarusjs.com/reference/vite-plugin#page-sources
142
+ * `root`: the app root. `addDependency(file)`: another file the output depends on (rebuilt when it changes in dev). */
143
+ export type SourceContext = {
144
+ route: string;
145
+ root: string;
146
+ addDependency(file: string): void;
147
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ /** An attribute of a built <meta> or <link> in any valid form: "x", 'x' or unquoted (transformHead output isn't normalized). */
2
+ export declare function metaAttr(tag: string, name: string): string | undefined;
3
+ /**
4
+ * A sitemap lastmod's time (ms), or NaN: a calendar date (2026-02-30 isn't one, though Date.parse rolls it over to
5
+ * March 2), optionally with a time and a zone, as sitemaps allow.
6
+ */
7
+ export declare function lastmodTime(value: string): number;
8
+ /**
9
+ * Precompressed copies for self-hosted servers that serve them directly (nginx gzip_static/brotli_static, Caddy
10
+ * precompressed): `x.html.br` and `x.html.gz` next to each text file, kept only when smaller than the original.
11
+ */
12
+ export declare function precompress(dir: string): void;
13
+ /**
14
+ * vite build --watch: run `once` (the whole build) again after each change under src/ or public/, debounced and one
15
+ * at a time. A failed rebuild is logged and the next change tries again. The watcher is on the builder (closable).
16
+ */
17
+ export declare function watchApp(builder: {
18
+ config: {
19
+ root: string;
20
+ logger: {
21
+ info(m: string): void;
22
+ error(m: string): void;
23
+ };
24
+ };
25
+ }, once: () => Promise<void>): void;
@@ -0,0 +1,49 @@
1
+ import { existsSync, readdirSync, readFileSync, watch as watchFs, writeFileSync } from 'node:fs';
2
+ import { brotliCompressSync, constants as zlibConstants, gzipSync } from 'node:zlib';
3
+ import { resolve } from 'node:path';
4
+ export function metaAttr(tag, name) {
5
+ return new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((v) => v !== undefined);
6
+ }
7
+ export function lastmodTime(value) {
8
+ const m = /^(\d{4})-(\d{2})-(\d{2})(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?$/.exec(value);
9
+ if (!m)
10
+ return NaN;
11
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
12
+ const day = new Date(Date.UTC(y, mo - 1, d));
13
+ if (day.getUTCFullYear() !== y || day.getUTCMonth() !== mo - 1 || day.getUTCDate() !== d)
14
+ return NaN;
15
+ return Date.parse(m[4] ? value : `${value}T00:00:00Z`);
16
+ }
17
+ export function precompress(dir) {
18
+ for (const name of readdirSync(dir, { recursive: true })) {
19
+ if (!/\.(html|js|css|svg|json|xml)$/.test(name))
20
+ continue;
21
+ const file = resolve(dir, name);
22
+ const data = readFileSync(file);
23
+ const br = brotliCompressSync(data, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 11, [zlibConstants.BROTLI_PARAM_SIZE_HINT]: data.length } });
24
+ const gz = gzipSync(data, { level: 9 });
25
+ if (br.length < data.length)
26
+ writeFileSync(file + '.br', br);
27
+ if (gz.length < data.length)
28
+ writeFileSync(file + '.gz', gz);
29
+ }
30
+ }
31
+ export function watchApp(builder, once) {
32
+ let timer;
33
+ let running = Promise.resolve();
34
+ const rebuild = () => {
35
+ clearTimeout(timer);
36
+ timer = setTimeout(() => {
37
+ running = running.then(once).then(() => builder.config.logger.info('clarusjs: rebuilt'), (err) => builder.config.logger.error(`clarusjs: rebuild failed: ${err?.message ?? err}`));
38
+ }, 100);
39
+ };
40
+ const watchers = ['src', 'public'].filter((d) => existsSync(resolve(builder.config.root, d))).map((d) => watchFs(resolve(builder.config.root, d), { recursive: true }, rebuild));
41
+ builder.clarusjsWatcher = {
42
+ async close() {
43
+ clearTimeout(timer);
44
+ for (const w of watchers)
45
+ w.close();
46
+ await running;
47
+ },
48
+ };
49
+ }
@@ -1,157 +1,11 @@
1
1
  import { type Plugin } from 'vite';
2
- import { type LibraryOption } from './libraries.ts';
3
- import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
4
2
  export { packageOf } from './build.ts';
5
3
  /** Newest commit time (unix seconds) of every file under a folder, from one `git log` (themes use it for "last updated"). */
6
4
  export { gitDates } from './sitemap.ts';
7
- import { type EnvOption } from './env.ts';
8
- import { type HeaderRules } from './headers.ts';
9
- import { type ModeTable } from '../server/modes.ts';
10
- import type { HeadTag, SiteOptions } from '../server/head.ts';
11
- /**
12
- * Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. Always with
13
- * forward slashes (`/@fs/C:/libs/c.tscl` on Windows). `path`: the platform's (a parameter for tests). @internal
14
- */
15
- export declare function clientUrlFor(root: string, file: string, path?: Pick<typeof import('node:path'), 'relative' | 'isAbsolute' | 'sep'>): string;
16
- /**
17
- * The Vite plugin's options: when routes render, the deploy adapter, fragment navigation, link checks, head tags, the
18
- * site's address, sitemap and robots, redirects, and page sources.
19
- * @see https://clarusjs.com/reference/vite-plugin#clarusjs
20
- */
21
- export type ClarusOptions = {
22
- /** When each route renders: { '/account/*': 'server' }. Routes default to 'static' (prerendered at build). */
23
- routes?: ModeTable;
24
- /**
25
- * Layouts by route (#456), outermost first, around the folder layouts (`+layout.tscl`): `{ layout: '/src/layouts/site.tscl',
26
- * include: ['/*'], exclude: ['/embed/*'] }` (patterns as in `routes`; include defaults to every route). A page with
27
- * `@layout none` gets none.
28
- */
29
- layouts?: {
30
- layout: string;
31
- include?: string[];
32
- exclude?: string[];
33
- }[];
34
- /**
35
- * Automatic component imports (#458): a kebab-case file under these folders is used by its name, without @import
36
- * (`src/components/forms/text-field.tscl` → `<forms-text-field>`, or `<text-field>` when no other has that name).
37
- * Defaults: `{ dirs: ['src/components', 'src/layouts'], auto: true }`. `libraries`: installed component libraries whose
38
- * components are used the same way (`libraries: ['@clarusjs/ui-primitives']` → `<ui-dialog>`), each described by its
39
- * package.json; your own components win over theirs.
40
- */
41
- components?: {
42
- dirs?: string[];
43
- auto?: boolean;
44
- libraries?: LibraryOption[];
45
- };
46
- /**
47
- * Where server routes deploy. 'netlify': a Netlify Function (Frameworks API) next to the static files. 'vercel': the
48
- * Build Output API in .vercel/output (static files, one Node function, routes), with the server bundled.
49
- * 'cloudflare': a worker in dist/client/_worker.js/ and _routes.json (Pages, or a Worker with static assets).
50
- * @see https://clarusjs.com/guide/deploy
51
- */
52
- adapter?: 'netlify' | 'vercel' | 'cloudflare';
53
- /** Fragment navigation: each static and server page also answers at <path>/index.frag.html. */
54
- fragments?: boolean;
55
- /** Page sources for other file types, such as Markdown from @clarusjs/content: `sources: [markdown()]`. */
56
- sources?: Source[];
57
- /**
58
- * Build-time link checking, after every page is built. `pages`: links to pages or files that don't exist (default
59
- * 'error'). `anchors`: links to a #id the target page doesn't have (default 'warn'). `strict`: warnings fail too.
60
- */
61
- links?: {
62
- pages?: LinkLevel;
63
- anchors?: LinkLevel;
64
- outside?: LinkLevel;
65
- strict?: boolean;
66
- };
67
- /**
68
- * Template lint levels for `clarusjs check`: `{ 'img-alt': 'off', 'accessible-name': 'error' }`. Rules warn by default.
69
- * @see https://clarusjs.com/guide/lint
70
- */
71
- lint?: LintConfig;
72
- /**
73
- * The project's own lint rules, run by `clarusjs check` beside the built-in ones.
74
- * @see https://clarusjs.com/guide/lint#writing-a-rule
75
- */
76
- lintRules?: LintRuleDef[];
77
- /**
78
- * Paths that moved: `{ '/old': '/new' }` (a site path or a full URL). The build writes a page at each old path that
79
- * sends visitors on, and `_redirects` lines (a real 301 on Netlify and Cloudflare Pages); dev answers 301.
80
- * @see https://clarusjs.com/guide/routing
81
- */
82
- redirects?: Record<string, string>;
83
- /**
84
- * Response headers by path pattern (`*` anything, `:name` one segment): `{ '/*': { 'X-Frame-Options': 'DENY' } }`.
85
- * The build writes them to `_headers` (read as is by Netlify and Cloudflare Pages; applied by `clarusjs serve` and
86
- * vite preview), after `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin` and
87
- * immutable caching for hashed assets. A name set by several matching patterns gets their values joined. `false`: no
88
- * `_headers` written.
89
- * @see https://clarusjs.com/guide/deploy#headers
90
- */
91
- headers?: HeaderRules | false;
92
- /**
93
- * The environment variables the site needs: `{ server: ['DATABASE_URL'], browser: ['VITE_API_URL'] }`. `vite build`
94
- * fails naming any that is missing (dev warns), and `.clarusjs/env.d.ts` types them as strings. Browser ones start
95
- * with Vite's prefix (VITE_). Server code reads every .env variable from process.env, whether named here or not.
96
- * @see https://clarusjs.com/guide/environment-variables
97
- */
98
- env?: EnvOption;
99
- /**
100
- * Every page's <head>: `titleTemplate` ('%s · Site') wraps the document title, `tags` are added unless the page has
101
- * its own with the same key. Anything else: export `transformHead(head, page)` from src/head.ts.
102
- */
103
- head?: {
104
- titleTemplate?: string;
105
- tags?: HeadTag[];
106
- jsonLd?: object | object[];
107
- };
108
- /**
109
- * The site's public address. Every page gets a canonical URL and social cards (Open Graph, Twitter) from its title,
110
- * description and an image (the page's og:image, or `image`); absolute links to the site are link-checked.
111
- */
112
- site?: SiteOptions;
113
- /**
114
- * With site.url, vite build writes sitemap.xml (static pages, dated from git). false: no sitemap. `exclude`: paths
115
- * left out ('/legal', '/tags/*' one segment, '/drafts/**' any depth). A page opts out itself with
116
- * <cl-head><meta name="sitemap" content="false"></cl-head> (removed from the built page) or noindex, and sets its
117
- * own date with <meta name="sitemap:lastmod" content="2026-11-01">. Each page's images (not alt="", not data:) are
118
- * listed with Google's image extension; `images: false` leaves them out. `include`: paths the build can't list (server
119
- * and client routes), or a function returning them (async, to read them from a database at build time).
120
- */
121
- sitemap?: boolean | {
122
- exclude?: string[];
123
- images?: boolean;
124
- include?: string[] | (() => string[] | Promise<string[]>);
125
- };
126
- /** With site.url, vite build writes robots.txt (allow all, and the sitemap), unless public/robots.txt exists. */
127
- robots?: boolean;
128
- /** Collapse whitespace in template text at build (default true). */
129
- collapseWhitespace?: boolean;
130
- /** At build, write .br and .gz next to dist/client's text files, for servers that serve them as is. Default false. */
131
- compress?: boolean;
132
- };
133
- export type { HeadTag };
134
- /**
135
- * How a build reports a broken link: fail (`'error'`), print a warning, or skip the check.
136
- * @see https://clarusjs.com/reference/vite-plugin#links
137
- */
138
- export type LinkLevel = 'error' | 'warn' | 'off';
139
- /**
140
- * A page source: files with another extension (such as Markdown) turned into .tscl text, then compiled like any
141
- * page. `route` is the page's route when the file is under src/pages.
142
- * @see https://clarusjs.com/reference/vite-plugin#page-sources
143
- */
144
- export type Source = {
145
- extension: string;
146
- toTscl(code: string, file: string, context: SourceContext): string;
147
- };
148
- /** @see https://clarusjs.com/reference/vite-plugin#page-sources
149
- * `root`: the app root. `addDependency(file)`: another file the output depends on (rebuilt when it changes in dev). */
150
- export type SourceContext = {
151
- route: string;
152
- root: string;
153
- addDependency(file: string): void;
154
- };
5
+ import type { ClarusOptions } from './options.ts';
6
+ export type { ClarusOptions, LinkLevel, Source, SourceContext } from './options.ts';
7
+ export type { HeadTag } from '../server/head.ts';
8
+ export { clientUrlFor } from './shared.ts';
155
9
  /**
156
10
  * The clarusjs Vite plugin: compiles `.tscl` files, serves pages in development, and on `vite build` builds the
157
11
  * browser code, the server and the prerendered pages.