clarusjs 0.4.0 → 0.6.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.d.ts +17 -1
- package/dist/check/generate.js +73 -3
- package/dist/cli/check.js +16 -6
- package/dist/cli/explain.js +13 -3
- package/dist/compiler/emit-server.d.ts +1 -1
- package/dist/compiler/emit-server.js +2 -2
- package/dist/compiler/index.d.ts +5 -0
- package/dist/compiler/index.js +1 -1
- package/dist/runtime/fragments.d.ts +5 -0
- package/dist/runtime/fragments.js +59 -0
- package/dist/runtime/loader.js +12 -1
- package/dist/runtime/router.d.ts +15 -0
- package/dist/runtime/router.js +101 -0
- package/dist/server/handler.d.ts +33 -0
- package/dist/server/handler.js +229 -10
- package/dist/server/modes.d.ts +6 -0
- package/dist/server/modes.js +28 -0
- package/dist/server/views.d.ts +17 -0
- package/dist/server/views.js +23 -0
- package/dist/vite/build.d.ts +10 -1
- package/dist/vite/build.js +38 -5
- package/dist/vite/manifest.d.ts +15 -4
- package/dist/vite/manifest.js +21 -4
- package/dist/vite/netlify.d.ts +4 -0
- package/dist/vite/netlify.js +50 -0
- package/dist/vite/plugin.d.ts +10 -1
- package/dist/vite/plugin.js +127 -17
- package/package.json +5 -1
package/dist/server/handler.js
CHANGED
|
@@ -1,29 +1,207 @@
|
|
|
1
|
-
|
|
1
|
+
import { modeFor } from './modes.js';
|
|
2
|
+
import { stringify } from '../runtime/serialize.js';
|
|
3
|
+
const DATA = '__data.json';
|
|
4
|
+
const FRAG = 'index.frag.html';
|
|
5
|
+
/** JSON that is safe inside a <script> element and in any HTML context: '<' never appears raw. */
|
|
6
|
+
const safeJson = (json) => json.replace(/</g, '\\u003c');
|
|
7
|
+
/** A whole path segment that is a parameter: [id], [$id]. Anything else, like v[2], is literal text. */
|
|
8
|
+
const PARAM = /^\[([A-Za-z_$][\w$]*)\]$/;
|
|
9
|
+
/** '/users/[id]' → keys ['id'] and a RegExp that captures each segment. */
|
|
10
|
+
function compile(path) {
|
|
11
|
+
const keys = [];
|
|
12
|
+
const source = path.split('/').map((seg) => {
|
|
13
|
+
const m = PARAM.exec(seg);
|
|
14
|
+
if (!m)
|
|
15
|
+
return seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
16
|
+
keys.push(m[1]);
|
|
17
|
+
return '([^/]+)';
|
|
18
|
+
}).join('/');
|
|
19
|
+
return { keys, regex: new RegExp(`^${source}$`) };
|
|
20
|
+
}
|
|
2
21
|
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.tscl' → '/about' */
|
|
3
22
|
export function routeFromFile(file) {
|
|
4
23
|
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.tscl$/, '').replace(/\/index$/, '');
|
|
5
24
|
return path || '/';
|
|
6
25
|
}
|
|
7
26
|
export function createHandler(pages, options = {}) {
|
|
8
|
-
|
|
27
|
+
// Static routes first, then dynamic ones with more fixed segments first: /users/new beats /users/[id].
|
|
28
|
+
const routes = Object.entries(pages)
|
|
29
|
+
.map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
|
|
30
|
+
.sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
|
|
31
|
+
const data = options.data ?? {};
|
|
32
|
+
const modes = options.modes ?? {};
|
|
9
33
|
const loaderUrl = options.loaderUrl ?? '/cl-loader.js';
|
|
34
|
+
function match(pathname) {
|
|
35
|
+
for (const route of routes) {
|
|
36
|
+
const m = route.regex.exec(pathname);
|
|
37
|
+
if (!m)
|
|
38
|
+
continue;
|
|
39
|
+
const params = {};
|
|
40
|
+
try {
|
|
41
|
+
route.keys.forEach((key, i) => { params[key] = decodeURIComponent(m[i + 1]); });
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return null; // a malformed %-escape names no page
|
|
45
|
+
}
|
|
46
|
+
return { route, params };
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
// entries() per route, asked once: prerendering and requests see the same list. null when there is none.
|
|
51
|
+
const entriesCache = new Map();
|
|
52
|
+
function entriesOf(route) {
|
|
53
|
+
if (!entriesCache.has(route)) {
|
|
54
|
+
const file = `/${route.file.replace(/\.tscl$/, '.load.ts')}`;
|
|
55
|
+
entriesCache.set(route, (async () => {
|
|
56
|
+
const mod = data[file] ? await data[file]() : undefined;
|
|
57
|
+
return mod?.entries ? await mod.entries() : null;
|
|
58
|
+
})());
|
|
59
|
+
}
|
|
60
|
+
return entriesCache.get(route);
|
|
61
|
+
}
|
|
62
|
+
// Without entries() a route isn't restricted here (the build reports it).
|
|
63
|
+
async function listed(route, params) {
|
|
64
|
+
const list = await entriesOf(route);
|
|
65
|
+
return !list || list.some((entry) => route.keys.every((key) => entry[key] === params[key]));
|
|
66
|
+
}
|
|
10
67
|
return {
|
|
11
|
-
routes:
|
|
68
|
+
routes: routes.map((r) => r.path).sort(),
|
|
69
|
+
/** Routes rendered per request ('server' mode), as their files name them. */
|
|
70
|
+
serverRoutes: routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path).sort(),
|
|
71
|
+
/** Whether a URL path belongs to a server route (what a host must send to this handler instead of a file). */
|
|
72
|
+
isServerPath(pathname) {
|
|
73
|
+
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
74
|
+
// <page>/index.frag.html belongs to that page when it exists; otherwise it is an ordinary path.
|
|
75
|
+
const owner = options.fragments && pathname.endsWith(`/${FRAG}`) ? match(trim(pathname.slice(0, -FRAG.length - 1) || '/')) : null;
|
|
76
|
+
const found = owner ?? match(trim(pathname));
|
|
77
|
+
return Boolean(found && modeFor(found.route.path, modes) === 'server');
|
|
78
|
+
},
|
|
79
|
+
/** Whether a route (as its file names it) has a load(). */
|
|
80
|
+
async hasLoader(path) {
|
|
81
|
+
const route = routes.find((r) => r.path === path);
|
|
82
|
+
const file = route && `/${route.file.replace(/\.tscl$/, '.load.ts')}`;
|
|
83
|
+
return Boolean(file && data[file] && typeof (await data[file]()).load === 'function');
|
|
84
|
+
},
|
|
85
|
+
/** Every concrete path to prerender: static routes as they are, dynamic ones from their entries(). */
|
|
86
|
+
async paths() {
|
|
87
|
+
const out = [];
|
|
88
|
+
for (const route of routes) {
|
|
89
|
+
const mode = modeFor(route.path, modes);
|
|
90
|
+
if (mode === 'server')
|
|
91
|
+
continue;
|
|
92
|
+
const add = (path) => {
|
|
93
|
+
out.push(path);
|
|
94
|
+
// A client page's data, fetched by the router: written next to its shell.
|
|
95
|
+
if (mode === 'client')
|
|
96
|
+
out.push(path === '/' ? `/${DATA}` : `${path}/${DATA}`);
|
|
97
|
+
// A static page's fragment, for fragment navigation.
|
|
98
|
+
else if (options.fragments)
|
|
99
|
+
out.push(path === '/' ? `/${FRAG}` : `${path}/${FRAG}`);
|
|
100
|
+
};
|
|
101
|
+
if (!route.keys.length) {
|
|
102
|
+
add(route.path);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const dataFile = route.file.replace(/\.tscl$/, '.load.ts');
|
|
106
|
+
const list = await entriesOf(route);
|
|
107
|
+
if (!list)
|
|
108
|
+
throw new Error(`${route.path} is a dynamic route: export entries() from ${dataFile} to list the pages to prerender`);
|
|
109
|
+
for (const params of list) {
|
|
110
|
+
add(route.path.split('/').map((seg) => {
|
|
111
|
+
const key = PARAM.exec(seg)?.[1];
|
|
112
|
+
if (key === undefined)
|
|
113
|
+
return seg;
|
|
114
|
+
const value = params[key];
|
|
115
|
+
// Each value fills one path segment and names a folder in the build: never empty, '.' or '..'.
|
|
116
|
+
// Path separators on any OS ('/', '\\') and NUL could step out of that folder once the segment is decoded.
|
|
117
|
+
// __data.json and index.frag.html are a page's data and fragment files, so they can't also name a page.
|
|
118
|
+
if (typeof value !== 'string' || value === '' || value === '.' || value === '..' || value === DATA || value === FRAG || /[/\\\0]/.test(value)) {
|
|
119
|
+
throw new Error(`${dataFile}: entries() gave ${JSON.stringify(value)} for "${key}"; each value must be a non-empty string without "/" or "\\", and not ".", "..", "${DATA}" or "${FRAG}"`);
|
|
120
|
+
}
|
|
121
|
+
return encodeURIComponent(value);
|
|
122
|
+
}).join('/'));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return out.sort();
|
|
126
|
+
},
|
|
12
127
|
async fetch(request) {
|
|
13
128
|
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
14
129
|
return new Response('Method Not Allowed', { status: 405 });
|
|
15
130
|
const pathname = new URL(request.url).pathname;
|
|
16
131
|
// '/guide/x/' is the same page as '/guide/x', in dev as on a static host.
|
|
17
|
-
const
|
|
132
|
+
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
133
|
+
// <client route>/__data.json is that page's props, for the router. Only for a client route: anywhere else the
|
|
134
|
+
// path is an ordinary page path (a server route may well have an [id] of "__data.json").
|
|
135
|
+
let found = match(trim(pathname));
|
|
136
|
+
let wantsData = false;
|
|
137
|
+
if (pathname.endsWith(`/${DATA}`)) {
|
|
138
|
+
const owner = match(trim(pathname.slice(0, -DATA.length - 1) || '/'));
|
|
139
|
+
if (owner && modeFor(owner.route.path, modes) === 'client') {
|
|
140
|
+
found = owner;
|
|
141
|
+
wantsData = true;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// <static or server route>/index.frag.html: that page's fragment, for fragment navigation.
|
|
145
|
+
let wantsFrag = false;
|
|
146
|
+
if (options.fragments && !wantsData && pathname.endsWith(`/${FRAG}`)) {
|
|
147
|
+
const owner = match(trim(pathname.slice(0, -FRAG.length - 1) || '/'));
|
|
148
|
+
if (owner && modeFor(owner.route.path, modes) !== 'client') {
|
|
149
|
+
found = owner;
|
|
150
|
+
wantsFrag = true;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
18
153
|
const head = request.method === 'HEAD';
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
154
|
+
const notFound = () => new Response(head ? null : 'Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
155
|
+
const mode = found && modeFor(found.route.path, modes);
|
|
156
|
+
if (!found)
|
|
157
|
+
return notFound();
|
|
158
|
+
// A prerendered dynamic route only has the pages its entries() lists, as on a static host.
|
|
159
|
+
if (mode !== 'server' && found.route.keys.length && !(await listed(found.route, found.params)))
|
|
160
|
+
return notFound();
|
|
161
|
+
if (mode === 'client' && !wantsData) {
|
|
162
|
+
// In matching order (static before dynamic, as on the server): the router takes the first match.
|
|
163
|
+
const client = options.client ?? {};
|
|
164
|
+
const prefix = (options.base ?? '/').replace(/\/$/, '');
|
|
165
|
+
const table = routes.filter((r) => client[r.path]).map((r) => ({ p: (prefix + r.path).replace(/(.)\/$/, '$1'), r: client[r.path] }));
|
|
166
|
+
const shell = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
|
|
167
|
+
`<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes">${safeJson(JSON.stringify(table))}</script>` +
|
|
168
|
+
`<script type="module" src="${loaderUrl}"></script><script type="module" src="${options.routerUrl ?? '/cl-router.js'}"></script>` +
|
|
169
|
+
'</head><body><noscript>This page is rendered in the browser and needs JavaScript.</noscript></body></html>';
|
|
170
|
+
return new Response(head ? null : shell, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
171
|
+
}
|
|
172
|
+
let props = found.params;
|
|
173
|
+
const dataFile = found.route.file.replace(/\.tscl$/, '.load.ts');
|
|
174
|
+
const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
|
|
175
|
+
if (mod?.load) {
|
|
176
|
+
let loaded;
|
|
177
|
+
try {
|
|
178
|
+
loaded = await mod.load({ params: found.params, request });
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
return failure(`${dataFile}: load() failed: ${err?.message ?? err}`);
|
|
182
|
+
}
|
|
183
|
+
if (loaded === null || typeof loaded !== 'object' || Array.isArray(loaded)) {
|
|
184
|
+
return failure(`${dataFile}: load() must return an object of page inputs, got ${Array.isArray(loaded) ? 'an array' : loaded === null ? 'null' : typeof loaded}`);
|
|
185
|
+
}
|
|
186
|
+
;
|
|
187
|
+
globalThis.__clLoaderRan = true; // recorded by prerender for the manifest
|
|
188
|
+
props = { ...found.params, ...loaded };
|
|
189
|
+
}
|
|
190
|
+
if (wantsData) {
|
|
191
|
+
return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
|
|
192
|
+
}
|
|
193
|
+
const html = (await found.route.load()).render(props);
|
|
194
|
+
if (wantsFrag)
|
|
195
|
+
return new Response(head ? null : toFragment(html), { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
22
196
|
const visible = maskComments(html);
|
|
23
197
|
const hasIslands = visible.includes('<cl-island ');
|
|
24
|
-
// Only pages with islands get a script, and only the loader; it fetches each island's own chunk.
|
|
25
|
-
|
|
26
|
-
const
|
|
198
|
+
// Only pages with islands get a script, and only the loader; it fetches each island's own chunk. With fragment
|
|
199
|
+
// navigation every page gets the navigation script instead, which brings the loader for islands that arrive.
|
|
200
|
+
const nav = options.fragments === true;
|
|
201
|
+
const style = hasIslands || nav ? '<style>cl-island{display:contents}</style>' : ''; // islands never affect layout
|
|
202
|
+
const script = nav
|
|
203
|
+
? `<script type="module" src="${options.navUrl ?? '/cl-nav.js'}"></script>`
|
|
204
|
+
: hasIslands ? `<script type="module" src="${loaderUrl}"></script>` : '';
|
|
27
205
|
const body = /<html[\s>]/i.test(visible)
|
|
28
206
|
? fullDocument(html, style, script)
|
|
29
207
|
: `<!doctype html><html><head><meta charset="utf-8"><title>clarusjs</title>${style}</head><body>${html}${script}</body></html>`;
|
|
@@ -31,6 +209,47 @@ export function createHandler(pages, options = {}) {
|
|
|
31
209
|
},
|
|
32
210
|
};
|
|
33
211
|
}
|
|
212
|
+
/** A 500 that tells the visitor nothing internal; the details go to the server log (and the build's output). */
|
|
213
|
+
function failure(message) {
|
|
214
|
+
console.error(`[clarusjs] ${message}`);
|
|
215
|
+
return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* A page's fragment: its <title>, then the element marked data-cl-swap (the region fragment navigation replaces), or
|
|
219
|
+
* its <body> when nothing is marked. Comments are ignored when looking; nested tags of the same name are balanced.
|
|
220
|
+
*/
|
|
221
|
+
export function toFragment(html) {
|
|
222
|
+
// Comments and raw-text contents (scripts, styles, textareas, the title) can hold tag-shaped text: blank them out.
|
|
223
|
+
const masked = maskComments(html).replace(/(<(script|style|textarea|title)\b[^>]*>)([\s\S]*?)(<\/\2\s*>)/gi, (_, open, _tag, body, close) => open + ' '.repeat(body.length) + close);
|
|
224
|
+
const title = /<title\b[^>]*>[\s\S]*?<\/title\s*>/i.exec(masked);
|
|
225
|
+
const titleHtml = title ? html.slice(title.index, title.index + title[0].length) : '<title>clarusjs</title>';
|
|
226
|
+
// The first start tag that carries a data-cl-swap attribute (boolean or with a value), attributes parsed properly.
|
|
227
|
+
const tags = /<([a-zA-Z][\w-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/g;
|
|
228
|
+
let marked = null;
|
|
229
|
+
for (let m = tags.exec(masked); m; m = tags.exec(masked)) {
|
|
230
|
+
const names = [...m[2].matchAll(/\s+([^\s"'>/=]+)(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?/g)].map((a) => a[1].toLowerCase());
|
|
231
|
+
if (names.includes('data-cl-swap')) {
|
|
232
|
+
marked = m;
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (marked) {
|
|
237
|
+
const tag = marked[1].toLowerCase();
|
|
238
|
+
const same = new RegExp(`<(/?)${tag}(?=[\\s>/])`, 'gi');
|
|
239
|
+
same.lastIndex = marked.index;
|
|
240
|
+
let depth = 0;
|
|
241
|
+
for (let m = same.exec(masked); m; m = same.exec(masked)) {
|
|
242
|
+
depth += m[1] ? -1 : 1;
|
|
243
|
+
if (depth === 0)
|
|
244
|
+
return titleHtml + html.slice(marked.index, masked.indexOf('>', m.index) + 1);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const open = /<body\b[^>]*>/i.exec(masked);
|
|
248
|
+
const close = masked.lastIndexOf('</body>');
|
|
249
|
+
if (!open || close === -1)
|
|
250
|
+
return `${titleHtml}<body>${html}</body>`;
|
|
251
|
+
return titleHtml + html.slice(open.index, close) + '</body>';
|
|
252
|
+
}
|
|
34
253
|
/** Same length as `html`, with every HTML comment blanked out, so positions found in it are valid in `html`. */
|
|
35
254
|
function maskComments(html) {
|
|
36
255
|
return html.replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length));
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type Mode = 'static' | 'server' | 'client';
|
|
2
|
+
export type ModeTable = Record<string, string>;
|
|
3
|
+
/** Throws on an unknown mode or a malformed pattern, naming it. */
|
|
4
|
+
export declare function checkModes(table: ModeTable): void;
|
|
5
|
+
/** The mode of a route (as its file names it, e.g. '/account/[id]'): the most specific matching pattern wins. */
|
|
6
|
+
export declare function modeFor(route: string, table: ModeTable): Mode;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Per-route rendering modes: when each route renders. 'static' at build (the default), 'server' per request,
|
|
2
|
+
// 'client' in the browser (the server sends a shell; the router renders the page from its data).
|
|
3
|
+
const MODES = ['static', 'server', 'client'];
|
|
4
|
+
/** Throws on an unknown mode or a malformed pattern, naming it. */
|
|
5
|
+
export function checkModes(table) {
|
|
6
|
+
for (const [pattern, mode] of Object.entries(table)) {
|
|
7
|
+
if (!pattern.startsWith('/'))
|
|
8
|
+
throw new Error(`clarusjs: route pattern "${pattern}" must start with /`);
|
|
9
|
+
if (pattern.slice(0, -1).includes('*') || (pattern.endsWith('*') && !pattern.endsWith('/*'))) {
|
|
10
|
+
throw new Error(`clarusjs: route pattern "${pattern}" may only use * as its last segment`);
|
|
11
|
+
}
|
|
12
|
+
if (!MODES.includes(mode))
|
|
13
|
+
throw new Error(`clarusjs: routes['${pattern}'] is "${mode}"; use 'static', 'server' or 'client'`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** The mode of a route (as its file names it, e.g. '/account/[id]'): the most specific matching pattern wins. */
|
|
17
|
+
export function modeFor(route, table) {
|
|
18
|
+
let best;
|
|
19
|
+
for (const [pattern, mode] of Object.entries(table)) {
|
|
20
|
+
const folder = pattern.endsWith('/*') ? pattern.slice(0, -2) : undefined;
|
|
21
|
+
const hit = folder !== undefined ? route === (folder || '/') || route.startsWith(`${folder}/`) : route === pattern;
|
|
22
|
+
// An exact pattern beats a folder of the same length.
|
|
23
|
+
const length = folder !== undefined ? folder.length : pattern.length + 0.5;
|
|
24
|
+
if (hit && (!best || length > best.length))
|
|
25
|
+
best = { length, mode: mode };
|
|
26
|
+
}
|
|
27
|
+
return best?.mode ?? 'static';
|
|
28
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
type View = {
|
|
2
|
+
render(props?: object): string;
|
|
3
|
+
};
|
|
4
|
+
type Registry = Record<string, () => Promise<View>>;
|
|
5
|
+
/** View name → inputs. Filled in by the generated .clarusjs/views.d.ts (declaration merging). */
|
|
6
|
+
export interface Views {
|
|
7
|
+
}
|
|
8
|
+
/** Without the generated registry any name is accepted; with it, only real views. */
|
|
9
|
+
export type ViewName = [keyof Views] extends [never] ? string : Extract<keyof Views, string>;
|
|
10
|
+
export type ViewProps<N> = N extends keyof Views ? Views[N] : Record<string, unknown>;
|
|
11
|
+
/** '/src/components/pill.tscl' → 'components/pill' */
|
|
12
|
+
export declare function viewName(file: string): string;
|
|
13
|
+
/** Called by the server entry with import.meta.glob('/src/**\/*.tscl'). */
|
|
14
|
+
export declare function registerViews(files: Registry): void;
|
|
15
|
+
/** Render a view to HTML. Its props are checked against its inputs once `clarusjs check` has generated the registry. */
|
|
16
|
+
export declare function render<N extends ViewName>(name: N, props: ViewProps<N>): Promise<string>;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// render(name, props): any view under src/ rendered to HTML from server code (a loader, an endpoint, a script that
|
|
2
|
+
// imports the built server). The server entry registers the views; `clarusjs check` writes .clarusjs/views.d.ts,
|
|
3
|
+
// which types each name with that view's inputs.
|
|
4
|
+
/** '/src/components/pill.tscl' → 'components/pill' */
|
|
5
|
+
export function viewName(file) {
|
|
6
|
+
return file.replace(/^.*?\/src\//, '').replace(/\.tscl$/, '');
|
|
7
|
+
}
|
|
8
|
+
// On globalThis: the bundled server and an app's own `import 'clarusjs/views'` may be two copies of this module.
|
|
9
|
+
const store = globalThis;
|
|
10
|
+
/** Called by the server entry with import.meta.glob('/src/**\/*.tscl'). */
|
|
11
|
+
export function registerViews(files) {
|
|
12
|
+
store.__clViews = new Map(Object.entries(files).map(([file, load]) => [viewName(file), load]));
|
|
13
|
+
}
|
|
14
|
+
/** Render a view to HTML. Its props are checked against its inputs once `clarusjs check` has generated the registry. */
|
|
15
|
+
export async function render(name, props) {
|
|
16
|
+
const views = store.__clViews;
|
|
17
|
+
if (!views)
|
|
18
|
+
throw new Error('clarusjs: no views are registered; render() runs in server code, after the server entry has loaded');
|
|
19
|
+
const load = views.get(name);
|
|
20
|
+
if (!load)
|
|
21
|
+
throw new Error(`clarusjs: no view "${name}"; views: ${[...views.keys()].sort().join(', ')}`);
|
|
22
|
+
return (await load()).render(props);
|
|
23
|
+
}
|
package/dist/vite/build.d.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
/** Absolute paths of every `.tscl` file under `srcDir` (empty if it doesn't exist). */
|
|
2
2
|
export declare function findClarusFiles(srcDir: string): string[];
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* '/' → 'index.html', '/about/team' → 'about/team/index.html', '/users/a%20b' → 'users/a b/index.html'.
|
|
5
|
+
* Segments are decoded because static hosts look files up by the decoded path. A decoded segment can't add a level:
|
|
6
|
+
* entries() values never contain '/' (and a page file's own name has none).
|
|
7
|
+
*/
|
|
4
8
|
export declare function routeToFile(route: string): string;
|
|
5
9
|
/**
|
|
6
10
|
* Call the built handler for every route (or only `only`) and write the HTML into `outDir`. Any failure fails the
|
|
@@ -10,4 +14,9 @@ export declare function routeToFile(route: string): string;
|
|
|
10
14
|
export declare function prerender(serverEntry: string, outDir: string, manifestFile: string, only?: string[]): Promise<{
|
|
11
15
|
routes: string[];
|
|
12
16
|
readers: string[];
|
|
17
|
+
loaded: string[];
|
|
18
|
+
server: {
|
|
19
|
+
route: string;
|
|
20
|
+
loader: boolean;
|
|
21
|
+
}[];
|
|
13
22
|
}>;
|
package/dist/vite/build.js
CHANGED
|
@@ -13,9 +13,26 @@ export function findClarusFiles(srcDir) {
|
|
|
13
13
|
}
|
|
14
14
|
return entries.filter((f) => f.endsWith('.tscl')).map((f) => resolve(srcDir, f)).sort();
|
|
15
15
|
}
|
|
16
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* '/' → 'index.html', '/about/team' → 'about/team/index.html', '/users/a%20b' → 'users/a b/index.html'.
|
|
18
|
+
* Segments are decoded because static hosts look files up by the decoded path. A decoded segment can't add a level:
|
|
19
|
+
* entries() values never contain '/' (and a page file's own name has none).
|
|
20
|
+
*/
|
|
17
21
|
export function routeToFile(route) {
|
|
18
|
-
const path = route.replace(/^\/+|\/+$/g, '')
|
|
22
|
+
const path = route.replace(/^\/+|\/+$/g, '').split('/').map((seg) => {
|
|
23
|
+
try {
|
|
24
|
+
return decodeURIComponent(seg);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return seg;
|
|
28
|
+
} // '100%' is a name, not an escape
|
|
29
|
+
}).join('/');
|
|
30
|
+
// A client page's data file is written as itself, next to the page's shell.
|
|
31
|
+
if (path === '__data.json' || path.endsWith('/__data.json'))
|
|
32
|
+
return path;
|
|
33
|
+
// A page's fragment, likewise.
|
|
34
|
+
if (path === 'index.frag.html' || path.endsWith('/index.frag.html'))
|
|
35
|
+
return path;
|
|
19
36
|
return path ? `${path}/index.html` : 'index.html';
|
|
20
37
|
}
|
|
21
38
|
/**
|
|
@@ -26,15 +43,23 @@ export function routeToFile(route) {
|
|
|
26
43
|
export async function prerender(serverEntry, outDir, manifestFile, only) {
|
|
27
44
|
const script = `
|
|
28
45
|
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
29
|
-
import { dirname, resolve } from 'node:path'
|
|
46
|
+
import { dirname, resolve, sep } from 'node:path'
|
|
30
47
|
import { pathToFileURL } from 'node:url'
|
|
31
48
|
const routeToFile = ${routeToFile.toString()}
|
|
32
49
|
const [entry, outDir, only] = process.argv.slice(1)
|
|
33
50
|
const { default: handler } = await import(pathToFileURL(entry).href)
|
|
34
|
-
|
|
51
|
+
let routes
|
|
52
|
+
try {
|
|
53
|
+
routes = only ? JSON.parse(only) : await handler.paths()
|
|
54
|
+
} catch (err) {
|
|
55
|
+
process.stderr.write('prerender: ' + (err && err.message || err))
|
|
56
|
+
process.exit(1)
|
|
57
|
+
}
|
|
35
58
|
const readers = []
|
|
59
|
+
const loaded = []
|
|
36
60
|
for (const route of routes) {
|
|
37
61
|
globalThis.__clManifestRead = false
|
|
62
|
+
globalThis.__clLoaderRan = false
|
|
38
63
|
let response
|
|
39
64
|
try {
|
|
40
65
|
response = await handler.fetch(new Request('http://localhost' + route))
|
|
@@ -47,11 +72,19 @@ export async function prerender(serverEntry, outDir, manifestFile, only) {
|
|
|
47
72
|
process.exit(1)
|
|
48
73
|
}
|
|
49
74
|
const file = resolve(outDir, routeToFile(route))
|
|
75
|
+
// Whatever a route decodes to, its page must land inside the output folder.
|
|
76
|
+
if (!file.startsWith(resolve(outDir) + sep)) {
|
|
77
|
+
process.stderr.write('prerender ' + route + ': outside the output folder')
|
|
78
|
+
process.exit(1)
|
|
79
|
+
}
|
|
50
80
|
mkdirSync(dirname(file), { recursive: true })
|
|
51
81
|
writeFileSync(file, await response.text())
|
|
52
82
|
if (globalThis.__clManifestRead) readers.push(route)
|
|
83
|
+
if (globalThis.__clLoaderRan) loaded.push(route)
|
|
53
84
|
}
|
|
54
|
-
|
|
85
|
+
const server = []
|
|
86
|
+
for (const route of handler.serverRoutes ?? []) server.push({ route, loader: await handler.hasLoader(route) })
|
|
87
|
+
process.stdout.write(JSON.stringify({ routes, readers, loaded, server }))
|
|
55
88
|
`;
|
|
56
89
|
const args = ['--input-type=module', '-e', script, serverEntry, outDir, ...(only ? [JSON.stringify(only)] : [])];
|
|
57
90
|
const env = { ...process.env, CLARUS_MANIFEST: manifestFile };
|
package/dist/vite/manifest.d.ts
CHANGED
|
@@ -7,9 +7,15 @@ export type IslandInfo = {
|
|
|
7
7
|
gzip: number;
|
|
8
8
|
};
|
|
9
9
|
export type RouteInfo = {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
/**
|
|
11
|
+
* 'static': prerendered at build. 'server': rendered per request by dist/server/index.mjs (its key is the route as
|
|
12
|
+
* its file names it). 'client': a prerendered shell; the router renders it in the browser from its __data.json.
|
|
13
|
+
*/
|
|
14
|
+
mode: 'static' | 'server' | 'client';
|
|
15
|
+
/** The prerendered file in dist/client (a client route's shell), or null for a server route. */
|
|
16
|
+
html: string | null;
|
|
17
|
+
/** 'build': load() ran once, when the page was prerendered. 'request': it runs on every request. */
|
|
18
|
+
loader: 'build' | 'request' | null;
|
|
13
19
|
islands: IslandInfo[];
|
|
14
20
|
/** Files relative to dist/client; gzip sizes in bytes. initialGzip is what loads with the page (attach="load"). */
|
|
15
21
|
js: {
|
|
@@ -33,6 +39,11 @@ export declare function describeRoute(route: string, html: string, opts: {
|
|
|
33
39
|
base: string;
|
|
34
40
|
chunks: ChunkGraph;
|
|
35
41
|
size(file: string): number;
|
|
42
|
+
loaded?: boolean;
|
|
43
|
+
client?: boolean;
|
|
36
44
|
}): RouteInfo;
|
|
37
45
|
/** Describe every prerendered route and write `<distDir>/clarusjs-manifest.json`. */
|
|
38
|
-
export declare function writeManifest(distDir: string, routes: string[], base: string
|
|
46
|
+
export declare function writeManifest(distDir: string, routes: string[], base: string, loaded?: string[], server?: {
|
|
47
|
+
route: string;
|
|
48
|
+
loader: boolean;
|
|
49
|
+
}[]): Manifest;
|
package/dist/vite/manifest.js
CHANGED
|
@@ -4,6 +4,7 @@ import { readFileSync, writeFileSync } from 'node:fs';
|
|
|
4
4
|
import { resolve } from 'node:path';
|
|
5
5
|
import { gzipSync } from 'node:zlib';
|
|
6
6
|
import { routeToFile } from './build.js';
|
|
7
|
+
import { matchRoute } from '../runtime/router.js';
|
|
7
8
|
const attrsOf = (tag) => {
|
|
8
9
|
const out = {};
|
|
9
10
|
for (const m of tag.matchAll(/([\w-]+)="([^"]*)"/g))
|
|
@@ -40,6 +41,13 @@ export function describeRoute(route, html, opts) {
|
|
|
40
41
|
closure(local(m[1]), all);
|
|
41
42
|
closure(local(m[1]), initial);
|
|
42
43
|
}
|
|
44
|
+
// A client route also loads its page's render module, named in the shell's route table.
|
|
45
|
+
const table = /<script type="application\/json" id="cl-routes">(.*?)<\/script>/.exec(html)?.[1];
|
|
46
|
+
const render = opts.client && table ? matchRoute(JSON.parse(table), route)?.r : undefined;
|
|
47
|
+
if (render) {
|
|
48
|
+
closure(local(render), all);
|
|
49
|
+
closure(local(render), initial);
|
|
50
|
+
}
|
|
43
51
|
for (const island of islands) {
|
|
44
52
|
closure(island.src, all);
|
|
45
53
|
if (island.attach === 'load')
|
|
@@ -47,11 +55,10 @@ export function describeRoute(route, html, opts) {
|
|
|
47
55
|
}
|
|
48
56
|
const sum = (files) => files.reduce((n, f) => n + opts.size(f), 0);
|
|
49
57
|
const css = [...html.matchAll(/<link\b[^>]*rel="stylesheet"[^>]*>/g)].map((m) => attrsOf(m[0]).href).filter(Boolean);
|
|
50
|
-
|
|
51
|
-
return { mode: 'static', html: routeToFile(route), loader: null, islands, js: { files: all, gzip: sum(all), initialGzip: sum(initial) }, css };
|
|
58
|
+
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 };
|
|
52
59
|
}
|
|
53
60
|
/** Describe every prerendered route and write `<distDir>/clarusjs-manifest.json`. */
|
|
54
|
-
export function writeManifest(distDir, routes, base) {
|
|
61
|
+
export function writeManifest(distDir, routes, base, loaded = [], server = []) {
|
|
55
62
|
const client = resolve(distDir, 'client');
|
|
56
63
|
const chunks = JSON.parse(readFileSync(resolve(client, '.vite/manifest.json'), 'utf8'));
|
|
57
64
|
const sizes = new Map();
|
|
@@ -61,8 +68,18 @@ export function writeManifest(distDir, routes, base) {
|
|
|
61
68
|
return sizes.get(file);
|
|
62
69
|
};
|
|
63
70
|
const manifest = { version: 1, routes: {} };
|
|
71
|
+
const dataFile = (route) => (route === '/' ? '/__data.json' : `${route}/__data.json`);
|
|
64
72
|
for (const route of routes) {
|
|
65
|
-
|
|
73
|
+
if (route.endsWith('/__data.json') || route.endsWith('/index.frag.html'))
|
|
74
|
+
continue; // data and fragments, not pages
|
|
75
|
+
const isClient = routes.includes(dataFile(route));
|
|
76
|
+
// A client route's loader runs when its data file is written.
|
|
77
|
+
const ran = loaded.includes(route) || (isClient && loaded.includes(dataFile(route)));
|
|
78
|
+
manifest.routes[route] = describeRoute(route, readFileSync(resolve(client, routeToFile(route)), 'utf8'), { base, chunks, size, loaded: ran, client: isClient });
|
|
79
|
+
}
|
|
80
|
+
// Server routes have no HTML at build time: what they ship is decided per request.
|
|
81
|
+
for (const { route, loader } of server) {
|
|
82
|
+
manifest.routes[route] = { mode: 'server', html: null, loader: loader ? 'request' : null, islands: [], js: { files: [], gzip: 0, initialGzip: 0 }, css: [] };
|
|
66
83
|
}
|
|
67
84
|
writeFileSync(resolve(distDir, 'clarusjs-manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
68
85
|
return manifest;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** '/account/[id]' → ['/account/:id', '/account/:id/'] (Netlify paths use URLPattern syntax). */
|
|
2
|
+
export declare function netlifyPaths(route: string, fragments?: boolean): string[];
|
|
3
|
+
/** Write (or, without server routes, remove) the function in `<root>/.netlify/v1/functions`. */
|
|
4
|
+
export declare function writeNetlifyFunction(root: string, serverEntry: string, serverRoutes: string[], fragments?: boolean): void;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Netlify adapter: server routes run as one Netlify Function (Frameworks API) calling the same fetch handler.
|
|
2
|
+
// Static routes stay files; preferStatic makes Netlify serve those first.
|
|
3
|
+
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { dirname, relative, resolve, sep } from 'node:path';
|
|
5
|
+
const FUNCTION = '.netlify/v1/functions/clarusjs-server.mjs';
|
|
6
|
+
/** '/account/[id]' → ['/account/:id', '/account/:id/'] (Netlify paths use URLPattern syntax). */
|
|
7
|
+
export function netlifyPaths(route, fragments = false) {
|
|
8
|
+
const segments = route.split('/');
|
|
9
|
+
const keyOf = (seg) => /^\[([A-Za-z_$][\w$]*)\]$/.exec(seg)?.[1];
|
|
10
|
+
const valid = (key) => /^[A-Za-z_]\w*$/.test(key);
|
|
11
|
+
// Names already valid in URLPattern are kept; others get p0, p1, … that aren't taken (URLPattern rejects duplicates).
|
|
12
|
+
const taken = new Set(segments.map(keyOf).filter((k) => k !== undefined && valid(k)));
|
|
13
|
+
let n = 0;
|
|
14
|
+
const fresh = () => {
|
|
15
|
+
while (taken.has(`p${n}`))
|
|
16
|
+
n++;
|
|
17
|
+
taken.add(`p${n}`);
|
|
18
|
+
return `p${n}`;
|
|
19
|
+
};
|
|
20
|
+
const path = segments.map((seg) => {
|
|
21
|
+
const key = keyOf(seg);
|
|
22
|
+
if (key !== undefined)
|
|
23
|
+
return `:${valid(key) ? key : fresh()}`;
|
|
24
|
+
return seg.replace(/[:*?+(){}\\]/g, '\\$&'); // literal text, not pattern syntax
|
|
25
|
+
}).join('/');
|
|
26
|
+
const paths = path === '/' || path === '' ? ['/'] : [path, `${path}/`];
|
|
27
|
+
// The page's fragment, for fragment navigation, comes from the same function.
|
|
28
|
+
if (fragments)
|
|
29
|
+
paths.push(path === '/' || path === '' ? '/index.frag.html' : `${path}/index.frag.html`);
|
|
30
|
+
return paths;
|
|
31
|
+
}
|
|
32
|
+
/** Write (or, without server routes, remove) the function in `<root>/.netlify/v1/functions`. */
|
|
33
|
+
export function writeNetlifyFunction(root, serverEntry, serverRoutes, fragments = false) {
|
|
34
|
+
const file = resolve(root, FUNCTION);
|
|
35
|
+
if (!serverRoutes.length) {
|
|
36
|
+
rmSync(file, { force: true });
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const entry = relative(dirname(file), serverEntry).split(sep).join('/');
|
|
40
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
41
|
+
writeFileSync(file, [
|
|
42
|
+
'// Generated by clarusjs: server routes on Netlify Functions. Static routes are files.',
|
|
43
|
+
`import handler from ${JSON.stringify(entry.startsWith('.') ? entry : `./${entry}`)}`,
|
|
44
|
+
'',
|
|
45
|
+
'export default (request) => handler.fetch(request)',
|
|
46
|
+
'',
|
|
47
|
+
`export const config = ${JSON.stringify({ path: serverRoutes.flatMap((r) => netlifyPaths(r, fragments)), preferStatic: true })}`,
|
|
48
|
+
'',
|
|
49
|
+
].join('\n'));
|
|
50
|
+
}
|
package/dist/vite/plugin.d.ts
CHANGED
|
@@ -1,4 +1,13 @@
|
|
|
1
1
|
import { type Plugin } from 'vite';
|
|
2
|
+
import { type ModeTable } from '../server/modes.ts';
|
|
2
3
|
/** Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. */
|
|
3
4
|
export declare function clientUrlFor(root: string, file: string): string;
|
|
4
|
-
export
|
|
5
|
+
export type ClarusOptions = {
|
|
6
|
+
/** When each route renders: { '/account/*': 'server' }. Routes default to 'static' (prerendered at build). */
|
|
7
|
+
routes?: ModeTable;
|
|
8
|
+
/** Where server routes deploy. 'netlify': a Netlify Function (Frameworks API) next to the static files. */
|
|
9
|
+
adapter?: 'netlify';
|
|
10
|
+
/** Fragment navigation: each static and server page also answers at <path>/index.frag.html. */
|
|
11
|
+
fragments?: boolean;
|
|
12
|
+
};
|
|
13
|
+
export default function clarusjs(options?: ClarusOptions): Plugin;
|