clarusjs 0.19.1 → 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.
- package/README.md +1 -1
- package/dist/check/generate.js +124 -25
- package/dist/cli/index.js +17 -0
- package/dist/cli/migrate-files.d.ts +5 -0
- package/dist/cli/migrate-files.js +22 -0
- package/dist/cli/migrate.d.ts +8 -0
- package/dist/cli/migrate.js +317 -0
- package/dist/compiler/emit-client.js +7 -4
- package/dist/compiler/emit-server.js +10 -3
- package/dist/compiler/factories.d.ts +38 -0
- package/dist/compiler/factories.js +273 -0
- package/dist/compiler/html-expr.d.ts +4 -0
- package/dist/compiler/html-expr.js +5 -1
- package/dist/compiler/index.js +8 -9
- package/dist/compiler/ir.d.ts +13 -0
- package/dist/compiler/ir.js +41 -12
- package/dist/compiler/jsdoc.d.ts +15 -0
- package/dist/compiler/jsdoc.js +81 -0
- package/dist/compiler/lint.js +9 -4
- package/dist/compiler/parse.d.ts +35 -9
- package/dist/compiler/parse.js +77 -8
- package/dist/compiler/script.d.ts +15 -5
- package/dist/compiler/script.js +112 -18
- package/dist/compiler/shared.d.ts +5 -0
- package/dist/compiler/shared.js +5 -3
- package/dist/compiler/strip-types.d.ts +20 -0
- package/dist/compiler/strip-types.js +148 -0
- package/dist/forms/index.js +26 -5
- package/dist/runtime/context.d.ts +39 -0
- package/dist/runtime/context.js +4 -0
- package/dist/runtime/fragments.js +6 -2
- package/dist/runtime/index.d.ts +1 -0
- package/dist/runtime/index.js +1 -0
- package/dist/runtime/navigate.js +2 -1
- package/dist/runtime/signals.d.ts +11 -6
- package/dist/runtime/signals.js +12 -3
- package/dist/vite/base-clash.d.ts +9 -0
- package/dist/vite/base-clash.js +54 -0
- package/dist/vite/build-app.d.ts +5 -0
- package/dist/vite/build-app.js +185 -0
- package/dist/vite/dev-server.d.ts +5 -0
- package/dist/vite/dev-server.js +67 -0
- package/dist/vite/graph.d.ts +45 -0
- package/dist/vite/graph.js +125 -0
- package/dist/vite/hmr.d.ts +19 -0
- package/dist/vite/hmr.js +53 -0
- package/dist/vite/links.d.ts +2 -0
- package/dist/vite/links.js +2 -0
- package/dist/vite/options.d.ts +147 -0
- package/dist/vite/options.js +1 -0
- package/dist/vite/output.d.ts +25 -0
- package/dist/vite/output.js +49 -0
- package/dist/vite/plugin.d.ts +4 -150
- package/dist/vite/plugin.js +68 -624
- package/dist/vite/preview.d.ts +3 -0
- package/dist/vite/preview.js +100 -0
- package/dist/vite/server-entry.d.ts +18 -0
- package/dist/vite/server-entry.js +83 -0
- package/dist/vite/shared.d.ts +34 -0
- package/dist/vite/shared.js +47 -0
- package/dist/vite/styles.d.ts +16 -0
- package/dist/vite/styles.js +56 -0
- package/package.json +6 -4
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { Parser } from 'acorn';
|
|
2
|
+
import { tsPlugin } from '@sveltejs/acorn-typescript';
|
|
3
|
+
const TS = Parser.extend(tsPlugin());
|
|
4
|
+
const TYPE_KEYS = new Set(['typeAnnotation', 'returnType', 'typeParameters', 'typeArguments']);
|
|
5
|
+
const NEEDS_CODE = {
|
|
6
|
+
TSEnumDeclaration: 'an enum (use a union of strings, or an object with as const)',
|
|
7
|
+
TSModuleDeclaration: 'a namespace (use a module)',
|
|
8
|
+
TSParameterProperty: 'a constructor parameter property (assign it in the constructor)',
|
|
9
|
+
TSImportEqualsDeclaration: 'import … = require(…)',
|
|
10
|
+
TSExportAssignment: 'export =',
|
|
11
|
+
};
|
|
12
|
+
function names(p) {
|
|
13
|
+
if (!p)
|
|
14
|
+
return [];
|
|
15
|
+
if (p.type === 'Identifier')
|
|
16
|
+
return [p.name];
|
|
17
|
+
if (p.type === 'ObjectPattern')
|
|
18
|
+
return p.properties.flatMap((x) => names(x.type === 'RestElement' ? x.argument : x.value));
|
|
19
|
+
if (p.type === 'ArrayPattern')
|
|
20
|
+
return p.elements.flatMap((x) => names(x));
|
|
21
|
+
if (p.type === 'AssignmentPattern')
|
|
22
|
+
return names(p.left);
|
|
23
|
+
if (p.type === 'RestElement')
|
|
24
|
+
return names(p.argument);
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
export class StripError extends Error {
|
|
28
|
+
pos;
|
|
29
|
+
constructor(message, pos) { super(message); this.pos = pos; }
|
|
30
|
+
}
|
|
31
|
+
export function stripTypes(code) {
|
|
32
|
+
let ast;
|
|
33
|
+
try {
|
|
34
|
+
ast = TS.parse(code, { ecmaVersion: 'latest', sourceType: 'module', locations: true });
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
throw new StripError(`script: ${e.message.replace(/ \(\d+:\d+\)$/, '')}`, e.pos ?? 0);
|
|
38
|
+
}
|
|
39
|
+
const out = code.split('');
|
|
40
|
+
const blank = (from, to) => { for (let i = from; i < to; i++)
|
|
41
|
+
if (out[i] !== '\n')
|
|
42
|
+
out[i] = ' '; };
|
|
43
|
+
const typeImports = [];
|
|
44
|
+
const commaAfter = (from) => {
|
|
45
|
+
for (let i = from; i < code.length;) {
|
|
46
|
+
if (/\s/.test(code[i]))
|
|
47
|
+
i++;
|
|
48
|
+
else if (code.startsWith('/*', i)) {
|
|
49
|
+
const e = code.indexOf('*/', i + 2);
|
|
50
|
+
i = e === -1 ? code.length : e + 2;
|
|
51
|
+
}
|
|
52
|
+
else if (code.startsWith('//', i)) {
|
|
53
|
+
const n = code.indexOf('\n', i);
|
|
54
|
+
i = n === -1 ? code.length : n;
|
|
55
|
+
}
|
|
56
|
+
else
|
|
57
|
+
return code[i] === ',' ? i : -1;
|
|
58
|
+
}
|
|
59
|
+
return -1;
|
|
60
|
+
};
|
|
61
|
+
const blankSpecifiers = (specs, all) => {
|
|
62
|
+
for (const s of specs) {
|
|
63
|
+
const after = commaAfter(s.end);
|
|
64
|
+
if (after !== -1) {
|
|
65
|
+
blank(s.start, after + 1);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const prev = all[all.indexOf(s) - 1];
|
|
69
|
+
const before = prev ? commaAfter(prev.end) : -1;
|
|
70
|
+
blank(s.start, s.end);
|
|
71
|
+
if (before !== -1 && out[before] === ',')
|
|
72
|
+
blank(before, before + 1);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const visit = (node, parent) => {
|
|
76
|
+
if (NEEDS_CODE[node.type] && !node.declare)
|
|
77
|
+
throw new StripError(`TypeScript that needs generated code isn't supported in a <script lang="ts">: ${NEEDS_CODE[node.type]}`, node.start);
|
|
78
|
+
if (node.abstract || node.accessibility || node.override || (node.readonly && parent?.type === 'ClassBody') || node.decorators?.length) {
|
|
79
|
+
throw new StripError('class modifiers (public, private, protected, readonly, abstract, override) and decorators aren\'t supported in a <script lang="ts">', node.start);
|
|
80
|
+
}
|
|
81
|
+
if (node.type === 'TSInterfaceDeclaration' || node.type === 'TSTypeAliasDeclaration' || node.type === 'TSDeclareFunction' || (node.declare && node.type !== 'PropertyDefinition') || ((node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') && node.exportKind === 'type')) {
|
|
82
|
+
return blank(node.start, node.end);
|
|
83
|
+
}
|
|
84
|
+
if (node.type === 'ImportDeclaration') {
|
|
85
|
+
if (node.importKind === 'type') {
|
|
86
|
+
typeImports.push({ text: code.slice(node.start, node.end), start: node.start });
|
|
87
|
+
return blank(node.start, node.end);
|
|
88
|
+
}
|
|
89
|
+
const types = node.specifiers.filter((s) => s.importKind === 'type');
|
|
90
|
+
if (types.length)
|
|
91
|
+
typeImports.push({ text: `import type { ${types.map((s) => code.slice(s.start, s.end).replace(/^type\s+/, '')).join(', ')} } from ${code.slice(node.source.start, node.source.end)}`, start: node.start });
|
|
92
|
+
blankSpecifiers(types, node.specifiers);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (node.type === 'ExportNamedDeclaration' && node.specifiers?.length)
|
|
96
|
+
blankSpecifiers(node.specifiers.filter((s) => s.exportKind === 'type'), node.specifiers);
|
|
97
|
+
if (node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression')
|
|
98
|
+
blank(node.expression.end, node.end);
|
|
99
|
+
else if (node.type === 'TSNonNullExpression')
|
|
100
|
+
blank(node.end - 1, node.end);
|
|
101
|
+
else if (node.type === 'TSTypeAssertion')
|
|
102
|
+
blank(node.start, node.expression.start);
|
|
103
|
+
if ((node.type === 'Identifier' && node.optional) || (node.type === 'VariableDeclarator' && node.definite)) {
|
|
104
|
+
const at = node.type === 'Identifier' ? node.start + node.name.length : node.id.start + (node.id.name?.length ?? 0);
|
|
105
|
+
const mark = code.slice(at).search(/[?!]/);
|
|
106
|
+
if (mark !== -1)
|
|
107
|
+
blank(at + mark, at + mark + 1);
|
|
108
|
+
}
|
|
109
|
+
if (node.implements?.length) {
|
|
110
|
+
const first = node.implements[0];
|
|
111
|
+
blank(code.lastIndexOf('implements', first.start), node.implements.at(-1).end);
|
|
112
|
+
}
|
|
113
|
+
for (const key of Object.keys(node)) {
|
|
114
|
+
if (key === 'loc')
|
|
115
|
+
continue;
|
|
116
|
+
const value = node[key];
|
|
117
|
+
const children = Array.isArray(value) ? value : [value];
|
|
118
|
+
for (const child of children) {
|
|
119
|
+
if (!child || typeof child.type !== 'string')
|
|
120
|
+
continue;
|
|
121
|
+
if (TYPE_KEYS.has(key) && child.type.startsWith('TS'))
|
|
122
|
+
blank(child.start, child.end);
|
|
123
|
+
else if (key === 'implements')
|
|
124
|
+
continue;
|
|
125
|
+
else if (!(node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression' || node.type === 'TSTypeAssertion') || key === 'expression')
|
|
126
|
+
visit(child, node);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
visit(ast);
|
|
131
|
+
const top = ast.body.map((s) => (s.type === 'ExportNamedDeclaration' && s.declaration ? s.declaration : s));
|
|
132
|
+
const values = top.flatMap((s) => (s.type === 'VariableDeclaration' ? s.declarations.flatMap((d) => names(d.id)) : (s.type === 'FunctionDeclaration' || s.type === 'ClassDeclaration') && s.id ? [s.id.name] : []));
|
|
133
|
+
const outer = new Map(ast.body.filter((s) => s.type === 'ExportNamedDeclaration' && s.declaration).map((s) => [s.declaration, s]));
|
|
134
|
+
const decls = top.filter((s) => s.type === 'TSInterfaceDeclaration' || s.type === 'TSTypeAliasDeclaration').map((s) => { const w = outer.get(s) ?? s; return { name: s.id.name, text: code.slice(w.start, w.end), start: w.start }; });
|
|
135
|
+
const word = (w) => new RegExp(`(?<![\\w$.])${w.replace(/\$/g, '\\$')}(?![\\w$])`);
|
|
136
|
+
const stays = new Set(decls.filter((d) => values.some((v) => new RegExp(`\\btypeof\\s+${v.replace(/\$/g, '\\$')}(?![\\w$])`).test(d.text))).map((d) => d.name));
|
|
137
|
+
for (let grew = true; grew;) {
|
|
138
|
+
grew = false;
|
|
139
|
+
for (const d of decls)
|
|
140
|
+
if (!stays.has(d.name) && [...stays].some((s) => word(s).test(d.text.slice(d.text.indexOf(d.name) + d.name.length)))) {
|
|
141
|
+
stays.add(d.name);
|
|
142
|
+
grew = true;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const typeDecls = decls.filter((d) => !stays.has(d.name)).map(({ text, start }) => ({ text, start }));
|
|
146
|
+
const stayingExports = [...outer].filter(([d]) => stays.has(d.id?.name)).map(([, s]) => s.start);
|
|
147
|
+
return { code: out.join(''), typeImports, typeDecls, stayingExports };
|
|
148
|
+
}
|
package/dist/forms/index.js
CHANGED
|
@@ -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
|
-
|
|
29
|
+
let at = here;
|
|
30
|
+
while (part?.startsWith('@')) {
|
|
30
31
|
const [model, ...rest] = part.slice(1).split('.');
|
|
31
|
-
const island = owner(
|
|
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('
|
|
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
|
-
|
|
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]);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A context's name, with its value's type (type checking only). Provide with it, `provide(tabs, { value })`, and read
|
|
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
|
|
5
|
+
*/
|
|
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). */
|
|
11
|
+
readonly __clContext?: T;
|
|
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
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A typed context key, to export from a `.ts` module that the providing and the reading components both import.
|
|
23
|
+
* `{ public: true }` lets islands read it: an island's context is written into the page (its HTML), so it's opt-in, on
|
|
24
|
+
* the key, where the type is; a component without a script reads any context.
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* // src/context.ts
|
|
28
|
+
* import { contextKey } from 'clarusjs/runtime'
|
|
29
|
+
* export const tabsKey = contextKey<{ value: string }>('tabs')
|
|
30
|
+
* export const themeKey = contextKey<'light' | 'dark'>('theme', { public: true }) // islands may read it
|
|
31
|
+
* ```
|
|
32
|
+
* @see https://clarusjs.com/reference/runtime#contextkey
|
|
33
|
+
*/
|
|
34
|
+
export declare function contextKey<T>(name: string, options: {
|
|
35
|
+
public: true;
|
|
36
|
+
}): PublicContextKey<T>;
|
|
37
|
+
export declare function contextKey<T>(name: string, options?: {
|
|
38
|
+
public?: false;
|
|
39
|
+
}): ContextKey<T>;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// Typed context keys: one name and one type shared by the components that provide a value and those that read it.
|
|
2
|
+
export function contextKey(name, options) {
|
|
3
|
+
return options?.public === true ? { name, public: true } : { name }; // exactly true: a stray "false" isn't consent
|
|
4
|
+
}
|
|
@@ -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
|
}
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -4,3 +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, type PublicContextKey } from './context.ts';
|
package/dist/runtime/index.js
CHANGED
|
@@ -5,3 +5,4 @@ export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './
|
|
|
5
5
|
export { parse as parseIslandData } from './serialize.js';
|
|
6
6
|
export { attrValue, baseAttrs, baseUrl, classValue, styleValue, UNSAFE_URL } from './attrs.js';
|
|
7
7
|
export { browser } from './env.js';
|
|
8
|
+
export { contextKey } from './context.js';
|
package/dist/runtime/navigate.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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
|
|
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.
|
package/dist/runtime/signals.js
CHANGED
|
@@ -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
|
+
}
|