clarusjs 0.13.0 → 0.15.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.d.ts +2 -5
- package/dist/check/generate.js +148 -13
- package/dist/cli/check.d.ts +4 -0
- package/dist/cli/check.js +3 -1
- package/dist/cli/mapper.js +19 -1
- package/dist/cli/project.d.ts +4 -0
- package/dist/cli/project.js +1 -1
- package/dist/compiler/class-style.d.ts +1 -1
- package/dist/compiler/class-style.js +6 -2
- package/dist/compiler/components.d.ts +32 -0
- package/dist/compiler/components.js +63 -0
- package/dist/compiler/emit-client.js +33 -4
- package/dist/compiler/emit-server.js +21 -11
- package/dist/compiler/html-expr.d.ts +11 -2
- package/dist/compiler/html-expr.js +38 -20
- package/dist/compiler/icon.d.ts +1 -1
- package/dist/compiler/icon.js +4 -0
- package/dist/compiler/index.d.ts +13 -1
- package/dist/compiler/index.js +64 -2
- package/dist/compiler/ir.d.ts +39 -0
- package/dist/compiler/ir.js +104 -11
- package/dist/compiler/lint.js +12 -1
- package/dist/compiler/parse.d.ts +44 -0
- package/dist/compiler/parse.js +93 -10
- package/dist/compiler/script.d.ts +21 -1
- package/dist/compiler/script.js +58 -3
- package/dist/compiler/shared.d.ts +6 -0
- package/dist/compiler/shared.js +14 -0
- package/dist/fetch/index.d.ts +157 -3
- package/dist/fetch/index.js +135 -14
- package/dist/forms/index.js +15 -3
- package/dist/runtime/attrs.d.ts +6 -0
- package/dist/runtime/attrs.js +16 -0
- package/dist/runtime/dom.d.ts +42 -1
- package/dist/runtime/dom.js +152 -23
- package/dist/runtime/html.d.ts +6 -0
- package/dist/runtime/html.js +12 -0
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/loader.js +32 -6
- package/dist/runtime/router.d.ts +6 -1
- package/dist/runtime/router.js +1 -1
- package/dist/runtime/server.d.ts +20 -2
- package/dist/runtime/server.js +48 -8
- package/dist/server/handler.d.ts +28 -1
- package/dist/server/handler.js +48 -2
- package/dist/server/modes.d.ts +2 -0
- package/dist/server/modes.js +5 -1
- package/dist/server/views.d.ts +1 -1
- package/dist/server/views.js +1 -1
- package/dist/vite/plugin.d.ts +19 -0
- package/dist/vite/plugin.js +61 -14
- package/package.json +1 -1
package/dist/server/handler.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { modeFor } from './modes.js';
|
|
2
|
-
import {
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
+
import { toBrowser } from '../runtime/server.js';
|
|
3
4
|
import { completeHead } from './head.js';
|
|
4
5
|
import { escape } from '../runtime/html.js';
|
|
5
6
|
const DATA = '__data.json';
|
|
6
7
|
const FRAG = 'index.frag.html';
|
|
7
8
|
const safeJson = (json) => json.replace(/</g, '\\u003c');
|
|
9
|
+
const loadedStore = new AsyncLocalStorage();
|
|
10
|
+
globalThis.__clLoadedStore = loadedStore;
|
|
8
11
|
const PARAM = /^\[([A-Za-z_$][\w$]*)\]$/;
|
|
9
12
|
function compile(path) {
|
|
10
13
|
const keys = [];
|
|
@@ -20,15 +23,20 @@ function compile(path) {
|
|
|
20
23
|
export function redirect(to, status = 302) {
|
|
21
24
|
return new Response(null, { status, headers: { location: to } });
|
|
22
25
|
}
|
|
26
|
+
export function isPageFile(file) {
|
|
27
|
+
return !/\/\+[^/]*$/.test(file);
|
|
28
|
+
}
|
|
23
29
|
export function routeFromFile(file) {
|
|
24
30
|
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.[^./]+$/, '').replace(/\/index$/, '');
|
|
25
31
|
return path || '/';
|
|
26
32
|
}
|
|
27
33
|
export function createHandler(pages, options = {}) {
|
|
28
34
|
const routes = Object.entries(pages)
|
|
35
|
+
.filter(([file]) => isPageFile(file))
|
|
29
36
|
.map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
|
|
30
37
|
.sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
|
|
31
38
|
const endpointRoutes = Object.entries(options.endpoints ?? {})
|
|
39
|
+
.filter(([file]) => isPageFile(file))
|
|
32
40
|
.map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
|
|
33
41
|
.sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
|
|
34
42
|
const matchEndpoint = (pathname) => {
|
|
@@ -46,6 +54,26 @@ export function createHandler(pages, options = {}) {
|
|
|
46
54
|
return undefined;
|
|
47
55
|
};
|
|
48
56
|
const data = options.data ?? {};
|
|
57
|
+
const guards = options.guards ?? {};
|
|
58
|
+
async function guarded(file, once, context) {
|
|
59
|
+
const folders = file.replace(/^\/?src\/pages\//, '').split('/').slice(0, -1);
|
|
60
|
+
for (let i = 0; i <= folders.length; i++) {
|
|
61
|
+
const key = `/src/pages/${[...folders.slice(0, i), '+guard.ts'].join('/')}`;
|
|
62
|
+
if (!guards[key])
|
|
63
|
+
continue;
|
|
64
|
+
try {
|
|
65
|
+
const mod = await guards[key]();
|
|
66
|
+
const route = routeFromFile(`/${file.replace(/^\//, '')}`);
|
|
67
|
+
const answer = await mod.guard?.({ ...context, url: new URL(context.request.url), ...(once ? builtOnce(route, context.request) : {}) });
|
|
68
|
+
if (answer instanceof Response)
|
|
69
|
+
return answer;
|
|
70
|
+
}
|
|
71
|
+
catch (err) {
|
|
72
|
+
throw new Error(`${key.slice(1)}: guard() failed: ${err?.message ?? err}`, { cause: err });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
49
77
|
const modes = options.modes ?? {};
|
|
50
78
|
const loaderUrl = options.loaderUrl ?? '/cl-loader.js';
|
|
51
79
|
function match(pathname) {
|
|
@@ -163,6 +191,16 @@ export function createHandler(pages, options = {}) {
|
|
|
163
191
|
const trimmed = path.length > 1 ? path.replace(/\/+$/, '') : path;
|
|
164
192
|
const found = !match(trimmed) && matchEndpoint(trimmed);
|
|
165
193
|
if (found) {
|
|
194
|
+
try {
|
|
195
|
+
const stop = await guarded(found.route.file, false, { request, params: found.params, cookies, locals });
|
|
196
|
+
if (stop)
|
|
197
|
+
return stop;
|
|
198
|
+
}
|
|
199
|
+
catch (err) {
|
|
200
|
+
if (options.dev)
|
|
201
|
+
throw err;
|
|
202
|
+
return failure(err.message);
|
|
203
|
+
}
|
|
166
204
|
const response = await callEndpoint(found.route.file, await found.route.load(), { request, params: found.params, cookies, locals }, options);
|
|
167
205
|
if (response)
|
|
168
206
|
return response;
|
|
@@ -244,6 +282,14 @@ export function createHandler(pages, options = {}) {
|
|
|
244
282
|
}
|
|
245
283
|
return new Response(head ? null : page, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
246
284
|
}
|
|
285
|
+
try {
|
|
286
|
+
const stop = await guarded(found.route.file, modeFor(found.route.path, modes) !== 'server', { params: found.params, locals, request, cookies });
|
|
287
|
+
if (stop)
|
|
288
|
+
return stop;
|
|
289
|
+
}
|
|
290
|
+
catch (err) {
|
|
291
|
+
return fail(err.message, err);
|
|
292
|
+
}
|
|
247
293
|
let props = found.route.path === '/500' ? { status: 500, ...found.params } : found.params;
|
|
248
294
|
const dataFile = found.route.file.replace(/\.[^./]+$/, '.load.ts');
|
|
249
295
|
const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
|
|
@@ -296,7 +342,7 @@ export function createHandler(pages, options = {}) {
|
|
|
296
342
|
let html;
|
|
297
343
|
try {
|
|
298
344
|
const module = await found.route.load();
|
|
299
|
-
html =
|
|
345
|
+
html = await loadedStore.run(componentData, () => module.render(props, undefined, { route: { path: pathname, params: found.params } }));
|
|
300
346
|
}
|
|
301
347
|
catch (err) {
|
|
302
348
|
return fail(`${found.route.file}: render failed: ${err?.message ?? err}`, err);
|
package/dist/server/modes.d.ts
CHANGED
|
@@ -2,5 +2,7 @@ export type Mode = 'static' | 'server' | 'client';
|
|
|
2
2
|
export type ModeTable = Record<string, string>;
|
|
3
3
|
/** Throws on an unknown mode or a malformed pattern, naming it. */
|
|
4
4
|
export declare function checkModes(table: ModeTable): void;
|
|
5
|
+
/** A route pattern: '/about' is that route; '/docs/*' is /docs and every route under it ('/*': all). */
|
|
6
|
+
export declare function routeMatches(route: string, pattern: string): boolean;
|
|
5
7
|
/** The mode of a route (as its file names it, e.g. '/account/[id]'): the most specific matching pattern wins. */
|
|
6
8
|
export declare function modeFor(route: string, table: ModeTable): Mode;
|
package/dist/server/modes.js
CHANGED
|
@@ -10,11 +10,15 @@ export function checkModes(table) {
|
|
|
10
10
|
throw new Error(`clarusjs: routes['${pattern}'] is "${mode}"; use 'static', 'server' or 'client'`);
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
|
+
export function routeMatches(route, pattern) {
|
|
14
|
+
const folder = pattern.endsWith('/*') ? pattern.slice(0, -2) : undefined;
|
|
15
|
+
return folder !== undefined ? route === (folder || '/') || route.startsWith(`${folder}/`) : route === pattern;
|
|
16
|
+
}
|
|
13
17
|
export function modeFor(route, table) {
|
|
14
18
|
let best;
|
|
15
19
|
for (const [pattern, mode] of Object.entries(table)) {
|
|
16
20
|
const folder = pattern.endsWith('/*') ? pattern.slice(0, -2) : undefined;
|
|
17
|
-
const hit =
|
|
21
|
+
const hit = routeMatches(route, pattern);
|
|
18
22
|
const length = folder !== undefined ? folder.length : pattern.length + 0.5;
|
|
19
23
|
if (hit && (!best || length > best.length))
|
|
20
24
|
best = { length, mode: mode };
|
package/dist/server/views.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { HTML } from '../runtime/html.ts';
|
|
2
2
|
type View = {
|
|
3
|
-
render(props?: object, slots?: Record<string, string>): string
|
|
3
|
+
render(props?: object, slots?: Record<string, string>): string | Promise<string>;
|
|
4
4
|
};
|
|
5
5
|
type Registry = Record<string, () => Promise<View>>;
|
|
6
6
|
/**
|
package/dist/server/views.js
CHANGED
|
@@ -38,7 +38,7 @@ export async function h(name, props = {}, children = []) {
|
|
|
38
38
|
const filled = await Promise.all(entries.map(([, content]) => childrenHtml(content)));
|
|
39
39
|
entries.forEach(([slot], k) => { if (filled[k])
|
|
40
40
|
slots[slot] = filled[k]; });
|
|
41
|
-
return html((await load()).render(props, Object.keys(slots).length ? slots : undefined));
|
|
41
|
+
return html(await (await load()).render(props, Object.keys(slots).length ? slots : undefined));
|
|
42
42
|
}
|
|
43
43
|
const tag = name.toLowerCase();
|
|
44
44
|
if (!/^[a-z][a-z0-9-]*$/.test(tag))
|
package/dist/vite/plugin.d.ts
CHANGED
|
@@ -18,6 +18,25 @@ export declare function clientUrlFor(root: string, file: string, path?: Pick<typ
|
|
|
18
18
|
export type ClarusOptions = {
|
|
19
19
|
/** When each route renders: { '/account/*': 'server' }. Routes default to 'static' (prerendered at build). */
|
|
20
20
|
routes?: ModeTable;
|
|
21
|
+
/**
|
|
22
|
+
* Layouts by route (#456), outermost first, around the folder layouts (`+layout.tscl`): `{ layout: '/src/layouts/site.tscl',
|
|
23
|
+
* include: ['/*'], exclude: ['/embed/*'] }` (patterns as in `routes`; include defaults to every route). A page with
|
|
24
|
+
* `@layout none` gets none.
|
|
25
|
+
*/
|
|
26
|
+
layouts?: {
|
|
27
|
+
layout: string;
|
|
28
|
+
include?: string[];
|
|
29
|
+
exclude?: string[];
|
|
30
|
+
}[];
|
|
31
|
+
/**
|
|
32
|
+
* Automatic component imports (#458): a kebab-case file under these folders is used by its name, without @import
|
|
33
|
+
* (`src/components/forms/text-field.tscl` → `<forms-text-field>`, or `<text-field>` when no other has that name).
|
|
34
|
+
* Defaults: `{ dirs: ['src/components', 'src/layouts'], auto: true }`.
|
|
35
|
+
*/
|
|
36
|
+
components?: {
|
|
37
|
+
dirs?: string[];
|
|
38
|
+
auto?: boolean;
|
|
39
|
+
};
|
|
21
40
|
/** Where server routes deploy. 'netlify': a Netlify Function (Frameworks API) next to the static files. */
|
|
22
41
|
adapter?: 'netlify';
|
|
23
42
|
/** Fragment navigation: each static and server page also answers at <path>/index.frag.html. */
|
package/dist/vite/plugin.js
CHANGED
|
@@ -23,6 +23,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
23
23
|
import { isRunnableDevEnvironment, normalizePath } from 'vite';
|
|
24
24
|
import { compile, scopeId, ClarusError } from '../compiler/index.js';
|
|
25
25
|
import { parse } from '../compiler/parse.js';
|
|
26
|
+
import { COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
|
|
26
27
|
import { findClarusFiles, packageOf as packageOfFile, prerender, reachableComponents, routeToFile } from './build.js';
|
|
27
28
|
export { packageOf } from './build.js';
|
|
28
29
|
export { gitDates } from './sitemap.js';
|
|
@@ -32,8 +33,8 @@ import { checkLinks } from './links.js';
|
|
|
32
33
|
import { checkRedirects, redirectFor, writeRedirects } from './redirects.js';
|
|
33
34
|
import { projectAliases, resolveAlias } from './aliases.js';
|
|
34
35
|
import { gitDates, sitemapFiles } from './sitemap.js';
|
|
35
|
-
import { checkModes, modeFor } from '../server/modes.js';
|
|
36
|
-
import { rootLinks, routeFromFile } from '../server/handler.js';
|
|
36
|
+
import { checkModes, modeFor, routeMatches } from '../server/modes.js';
|
|
37
|
+
import { isPageFile, rootLinks, routeFromFile } from '../server/handler.js';
|
|
37
38
|
import { basePath } from '../server/head.js';
|
|
38
39
|
import { acceptsEncoding, sendResponse, toRequest } from './node.js';
|
|
39
40
|
import { resolveIcon } from '../icons.js';
|
|
@@ -105,7 +106,7 @@ function pageGraph(root, files, aliases = []) {
|
|
|
105
106
|
out.push(sheet);
|
|
106
107
|
};
|
|
107
108
|
const pages = new Map();
|
|
108
|
-
for (const file of files.
|
|
109
|
+
for (const file of files.pages(root)) {
|
|
109
110
|
const css = [];
|
|
110
111
|
const seen = new Set();
|
|
111
112
|
collect(file, css, seen);
|
|
@@ -114,6 +115,23 @@ function pageGraph(root, files, aliases = []) {
|
|
|
114
115
|
}
|
|
115
116
|
return pages;
|
|
116
117
|
}
|
|
118
|
+
function layoutsFor(root, file, config) {
|
|
119
|
+
const pages = resolve(root, 'src/pages');
|
|
120
|
+
const rel = relative(pages, file);
|
|
121
|
+
if (rel.startsWith('..') || isAbsolute(rel) || !isPageFile(file.split(sep).join('/')))
|
|
122
|
+
return undefined;
|
|
123
|
+
const route = routeFromFile(`/src/pages/${rel.split(sep).join('/')}`);
|
|
124
|
+
const out = config
|
|
125
|
+
.filter((l) => (l.include ?? ['/*']).some((p) => routeMatches(route, p)) && !(l.exclude ?? []).some((p) => routeMatches(route, p)))
|
|
126
|
+
.map((l) => l.layout);
|
|
127
|
+
const folders = dirname(rel) === '.' ? [] : dirname(rel).split(sep);
|
|
128
|
+
for (let i = 0; i <= folders.length; i++) {
|
|
129
|
+
const layout = resolve(pages, ...folders.slice(0, i), '+layout.tscl');
|
|
130
|
+
if (existsSync(layout))
|
|
131
|
+
out.push(`/${relative(root, layout).split(sep).join('/')}`);
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
117
135
|
function componentLoaderOf(root, file) {
|
|
118
136
|
if (!file.endsWith('.tscl') || real(file).startsWith(real(resolve(root, 'src/pages')) + sep))
|
|
119
137
|
return undefined;
|
|
@@ -126,7 +144,7 @@ function writeStyles(root, files) {
|
|
|
126
144
|
const outDir = resolve(root, '.clarusjs');
|
|
127
145
|
for (const file of files.components(root)) {
|
|
128
146
|
try {
|
|
129
|
-
let out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file), icon: iconsFor(file) }).css;
|
|
147
|
+
let out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file), icon: iconsFor(file), layouts: files.layouts(file, root), components: files.names(root) }).css;
|
|
130
148
|
out = out.replace(/^(?:[ \t]*@(?:reference|import)\b[^;{]*;[ \t]*\n?)+/, (statements) => {
|
|
131
149
|
for (const statement of statements.split(';').map((x) => x.trim()).filter(Boolean)) {
|
|
132
150
|
head.add(statement.replace(/(["'])(\.{1,2}\/[^"']*)\1/, (_, q, spec) => {
|
|
@@ -153,7 +171,7 @@ const SERVER_OUT = 'dist/server';
|
|
|
153
171
|
const entryName = (root, file) => relative(root, file).split(sep).join('/').replace(/\.[^./\\]+$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3));
|
|
154
172
|
function clientPages(appRoot, modes, files) {
|
|
155
173
|
const pages = new Map();
|
|
156
|
-
for (const file of files.
|
|
174
|
+
for (const file of files.pages(appRoot)) {
|
|
157
175
|
const route = routeFromFile(`/${relative(appRoot, file).split(sep).join('/')}`);
|
|
158
176
|
if (modeFor(route, modes) === 'client')
|
|
159
177
|
pages.set(route, file);
|
|
@@ -195,6 +213,14 @@ export default function clarusjs(options = {}) {
|
|
|
195
213
|
let extra = () => [];
|
|
196
214
|
const files = {
|
|
197
215
|
find: (dir) => findClarusFiles(dir, extensions).filter((f) => f.endsWith('.tscl') || f.includes(`${sep}src${sep}pages${sep}`)),
|
|
216
|
+
pages: (root) => files.find(resolve(root, 'src/pages')).filter((f) => isPageFile(f.split(sep).join('/'))),
|
|
217
|
+
layouts: (file, root) => layoutsFor(root, file, options.layouts ?? []),
|
|
218
|
+
names: (root) => {
|
|
219
|
+
if (options.components?.auto === false)
|
|
220
|
+
return undefined;
|
|
221
|
+
const found = findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => relative(root, f).split(sep).join('/'));
|
|
222
|
+
return componentIndex(found, options.components?.dirs ?? COMPONENT_DIRS).names;
|
|
223
|
+
},
|
|
198
224
|
components: (appRoot) => reachableComponents(appRoot, [...files.find(resolve(appRoot, 'src')), ...extra(appRoot).filter((f) => existsSync(f))], (file) => files.read(file, appRoot), extensions, aliases),
|
|
199
225
|
read: (file, appRoot) => {
|
|
200
226
|
const code = readFileSync(file, 'utf8');
|
|
@@ -238,7 +264,7 @@ export default function clarusjs(options = {}) {
|
|
|
238
264
|
};
|
|
239
265
|
return {
|
|
240
266
|
name: 'clarusjs',
|
|
241
|
-
api: { sources, lint: options.lint, lintRules: options.lintRules },
|
|
267
|
+
api: { sources, lint: options.lint, lintRules: options.lintRules, components: options.components },
|
|
242
268
|
config(userConfig, env) {
|
|
243
269
|
extra = (appRoot) => pluginsOf(userConfig.plugins).flatMap((p) => p.api?.clarusComponents?.(appRoot) ?? []);
|
|
244
270
|
const projectRoot = resolve(userConfig.root ?? process.cwd());
|
|
@@ -276,7 +302,7 @@ export default function clarusjs(options = {}) {
|
|
|
276
302
|
const input = { [LOADER_ENTRY]: here('../runtime/loader') };
|
|
277
303
|
const components = files.components(appRoot);
|
|
278
304
|
for (const file of components) {
|
|
279
|
-
if (compile(files.read(file, appRoot), { file, target: 'client', icon: iconsFor(file) }).stateful)
|
|
305
|
+
if (compile(files.read(file, appRoot), { file, target: 'client', icon: iconsFor(file), layouts: files.layouts(file, appRoot), components: files.names(appRoot) }).stateful)
|
|
280
306
|
input[entryName(appRoot, file)] = file;
|
|
281
307
|
}
|
|
282
308
|
const client = clientPages(appRoot, modes, files);
|
|
@@ -327,6 +353,12 @@ export default function clarusjs(options = {}) {
|
|
|
327
353
|
root = config.root;
|
|
328
354
|
command = config.command;
|
|
329
355
|
base = config.base;
|
|
356
|
+
if (options.components?.auto !== false) {
|
|
357
|
+
const found = findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => relative(root, f).split(sep).join('/'));
|
|
358
|
+
for (const file of componentIndex(found, options.components?.dirs ?? COMPONENT_DIRS).skipped) {
|
|
359
|
+
config.logger.warn(`clarusjs: ${file} isn't imported automatically: its name isn't kebab-case (rename it, or @import it)`);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
330
362
|
},
|
|
331
363
|
async buildApp(builder) {
|
|
332
364
|
const { client, ssr } = builder.environments;
|
|
@@ -336,7 +368,7 @@ export default function clarusjs(options = {}) {
|
|
|
336
368
|
if (watching)
|
|
337
369
|
client.config.build.watch = ssr.config.build.watch = null;
|
|
338
370
|
const once = async () => {
|
|
339
|
-
checkRedirects(options.redirects ?? {}, files.
|
|
371
|
+
checkRedirects(options.redirects ?? {}, files.pages(builder.config.root).map((f) => routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`)));
|
|
340
372
|
await builder.build(client);
|
|
341
373
|
await builder.build(ssr);
|
|
342
374
|
const entry = resolve(builder.config.root, SERVER_OUT, 'index.mjs');
|
|
@@ -399,7 +431,7 @@ export default function clarusjs(options = {}) {
|
|
|
399
431
|
site: options.site?.url,
|
|
400
432
|
});
|
|
401
433
|
const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn' };
|
|
402
|
-
const sourceOf = new Map(files.
|
|
434
|
+
const sourceOf = new Map(files.pages(builder.config.root).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
|
|
403
435
|
const pattern = (route) => new RegExp(`^${route.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
|
|
404
436
|
const fileOf = (page) => sourceOf.get(page) ?? [...sourceOf].find(([route]) => pattern(route).test(page))?.[1];
|
|
405
437
|
const locate = (page, href) => {
|
|
@@ -543,7 +575,8 @@ export default function clarusjs(options = {}) {
|
|
|
543
575
|
` data: import.meta.glob('/src/pages/**/*.load.ts'),\n` +
|
|
544
576
|
` componentLoaders: ${JSON.stringify(componentLoaders)},\n` +
|
|
545
577
|
` componentData: import.meta.glob(['/src/**/*.load.ts', '!/src/pages/**']),\n` +
|
|
546
|
-
`
|
|
578
|
+
` guards: import.meta.glob('/src/pages/**/+guard.ts'),\n` +
|
|
579
|
+
` endpoints: import.meta.glob(['/src/pages/**/*.ts', '!/src/pages/**/*.load.ts', '!/src/pages/**/*.d.ts', '!/src/pages/**/+*']),\n` +
|
|
547
580
|
` modes: ${JSON.stringify(modes)},\n` +
|
|
548
581
|
` routerUrl: ${JSON.stringify(routerUrl)},\n` +
|
|
549
582
|
` client: ${JSON.stringify(client)},\n` +
|
|
@@ -561,6 +594,8 @@ export default function clarusjs(options = {}) {
|
|
|
561
594
|
transform: {
|
|
562
595
|
filter: { id: fileRe },
|
|
563
596
|
async handler(raw, id) {
|
|
597
|
+
if (/[?&](raw|url|inline)\b/.test(id))
|
|
598
|
+
return null;
|
|
564
599
|
const file = id.replace(/\?.*$/, '');
|
|
565
600
|
const src = sources.find((x) => file.endsWith(x.extension));
|
|
566
601
|
if (src && (/[?&](raw|url|inline)\b/.test(id) || !normalizePath(file).startsWith(normalizePath(resolve(root, 'src/pages')) + '/')))
|
|
@@ -576,7 +611,7 @@ export default function clarusjs(options = {}) {
|
|
|
576
611
|
const clientUrl = urls
|
|
577
612
|
? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/')) ?? urls.get(real(file))
|
|
578
613
|
: command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
|
|
579
|
-
if (urls && !clientUrl && compile(code, { file, target: 'client', icon: iconsFor(file) }).stateful) {
|
|
614
|
+
if (urls && !clientUrl && compile(code, { file, target: 'client', icon: iconsFor(file), layouts: files.layouts(file, root), components: files.names(root) }).stateful) {
|
|
580
615
|
this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
|
|
581
616
|
}
|
|
582
617
|
let parsed;
|
|
@@ -600,7 +635,8 @@ export default function clarusjs(options = {}) {
|
|
|
600
635
|
const collapseWhitespace = command === 'build' && options.collapseWhitespace !== false;
|
|
601
636
|
const loader = componentLoaderOf(root, file) ? relative(root, file).split(sep).join('/') : undefined;
|
|
602
637
|
const hot = command === 'serve' && target === 'client' ? '/cl-hot.js' : undefined;
|
|
603
|
-
const
|
|
638
|
+
const layouts = files.layouts(file, root);
|
|
639
|
+
const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot, icon: iconsFor(file), layouts, components: files.names(root) });
|
|
604
640
|
if (consumer === 'server' && !renderQuery)
|
|
605
641
|
for (const w of out.warnings)
|
|
606
642
|
this.warn(w.message);
|
|
@@ -690,9 +726,20 @@ export default function clarusjs(options = {}) {
|
|
|
690
726
|
return void res.writeHead(301, { location: to }).end();
|
|
691
727
|
}
|
|
692
728
|
const app = await env.runner.import(ENTRY);
|
|
693
|
-
|
|
694
|
-
|
|
729
|
+
let response = await app.default.fetch(toRequest(req));
|
|
730
|
+
const html = response.headers.get('content-type')?.startsWith('text/html');
|
|
731
|
+
if (response.status === 404 && !html)
|
|
695
732
|
return next();
|
|
733
|
+
if (html && req.method !== 'HEAD') {
|
|
734
|
+
const text = await response.clone().text();
|
|
735
|
+
const has = /<script\b[^>]*\ssrc=["'][^"']*\/@vite\/client["']/i.test(text);
|
|
736
|
+
if (!has && /<\/head>/i.test(text)) {
|
|
737
|
+
const client = `<script type="module" src="${server.config.base}@vite/client"></script>`;
|
|
738
|
+
const headers = new Headers(response.headers);
|
|
739
|
+
headers.delete('content-length');
|
|
740
|
+
response = new Response(text.replace(/<\/head>/i, `${client}</head>`), { status: response.status, statusText: response.statusText, headers });
|
|
741
|
+
}
|
|
742
|
+
}
|
|
696
743
|
await sendResponse(res, response);
|
|
697
744
|
}
|
|
698
745
|
catch (err) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clarusjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "Clear, compiled views: templates compiled to server HTML, with JavaScript only for interactive islands. SSR, SSG and CSR from one component model, built on Vite.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|