clarusjs 0.16.0 → 0.18.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/dist/check/generate.js +97 -8
- package/dist/cli/check.d.ts +3 -0
- package/dist/cli/check.js +55 -3
- package/dist/cli/explain.js +3 -0
- package/dist/cli/index.js +21 -3
- package/dist/cli/project.d.ts +5 -0
- package/dist/cli/project.js +1 -1
- package/dist/compiler/emit-client.js +33 -8
- package/dist/compiler/events.d.ts +9 -0
- package/dist/compiler/events.js +46 -0
- package/dist/compiler/html-expr.js +14 -7
- package/dist/compiler/index.js +32 -5
- package/dist/compiler/ir.d.ts +15 -0
- package/dist/compiler/ir.js +87 -11
- package/dist/compiler/lint.d.ts +6 -2
- package/dist/compiler/lint.js +114 -5
- package/dist/compiler/loops.d.ts +13 -0
- package/dist/compiler/loops.js +49 -0
- package/dist/compiler/parse.d.ts +23 -0
- package/dist/compiler/parse.js +149 -1
- package/dist/compiler/script.d.ts +2 -0
- package/dist/compiler/script.js +78 -1
- package/dist/forms/index.js +35 -15
- package/dist/forms/types.d.ts +7 -0
- package/dist/node/serve.d.ts +26 -0
- package/dist/node/serve.js +150 -0
- package/dist/runtime/attrs.d.ts +13 -0
- package/dist/runtime/attrs.js +13 -0
- package/dist/runtime/dom.d.ts +32 -2
- package/dist/runtime/dom.js +170 -45
- package/dist/runtime/hot.js +3 -2
- package/dist/runtime/index.d.ts +2 -2
- package/dist/runtime/index.js +2 -2
- package/dist/runtime/loader.js +26 -7
- package/dist/runtime/motion.d.ts +59 -0
- package/dist/runtime/motion.js +339 -0
- package/dist/runtime/navigate.d.ts +2 -0
- package/dist/runtime/navigate.js +7 -1
- package/dist/runtime/navigation.d.ts +44 -0
- package/dist/runtime/navigation.js +69 -3
- package/dist/runtime/signals.d.ts +2 -0
- package/dist/runtime/signals.js +31 -0
- package/dist/seo.d.ts +140 -0
- package/dist/seo.js +64 -0
- package/dist/server/handler.d.ts +1 -0
- package/dist/server/handler.js +1 -0
- package/dist/server/head.js +5 -0
- package/dist/vite/cloudflare.d.ts +3 -0
- package/dist/vite/cloudflare.js +55 -0
- package/dist/vite/env.d.ts +19 -0
- package/dist/vite/env.js +34 -0
- package/dist/vite/headers.d.ts +27 -0
- package/dist/vite/headers.js +70 -0
- package/dist/vite/manifest.d.ts +11 -1
- package/dist/vite/manifest.js +10 -1
- package/dist/vite/netlify.d.ts +5 -2
- package/dist/vite/netlify.js +4 -2
- package/dist/vite/node.d.ts +4 -0
- package/dist/vite/node.js +9 -2
- package/dist/vite/plugin.d.ts +25 -2
- package/dist/vite/plugin.js +84 -9
- package/dist/vite/vercel.d.ts +3 -0
- package/dist/vite/vercel.js +53 -0
- package/package.json +14 -1
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Navigations go through the Navigation API, so the page's navigator (fragments or the client router) takes them
|
|
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
|
-
import { onDispose, state } from './signals.js';
|
|
5
|
+
import { effect, onDispose, state } from './signals.js';
|
|
6
6
|
const navigation = globalThis.navigation;
|
|
7
7
|
const browser = typeof document !== 'undefined';
|
|
8
8
|
/**
|
|
@@ -30,6 +30,70 @@ if (browser) {
|
|
|
30
30
|
for (const type of ['popstate', 'hashchange'])
|
|
31
31
|
addEventListener(type, update);
|
|
32
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* The current page's query, as a store kept in step with `currentUrl`: `let query = shared(searchParams)`, then
|
|
35
|
+
* `query?.get('q')`. `null` on the server, like `currentUrl`. Change it with `setSearch()`.
|
|
36
|
+
* @example
|
|
37
|
+
* ```tscl
|
|
38
|
+
* <script>
|
|
39
|
+
* import { searchParams } from 'clarusjs/navigation'
|
|
40
|
+
* let query = shared(searchParams)
|
|
41
|
+
* </script>
|
|
42
|
+
* <p>Results for {{ query?.get('q') ?? 'everything' }}</p>
|
|
43
|
+
* ```
|
|
44
|
+
* @see https://clarusjs.com/guide/navigation#query-strings
|
|
45
|
+
*/
|
|
46
|
+
export const searchParams = state(currentUrl.get() ? new URLSearchParams(currentUrl.get().search) : null);
|
|
47
|
+
effect(() => {
|
|
48
|
+
const url = currentUrl.get();
|
|
49
|
+
searchParams.set(url ? new URLSearchParams(url.search) : null);
|
|
50
|
+
});
|
|
51
|
+
/**
|
|
52
|
+
* Change the current URL's query and go there: each key is set (a string or number), repeated (an array) or removed
|
|
53
|
+
* (`null`); the path, hash and other params stay. Replaces the history entry by default, as a search box or filter
|
|
54
|
+
* should (so Back leaves the page, not each keystroke); `{ replace: false }` adds one. Keeps the scroll position by
|
|
55
|
+
* default (`{ scroll: true }` goes to the top, as a new page does).
|
|
56
|
+
* @example
|
|
57
|
+
* ```ts
|
|
58
|
+
* setSearch({ q: input.value, page: null }) // a new search starts at page 1
|
|
59
|
+
* setSearch({ page: 3 }, { replace: false }) // pages are worth a Back step
|
|
60
|
+
* ```
|
|
61
|
+
* @see https://clarusjs.com/guide/navigation#query-strings
|
|
62
|
+
*/
|
|
63
|
+
export function setSearch(changes, options = {}) {
|
|
64
|
+
if (!browser)
|
|
65
|
+
return Promise.resolve();
|
|
66
|
+
const url = new URL(location.href);
|
|
67
|
+
for (const [key, value] of Object.entries(changes)) {
|
|
68
|
+
if (value === null)
|
|
69
|
+
url.searchParams.delete(key);
|
|
70
|
+
else if (!Array.isArray(value))
|
|
71
|
+
url.searchParams.set(key, String(value)); // keeps its place
|
|
72
|
+
else {
|
|
73
|
+
url.searchParams.delete(key);
|
|
74
|
+
for (const v of value)
|
|
75
|
+
url.searchParams.append(key, String(v));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return navigate(url, { replace: options.replace ?? true, state: options.state, scroll: options.scroll ?? false });
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* What `navigate(url, { state })` stored with the current history entry (`undefined` if nothing, or on the server).
|
|
82
|
+
* Kept by the browser for Back and Forward, not in the URL: for things like where the visitor came from.
|
|
83
|
+
* @example
|
|
84
|
+
* ```ts
|
|
85
|
+
* await navigate('/results', { state: { from: 'search' } })
|
|
86
|
+
* // later, on /results:
|
|
87
|
+
* const from = (navigationState() as { from?: string } | undefined)?.from
|
|
88
|
+
* ```
|
|
89
|
+
* @see https://clarusjs.com/guide/navigation#history-state
|
|
90
|
+
*/
|
|
91
|
+
export function navigationState() {
|
|
92
|
+
if (!browser)
|
|
93
|
+
return undefined;
|
|
94
|
+
const entry = navigation?.currentEntry;
|
|
95
|
+
return (entry ? entry.getState() : history.state);
|
|
96
|
+
}
|
|
33
97
|
/**
|
|
34
98
|
* Go to `to`, as a link click would: the page's navigator swaps or renders it. Resolves once the new page is shown,
|
|
35
99
|
* and also when the navigation is cancelled or a newer one replaces it (so check `currentUrl` when it matters);
|
|
@@ -50,7 +114,8 @@ export async function navigate(to, options = {}) {
|
|
|
50
114
|
if (!navigation)
|
|
51
115
|
return options.replace ? location.replace(String(to)) : location.assign(String(to));
|
|
52
116
|
try {
|
|
53
|
-
|
|
117
|
+
// scroll: false reaches the navigator (navigate.ts) as info: it keeps the scroll position for this navigation.
|
|
118
|
+
await navigation.navigate(String(to), { history: options.replace ? 'replace' : 'auto', state: options.state, info: { scroll: options.scroll ?? true } }).finished;
|
|
54
119
|
}
|
|
55
120
|
catch (err) {
|
|
56
121
|
if (err.name != 'AbortError')
|
|
@@ -161,7 +226,8 @@ if (browser) {
|
|
|
161
226
|
// A view transition: the browser snapshots this page, then the swap (which waits for this) runs inside it.
|
|
162
227
|
const start = document.startViewTransition;
|
|
163
228
|
if (step == 'swapping' && transitions && start) {
|
|
164
|
-
|
|
229
|
+
// A newer page change (Back before this one swapped) skips this transition: its ready rejects, as expected.
|
|
230
|
+
await new Promise((snapshot) => start.call(document, () => { snapshot(); return new Promise((r) => (done = r)); }).ready.catch(() => { }));
|
|
165
231
|
}
|
|
166
232
|
};
|
|
167
233
|
}
|
|
@@ -28,6 +28,8 @@ export type ReadSignal<T> = {
|
|
|
28
28
|
* @see https://clarusjs.com/reference/runtime#scope
|
|
29
29
|
*/
|
|
30
30
|
export declare function scope(fn: () => void): () => void;
|
|
31
|
+
/** Run `fn` when the wiring pass ends (now if none), in the scope it was asked from (#550). @internal */
|
|
32
|
+
export declare function afterWiring(fn: () => void): void;
|
|
31
33
|
/**
|
|
32
34
|
* Run `fn` when the enclosing scope is disposed (an island leaving the page, an @if branch or @for row going away).
|
|
33
35
|
* Outside a scope it does nothing.
|
package/dist/runtime/signals.js
CHANGED
|
@@ -18,17 +18,48 @@ export function scope(fn) {
|
|
|
18
18
|
const prev = currentScope;
|
|
19
19
|
const cleanups = [];
|
|
20
20
|
currentScope = cleanups;
|
|
21
|
+
// The outermost scope is a wiring pass: what waits for it runs at its end.
|
|
22
|
+
const outer = !after;
|
|
23
|
+
if (outer)
|
|
24
|
+
after = [];
|
|
25
|
+
let wired = false;
|
|
21
26
|
try {
|
|
22
27
|
fn();
|
|
28
|
+
wired = true;
|
|
23
29
|
}
|
|
24
30
|
finally {
|
|
25
31
|
currentScope = prev;
|
|
32
|
+
if (outer) {
|
|
33
|
+
const waiting = after;
|
|
34
|
+
after = null;
|
|
35
|
+
if (wired)
|
|
36
|
+
for (const run of waiting)
|
|
37
|
+
run();
|
|
38
|
+
}
|
|
26
39
|
}
|
|
27
40
|
const dispose = () => { for (const c of cleanups.splice(0).reverse())
|
|
28
41
|
c(); };
|
|
29
42
|
onDispose(dispose);
|
|
30
43
|
return dispose;
|
|
31
44
|
}
|
|
45
|
+
// What waits for the wiring pass that's running (null when none is).
|
|
46
|
+
let after = null;
|
|
47
|
+
/** Run `fn` when the wiring pass ends (now if none), in the scope it was asked from (#550). @internal */
|
|
48
|
+
export function afterWiring(fn) {
|
|
49
|
+
if (!after)
|
|
50
|
+
return fn();
|
|
51
|
+
const owner = currentScope;
|
|
52
|
+
after.push(() => {
|
|
53
|
+
const prev = currentScope;
|
|
54
|
+
currentScope = owner;
|
|
55
|
+
try {
|
|
56
|
+
fn();
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
currentScope = prev;
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
32
63
|
/**
|
|
33
64
|
* Run `fn` when the enclosing scope is disposed (an island leaving the page, an @if branch or @for row going away).
|
|
34
65
|
* Outside a scope it does nothing.
|
package/dist/seo.d.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A person, by name or with a link.
|
|
3
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
4
|
+
*/
|
|
5
|
+
export type PersonInput = string | {
|
|
6
|
+
name: string;
|
|
7
|
+
url?: string;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* An article or blog post. People may be names; dates may be Date objects (written as ISO strings).
|
|
11
|
+
* @example
|
|
12
|
+
* <script type="application/ld+json">{{ article({ headline: title, datePublished: date, author: 'Ada' }) }}</script>
|
|
13
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
14
|
+
*/
|
|
15
|
+
export declare function article(a: {
|
|
16
|
+
headline: string;
|
|
17
|
+
datePublished: string | Date;
|
|
18
|
+
dateModified?: string | Date;
|
|
19
|
+
author?: PersonInput | PersonInput[];
|
|
20
|
+
image?: string | string[];
|
|
21
|
+
description?: string;
|
|
22
|
+
url?: string;
|
|
23
|
+
}): {
|
|
24
|
+
'@context': 'https://schema.org';
|
|
25
|
+
'@type': "Article";
|
|
26
|
+
headline: string;
|
|
27
|
+
datePublished: string;
|
|
28
|
+
dateModified: string | undefined;
|
|
29
|
+
author: {
|
|
30
|
+
'@type': string;
|
|
31
|
+
name: string;
|
|
32
|
+
url?: string | undefined;
|
|
33
|
+
}[] | {
|
|
34
|
+
'@type': string;
|
|
35
|
+
name: string;
|
|
36
|
+
url?: string | undefined;
|
|
37
|
+
} | undefined;
|
|
38
|
+
image: string | string[] | undefined;
|
|
39
|
+
description: string | undefined;
|
|
40
|
+
url: string | undefined;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* The trail to a page, outermost first: each step's name and absolute URL.
|
|
44
|
+
* @example
|
|
45
|
+
* <script type="application/ld+json">{{ breadcrumbs([{ name: 'Docs', url: 'https://example.com/docs' }]) }}</script>
|
|
46
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
47
|
+
*/
|
|
48
|
+
export declare function breadcrumbs(steps: {
|
|
49
|
+
name: string;
|
|
50
|
+
url: string;
|
|
51
|
+
}[]): {
|
|
52
|
+
'@context': 'https://schema.org';
|
|
53
|
+
'@type': "BreadcrumbList";
|
|
54
|
+
itemListElement: {
|
|
55
|
+
'@type': string;
|
|
56
|
+
position: number;
|
|
57
|
+
name: string;
|
|
58
|
+
item: string;
|
|
59
|
+
}[];
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* A product, with an offer (price, currency, availability) and a rating.
|
|
63
|
+
* @example
|
|
64
|
+
* <script type="application/ld+json">{{ product({ name, offers: { price: 49.5, currency: 'EUR', availability: 'InStock' } }) }}</script>
|
|
65
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
66
|
+
*/
|
|
67
|
+
export declare function product(p: {
|
|
68
|
+
name: string;
|
|
69
|
+
description?: string;
|
|
70
|
+
image?: string | string[];
|
|
71
|
+
sku?: string;
|
|
72
|
+
brand?: string;
|
|
73
|
+
offers?: {
|
|
74
|
+
price: number | string;
|
|
75
|
+
currency: string;
|
|
76
|
+
availability?: 'InStock' | 'OutOfStock' | 'PreOrder' | 'BackOrder' | 'Discontinued';
|
|
77
|
+
url?: string;
|
|
78
|
+
};
|
|
79
|
+
rating?: {
|
|
80
|
+
value: number;
|
|
81
|
+
count: number;
|
|
82
|
+
};
|
|
83
|
+
}): {
|
|
84
|
+
'@context': 'https://schema.org';
|
|
85
|
+
'@type': "Product";
|
|
86
|
+
name: string;
|
|
87
|
+
description: string | undefined;
|
|
88
|
+
image: string | string[] | undefined;
|
|
89
|
+
sku: string | undefined;
|
|
90
|
+
brand: {
|
|
91
|
+
'@type': string;
|
|
92
|
+
name: string;
|
|
93
|
+
} | undefined;
|
|
94
|
+
offers: {
|
|
95
|
+
'@type': string;
|
|
96
|
+
price: string | number;
|
|
97
|
+
priceCurrency: string;
|
|
98
|
+
availability: string | undefined;
|
|
99
|
+
url: string | undefined;
|
|
100
|
+
} | undefined;
|
|
101
|
+
aggregateRating: {
|
|
102
|
+
'@type': string;
|
|
103
|
+
ratingValue: number;
|
|
104
|
+
reviewCount: number;
|
|
105
|
+
} | undefined;
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* The organization behind a site: its name, address, logo and profiles elsewhere (`sameAs`).
|
|
109
|
+
* @example
|
|
110
|
+
* clarusjs({ head: { jsonLd: organization({ name: 'Acme', url: 'https://acme.example' }) } })
|
|
111
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
112
|
+
*/
|
|
113
|
+
export declare function organization(o: {
|
|
114
|
+
name: string;
|
|
115
|
+
url: string;
|
|
116
|
+
logo?: string;
|
|
117
|
+
sameAs?: string[];
|
|
118
|
+
}): {
|
|
119
|
+
'@context': 'https://schema.org';
|
|
120
|
+
'@type': "Organization";
|
|
121
|
+
name: string;
|
|
122
|
+
url: string;
|
|
123
|
+
logo: string | undefined;
|
|
124
|
+
sameAs: string[] | undefined;
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* The site itself: its name and address (search engines show the name).
|
|
128
|
+
* @example
|
|
129
|
+
* clarusjs({ head: { jsonLd: website({ name: 'Acme docs', url: 'https://acme.example/docs/' }) } })
|
|
130
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
131
|
+
*/
|
|
132
|
+
export declare function website(w: {
|
|
133
|
+
name: string;
|
|
134
|
+
url: string;
|
|
135
|
+
}): {
|
|
136
|
+
'@context': 'https://schema.org';
|
|
137
|
+
'@type': "WebSite";
|
|
138
|
+
name: string;
|
|
139
|
+
url: string;
|
|
140
|
+
};
|
package/dist/seo.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
const thing = (type) => ({ '@context': 'https://schema.org', '@type': type });
|
|
2
|
+
const absolute = (where, url) => {
|
|
3
|
+
if (!/^https?:\/\//.test(url))
|
|
4
|
+
throw new Error(`clarusjs/seo: ${where} "${url}" is relative: JSON-LD needs absolute URLs (https://…)`);
|
|
5
|
+
return url;
|
|
6
|
+
};
|
|
7
|
+
const urls = (where, value) => (Array.isArray(value) ? value.map((u, i) => absolute(`${where}[${i}]`, u)) : absolute(where, value));
|
|
8
|
+
const date = (where, value) => {
|
|
9
|
+
if (value instanceof Date)
|
|
10
|
+
return value.toISOString();
|
|
11
|
+
if (Number.isNaN(Date.parse(value)))
|
|
12
|
+
throw new Error(`clarusjs/seo: ${where} "${value}" is not a date`);
|
|
13
|
+
return value;
|
|
14
|
+
};
|
|
15
|
+
const person = (where, p) => (typeof p === 'string' ? { '@type': 'Person', name: p } : { '@type': 'Person', name: p.name, ...(p.url ? { url: absolute(`${where}.url`, p.url) } : {}) });
|
|
16
|
+
const defined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
17
|
+
export function article(a) {
|
|
18
|
+
return defined({
|
|
19
|
+
...thing('Article'),
|
|
20
|
+
headline: a.headline,
|
|
21
|
+
datePublished: date('article.datePublished', a.datePublished),
|
|
22
|
+
dateModified: a.dateModified === undefined ? undefined : date('article.dateModified', a.dateModified),
|
|
23
|
+
author: a.author === undefined ? undefined : Array.isArray(a.author) ? a.author.map((p, i) => person(`article.author[${i}]`, p)) : person('article.author', a.author),
|
|
24
|
+
image: a.image === undefined ? undefined : urls('article.image', a.image),
|
|
25
|
+
description: a.description,
|
|
26
|
+
url: a.url === undefined ? undefined : absolute('article.url', a.url),
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
export function breadcrumbs(steps) {
|
|
30
|
+
return {
|
|
31
|
+
...thing('BreadcrumbList'),
|
|
32
|
+
itemListElement: steps.map((s, i) => ({ '@type': 'ListItem', position: i + 1, name: s.name, item: absolute(`breadcrumbs[${i}].url`, s.url) })),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export function product(p) {
|
|
36
|
+
return defined({
|
|
37
|
+
...thing('Product'),
|
|
38
|
+
name: p.name,
|
|
39
|
+
description: p.description,
|
|
40
|
+
image: p.image === undefined ? undefined : urls('product.image', p.image),
|
|
41
|
+
sku: p.sku,
|
|
42
|
+
brand: p.brand === undefined ? undefined : { '@type': 'Brand', name: p.brand },
|
|
43
|
+
offers: p.offers === undefined ? undefined : defined({
|
|
44
|
+
'@type': 'Offer',
|
|
45
|
+
price: p.offers.price,
|
|
46
|
+
priceCurrency: p.offers.currency,
|
|
47
|
+
availability: p.offers.availability === undefined ? undefined : `https://schema.org/${p.offers.availability}`,
|
|
48
|
+
url: p.offers.url === undefined ? undefined : absolute('product.offers.url', p.offers.url),
|
|
49
|
+
}),
|
|
50
|
+
aggregateRating: p.rating === undefined ? undefined : { '@type': 'AggregateRating', ratingValue: p.rating.value, reviewCount: p.rating.count },
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
export function organization(o) {
|
|
54
|
+
return defined({
|
|
55
|
+
...thing('Organization'),
|
|
56
|
+
name: o.name,
|
|
57
|
+
url: absolute('organization.url', o.url),
|
|
58
|
+
logo: o.logo === undefined ? undefined : absolute('organization.logo', o.logo),
|
|
59
|
+
sameAs: o.sameAs === undefined ? undefined : o.sameAs.map((u, i) => absolute(`organization.sameAs[${i}]`, u)),
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
export function website(w) {
|
|
63
|
+
return { ...thing('WebSite'), name: w.name, url: absolute('website.url', w.url) };
|
|
64
|
+
}
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -184,6 +184,7 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
|
|
|
184
184
|
fetch(request: Request): Promise<Response>;
|
|
185
185
|
routes: string[];
|
|
186
186
|
serverRoutes: string[];
|
|
187
|
+
base: string;
|
|
187
188
|
paths(): Promise<string[]>;
|
|
188
189
|
hasLoader(route: string): Promise<boolean>;
|
|
189
190
|
readsCookies(route: string): Promise<boolean>;
|
package/dist/server/handler.js
CHANGED
|
@@ -111,6 +111,7 @@ export function createHandler(pages, options = {}) {
|
|
|
111
111
|
}
|
|
112
112
|
const handler = {
|
|
113
113
|
routes: routes.map((r) => r.path).sort(),
|
|
114
|
+
base: options.base ?? '/',
|
|
114
115
|
serverRoutes: [...routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path), ...endpointRoutes.map((r) => r.path)].sort(),
|
|
115
116
|
isServerPath(pathname) {
|
|
116
117
|
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
package/dist/server/head.js
CHANGED
|
@@ -55,6 +55,11 @@ export function completeHead(html, mask, options, page) {
|
|
|
55
55
|
const find = (k) => spansOf(head, mask).find((t) => key(t.text) === k);
|
|
56
56
|
const rawTitle = /<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(own.find((t) => key(t) === 'title') ?? find('title')?.text ?? '')?.[1] ?? '';
|
|
57
57
|
const title = find('title');
|
|
58
|
+
for (let i = 0; i < own.length; i++) {
|
|
59
|
+
if (key(own[i]) !== 'title' || !/^<title\b[^>]*\sdata-cl-template\b/i.test(own[i]))
|
|
60
|
+
continue;
|
|
61
|
+
own[i] = own[i].replace(/\s+data-cl-template(?:="[^"]*")?/i, '').replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title\s*>)/i, (_, a, text, b) => options.titleTemplate ? a + escape(options.titleTemplate).replace('%s', () => text) + b : a + text + b);
|
|
62
|
+
}
|
|
58
63
|
if (options.titleTemplate && title && !own.some((t) => key(t) === 'title')) {
|
|
59
64
|
const wrapped = title.text.replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title\s*>)/i, (_, a, text, b) => a + escape(options.titleTemplate).replace('%s', () => text) + b);
|
|
60
65
|
head = head.slice(0, title.at) + wrapped + head.slice(title.at + title.text.length);
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** '/account/[id]' → ['/account/*']; '/api/hello' → ['/api/hello', '/api/hello/'] (Pages routes: * only). */
|
|
2
|
+
export declare function cloudflareRoutes(route: string, prefix: string, fragments?: boolean): string[];
|
|
3
|
+
export declare function writeCloudflareWorker(client: string, server: string, serverRoutes: string[], base: string, fragments?: boolean): void;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { cpSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { headersCode } from './headers.js';
|
|
4
|
+
const WORKER = '_worker.js';
|
|
5
|
+
export function cloudflareRoutes(route, prefix, fragments = false) {
|
|
6
|
+
const segments = route.split('/');
|
|
7
|
+
const at = segments.findIndex((seg) => /^\[[^\]]+\]$/.test(seg));
|
|
8
|
+
if (at !== -1)
|
|
9
|
+
return [`${prefix}${segments.slice(0, at).join('/')}/*`];
|
|
10
|
+
const path = route === '/' ? '' : route;
|
|
11
|
+
return [...(path ? [`${prefix}${path}`] : []), `${prefix}${path}/`, ...(fragments ? [`${prefix}${path}/index.frag.html`] : [])];
|
|
12
|
+
}
|
|
13
|
+
export function writeCloudflareWorker(client, server, serverRoutes, base, fragments = false) {
|
|
14
|
+
const worker = resolve(client, WORKER);
|
|
15
|
+
const routesFile = resolve(client, '_routes.json');
|
|
16
|
+
rmSync(worker, { recursive: true, force: true });
|
|
17
|
+
rmSync(routesFile, { force: true });
|
|
18
|
+
rmSync(resolve(client, '.assetsignore'), { force: true });
|
|
19
|
+
const prefix = base.replace(/\/$/, '');
|
|
20
|
+
if (!serverRoutes.length && !prefix)
|
|
21
|
+
return;
|
|
22
|
+
cpSync(server, resolve(worker, 'server'), { recursive: true });
|
|
23
|
+
writeFileSync(resolve(worker, 'index.js'), [
|
|
24
|
+
"// Generated by clarusjs: server routes on Cloudflare (Pages' _worker.js, or a Worker with static assets).",
|
|
25
|
+
"import handler from './server/index.mjs'",
|
|
26
|
+
`const base = ${JSON.stringify(prefix)}`,
|
|
27
|
+
headersCode(client),
|
|
28
|
+
'export default {',
|
|
29
|
+
' async fetch(request, env) {',
|
|
30
|
+
' const url = new URL(request.url)',
|
|
31
|
+
" // One path: runs of / collapsed, and a 400 for what decoding would turn into another path (dot segments, \\).",
|
|
32
|
+
" const path = url.pathname.replace(/\\/{2,}/g, '/')",
|
|
33
|
+
' let decoded',
|
|
34
|
+
" try { decoded = decodeURIComponent(path) } catch { return new Response('Bad Request: malformed URL', { status: 400 }) }",
|
|
35
|
+
" if (/\\\\|(^|\\/)\\.\\.?(\\/|$)/.test(decoded)) return new Response('Bad Request: malformed URL', { status: 400 })",
|
|
36
|
+
" const inBase = !base ? path : path === base ? '/' : path.startsWith(base + '/') ? path.slice(base.length) : undefined",
|
|
37
|
+
' if (inBase === undefined) return env.ASSETS.fetch(request)',
|
|
38
|
+
' url.pathname = inBase',
|
|
39
|
+
' // Not a server route: a static file, which sits at the folder\'s root, so without the base (a Worker without',
|
|
40
|
+
' // run_worker_first, a site under a base, or more server routes than _routes.json can list).',
|
|
41
|
+
" // _headers applied here by the path asked: Cloudflare would match them (written with the base) against the path",
|
|
42
|
+
" // without it, and may not apply them to what a worker returns. Only headers the file lacks are added.",
|
|
43
|
+
' if (!handler.isServerPath(inBase)) return withHeaders(await env.ASSETS.fetch(new Request(url, request)), path)',
|
|
44
|
+
' const response = await handler.fetch(new Request(url, request))',
|
|
45
|
+
' return withHeaders(response, path)',
|
|
46
|
+
' },',
|
|
47
|
+
'}',
|
|
48
|
+
'',
|
|
49
|
+
].join('\n'));
|
|
50
|
+
const listed = serverRoutes.flatMap((r) => cloudflareRoutes(r, prefix, fragments));
|
|
51
|
+
const wanted = prefix ? [prefix, `${prefix}/*`] : listed;
|
|
52
|
+
const include = wanted.length > 100 || wanted.some((r) => r.length > 100) ? ['/*'] : wanted;
|
|
53
|
+
writeFileSync(routesFile, JSON.stringify({ version: 1, include, exclude: [] }));
|
|
54
|
+
writeFileSync(resolve(client, '.assetsignore'), `${WORKER}\n_routes.json\n`);
|
|
55
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** @see https://clarusjs.com/guide/environment-variables */
|
|
2
|
+
export type EnvOption = {
|
|
3
|
+
server?: string[];
|
|
4
|
+
browser?: string[];
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Takes back what an earlier load put in process.env (a dev server restarted, a second build in one process): those
|
|
8
|
+
* values are the plugin's, not the host's. Call it before Vite's loadEnv, which prefers process.env to the files. A
|
|
9
|
+
* value the host changed since stays the host's.
|
|
10
|
+
*/
|
|
11
|
+
export declare function releaseServerEnv(): void;
|
|
12
|
+
/**
|
|
13
|
+
* `all`: Vite's loadEnv(mode, dir, '') (`.env`, `.env.local`, `.env.[mode]`, `.env.[mode].local`). Puts every variable
|
|
14
|
+
* without a browser prefix in process.env for server code, unless already set (the host's value wins). Then checks the
|
|
15
|
+
* `env` option: a missing variable is the returned message.
|
|
16
|
+
*/
|
|
17
|
+
export declare function loadServerEnv(all: Record<string, string>, prefixes: string[], required?: EnvOption): string | undefined;
|
|
18
|
+
/** .clarusjs/env.d.ts: the named variables as strings, on import.meta.env and process.env. */
|
|
19
|
+
export declare function writeEnvTypes(root: string, env: EnvOption): void;
|
package/dist/vite/env.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
const loaded = new Map();
|
|
4
|
+
export function releaseServerEnv() {
|
|
5
|
+
for (const [key, value] of loaded)
|
|
6
|
+
if (process.env[key] === value)
|
|
7
|
+
delete process.env[key];
|
|
8
|
+
loaded.clear();
|
|
9
|
+
}
|
|
10
|
+
export function loadServerEnv(all, prefixes, required = {}) {
|
|
11
|
+
for (const [key, value] of Object.entries(all)) {
|
|
12
|
+
if (!prefixes.some((p) => key.startsWith(p)) && process.env[key] === undefined) {
|
|
13
|
+
process.env[key] = value;
|
|
14
|
+
loaded.set(key, value);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
for (const key of required.browser ?? []) {
|
|
18
|
+
if (!prefixes.some((p) => key.startsWith(p)))
|
|
19
|
+
throw new Error(`clarusjs: env.browser: '${key}' doesn't start with ${prefixes.join(' or ')}, so Vite won't send it to the browser`);
|
|
20
|
+
}
|
|
21
|
+
const missing = [
|
|
22
|
+
...(required.server ?? []).filter((k) => !process.env[k]).map((k) => `${k} (server)`),
|
|
23
|
+
...(required.browser ?? []).filter((k) => !all[k]).map((k) => `${k} (browser)`),
|
|
24
|
+
];
|
|
25
|
+
return missing.length ? `clarusjs: missing environment variables: ${missing.join(', ')}. Set them in the environment or a .env file (https://clarusjs.com/guide/environment-variables)` : undefined;
|
|
26
|
+
}
|
|
27
|
+
export function writeEnvTypes(root, env) {
|
|
28
|
+
const lines = (keys = [], indent) => keys.map((k) => `${indent}readonly ${k}: string\n`).join('');
|
|
29
|
+
mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
|
|
30
|
+
writeFileSync(resolve(root, '.clarusjs/env.d.ts'), "// Generated by clarusjs from the env option: the variables the build requires. Add it to your tsconfig's include.\n" +
|
|
31
|
+
`interface ImportMetaEnv {\n${lines(env.browser, ' ')}}\n` +
|
|
32
|
+
'interface ImportMeta {\n readonly env: ImportMetaEnv\n}\n' +
|
|
33
|
+
`declare namespace NodeJS {\n interface ProcessEnv {\n${lines(env.server, ' ')} }\n}\n`);
|
|
34
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export type HeaderRules = Record<string, Record<string, string>>;
|
|
2
|
+
/** Sent unless `headers: false`: safe for any site. A CSP depends on the site, so there's none by default. */
|
|
3
|
+
export declare const defaultHeaders: (assetsDir: string) => HeaderRules;
|
|
4
|
+
export declare function checkHeaders(headers: HeaderRules): void;
|
|
5
|
+
/** The default headers, then the site's, as _headers lines under the base prefix ('' or '/docs'), after public/'s. */
|
|
6
|
+
export declare function writeHeaders(out: string, headers: HeaderRules, prefix: string, assetsDir: string): void;
|
|
7
|
+
export type ParsedRule = {
|
|
8
|
+
regex: RegExp;
|
|
9
|
+
headers: [string, string][];
|
|
10
|
+
};
|
|
11
|
+
/** _headers text → rules: a pattern line, then indented `Name: value` lines. Comments (#) and blank lines skipped. */
|
|
12
|
+
export declare function parseHeaders(text: string): ParsedRule[];
|
|
13
|
+
/**
|
|
14
|
+
* '/a//b/../c/' → '/a/c/': the path a file lookup resolves to (backslashes too, as Windows reads them). Match rules
|
|
15
|
+
* against this, so a path written another way gets the headers of the file it serves.
|
|
16
|
+
*/
|
|
17
|
+
export declare const canonical: (path: string) => string;
|
|
18
|
+
/** Every matching rule's headers, in order; a name set by several is joined with ', ', as Netlify and Cloudflare do. */
|
|
19
|
+
export declare function headersFor(rules: ParsedRule[], pathname: string): Map<string, string>;
|
|
20
|
+
/** dist/client/_headers, parsed; none when it doesn't exist. */
|
|
21
|
+
export declare function readHeaders(dir: string): ParsedRule[];
|
|
22
|
+
/**
|
|
23
|
+
* JavaScript for a generated function or worker: `withHeaders(response, path)` adds the _headers rules matching `path`
|
|
24
|
+
* (as written, or decoded) to a response that doesn't set them itself. For hosts that apply _headers to static files
|
|
25
|
+
* only (Netlify, Cloudflare Pages).
|
|
26
|
+
*/
|
|
27
|
+
export declare function headersCode(dir: string): string;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { posix, resolve } from 'node:path';
|
|
3
|
+
export const defaultHeaders = (assetsDir) => ({
|
|
4
|
+
'/*': { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' },
|
|
5
|
+
[`/${assetsDir}/*`]: { 'Cache-Control': 'public, max-age=31536000, immutable' },
|
|
6
|
+
});
|
|
7
|
+
export function checkHeaders(headers) {
|
|
8
|
+
for (const [pattern, set] of Object.entries(headers)) {
|
|
9
|
+
if (!pattern.startsWith('/'))
|
|
10
|
+
throw new Error(`clarusjs: headers['${pattern}']: patterns start with /`);
|
|
11
|
+
for (const [name, value] of Object.entries(set)) {
|
|
12
|
+
if (/[\r\n]/.test(pattern + name + value) || !name.trim())
|
|
13
|
+
throw new Error(`clarusjs: headers['${pattern}']['${name}']: names and values are one line`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function writeHeaders(out, headers, prefix, assetsDir) {
|
|
18
|
+
checkHeaders(headers);
|
|
19
|
+
const rules = [...Object.entries(defaultHeaders(assetsDir)), ...Object.entries(headers)];
|
|
20
|
+
const lines = rules.map(([pattern, set]) => `${prefix}${pattern}\n${Object.entries(set).map(([k, v]) => ` ${k}: ${v}\n`).join('')}`);
|
|
21
|
+
const file = resolve(out, '_headers');
|
|
22
|
+
writeFileSync(file, (existsSync(file) ? readFileSync(file, 'utf8').replace(/\n?$/, '\n') : '') + lines.join(''));
|
|
23
|
+
}
|
|
24
|
+
export function parseHeaders(text) {
|
|
25
|
+
const rules = [];
|
|
26
|
+
for (const line of text.split(/\r?\n/)) {
|
|
27
|
+
if (!line.trim() || line.trim().startsWith('#'))
|
|
28
|
+
continue;
|
|
29
|
+
if (!/^\s/.test(line)) {
|
|
30
|
+
const source = line.trim().split('/').map((seg) => seg.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/^:\w+$/, '[^/]+')).join('/');
|
|
31
|
+
rules.push({ regex: new RegExp(`^${source}${source.endsWith('/') ? '' : '/?'}$`, 'i'), headers: [] });
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
const at = line.indexOf(':');
|
|
35
|
+
if (at > 0 && rules.length)
|
|
36
|
+
rules.at(-1).headers.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return rules;
|
|
40
|
+
}
|
|
41
|
+
export const canonical = (path) => posix.normalize(`/${path}`.replace(/\\/g, '/'));
|
|
42
|
+
export function headersFor(rules, pathname) {
|
|
43
|
+
const out = new Map();
|
|
44
|
+
for (const rule of rules) {
|
|
45
|
+
if (!rule.regex.test(pathname))
|
|
46
|
+
continue;
|
|
47
|
+
for (const [name, value] of rule.headers) {
|
|
48
|
+
const key = name.toLowerCase();
|
|
49
|
+
out.set(key, out.has(key) ? `${out.get(key)}, ${value}` : value);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
export function readHeaders(dir) {
|
|
55
|
+
const file = resolve(dir, '_headers');
|
|
56
|
+
return existsSync(file) ? parseHeaders(readFileSync(file, 'utf8')) : [];
|
|
57
|
+
}
|
|
58
|
+
export function headersCode(dir) {
|
|
59
|
+
const rules = readHeaders(dir).map((rule) => [rule.regex.source, rule.headers]);
|
|
60
|
+
return [
|
|
61
|
+
`const rules = ${JSON.stringify(rules)}.map(([src, headers]) => [new RegExp(src, 'i'), headers])`,
|
|
62
|
+
'function withHeaders(response, path) {',
|
|
63
|
+
' let decoded = path',
|
|
64
|
+
' try { decoded = decodeURIComponent(path) } catch {}',
|
|
65
|
+
' const headers = new Headers(response.headers)',
|
|
66
|
+
' for (const [regex, set] of rules) if (regex.test(decoded) || regex.test(path)) for (const [name, value] of set) if (!response.headers.has(name)) headers.set(name, headers.has(name) ? `${headers.get(name)}, ${value}` : value)',
|
|
67
|
+
' return new Response(response.body, { status: response.status, statusText: response.statusText, headers })',
|
|
68
|
+
'}',
|
|
69
|
+
].join('\n');
|
|
70
|
+
}
|
package/dist/vite/manifest.d.ts
CHANGED
|
@@ -34,6 +34,16 @@ export type RouteInfo = {
|
|
|
34
34
|
initialGzip: number;
|
|
35
35
|
};
|
|
36
36
|
css: string[];
|
|
37
|
+
/** Its config and folder layouts (#456), outermost first, from the root (`src/pages/+layout.tscl`); none: left out. */
|
|
38
|
+
layouts?: string[];
|
|
39
|
+
/** Its folders' +guard.ts (#457), outer first; none: left out. */
|
|
40
|
+
guards?: string[];
|
|
41
|
+
};
|
|
42
|
+
/** A page's layouts and guards, by its route as its file names it (`/blog/[slug]`). */
|
|
43
|
+
export type RouteParts = {
|
|
44
|
+
route: string;
|
|
45
|
+
layouts: string[];
|
|
46
|
+
guards: string[];
|
|
37
47
|
};
|
|
38
48
|
/**
|
|
39
49
|
* The built site's route manifest (`dist/clarusjs-manifest.json`).
|
|
@@ -61,4 +71,4 @@ export declare function writeManifest(distDir: string, routes: string[], base: s
|
|
|
61
71
|
route: string;
|
|
62
72
|
loader: boolean;
|
|
63
73
|
cookies?: boolean;
|
|
64
|
-
}[]): Manifest;
|
|
74
|
+
}[], parts?: RouteParts[]): Manifest;
|
package/dist/vite/manifest.js
CHANGED
|
@@ -52,7 +52,7 @@ export function describeRoute(route, html, opts) {
|
|
|
52
52
|
const css = [...html.matchAll(/<link\b[^>]*rel="stylesheet"[^>]*>/g)].map((m) => attrsOf(m[0]).href).filter(Boolean);
|
|
53
53
|
return { mode: opts.client ? 'client' : 'static', html: routeToFile(route), loader: opts.loaded ? 'build' : null, islands, js: { files: all, gzip: sum(all), initialGzip: sum(initial) }, css };
|
|
54
54
|
}
|
|
55
|
-
export function writeManifest(distDir, routes, base, loaded = [], server = []) {
|
|
55
|
+
export function writeManifest(distDir, routes, base, loaded = [], server = [], parts = []) {
|
|
56
56
|
const client = resolve(distDir, 'client');
|
|
57
57
|
const chunks = JSON.parse(readFileSync(resolve(client, '.vite/manifest.json'), 'utf8'));
|
|
58
58
|
const sizes = new Map();
|
|
@@ -73,6 +73,15 @@ export function writeManifest(distDir, routes, base, loaded = [], server = []) {
|
|
|
73
73
|
for (const { route, loader, cookies } of server) {
|
|
74
74
|
manifest.routes[route] = { mode: 'server', html: null, loader: loader ? 'request' : null, ...(cookies ? { cookies: true } : {}), islands: [], js: { files: [], gzip: 0, initialGzip: 0 }, css: [] };
|
|
75
75
|
}
|
|
76
|
+
const params = (route) => route.split('[').length;
|
|
77
|
+
const table = [...parts].sort((a, b) => params(a.route) - params(b.route) || b.route.split('/').length - a.route.split('/').length).map((p) => ({ p: p.route, r: p.route }));
|
|
78
|
+
for (const [route, info] of Object.entries(manifest.routes)) {
|
|
79
|
+
const found = parts.find((p) => p.route === route) ?? parts.find((p) => p.route === matchRoute(table, route)?.r);
|
|
80
|
+
if (found?.layouts.length)
|
|
81
|
+
info.layouts = found.layouts;
|
|
82
|
+
if (found?.guards.length)
|
|
83
|
+
info.guards = found.guards;
|
|
84
|
+
}
|
|
76
85
|
writeFileSync(resolve(distDir, 'clarusjs-manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
77
86
|
return manifest;
|
|
78
87
|
}
|