clarusjs 0.17.0 → 0.19.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.
@@ -44,6 +44,8 @@ export function emitClient(ir, hot) {
44
44
  rendersHtml && hasFors && 'forHtml as __cl_forHtml',
45
45
  hasRegions && 'regionHtml as __cl_regionHtml',
46
46
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
47
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_baseUrl(')) && 'baseUrl as __cl_baseUrl',
48
+ all.some((n) => n.kind === 'attr' && n.name === '...' && !!n.base) && 'baseAttrs as __cl_baseAttrs',
47
49
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
48
50
  ].filter(Boolean);
49
51
  let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
@@ -113,7 +115,7 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
113
115
  lines.push(`__cl_text(__cl_h[${h.index}], () => ${wrapExpr(rw.expr(h.expr))})`);
114
116
  for (const a of nodes) {
115
117
  if (a.kind === 'attr' && a.reactive && a.name === '...')
116
- lines.push(`__cl_spread(${ctx}, ${a.index}, () => ${attrValueExpr(a.value, rw.expr)}, ${JSON.stringify(a.skip ?? [])}, ${JSON.stringify(a.tag)})`);
118
+ lines.push(`__cl_spread(${ctx}, ${a.index}, () => ${a.base ? `__cl_baseAttrs(${JSON.stringify(a.base)}, ${attrValueExpr(a.value, rw.expr)})` : attrValueExpr(a.value, rw.expr)}, ${JSON.stringify(a.skip ?? [])}, ${JSON.stringify(a.tag)})`);
117
119
  else if (a.kind === 'attr' && a.reactive)
118
120
  lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
119
121
  if (a.kind === 'connect')
@@ -12,6 +12,8 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
12
12
  html.includes('__cl_spreadHtml(') && 'spreadHtml as __cl_spreadHtml',
13
13
  html.includes('__cl_passedHtml(') && 'passedHtml as __cl_passedHtml',
14
14
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
15
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_baseUrl(')) && 'baseUrl as __cl_baseUrl',
16
+ all.some((n) => n.kind === 'attr' && n.name === '...' && !!n.base) && 'baseAttrs as __cl_baseAttrs',
15
17
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
16
18
  all.some((n) => (n.kind === 'if' || n.kind === 'await') && n.block >= 0) && 'blockHtml as __cl_blockHtml',
17
19
  all.some((n) => n.kind === 'await' && n.block < 0) && 'awaitHtml as __cl_awaitHtml',
@@ -16,9 +16,11 @@ export function htmlExpr(nodes, rw = asWritten, top) {
16
16
  if (n.kind === 'connect' || n.kind === 'use')
17
17
  return '""';
18
18
  if (n.kind === 'attr' && n.name === '...' && 'expr' in n.value && n.value.expr === '__cl_attrs')
19
- return `__cl_passedHtml(__cl_attrs, ${JSON.stringify((n.skip ?? []).filter((x) => x !== 'engine' && x !== 'use' && !x.includes('.')))})`;
19
+ return `__cl_passedHtml(${n.base ? `__cl_baseAttrs(${JSON.stringify(n.base)}, __cl_attrs)` : '__cl_attrs'}, ${JSON.stringify((n.skip ?? []).filter((x) => x !== 'engine' && x !== 'use' && !x.includes('.')))})`;
20
20
  if (n.kind === 'attr' && n.name === '...')
21
- return `__cl_spreadHtml(${attrValueExpr(n.value, rw.expr)}, ${JSON.stringify(n.skip ?? [])}, ${JSON.stringify(n.tag)}${rw === asWritten && n.where ? `, ${JSON.stringify(n.where)}` : ''})`;
21
+ return `__cl_spreadHtml(${n.base ? `__cl_baseAttrs(${JSON.stringify(n.base)}, ${attrValueExpr(n.value, rw.expr)})` : attrValueExpr(n.value, rw.expr)}, ${JSON.stringify(n.skip ?? [])}, ${JSON.stringify(n.tag)}${rw === asWritten && n.where ? `, ${JSON.stringify(n.where)}` : ''})`;
22
+ if (n.kind === 'attr' && n.content)
23
+ return '""';
22
24
  if (n.kind === 'attr')
23
25
  return `__cl_attrHtml(${JSON.stringify(n.name)}, ${attrValueExpr(n.value, rw.expr)}${tagArg(n)})`;
24
26
  if (n.kind === 'if') {
@@ -36,6 +36,11 @@ export type CompileOptions = {
36
36
  collapseWhitespace?: boolean;
37
37
  loader?: string;
38
38
  hot?: string;
39
+ /**
40
+ * Vite's base path (`/docs/`): root-relative URL attributes (href, src, srcset, action…) get it, static ones written
41
+ * in, dynamic ones through `baseUrl()`. `'/'` or none: nothing changes. The Vite plugin passes it.
42
+ */
43
+ base?: string;
39
44
  /** Finds `<icon name="set:name">` icons: `(name) => resolveIcon(name, file)` from clarusjs/icons. Without it, `<icon>` is an error. */
40
45
  icon?: IconResolver;
41
46
  };
@@ -45,7 +45,7 @@ function compileParsed(parsed, source, options) {
45
45
  }
46
46
  if (options.renderImports && parsed.serverScript)
47
47
  throw new ClarusError('<script server> runs on the server only, and this component renders in the browser (a client route, or a child of an island, which re-renders it): make the route static or server, or render the component outside the island', options.file, source, parsed.serverScript.tag);
48
- const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace, icon: options.icon });
48
+ const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace, icon: options.icon, base: options.base });
49
49
  warnings.push(...ir.warnings);
50
50
  if (options.target === 'client')
51
51
  return { code: emitClient(ir, options.hot), stateful: ir.stateful, css, warnings };
@@ -62,6 +62,8 @@ export type IRNode = {
62
62
  tag: string;
63
63
  skip?: string[];
64
64
  where?: string;
65
+ content?: true;
66
+ base?: string;
65
67
  } | {
66
68
  kind: 'connect';
67
69
  expr: string;
@@ -154,4 +156,5 @@ export declare const SPREAD_REFUSED: Set<string>;
154
156
  export declare function lower(parsed: ParsedFile, file: string, source: string, options?: {
155
157
  collapseWhitespace?: boolean;
156
158
  icon?: IconResolver;
159
+ base?: string;
157
160
  }): ComponentIR;
@@ -5,12 +5,14 @@ import { iconElement } from './icon.js';
5
5
  import { ClarusError } from './errors.js';
6
6
  import { outerIndexIn } from './loops.js';
7
7
  import { FOR_IMPLICIT, importNames } from './parse.js';
8
+ import { baseUrl, isBaseAttr } from '../runtime/attrs.js';
8
9
  import { analyzeScript, providesIn, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
9
10
  const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
10
11
  export const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
11
12
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
12
13
  const iconBodies = new WeakMap();
13
14
  export function lower(parsed, file, source, options = {}) {
15
+ const base = options.base && options.base !== '/' ? options.base : undefined;
14
16
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
15
17
  const outer = outerIndexIn(parsed.nodes);
16
18
  if (outer)
@@ -455,10 +457,11 @@ export function lower(parsed, file, source, options = {}) {
455
457
  emitStatic(`<${node.tag}`);
456
458
  const elementEvents = attrs.filter((a) => a.kind === 'event');
457
459
  const dynamic = [];
460
+ let textareaValue;
458
461
  let engine = false;
459
462
  for (const a of attrs) {
460
463
  if (a.kind === 'static')
461
- emitStatic(a.value === true ? ` ${a.name}` : ` ${a.name}="${a.value}"`);
464
+ emitStatic(a.value === true ? ` ${a.name}` : ` ${a.name}="${base ? baseUrl(base, a.name, a.value) : a.value}"`);
462
465
  else if (a.kind === 'event') {
463
466
  if (!stateful)
464
467
  fail('event bindings need a <script> with state; this component is static', a.start);
@@ -481,7 +484,7 @@ export function lower(parsed, file, source, options = {}) {
481
484
  const reactive = stateful && (referencesNames(a.expr, scriptScope) || referencesNames(a.expr, loopNames));
482
485
  const skip = [...new Set(attrs.filter((x) => x !== a && x.kind !== 'event').map((x) => x.name.toLowerCase()))];
483
486
  const at = new ClarusError('', file, source, a.start);
484
- const node_ = { kind: 'attr', name: '...', value: { expr: a.expr }, reactive, index: -1, tag: node.tag, skip, ...(a.expr === '__cl_attrs' ? {} : { where: `${file}:${at.line}:${at.column}` }) };
487
+ const node_ = { kind: 'attr', name: '...', value: { expr: a.expr }, reactive, index: -1, tag: node.tag, skip, ...(a.expr === '__cl_attrs' ? {} : { where: `${file}:${at.line}:${at.column}` }), ...(base ? { base } : {}) };
485
488
  if (reactive)
486
489
  dynamic.push(node_);
487
490
  out.push(node_);
@@ -515,8 +518,14 @@ export function lower(parsed, file, source, options = {}) {
515
518
  for (const e of exprs)
516
519
  checkExpr(e.expr, file, source, e.start);
517
520
  const reactive = stateful && exprs.some((e) => referencesNames(e.expr, scriptScope) || referencesNames(e.expr, loopNames));
518
- const value = a.kind === 'prop' ? { expr: a.expr } : { parts: a.parts.map((p) => (typeof p === 'string' ? p : { expr: p.expr })) };
519
- const node_ = { kind: 'attr', name: a.name, value, reactive, index: -1, tag: node.tag };
521
+ const written = a.kind === 'prop' ? { expr: a.expr } : { parts: a.parts.map((p) => (typeof p === 'string' ? p : { expr: p.expr })) };
522
+ const value = base && isBaseAttr(a.name)
523
+ ? { expr: `__cl_baseUrl(${JSON.stringify(base)}, ${JSON.stringify(a.name)}, ${a.kind === 'prop' ? `(${a.expr})` : `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')`})` }
524
+ : written;
525
+ const content = node.tag === 'textarea' && a.name === 'value';
526
+ const node_ = { kind: 'attr', name: a.name, value, reactive, index: -1, tag: node.tag, ...(content ? { content: true } : {}) };
527
+ if (content)
528
+ textareaValue = a.kind === 'prop' ? a.expr : `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')`;
520
529
  if (reactive)
521
530
  dynamic.push(node_);
522
531
  out.push(node_);
@@ -537,6 +546,12 @@ export function lower(parsed, file, source, options = {}) {
537
546
  }
538
547
  }
539
548
  emitStatic('>');
549
+ if (textareaValue !== undefined) {
550
+ emitStatic('\n');
551
+ out.push({ kind: 'hole', expr: textareaValue, reactive: false, index: -1 });
552
+ emitStatic('</textarea>');
553
+ return;
554
+ }
540
555
  const iconBody = iconBodies.get(node);
541
556
  if (iconBody !== undefined)
542
557
  emitStatic(iconBody);
@@ -1,3 +1,9 @@
1
+ /**
2
+ * What `attrValue()` puts in place of a URL it refuses (a `javascript:` link, say): an address that goes nowhere.
3
+ * @example
4
+ * attrValue('href', 'javascript:alert(1)') === UNSAFE_URL // true
5
+ * @see https://clarusjs.com/reference/runtime#attrvalue
6
+ */
1
7
  export declare const UNSAFE_URL = "about:invalid#unsafe";
2
8
  /**
3
9
  * A class from a string (as written), an object (its truthy keys) or an array (flattened, falsy entries dropped), like
@@ -18,8 +24,35 @@ export declare function classValue(value: unknown): string;
18
24
  export declare function styleValue(value: unknown): string;
19
25
  /**
20
26
  * What an attribute should become: `null` removes it, `true` makes it a bare boolean attribute, a string is its value.
27
+ * URL attributes (`href`, `src`…) are checked: a relative URL or a safe scheme passes, anything else becomes
28
+ * `UNSAFE_URL`. The same check templates use, for packages that write attributes themselves (`@clarusjs/editor`).
29
+ * @example
30
+ * attrValue('href', '/docs') // '/docs'
31
+ * attrValue('href', 'javascript:alert(1)') // UNSAFE_URL
32
+ * attrValue('disabled', true) // true
33
+ * @see https://clarusjs.com/reference/runtime#attrvalue
21
34
  */
22
35
  export declare function attrValue(name: string, value: unknown, tag?: string): string | true | null;
36
+ /** Whether a site's base applies to this attribute's URL (srcset included). @internal The compiler asks. */
37
+ export declare const isBaseAttr: (name: string) => boolean;
38
+ /**
39
+ * A URL attribute's value with the site's base: a root-relative URL (one `/`) gets it, unless it's already under it
40
+ * (`href()` and `withBase()` give such URLs), so the base never doubles; `srcset` gets it on each candidate. Anything else (another attribute, a full or `//` URL, `#`, `?`, a
41
+ * relative path, a value that isn't a string) is returned as it is, and base `/` changes nothing.
42
+ * @internal The compiler and h() call this; apps use `withBase()` from clarusjs/navigation.
43
+ */
44
+ export declare function baseUrl(base: string, name: string, value: unknown): unknown;
45
+ /**
46
+ * `url` is already under the base path `prefix` (`/docs`): it is the prefix, or the prefix then `/`, `?` or `#`
47
+ * (`/docs/guide`, `/docs?q=1`, `/docs#top`; not `/documents`). '' (base /): every root-relative URL. @internal
48
+ */
49
+ export declare const underBase: (prefix: string, url: string) => boolean;
50
+ /**
51
+ * An attributes object (a spread, or what a component passes on to its root) with the site's base on its URL
52
+ * attributes, as baseUrl() gives each one. The same object when there's nothing to do.
53
+ * @internal The compiler calls this under a base.
54
+ */
55
+ export declare function baseAttrs(base: string, obj: unknown): unknown;
23
56
  /**
24
57
  * A spread's attributes (#405): each key with its value as attrValue gives it, except the names written on the element
25
58
  * (`skip`, lowercase), class and style (merged with the element's own), and what a spread may never set, listed in
@@ -13,6 +13,12 @@ const ANIMATION_ELEMENTS = new Set(['animate', 'set', 'animatemotion', 'animatet
13
13
  const IMAGE_ATTRS = new Set(['src', 'srcset', 'poster']);
14
14
  const SAFE_SCHEMES = new Set(['http', 'https', 'mailto', 'tel']);
15
15
  const RASTER_DATA = /^data:image\/(png|gif|jpe?g|webp|avif|bmp);/i;
16
+ /**
17
+ * What `attrValue()` puts in place of a URL it refuses (a `javascript:` link, say): an address that goes nowhere.
18
+ * @example
19
+ * attrValue('href', 'javascript:alert(1)') === UNSAFE_URL // true
20
+ * @see https://clarusjs.com/reference/runtime#attrvalue
21
+ */
16
22
  export const UNSAFE_URL = 'about:invalid#unsafe';
17
23
  /**
18
24
  * Allowlist: a relative URL, a safe scheme, or (for image attributes) a raster data: image or an object URL.
@@ -60,6 +66,13 @@ export function styleValue(value) {
60
66
  }
61
67
  /**
62
68
  * What an attribute should become: `null` removes it, `true` makes it a bare boolean attribute, a string is its value.
69
+ * URL attributes (`href`, `src`…) are checked: a relative URL or a safe scheme passes, anything else becomes
70
+ * `UNSAFE_URL`. The same check templates use, for packages that write attributes themselves (`@clarusjs/editor`).
71
+ * @example
72
+ * attrValue('href', '/docs') // '/docs'
73
+ * attrValue('href', 'javascript:alert(1)') // UNSAFE_URL
74
+ * attrValue('disabled', true) // true
75
+ * @see https://clarusjs.com/reference/runtime#attrvalue
63
76
  */
64
77
  export function attrValue(name, value, tag) {
65
78
  if (value == null)
@@ -99,6 +112,68 @@ export function attrValue(name, value, tag) {
99
112
  return UNSAFE_URL;
100
113
  return s;
101
114
  }
115
+ // Attributes whose URL a site's base applies to (Vite's base: a site at /docs/), for the compiler and h().
116
+ const BASE_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'poster', 'cite', 'data', 'xlink:href']);
117
+ const rooted = (u) => u.startsWith('/') && !u.startsWith('//');
118
+ /** Whether a site's base applies to this attribute's URL (srcset included). @internal The compiler asks. */
119
+ export const isBaseAttr = (name) => BASE_ATTRS.has(name.toLowerCase()) || name.toLowerCase() === 'srcset';
120
+ /**
121
+ * A URL attribute's value with the site's base: a root-relative URL (one `/`) gets it, unless it's already under it
122
+ * (`href()` and `withBase()` give such URLs), so the base never doubles; `srcset` gets it on each candidate. Anything else (another attribute, a full or `//` URL, `#`, `?`, a
123
+ * relative path, a value that isn't a string) is returned as it is, and base `/` changes nothing.
124
+ * @internal The compiler and h() call this; apps use `withBase()` from clarusjs/navigation.
125
+ */
126
+ export function baseUrl(base, name, value) {
127
+ if (base === '/' || typeof value !== 'string')
128
+ return value;
129
+ const n = name.toLowerCase();
130
+ const prefix = base.replace(/\/$/, '');
131
+ const add = (u) => (rooted(u) && !underBase(prefix, u) ? prefix + u : u);
132
+ if (BASE_ATTRS.has(n))
133
+ return add(value);
134
+ if (n !== 'srcset')
135
+ return value;
136
+ // As HTML reads a srcset: a URL runs to the next whitespace (commas inside it stay), commas at its end part two
137
+ // candidates, and its descriptors (1x, 640w) run to the next comma.
138
+ let out = '';
139
+ for (let i = 0; i < value.length;) {
140
+ let j = i;
141
+ while (j < value.length && /[\s,]/.test(value[j]))
142
+ j++;
143
+ out += value.slice(i, j);
144
+ if ((i = j) >= value.length)
145
+ break;
146
+ while (j < value.length && !/\s/.test(value[j]))
147
+ j++;
148
+ let url = value.slice(i, j);
149
+ const commas = /,+$/.exec(url)?.[0] ?? '';
150
+ url = url.slice(0, url.length - commas.length);
151
+ out += add(url) + commas;
152
+ i = j;
153
+ if (commas)
154
+ continue;
155
+ while (j < value.length && value[j] !== ',')
156
+ j++;
157
+ out += value.slice(i, j);
158
+ i = j;
159
+ }
160
+ return out;
161
+ }
162
+ /**
163
+ * `url` is already under the base path `prefix` (`/docs`): it is the prefix, or the prefix then `/`, `?` or `#`
164
+ * (`/docs/guide`, `/docs?q=1`, `/docs#top`; not `/documents`). '' (base /): every root-relative URL. @internal
165
+ */
166
+ export const underBase = (prefix, url) => url.startsWith(prefix) && (url.length === prefix.length || '/?#'.includes(url[prefix.length]));
167
+ /**
168
+ * An attributes object (a spread, or what a component passes on to its root) with the site's base on its URL
169
+ * attributes, as baseUrl() gives each one. The same object when there's nothing to do.
170
+ * @internal The compiler calls this under a base.
171
+ */
172
+ export function baseAttrs(base, obj) {
173
+ if (base === '/' || !obj || typeof obj !== 'object' || Array.isArray(obj))
174
+ return obj;
175
+ return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, baseUrl(base, k, v)]));
176
+ }
102
177
  const ATTR_NAME = /^[a-zA-Z_:][-a-zA-Z0-9_:.]*$/;
103
178
  /**
104
179
  * A spread's attributes (#405): each key with its value as attrValue gives it, except the names written on the element
@@ -586,8 +586,13 @@ export function attr(ctx, index, name, fn, tag) {
586
586
  const el = marked(ctx, `[data-cl-a="${index}"]`);
587
587
  if (!el)
588
588
  return;
589
+ let first = true;
589
590
  effect(() => {
590
591
  const raw = fn();
592
+ // At attach, a field already typed in (before the island's code loaded) keeps what was typed: the loader's
593
+ // replayed input event then writes it to state. Its value differs from the one the server rendered.
594
+ const typed = first && name === 'value' && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') && el.value !== el.defaultValue;
595
+ first = false;
591
596
  // <select multiple> bound to an array: each option selected when the array has its value.
592
597
  if (name === 'value' && Array.isArray(raw) && el.tagName === 'SELECT' && el.multiple) {
593
598
  const values = raw.map(String); // option values are text: [1, 2] selects "1" and "2"
@@ -601,7 +606,7 @@ export function attr(ctx, index, name, fn, tag) {
601
606
  else
602
607
  el.setAttribute(name, v === true ? '' : v);
603
608
  // A form field shows its property once someone has typed or clicked in it, not the attribute: set both.
604
- if (name === 'value' && 'value' in el) {
609
+ if (name === 'value' && 'value' in el && !typed) {
605
610
  const field = el;
606
611
  const next = v === null || v === true ? '' : v;
607
612
  // A number field showing the same number keeps what was typed ("1.0" isn't rewritten to "1" mid-typing).
@@ -2,5 +2,5 @@ export { state, derived, shared, effect, scope, onDispose, untrack, batch, type
2
2
  export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, declare, use, values, provideOn, type Hole, type Block, type Ctx } from './dom.ts';
3
3
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.ts';
4
4
  export { parse as parseIslandData } from './serialize.ts';
5
- export { classValue, styleValue } from './attrs.ts';
5
+ export { attrValue, baseAttrs, baseUrl, classValue, styleValue, UNSAFE_URL } from './attrs.ts';
6
6
  export { browser } from './env.ts';
@@ -3,5 +3,5 @@ export { state, derived, shared, effect, scope, onDispose, untrack, batch } from
3
3
  export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, declare, use, values, provideOn } from './dom.js';
4
4
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.js';
5
5
  export { parse as parseIslandData } from './serialize.js';
6
- export { classValue, styleValue } from './attrs.js';
6
+ export { attrValue, baseAttrs, baseUrl, classValue, styleValue, UNSAFE_URL } from './attrs.js';
7
7
  export { browser } from './env.js';
@@ -162,8 +162,15 @@ async function attachOne(el, load, recorded) {
162
162
  loading.delete(el);
163
163
  }
164
164
  recorded.stop();
165
- if (el.hasAttribute('data-cl-ready'))
165
+ if (el.hasAttribute('data-cl-ready')) {
166
+ // Fields filled before attach with no input to replay (form restore, autofill: the value differs from the
167
+ // server's) send one now, before a replayed submit reads state; a field typed in gets its recorded input, once.
168
+ for (const f of el.querySelectorAll('input,textarea'))
169
+ // the value check first: owner() walks siblings, too slow to run for every row's field
170
+ if (f.value !== f.defaultValue && owner(f) === el && !recorded.events.some((e) => e.target === f && e.type === 'input'))
171
+ f.dispatchEvent(new Event('input', { bubbles: true }));
166
172
  replay(recorded.events);
173
+ }
167
174
  }
168
175
  /**
169
176
  * Attach every island under `root` that isn't attached yet. Resolves once the islands that attach right away
@@ -202,3 +202,29 @@ type ParamsOf<R> = R extends keyof Routes ? Routes[R] : Record<string, string>;
202
202
  * @see https://clarusjs.com/reference/navigation#href
203
203
  */
204
204
  export declare function href<R extends RouteName>(route: R, ...params: [keyof Routes] extends [never] ? [Record<string, string>?] : keyof ParamsOf<R> extends never ? [] : [ParamsOf<R>]): string;
205
+ /**
206
+ * The path a site's own URLs start with, from Vite's base: `/docs/` gives `/docs`; `/` and a full-URL (CDN) base give
207
+ * '' (a CDN serves the assets; pages, and so links and navigations, stay on the site). @internal
208
+ */
209
+ export declare function sitePrefix(base: string): string;
210
+ /** `path` with `base` in front, when it's root-relative (one `/`). @internal withBase() and navigate() call this. */
211
+ export declare function addBase(base: string, path: string): string;
212
+ /** `url` without a leading `base`: the reverse of addBase(). @internal withoutBase() calls this. */
213
+ export declare function removeBase(base: string, url: string): string;
214
+ /**
215
+ * A root-relative path with the site's base (Vite's `base`): `withBase('/guide')` is `/docs/guide` at a site under
216
+ * `/docs/`; a path already under it is returned as it is. For URLs built in code (`fetch()`, a link from data); templates' URL attributes get the base by themselves.
217
+ * Full URLs, `//host`, `#…`, `?…` and relative paths are returned as they are.
218
+ * @example
219
+ * fetch(withBase('/api/items'))
220
+ * @see https://clarusjs.com/reference/navigation#withbase
221
+ */
222
+ export declare function withBase(path: string): string;
223
+ /**
224
+ * A URL's path without the site's base, the reverse of `withBase()`: `/docs/guide` is `/guide` at a site under
225
+ * `/docs/`, to compare a link (which has the base) with a route (which doesn't). Others are returned as they are.
226
+ * @example
227
+ * withoutBase(link.getAttribute('href')) === '/guide'
228
+ * @see https://clarusjs.com/reference/navigation#withoutbase
229
+ */
230
+ export declare function withoutBase(url: string): string;
@@ -3,6 +3,7 @@
3
3
  // over exactly like a link click; without it they are normal page loads. Island scripts also run on the server,
4
4
  // where this does nothing.
5
5
  import { effect, onDispose, state } from './signals.js';
6
+ import { underBase } from './attrs.js';
6
7
  const navigation = globalThis.navigation;
7
8
  const browser = typeof document !== 'undefined';
8
9
  /**
@@ -111,6 +112,8 @@ export function navigationState() {
111
112
  export async function navigate(to, options = {}) {
112
113
  if (!browser)
113
114
  return;
115
+ if (typeof to === 'string')
116
+ to = addBase(siteBase(), to); // a path without the site's base, as everywhere
114
117
  if (!navigation)
115
118
  return options.replace ? location.replace(String(to)) : location.assign(String(to));
116
119
  try {
@@ -292,6 +295,51 @@ export function href(route,
292
295
  // Without the generated routes, params are optional; with them, required exactly when the route has some.
293
296
  ...params) {
294
297
  const values = (params[0] ?? {});
295
- const base = (import.meta.env?.BASE_URL ?? '/').replace(/\/$/, '');
298
+ const base = sitePrefix(import.meta.env?.BASE_URL ?? '/');
296
299
  return base + route.replace(/\[([^\]]+)\]/g, (_, key) => encodeURIComponent(values[key] ?? ''));
297
300
  }
301
+ /**
302
+ * The path a site's own URLs start with, from Vite's base: `/docs/` gives `/docs`; `/` and a full-URL (CDN) base give
303
+ * '' (a CDN serves the assets; pages, and so links and navigations, stay on the site). @internal
304
+ */
305
+ export function sitePrefix(base) {
306
+ return /^https?:\/\//i.test(base) ? '' : base.replace(/\/$/, '');
307
+ }
308
+ const siteBase = () => sitePrefix(import.meta.env?.BASE_URL ?? '/') + '/';
309
+ /** `path` with `base` in front, when it's root-relative (one `/`). @internal withBase() and navigate() call this. */
310
+ export function addBase(base, path) {
311
+ const b = base.replace(/\/$/, '');
312
+ // already under it (href() gives such paths): as it is, so the base never doubles
313
+ return path.startsWith('/') && !path.startsWith('//') && !underBase(b, path) ? b + path : path;
314
+ }
315
+ /** `url` without a leading `base`: the reverse of addBase(). @internal withoutBase() calls this. */
316
+ export function removeBase(base, url) {
317
+ const b = base.replace(/\/$/, '');
318
+ if (!b)
319
+ return url;
320
+ if (!underBase(b, url))
321
+ return url;
322
+ const rest = url.slice(b.length);
323
+ return rest.startsWith('/') ? rest : '/' + rest; // '/docs?q=1' → '/?q=1'
324
+ }
325
+ /**
326
+ * A root-relative path with the site's base (Vite's `base`): `withBase('/guide')` is `/docs/guide` at a site under
327
+ * `/docs/`; a path already under it is returned as it is. For URLs built in code (`fetch()`, a link from data); templates' URL attributes get the base by themselves.
328
+ * Full URLs, `//host`, `#…`, `?…` and relative paths are returned as they are.
329
+ * @example
330
+ * fetch(withBase('/api/items'))
331
+ * @see https://clarusjs.com/reference/navigation#withbase
332
+ */
333
+ export function withBase(path) {
334
+ return addBase(siteBase(), path);
335
+ }
336
+ /**
337
+ * A URL's path without the site's base, the reverse of `withBase()`: `/docs/guide` is `/guide` at a site under
338
+ * `/docs/`, to compare a link (which has the base) with a route (which doesn't). Others are returned as they are.
339
+ * @example
340
+ * withoutBase(link.getAttribute('href')) === '/guide'
341
+ * @see https://clarusjs.com/reference/navigation#withoutbase
342
+ */
343
+ export function withoutBase(url) {
344
+ return removeBase(siteBase(), url);
345
+ }
@@ -83,7 +83,11 @@ export async function swapIn(html, title = (t) => t) {
83
83
  document.title = title(doc.title); // before islands attach: the loader announces it
84
84
  document.body.replaceWith(doc.body);
85
85
  for (const old of doc.head.querySelectorAll('script:not([src])')) {
86
+ // scripts only: data (JSON-LD, JSON) isn't run, and a module stays one
87
+ if (old.type && !/^(module|(text|application)\/javascript)$/i.test(old.type))
88
+ continue;
86
89
  const script = document.createElement('script');
90
+ script.type = old.type;
87
91
  script.textContent = old.textContent;
88
92
  document.head.append(script);
89
93
  script.remove();
@@ -1,6 +1,6 @@
1
1
  import { attrHtml } from './html.ts';
2
2
  export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml, passedHtml } from './html.ts';
3
- export { classValue, styleValue, passed } from './attrs.ts';
3
+ export { classValue, styleValue, passed, baseUrl, baseAttrs } from './attrs.ts';
4
4
  /**
5
5
  * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
6
6
  * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
@@ -2,7 +2,7 @@
2
2
  import { attrHtml, escape, HTML } from './html.js';
3
3
  import { stringify } from './serialize.js';
4
4
  export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml, passedHtml } from './html.js';
5
- export { classValue, styleValue, passed } from './attrs.js';
5
+ export { classValue, styleValue, passed, baseUrl, baseAttrs } from './attrs.js';
6
6
  export function island(name, src, props, html, state, attach, paths) {
7
7
  // Slot content that awaits (#430) makes the island's HTML a promise: wrap it once it's there.
8
8
  if (html instanceof Promise)
@@ -8,6 +8,7 @@ const FRAG = 'index.frag.html';
8
8
  const safeJson = (json) => json.replace(/</g, '\\u003c');
9
9
  const loadedStore = new AsyncLocalStorage();
10
10
  globalThis.__clLoadedStore = loadedStore;
11
+ const viewBase = (globalThis.__clViewBase ??= new AsyncLocalStorage());
11
12
  const PARAM = /^\[([A-Za-z_$][\w$]*)\]$/;
12
13
  function compile(path) {
13
14
  const keys = [];
@@ -372,6 +373,9 @@ export function createHandler(pages, options = {}) {
372
373
  return new Response(head ? null : body, { headers: { 'content-type': 'text/html; charset=utf-8' } });
373
374
  }
374
375
  }
376
+ const respond = handler.fetch;
377
+ const base = /^https?:\/\//.test(options.base ?? '/') ? '/' : (options.base ?? '/');
378
+ handler.fetch = (request) => viewBase.run(base, () => respond(request));
375
379
  return handler;
376
380
  }
377
381
  function pagePath(pathname, fragment) {
@@ -25,7 +25,7 @@ export type SiteOptions = {
25
25
  name?: string;
26
26
  image?: string;
27
27
  };
28
- export declare function renderTag([tag, attrs, content]: HeadTag): string;
28
+ export declare function renderTag([tag, attrs, content]: HeadTag, base?: string): string;
29
29
  /**
30
30
  * The full document `html` with its head completed, in order: <cl-head> tags from the page (they win), the title
31
31
  * template, site tags for keys the page left unset, canonical and social defaults for keys still unset, JSON-LD,
@@ -35,5 +35,8 @@ export declare function completeHead(html: string, mask: (html: string) => strin
35
35
  route: string;
36
36
  path: string;
37
37
  }): string;
38
- /** Vite's base as a path: an absolute base (https://cdn.example.com/docs/) counts by its pathname. */
38
+ /**
39
+ * Vite's base as the path pages live under. A full-URL base (https://cdn.example.com/docs/) moves only the assets, as
40
+ * in Vite: pages stay at the site's root, '/' (#653; the compiler, navigate() and the link checker agree).
41
+ */
39
42
  export declare function basePath(base?: string): string;
@@ -1,7 +1,8 @@
1
+ import { baseUrl } from '../runtime/attrs.js';
1
2
  import { escape, json } from '../runtime/html.js';
2
3
  const VOID = new Set(['meta', 'link', 'base']);
3
- export function renderTag([tag, attrs, content]) {
4
- const a = Object.entries(attrs).map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${escape(v)}"`)).join('');
4
+ export function renderTag([tag, attrs, content], base = '/') {
5
+ const a = Object.entries(attrs).map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${escape(baseUrl(base, k, v))}"`)).join('');
5
6
  return VOID.has(tag) && content === undefined ? `<${tag}${a}>` : `<${tag}${a}>${content ?? ''}</${tag}>`;
6
7
  }
7
8
  function key(tag) {
@@ -70,7 +71,7 @@ export function completeHead(html, mask, options, page) {
70
71
  const fill = (tag) => { if (!find(key(tag) ?? ''))
71
72
  head += tag; };
72
73
  for (const t of options.tags ?? []) {
73
- const tag = renderTag(t);
74
+ const tag = renderTag(t, options.base && !/^https?:\/\//.test(options.base) ? options.base : '/');
74
75
  if (key(tag))
75
76
  fill(tag);
76
77
  else
@@ -106,7 +107,10 @@ function social(head, title, options, page, pageSet, mask) {
106
107
  }
107
108
  const root = new URL(basePath(options.base), options.site.url.replace(/\/?$/, '/'));
108
109
  const url = new URL(`./${page.path.slice(1)}`, root).href;
109
- const absolute = (u) => (u.startsWith('/') && !u.startsWith('//') ? new URL(u.slice(1), root).href : new URL(u, url.endsWith('/') ? url : `${url}/`).href);
110
+ const prefix = basePath(options.base).replace(/\/$/, '');
111
+ const absolute = (u) => (u.startsWith('/') && !u.startsWith('//')
112
+ ? (prefix && (u === prefix || u.startsWith(prefix + '/')) ? new URL(u, root.origin).href : new URL(u.slice(1), root).href)
113
+ : new URL(u, url.endsWith('/') ? url : `${url}/`).href);
110
114
  for (const [property, value] of [['og:image', pageSet.image], ['og:url', pageSet.url]]) {
111
115
  if (relative(value))
112
116
  head = setTag(head, `<meta property="${property}" content="${escape(absolute(value))}">`, mask);
@@ -130,5 +134,5 @@ function social(head, title, options, page, pageSet, mask) {
130
134
  return head;
131
135
  }
132
136
  export function basePath(base = '/') {
133
- return /^https?:\/\//i.test(base) ? new URL(base).pathname : base;
137
+ return /^https?:\/\//i.test(base) ? '/' : base;
134
138
  }
@@ -1,4 +1,5 @@
1
1
  import { HTML } from '../runtime/html.ts';
2
+ /** @internal createHandler() calls this with its base. */
2
3
  type View = {
3
4
  render(props?: object, slots?: Record<string, string>): string | Promise<string>;
4
5
  };
@@ -1,4 +1,6 @@
1
+ import { baseUrl } from '../runtime/attrs.js';
1
2
  import { attrHtml, escape, HTML } from '../runtime/html.js';
3
+ const requestBase = () => globalThis.__clViewBase?.getStore();
2
4
  export function viewName(file) {
3
5
  return file.replace(/^.*?\/src\//, '').replace(/\.[^./]+$/, '');
4
6
  }
@@ -53,7 +55,7 @@ export async function h(name, props = {}, children = []) {
53
55
  throw new Error(`h(): "${key}" isn't an attribute name`);
54
56
  if (/^on/i.test(key) || key.toLowerCase() === 'srcdoc')
55
57
  throw new Error(`h(): "${key}" can't be set from code (event handlers and srcdoc run code); use a .tscl view`);
56
- attrs += attrHtml(key, value, tag);
58
+ attrs += attrHtml(key, baseUrl(requestBase() ?? '/', key, value), tag);
57
59
  }
58
60
  const inner = await childrenHtml(children);
59
61
  if (VOID.has(tag) && inner)
@@ -1,5 +1,5 @@
1
1
  export type LinkIssue = {
2
- kind: 'pages' | 'anchors';
2
+ kind: 'pages' | 'anchors' | 'outside';
3
3
  page: string;
4
4
  href: string;
5
5
  message: string;
@@ -43,7 +43,7 @@ const ids = (html) => new Set([...html.matchAll(/\s(?:id|name)="([^"]+)"/g)].map
43
43
  const hrefs = (html) => [...html.replace(/<!--[\s\S]*?-->/g, '').matchAll(/<a\b[^>]*?\shref="([^"]*)"/g)].map((m) => m[1].replace(/&amp;/g, '&'));
44
44
  export function checkLinks(options) {
45
45
  const { outDir } = options;
46
- const base = /^https?:\/\//.test(options.base) ? new URL(options.base).pathname : options.base;
46
+ const base = /^https?:\/\//i.test(options.base) ? '/' : options.base;
47
47
  const siteRoot = options.site ? new URL(base, options.site.replace(/\/?$/, '/')) : undefined;
48
48
  const routes = new Set(options.routes.map(trim));
49
49
  const client = new Set(options.clientRoutes.map(trim));
@@ -59,17 +59,24 @@ export function checkLinks(options) {
59
59
  const issues = [];
60
60
  for (const page of [...routes].filter((r) => !client.has(r))) {
61
61
  for (let href of hrefs(read(page))) {
62
- if (siteRoot && /^https?:/i.test(href)) {
63
- const u = new URL(href);
62
+ if (siteRoot && /^(https?:)?\/\//i.test(href)) {
63
+ const u = new URL(href, siteRoot);
64
64
  if (u.origin === siteRoot.origin && (u.pathname.startsWith(siteRoot.pathname) || `${u.pathname}/` === siteRoot.pathname)) {
65
65
  href = base + u.pathname.slice(Math.min(u.pathname.length, siteRoot.pathname.length)) + u.search + u.hash;
66
66
  }
67
+ else if (u.origin === siteRoot.origin && base !== '/') {
68
+ issues.push({ kind: 'outside', page, href, message: `${href} is outside the base ${base} (fine for another site on this origin)` });
69
+ continue;
70
+ }
67
71
  }
68
72
  if (/^[a-z][\w+.-]*:|^\/\//i.test(href) || href === '')
69
73
  continue;
70
74
  const url = new URL(href, `http://site${base}${page === '/' ? '' : page.slice(1) + '/'}`);
71
- if (!url.pathname.startsWith(base) && `${url.pathname}/` !== base)
75
+ if (!url.pathname.startsWith(base) && `${url.pathname}/` !== base) {
76
+ if (base !== '/' && href.startsWith('/'))
77
+ issues.push({ kind: 'outside', page, href, message: `${href} is outside the base ${base} (fine for another site on this origin)` });
72
78
  continue;
79
+ }
73
80
  let path = trim(decode(url.pathname.slice(base.length - 1)) || '/');
74
81
  if (path.endsWith('/index.html'))
75
82
  path = trim(path.slice(0, -'index.html'.length));
@@ -61,6 +61,7 @@ export type ClarusOptions = {
61
61
  links?: {
62
62
  pages?: LinkLevel;
63
63
  anchors?: LinkLevel;
64
+ outside?: LinkLevel;
64
65
  strict?: boolean;
65
66
  };
66
67
  /**
@@ -466,6 +466,12 @@ export default function clarusjs(options = {}) {
466
466
  pageRoutes.push(...moved);
467
467
  clientRoutes.push(...moved);
468
468
  }
469
+ const prefix = basePath(builder.config.base).replace(/\/$/, '');
470
+ if (prefix)
471
+ for (const r of [...pageRoutes, ...server.map((x) => x.route)]) {
472
+ if (r === prefix || r.startsWith(prefix + '/'))
473
+ builder.config.logger.warn(`clarusjs: route ${r} starts with the base ${builder.config.base}: links to it can't be told from links under the base; rename the route or the base`);
474
+ }
469
475
  const issues = checkLinks({
470
476
  outDir: out,
471
477
  routes: pageRoutes,
@@ -474,7 +480,7 @@ export default function clarusjs(options = {}) {
474
480
  base: builder.config.base,
475
481
  site: options.site?.url,
476
482
  });
477
- const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn' };
483
+ const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn', outside: options.links?.outside ?? 'warn' };
478
484
  const sourceOf = new Map(files.pages(builder.config.root).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
479
485
  const pattern = (route) => new RegExp(`^${route.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
480
486
  const fileOf = (page) => sourceOf.get(page) ?? [...sourceOf].find(([route]) => pattern(route).test(page))?.[1];
@@ -483,7 +489,8 @@ export default function clarusjs(options = {}) {
483
489
  if (!file)
484
490
  return page;
485
491
  const rel = relative(builder.config.root, file).split(sep).join('/');
486
- const line = readFileSync(file, 'utf8').split('\n').findIndex((l) => l.includes(href));
492
+ const written = href.startsWith(builder.config.base) ? href.slice(builder.config.base.length - 1) : href;
493
+ const line = readFileSync(file, 'utf8').split('\n').findIndex((l) => l.includes(href) || l.includes(written));
487
494
  return line === -1 ? `${rel} (${page})` : `${rel}:${line + 1}`;
488
495
  };
489
496
  const errors = [];
@@ -684,7 +691,7 @@ export default function clarusjs(options = {}) {
684
691
  const loader = componentLoaderOf(root, file) ? relative(root, file).split(sep).join('/') : undefined;
685
692
  const hot = command === 'serve' && target === 'client' ? '/cl-hot.js' : undefined;
686
693
  const layouts = files.layouts(file, root);
687
- const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot, icon: iconsFor(file), layouts, components: files.names(root) });
694
+ const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot, icon: iconsFor(file), layouts, components: files.names(root), base: /^https?:\/\//.test(base) ? '/' : base });
688
695
  if (consumer === 'server' && !renderQuery)
689
696
  for (const w of out.warnings)
690
697
  this.warn(w.message);
@@ -1,5 +1,6 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { resolve } from 'node:path';
3
+ import { basePath } from '../server/head.js';
3
4
  const xml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
4
5
  export function gitDates(root, dir) {
5
6
  const dates = new Map();
@@ -21,7 +22,7 @@ export function gitDates(root, dir) {
21
22
  return dates;
22
23
  }
23
24
  export function sitemapXml(siteUrl, base, pages) {
24
- const root = new URL(/^https?:\/\//i.test(base) ? new URL(base).pathname : base, siteUrl.replace(/\/?$/, '/'));
25
+ const root = new URL(basePath(base), siteUrl.replace(/\/?$/, '/'));
25
26
  const urls = pages.map(({ path, lastmod, images = [], alternates = [] }) => {
26
27
  const loc = new URL(`./${path.slice(1)}`, root).href;
27
28
  const date = lastmod === undefined ? '' : `<lastmod>${new Date(lastmod * 1000).toISOString().slice(0, 10)}</lastmod>`;
@@ -49,7 +50,7 @@ export function sitemapFiles(siteUrl, base, pages, max = 50_000, maxBytes = 52_4
49
50
  if (chunks.length === 1)
50
51
  return [{ file: 'sitemap.xml', xml: sitemapXml(siteUrl, base, pages) }];
51
52
  const parts = chunks.map((chunk, i) => ({ file: `sitemap-${i + 1}.xml`, xml: sitemapXml(siteUrl, base, chunk) }));
52
- const root = new URL(/^https?:\/\//i.test(base) ? new URL(base).pathname : base, siteUrl.replace(/\/?$/, '/'));
53
+ const root = new URL(basePath(base), siteUrl.replace(/\/?$/, '/'));
53
54
  const entries = parts.map((p) => `<sitemap><loc>${xml(new URL(p.file, root).href)}</loc></sitemap>\n`).join('');
54
55
  return [...parts, { file: 'sitemap.xml', xml: `<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries}</sitemapindex>\n` }];
55
56
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clarusjs",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "Clear, compiled views: templates compiled to server HTML, with JavaScript only for interactive islands. SSR, SSG and CSR from one component model, built on Vite.",
5
5
  "license": "MIT",
6
6
  "keywords": [