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
@@ -53,6 +53,7 @@ function print(node, code, hook, parent = null, key = '') {
53
53
  return out + code.slice(pos, node.end);
54
54
  }
55
55
  const TS = 'TypeScript syntax in a <script> (scripts are JavaScript): ';
56
+ const EXPORT_WHY = "its names are for this component's template, and it runs once per use. Put a value other files need in a .ts module and import it here; a type can be exported (export interface, export type), or written as a JSDoc @typedef";
56
57
  const TS_WHERE = '. For TypeScript, write <script lang="ts">; in JavaScript, types come from JSDoc, @input and the .ts modules a script imports';
57
58
  function typescriptAt(code, pos) {
58
59
  const before = code.slice(0, pos).trimEnd();
@@ -239,6 +240,17 @@ export function wrapExpr(expr) {
239
240
  const t = parseExpr(expr).type;
240
241
  return t === 'SequenceExpression' || t === 'ObjectExpression' ? `(${expr})` : expr;
241
242
  }
243
+ export function usesRuntime(code, imports, name) {
244
+ if (scriptNames(code).has(name) || imports.some((line) => scriptNames(line).has(name)))
245
+ return false;
246
+ let found = false;
247
+ print(parseScript(code), code, (node, parent, key) => {
248
+ if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === name && !isBinding(parent, key))
249
+ found = true;
250
+ return undefined;
251
+ });
252
+ return found;
253
+ }
242
254
  export function scriptNames(code) {
243
255
  const names = new Set();
244
256
  for (const stmt of parseScript(code).body) {
@@ -283,7 +295,7 @@ export function serverScriptParts(code, file, source, offset) {
283
295
  let body = code;
284
296
  for (const stmt of ast.body) {
285
297
  if (stmt.type.startsWith('Export'))
286
- throw new ClarusError('a <script server> cannot export anything: its names are for the template', file, source, offset + stmt.start);
298
+ throw new ClarusError(`a <script server> can't export a value: ${EXPORT_WHY}`, file, source, offset + stmt.start);
287
299
  if (stmt.type !== 'ImportDeclaration')
288
300
  continue;
289
301
  imports.push(code.slice(stmt.start, stmt.end));
@@ -423,7 +435,7 @@ export function analyzeScript(code, file, source, offset) {
423
435
  throw new ClarusError("an island's <script> can't await at the top level (the browser attaches it without waiting): await data on the server in a <script server>, or in the browser inside a function, such as a resource()'s fetcher or an event handler", file, source, offset + tla.start);
424
436
  for (const stmt of ast.body) {
425
437
  if (stmt.type.startsWith('Export')) {
426
- throw new ClarusError('a <script> cannot export anything', file, source, offset + stmt.start);
438
+ throw new ClarusError(`a <script> can't export a value: ${EXPORT_WHY}`, file, source, offset + stmt.start);
427
439
  }
428
440
  if (stmt.type !== 'VariableDeclaration')
429
441
  continue;
@@ -26,13 +26,14 @@ function pathOf(field, root) {
26
26
  }
27
27
  through += openSlots(here);
28
28
  let part = here.getAttribute('data-cl-path');
29
- if (part?.startsWith('@')) {
29
+ let at = here;
30
+ while (part?.startsWith('@')) {
30
31
  const [model, ...rest] = part.slice(1).split('.');
31
- const island = owner(here);
32
+ const island = owner(at);
32
33
  if (!island?.hasAttribute(`data-cl-path-${model}`))
33
34
  return '';
34
35
  part = [island.getAttribute(`data-cl-path-${model}`), ...rest].filter(Boolean).join('.');
35
- el = island;
36
+ el = at = island;
36
37
  through = openSlots(island);
37
38
  }
38
39
  if (part)
@@ -198,7 +199,10 @@ export function form(values, options = {}) {
198
199
  const go = (id) => {
199
200
  showStep(id, true);
200
201
  const step = steps().find((s) => s.id === id);
201
- step?.querySelector('input, select, textarea, button, [tabindex]')?.focus();
202
+ const title = step?.querySelector('legend, h1, h2, h3, h4, h5, h6');
203
+ if (title && !title.hasAttribute('tabindex'))
204
+ title.tabIndex = -1;
205
+ (title ?? step?.querySelector('input, select, textarea, button, [tabindex]'))?.focus();
202
206
  };
203
207
  const errorsIn = (step) => new Set(fields().filter((f) => step.contains(f.el) && shown(f.path) && errorsNow[f.path]).map((f) => f.path)).size;
204
208
  const refreshSoon = () => {
@@ -243,7 +247,24 @@ export function form(values, options = {}) {
243
247
  refresh();
244
248
  check();
245
249
  };
246
- const onSubmit = (e) => { e.preventDefault(); void engine.submit(); };
250
+ let native = false;
251
+ const onSubmit = (e) => {
252
+ if (native)
253
+ return;
254
+ e.preventDefault();
255
+ const form = e.currentTarget, by = e.submitter;
256
+ void engine.submit().then((ok) => {
257
+ if (!ok || options.submit || !(form instanceof HTMLFormElement) || !form.isConnected)
258
+ return;
259
+ native = true;
260
+ try {
261
+ form.requestSubmit(by?.isConnected ? by : null);
262
+ }
263
+ finally {
264
+ native = false;
265
+ }
266
+ });
267
+ };
247
268
  const listeners = [['input', onInput], ['change', onInput], ['focusout', onLeave], ['submit', onSubmit]];
248
269
  const toFirstError = () => {
249
270
  const first = fields().find((f) => errorsNow[f.path]);
@@ -1,13 +1,23 @@
1
1
  /**
2
2
  * A context's name, with its value's type (type checking only). Provide with it, `provide(tabs, { value })`, and read
3
3
  * with it, `const tabs = context(tabsKey)`; a value of another shape is a type error on either side.
4
- * @see https://clarusjs.com/guide/context#typed-keys
4
+ * @see https://clarusjs.com/guide/context
5
5
  */
6
- export type ContextKey<T> = {
7
- readonly name: string; /** Islands may read it: its value is written into the page. */
8
- readonly public?: true; /** The value's type, for type checking (never set). */
6
+ export interface ContextKey<T> {
7
+ readonly name: string;
8
+ /** Islands may read it: its value is written into the page. */
9
+ readonly public?: true;
10
+ /** The value's type, for type checking (never set). */
9
11
  readonly __clContext?: T;
10
- };
12
+ }
13
+ /**
14
+ * A context key islands may read, from `contextKey(name, { public: true })`: its value is written into the page.
15
+ * Interfaces, not type aliases or intersections, so editors show both keys by name.
16
+ * @see https://clarusjs.com/reference/runtime#contextkey
17
+ */
18
+ export interface PublicContextKey<T> extends ContextKey<T> {
19
+ readonly public: true;
20
+ }
11
21
  /**
12
22
  * A typed context key, to export from a `.ts` module that the providing and the reading components both import.
13
23
  * `{ public: true }` lets islands read it: an island's context is written into the page (its HTML), so it's opt-in, on
@@ -23,9 +33,7 @@ export type ContextKey<T> = {
23
33
  */
24
34
  export declare function contextKey<T>(name: string, options: {
25
35
  public: true;
26
- }): ContextKey<T> & {
27
- readonly public: true;
28
- };
36
+ }): PublicContextKey<T>;
29
37
  export declare function contextKey<T>(name: string, options?: {
30
38
  public?: false;
31
39
  }): ContextKey<T>;
@@ -27,14 +27,18 @@ isCurrent = () => true) {
27
27
  for (const title of next.querySelectorAll('title'))
28
28
  title.remove(); // some parsers leave the leading <title> in the body
29
29
  // The page's stylesheets: add the ones not loaded yet to <head>, and wait for them, so nothing shows unstyled.
30
+ // A sheet is known by its URL without the dev server's cache-buster: a hot update relinks it as href?t=…, and a
31
+ // second, stale copy added after it would win the cascade on every later update.
32
+ const sheet = (href) => href.replace(/[?&]t=\d+$/, '');
30
33
  const loading = [];
31
34
  for (const link of doc.querySelectorAll('link[rel="stylesheet"]')) {
32
35
  link.remove();
33
- if (document.head.querySelector(`link[rel="stylesheet"][href="${CSS.escape(link.getAttribute('href'))}"]`))
34
- continue;
35
36
  const added = document.createElement('link');
36
37
  added.rel = 'stylesheet';
37
38
  added.href = link.getAttribute('href');
39
+ // Resolved URLs (.href): Vite writes a relinked sheet's as an absolute URL, the page's own are relative
40
+ if ([...document.head.querySelectorAll('link[rel="stylesheet"]')].some((l) => sheet(l.href) === sheet(added.href)))
41
+ continue;
38
42
  loading.push(new Promise((done) => { added.onload = added.onerror = done; }));
39
43
  document.head.append(added);
40
44
  }
@@ -4,4 +4,4 @@ export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './
4
4
  export { parse as parseIslandData } from './serialize.ts';
5
5
  export { attrValue, baseAttrs, baseUrl, classValue, styleValue, UNSAFE_URL } from './attrs.ts';
6
6
  export { browser } from './env.ts';
7
- export { contextKey, type ContextKey } from './context.ts';
7
+ export { contextKey, type ContextKey, type PublicContextKey } from './context.ts';
@@ -19,7 +19,8 @@ export function takeOver(pick) {
19
19
  export function onNavigate(e, pick) {
20
20
  // A #hash, and the page's own history.pushState/replaceState (same-document push or replace), are never a page
21
21
  // load, except while a swap runs after its URL changed: they abort it, so this navigation shows the new page.
22
- if (!e.canIntercept || e.hashChange || e.downloadRequest != null || e.formData)
22
+ // A reload is a reload (location.reload(), the dev server's after an edit): the page's scripts run again.
23
+ if (!e.canIntercept || e.hashChange || e.downloadRequest != null || e.formData || e.navigationType == 'reload')
23
24
  return;
24
25
  // Push and replace (same-document ones too: never reloads; back/forward is a traverse).
25
26
  const hold = /^(p|rep)/.test(e.navigationType);
@@ -3,18 +3,18 @@
3
3
  * In an island's script you read and write a `state()` as a plain variable; in a `.ts` module, through these.
4
4
  * @see https://clarusjs.com/reference/runtime#state
5
5
  */
6
- export type Signal<T> = {
6
+ export interface Signal<T> {
7
7
  get(): T;
8
8
  set(v: T): void;
9
9
  readonly initial: T;
10
- };
10
+ }
11
11
  /**
12
12
  * A value to read, not write: what `derived()` gives.
13
13
  * @see https://clarusjs.com/reference/runtime#derived
14
14
  */
15
- export type ReadSignal<T> = {
15
+ export interface ReadSignal<T> {
16
16
  get(): T;
17
- };
17
+ }
18
18
  /**
19
19
  * Run `fn`; everything it creates (effects, onDispose cleanups, nested scopes) is undone by the returned dispose. An
20
20
  * island's script already runs in one, disposed when the island leaves the page.
@@ -83,16 +83,21 @@ export declare function batch(fn: () => void): void;
83
83
  export declare function state<T>(initial: T): Signal<T>;
84
84
  /**
85
85
  * Run `fn` now and again whenever a signal it read changes. Returns a function that stops it; in an island it stops
86
- * when the island leaves the page.
86
+ * when the island leaves the page. A function `fn` returns is its cleanup: it runs before the next run and when the
87
+ * effect stops (a timer cleared, a listener removed), without subscribing to what it reads.
87
88
  * @example
88
89
  * ```ts
89
90
  * effect(() => {
90
91
  * document.title = `${count.get()} new messages`
91
92
  * })
93
+ * effect(() => {
94
+ * const timer = setInterval(tick, delay.get())
95
+ * return () => clearInterval(timer)
96
+ * })
92
97
  * ```
93
98
  * @see https://clarusjs.com/reference/runtime#effect
94
99
  */
95
- export declare function effect(fn: () => void): () => void;
100
+ export declare function effect(fn: () => void | (() => void)): () => void;
96
101
  /**
97
102
  * A value computed from other signals, kept up to date as they change. Read-only. In an island's script it reads as
98
103
  * a plain variable.
@@ -165,29 +165,38 @@ export function state(initial) {
165
165
  }
166
166
  /**
167
167
  * Run `fn` now and again whenever a signal it read changes. Returns a function that stops it; in an island it stops
168
- * when the island leaves the page.
168
+ * when the island leaves the page. A function `fn` returns is its cleanup: it runs before the next run and when the
169
+ * effect stops (a timer cleared, a listener removed), without subscribing to what it reads.
169
170
  * @example
170
171
  * ```ts
171
172
  * effect(() => {
172
173
  * document.title = `${count.get()} new messages`
173
174
  * })
175
+ * effect(() => {
176
+ * const timer = setInterval(tick, delay.get())
177
+ * return () => clearInterval(timer)
178
+ * })
174
179
  * ```
175
180
  * @see https://clarusjs.com/reference/runtime#effect
176
181
  */
177
182
  export function effect(fn) {
183
+ let cleanup;
184
+ const clean = () => { if (typeof cleanup == 'function')
185
+ untrack(cleanup); cleanup = undefined; };
178
186
  const e = {
179
187
  deps: new Set(),
180
188
  active: true,
181
189
  run() {
182
190
  if (!e.active)
183
191
  return;
192
+ clean();
184
193
  for (const subs of e.deps)
185
194
  subs.delete(e);
186
195
  e.deps.clear();
187
196
  const prev = current;
188
197
  current = e;
189
198
  try {
190
- fn();
199
+ cleanup = fn();
191
200
  }
192
201
  finally {
193
202
  current = prev;
@@ -196,7 +205,7 @@ export function effect(fn) {
196
205
  };
197
206
  e.run();
198
207
  const stop = () => { e.active = false; for (const subs of e.deps)
199
- subs.delete(e); e.deps.clear(); };
208
+ subs.delete(e); e.deps.clear(); clean(); };
200
209
  onDispose(stop);
201
210
  return stop;
202
211
  }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Paths that start with the base itself (base `/about/`: the route `/about`, the public file `/about/logo.png`): their
3
+ * links can't be told from links under the base, so one of them is rewritten or left wrong (#659). A route whose first
4
+ * segments are parameters (`/[lang]/guide`, base `/en/`) does for the values that equal the base's segments.
5
+ * Routes may be concrete (`/about/team`) or patterns; a CDN base (a full URL) has no path, so nothing clashes.
6
+ */
7
+ export declare function baseClashes(base: string, routes: readonly string[], publicFiles: readonly string[], redirects?: readonly string[]): string[];
8
+ /** The files in Vite's public folder, as the root-relative paths they're served at. */
9
+ export declare function publicFiles(dir: string | false): string[];
@@ -0,0 +1,54 @@
1
+ import { readdirSync } from 'node:fs';
2
+ import { sep } from 'node:path';
3
+ import { basePath } from '../server/head.js';
4
+ export function baseClashes(base, routes, publicFiles, redirects = []) {
5
+ const prefix = basePath(base).replace(/\/$/, '');
6
+ if (!prefix)
7
+ return [];
8
+ const baseSegments = prefix.split('/').slice(1);
9
+ const under = (path) => path === prefix || path.startsWith(prefix + '/');
10
+ const out = [];
11
+ for (const route of routes) {
12
+ if (under(route)) {
13
+ out.push(`route ${route} starts with the base ${base}`);
14
+ continue;
15
+ }
16
+ const segments = route.split('/').slice(1);
17
+ const when = [];
18
+ let clashes = true;
19
+ for (let i = 0; i < baseSegments.length; i++) {
20
+ const seg = segments[i];
21
+ const rest = seg && /^\[\.\.\.([^\]]+)\]$/.exec(seg);
22
+ if (rest) {
23
+ when.push(`${rest[1]} starts with "${baseSegments.slice(i).join('/')}"`);
24
+ break;
25
+ }
26
+ const param = seg && /^\[([^\]]+)\]$/.exec(seg);
27
+ if (param)
28
+ when.push(`${param[1]} is "${baseSegments[i]}"`);
29
+ else if (seg !== baseSegments[i]) {
30
+ clashes = false;
31
+ break;
32
+ }
33
+ }
34
+ if (clashes && when.length)
35
+ out.push(`route ${route} starts with the base ${base} when ${when.join(' and ')}`);
36
+ }
37
+ for (const file of publicFiles)
38
+ if (under(file))
39
+ out.push(`public file ${file} starts with the base ${base}`);
40
+ for (const from of redirects)
41
+ if (under(from))
42
+ out.push(`redirect from ${from} starts with the base ${base}`);
43
+ return out;
44
+ }
45
+ export function publicFiles(dir) {
46
+ if (!dir)
47
+ return [];
48
+ try {
49
+ return readdirSync(dir, { recursive: true, withFileTypes: true }).filter((e) => e.isFile()).map((e) => `/${`${e.parentPath}${sep}${e.name}`.slice(dir.length + 1).split(sep).join('/')}`);
50
+ }
51
+ catch {
52
+ return [];
53
+ }
54
+ }
@@ -0,0 +1,5 @@
1
+ import type { ViteBuilder } from 'vite';
2
+ import { type Files } from './graph.ts';
3
+ import type { ClarusOptions } from './options.ts';
4
+ /** The plugin's buildApp: the whole build, in order (the server build needs the client's hashed URLs, prerendering the server build). */
5
+ export declare function buildApp(builder: ViteBuilder, options: ClarusOptions, files: Files): Promise<void>;
@@ -0,0 +1,185 @@
1
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname, relative, resolve, sep } from 'node:path';
3
+ import { rootLinks, routeFromFile } from '../server/handler.js';
4
+ import { basePath } from '../server/head.js';
5
+ import { prerender, routeToFile } from './build.js';
6
+ import { writeManifest } from './manifest.js';
7
+ import { writeNetlifyFunction } from './netlify.js';
8
+ import { writeVercelOutput } from './vercel.js';
9
+ import { writeCloudflareWorker } from './cloudflare.js';
10
+ import { checkLinks } from './links.js';
11
+ import { checkRedirects, writeRedirects } from './redirects.js';
12
+ import { checkHeaders, writeHeaders } from './headers.js';
13
+ import { baseClashes, publicFiles } from './base-clash.js';
14
+ import { gitDates, sitemapFiles } from './sitemap.js';
15
+ import { routeParts } from './graph.js';
16
+ import { lastmodTime, metaAttr, precompress, watchApp } from './output.js';
17
+ import { CLIENT_OUT, SERVER_OUT } from './shared.js';
18
+ export async function buildApp(builder, options, files) {
19
+ const { client, ssr } = builder.environments;
20
+ if (!client || !ssr)
21
+ return;
22
+ const watching = !!client.config.build.watch;
23
+ if (watching)
24
+ client.config.build.watch = ssr.config.build.watch = null;
25
+ const once = async () => {
26
+ if (options.headers)
27
+ checkHeaders(options.headers);
28
+ checkRedirects(options.redirects ?? {}, files.pages(builder.config.root).map((f) => routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`)));
29
+ await builder.build(client);
30
+ await builder.build(ssr);
31
+ const entry = resolve(builder.config.root, SERVER_OUT, 'index.mjs');
32
+ const out = resolve(builder.config.root, CLIENT_OUT);
33
+ const dist = dirname(out);
34
+ const manifestFile = resolve(dist, 'clarusjs-manifest.json');
35
+ rmSync(manifestFile, { force: true });
36
+ const { routes, readers, loaded, server } = await prerender(entry, out, manifestFile);
37
+ const parts = routeParts(builder.config.root, files);
38
+ writeManifest(dist, routes, builder.config.base, loaded, server, parts);
39
+ if (readers.length) {
40
+ await prerender(entry, out, manifestFile, readers);
41
+ writeManifest(dist, routes, builder.config.base, loaded, server, parts);
42
+ }
43
+ const pageRoutes = routes.filter((r) => !/\/(__data\.json|index\.frag\.html)$/.test(r));
44
+ const clientRoutes = pageRoutes.filter((r) => routes.includes(r === '/' ? '/__data.json' : `${r}/__data.json`));
45
+ const markers = new Map();
46
+ for (const page of pageRoutes) {
47
+ const file = resolve(out, routeToFile(page));
48
+ let html = readFileSync(file, 'utf8');
49
+ const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
50
+ const optOut = tags.find((tag) => metaAttr(tag, 'name')?.toLowerCase() === 'sitemap' && metaAttr(tag, 'content') === 'false');
51
+ const dated = tags.find((tag) => metaAttr(tag, 'name')?.toLowerCase() === 'sitemap:lastmod');
52
+ let lastmod;
53
+ if (dated) {
54
+ const value = metaAttr(dated, 'content') ?? '';
55
+ const time = lastmodTime(value);
56
+ if (Number.isNaN(time))
57
+ throw new Error(`clarusjs: ${page}: sitemap:lastmod '${value}' isn't a date (YYYY-MM-DD)`);
58
+ lastmod = time / 1000;
59
+ }
60
+ for (const marker of [optOut, dated])
61
+ if (marker)
62
+ html = html.replace(marker, '');
63
+ if (optOut || dated)
64
+ writeFileSync(file, html);
65
+ markers.set(page, { out: !!optOut, ...(lastmod === undefined ? {} : { lastmod }) });
66
+ }
67
+ if (pageRoutes.includes('/404') && !clientRoutes.includes('/404')) {
68
+ const html = rootLinks(readFileSync(resolve(out, routeToFile('/404')), 'utf8'), basePath(builder.config.base));
69
+ writeFileSync(resolve(out, routeToFile('/404')), html);
70
+ writeFileSync(resolve(out, '404.html'), html);
71
+ }
72
+ if (pageRoutes.includes('/500') && !clientRoutes.includes('/500')) {
73
+ const html = rootLinks(readFileSync(resolve(out, routeToFile('/500')), 'utf8'), basePath(builder.config.base));
74
+ writeFileSync(resolve(out, routeToFile('/500')), html);
75
+ writeFileSync(resolve(out, '500.html'), html);
76
+ }
77
+ if (options.headers !== false)
78
+ writeHeaders(out, options.headers ?? {}, basePath(builder.config.base).replace(/\/$/, ''), builder.config.build.assetsDir);
79
+ for (const clash of baseClashes(builder.config.base, [...pageRoutes, ...server.map((x) => x.route)], publicFiles(builder.config.publicDir), Object.keys(options.redirects ?? {}))) {
80
+ builder.config.logger.warn(`clarusjs: ${clash}: links to it can't be told from links under the base; rename it or the base`);
81
+ }
82
+ if (options.redirects) {
83
+ writeRedirects(out, options.redirects, basePath(builder.config.base).replace(/\/$/, ''), routes);
84
+ const moved = Object.keys(options.redirects).map((from) => (from.length > 1 ? from.replace(/\/+$/, '') : from));
85
+ pageRoutes.push(...moved);
86
+ clientRoutes.push(...moved);
87
+ }
88
+ const issues = checkLinks({
89
+ outDir: out,
90
+ routes: pageRoutes,
91
+ serverRoutes: server.map((x) => x.route),
92
+ clientRoutes,
93
+ base: builder.config.base,
94
+ site: options.site?.url,
95
+ ignore: [...(options.links?.ignore ?? []), ...builder.config.plugins.flatMap((p) => p.api?.clarusLinksIgnore?.() ?? [])],
96
+ });
97
+ const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn', outside: options.links?.outside ?? 'warn' };
98
+ const sourceOf = new Map(files.pages(builder.config.root).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
99
+ const pattern = (route) => new RegExp(`^${route.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
100
+ const fileOf = (page) => sourceOf.get(page) ?? [...sourceOf].find(([route]) => pattern(route).test(page))?.[1];
101
+ const locate = (page, href) => {
102
+ const file = fileOf(page);
103
+ if (!file)
104
+ return page;
105
+ const rel = relative(builder.config.root, file).split(sep).join('/');
106
+ const written = href.startsWith(builder.config.base) ? href.slice(builder.config.base.length - 1) : href;
107
+ const whole = (l, x) => ['"', "'"].some((q) => l.includes(q + x + q)) || l.includes(`](${x})`) || l.includes(`](${x} `);
108
+ const lines = readFileSync(file, 'utf8').split('\n');
109
+ let line = lines.findIndex((l) => whole(l, href) || whole(l, written));
110
+ if (line === -1)
111
+ line = lines.findIndex((l) => (href.length > 1 && l.includes(href)) || (written.length > 1 && l.includes(written)));
112
+ return line === -1 ? `${rel} (${page})` : `${rel}:${line + 1}`;
113
+ };
114
+ const errors = [];
115
+ for (const issue of issues) {
116
+ const level = levels[issue.kind];
117
+ if (level === 'off')
118
+ continue;
119
+ const text = `${locate(issue.page, issue.href)}: ${issue.message}`;
120
+ if (level === 'error' || options.links?.strict)
121
+ errors.push(text);
122
+ else
123
+ builder.config.logger.warn(`clarusjs: ${text}`);
124
+ }
125
+ if (errors.length)
126
+ throw new Error(`clarusjs: broken links:\n ${errors.join('\n ')}`);
127
+ if (options.site && options.sitemap !== false) {
128
+ const dates = gitDates(builder.config.root, 'src/pages');
129
+ const epoch = process.env.SOURCE_DATE_EPOCH ? Number(process.env.SOURCE_DATE_EPOCH) : undefined;
130
+ const exclude = (typeof options.sitemap === 'object' ? options.sitemap.exclude ?? [] : [])
131
+ .map((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*\*|\*/g, (s) => (s === '**' ? '.*' : '[^/]+'))}$`));
132
+ const images = typeof options.sitemap !== 'object' || options.sitemap.images !== false;
133
+ const sitemapMeta = (page) => {
134
+ const file = resolve(out, routeToFile(page));
135
+ const html = readFileSync(file, 'utf8');
136
+ const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
137
+ const attr = metaAttr;
138
+ const { out: optOut, lastmod } = markers.get(page) ?? { out: false };
139
+ const decode = (v) => v.replace(/&(amp|quot|#39|lt|gt);/g, (_, e) => ({ amp: '&', quot: '"', '#39': "'", lt: '<', gt: '>' })[e]);
140
+ const pics = images ? [...new Set([...html.matchAll(/<img\b[^>]*>/gi)].map(([tag]) => tag)
141
+ .filter((tag) => attr(tag, 'alt') !== '')
142
+ .map((tag) => decode(attr(tag, 'src') ?? ''))
143
+ .filter((src) => src && !/^data:/i.test(src)))].slice(0, 1000) : [];
144
+ const alternates = [...html.matchAll(/<link\b[^>]*>/gi)].map(([tag]) => tag)
145
+ .filter((tag) => /(^|\s)alternate(\s|$)/i.test(attr(tag, 'rel') ?? '') && attr(tag, 'hreflang') && attr(tag, 'href'))
146
+ .map((tag) => ({ hreflang: attr(tag, 'hreflang'), href: decode(attr(tag, 'href')) }));
147
+ return { out: optOut || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? '')), ...(lastmod === undefined ? {} : { lastmod }), images: pics, alternates };
148
+ };
149
+ const pages = pageRoutes.filter((page) => page !== '/404' && page !== '/500' && !clientRoutes.includes(page))
150
+ .map((path) => ({ path, meta: sitemapMeta(path) }));
151
+ const keptOut = new Set(pages.filter(({ path, meta }) => meta.out || exclude.some((re) => re.test(path))).map((p) => p.path));
152
+ const listedPages = pages.filter(({ path }) => !keptOut.has(path));
153
+ const entries = listedPages.map(({ path, meta }) => ({ path, lastmod: meta.lastmod ?? dates.get(fileOf(path) ?? '') ?? epoch, images: meta.images, alternates: meta.alternates }));
154
+ const include = typeof options.sitemap === 'object' ? options.sitemap.include : undefined;
155
+ const extra = typeof include === 'function' ? await include() : include ?? [];
156
+ const listed = new Set(entries.map((p) => p.path));
157
+ for (const path of extra) {
158
+ if (typeof path !== 'string' || !path.startsWith('/'))
159
+ throw new Error(`clarusjs: sitemap.include: '${String(path)}' isn't a path (start it with /)`);
160
+ if (listed.has(path) || keptOut.has(path) || exclude.some((re) => re.test(path)))
161
+ continue;
162
+ entries.push({ path, lastmod: undefined, images: [], alternates: [] });
163
+ listed.add(path);
164
+ }
165
+ for (const { file, xml } of sitemapFiles(options.site.url, builder.config.base, entries))
166
+ writeFileSync(resolve(out, file), xml);
167
+ }
168
+ if (options.site && options.robots !== false && !existsSync(resolve(out, 'robots.txt'))) {
169
+ const sitemap = options.sitemap !== false ? `\nSitemap: ${new URL('sitemap.xml', new URL(builder.config.base, options.site.url.replace(/\/?$/, '/'))).href}\n` : '';
170
+ writeFileSync(resolve(out, 'robots.txt'), `User-agent: *\nAllow: /\n${sitemap}`);
171
+ }
172
+ if (options.adapter === 'netlify')
173
+ writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true, out);
174
+ rmSync(resolve(out, '.vite'), { recursive: true, force: true });
175
+ if (options.compress)
176
+ precompress(out);
177
+ if (options.adapter === 'vercel')
178
+ writeVercelOutput(builder.config.root, out, dirname(entry), server.map((s) => s.route), basePath(builder.config.base), options.fragments === true);
179
+ if (options.adapter === 'cloudflare')
180
+ writeCloudflareWorker(out, dirname(entry), server.map((s) => s.route), basePath(builder.config.base), options.fragments === true);
181
+ };
182
+ await once();
183
+ if (watching)
184
+ watchApp(builder, once);
185
+ }
@@ -0,0 +1,5 @@
1
+ import { type ViteDevServer } from 'vite';
2
+ import type { Files } from './graph.ts';
3
+ import type { ClarusOptions } from './options.ts';
4
+ /** The plugin's configureServer. */
5
+ export declare function configureDev(server: ViteDevServer, files: Files, options: Pick<ClarusOptions, 'redirects'>): () => void;
@@ -0,0 +1,67 @@
1
+ import { dirname, relative, resolve, sep } from 'node:path';
2
+ import { isRunnableDevEnvironment, normalizePath } from 'vite';
3
+ import { basePath } from '../server/head.js';
4
+ import { routeFromFile } from '../server/handler.js';
5
+ import { baseClashes, publicFiles } from './base-clash.js';
6
+ import { sendResponse, toRequest } from './node.js';
7
+ import { redirectFor } from './redirects.js';
8
+ import { ENTRY } from './shared.js';
9
+ export function configureDev(server, files, options) {
10
+ const devRoutes = files.pages(server.config.root).map((f) => routeFromFile(`/${relative(server.config.root, f).split(sep).join('/')}`));
11
+ for (const clash of baseClashes(server.config.base, devRoutes, publicFiles(server.config.publicDir), Object.keys(options.redirects ?? {}))) {
12
+ server.config.logger.warn(`clarusjs: ${clash}: links to it can't be told from links under the base; rename it or the base`);
13
+ }
14
+ const relayout = (file) => {
15
+ const folder = dirname(normalizePath(file));
16
+ if (!/\/\+layout\.tscl$/.test(normalizePath(file)) || !(folder + '/').startsWith(normalizePath(resolve(server.config.root, 'src/pages')) + '/'))
17
+ return;
18
+ const pages = files.pages(server.config.root).filter((p) => normalizePath(p).startsWith(folder + '/'));
19
+ for (const env of Object.values(server.environments)) {
20
+ for (const page of pages) {
21
+ for (const mod of env.moduleGraph.getModulesByFile(normalizePath(page)) ?? [])
22
+ env.moduleGraph.invalidateModule(mod);
23
+ if (isRunnableDevEnvironment(env))
24
+ for (const mod of env.runner.evaluatedModules.getModulesByFile(normalizePath(page)) ?? [])
25
+ env.runner.evaluatedModules.invalidateModule(mod);
26
+ }
27
+ }
28
+ server.environments.client.hot.send({ type: 'full-reload' });
29
+ };
30
+ server.watcher.on('add', relayout);
31
+ server.watcher.on('unlink', relayout);
32
+ return () => {
33
+ server.middlewares.use(async (req, res, next) => {
34
+ try {
35
+ const env = server.environments.ssr;
36
+ if (!isRunnableDevEnvironment(env))
37
+ return next();
38
+ if (options.redirects) {
39
+ const prefix = basePath(server.config.base).replace(/\/$/, '');
40
+ const pathname = new URL(req.url ?? '/', 'http://x').pathname;
41
+ const to = redirectFor(options.redirects, pathname.startsWith(prefix + '/') ? pathname.slice(prefix.length) : pathname, prefix);
42
+ if (to !== undefined)
43
+ return void res.writeHead(301, { location: to }).end();
44
+ }
45
+ const app = await env.runner.import(ENTRY);
46
+ let response = await app.default.fetch(toRequest(req));
47
+ const html = response.headers.get('content-type')?.startsWith('text/html');
48
+ if (response.status === 404 && !html)
49
+ return next();
50
+ if (html && req.method !== 'HEAD') {
51
+ const text = await response.clone().text();
52
+ const has = /<script\b[^>]*\ssrc=["'][^"']*\/@vite\/client["']/i.test(text);
53
+ if (!has && /<\/head>/i.test(text)) {
54
+ const client = `<script type="module" src="${server.config.base}@vite/client"></script>`;
55
+ const headers = new Headers(response.headers);
56
+ headers.delete('content-length');
57
+ response = new Response(text.replace(/<\/head>/i, `${client}</head>`), { status: response.status, statusText: response.statusText, headers });
58
+ }
59
+ }
60
+ await sendResponse(res, response);
61
+ }
62
+ catch (err) {
63
+ next(err);
64
+ }
65
+ });
66
+ };
67
+ }