clarusjs 0.0.1 → 0.2.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.
@@ -0,0 +1,55 @@
1
+ // Build-time helpers for the Vite plugin: find components, and prerender every route to static HTML.
2
+ import { spawnSync } from 'node:child_process';
3
+ import { readdirSync } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+ /** Absolute paths of every `.clarus` file under `srcDir` (empty if it doesn't exist). */
6
+ export function findClarusFiles(srcDir) {
7
+ let entries;
8
+ try {
9
+ entries = readdirSync(srcDir, { recursive: true });
10
+ }
11
+ catch {
12
+ return [];
13
+ }
14
+ return entries.filter((f) => f.endsWith('.clarus')).map((f) => resolve(srcDir, f)).sort();
15
+ }
16
+ /** '/' → 'index.html', '/about/team' → 'about/team/index.html' */
17
+ export function routeToFile(route) {
18
+ const path = route.replace(/^\/+|\/+$/g, '');
19
+ return path ? `${path}/index.html` : 'index.html';
20
+ }
21
+ /**
22
+ * Call the built handler for every route and write the HTML into `outDir`. Any failure fails the build.
23
+ * Runs in a fresh Node process so a rebuilt server bundle is never served from a module cache.
24
+ */
25
+ export async function prerender(serverEntry, outDir) {
26
+ const script = `
27
+ import { mkdirSync, writeFileSync } from 'node:fs'
28
+ import { dirname, resolve } from 'node:path'
29
+ import { pathToFileURL } from 'node:url'
30
+ const routeToFile = ${routeToFile.toString()}
31
+ const [entry, outDir] = process.argv.slice(1)
32
+ const { default: handler } = await import(pathToFileURL(entry).href)
33
+ for (const route of handler.routes) {
34
+ let response
35
+ try {
36
+ response = await handler.fetch(new Request('http://localhost' + route))
37
+ } catch (err) {
38
+ process.stderr.write('prerender ' + route + ': ' + (err && err.message || err))
39
+ process.exit(1)
40
+ }
41
+ if (response.status !== 200) {
42
+ process.stderr.write('prerender ' + route + ': status ' + response.status)
43
+ process.exit(1)
44
+ }
45
+ const file = resolve(outDir, routeToFile(route))
46
+ mkdirSync(dirname(file), { recursive: true })
47
+ writeFileSync(file, await response.text())
48
+ }
49
+ process.stdout.write(JSON.stringify(handler.routes))
50
+ `;
51
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', script, serverEntry, outDir], { encoding: 'utf8' });
52
+ if (result.status !== 0)
53
+ throw new Error(result.stderr.trim() || `prerender failed (exit ${result.status})`);
54
+ return JSON.parse(result.stdout);
55
+ }
@@ -0,0 +1,3 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ export declare function toRequest(req: IncomingMessage): Request;
3
+ export declare function sendResponse(res: ServerResponse, response: Response): Promise<void>;
@@ -0,0 +1,15 @@
1
+ export function toRequest(req) {
2
+ const headers = new Headers();
3
+ for (const [key, value] of Object.entries(req.headers)) {
4
+ if (Array.isArray(value))
5
+ value.forEach((v) => headers.append(key, v));
6
+ else if (value !== undefined)
7
+ headers.set(key, value);
8
+ }
9
+ return new Request(`http://${req.headers.host ?? 'localhost'}${req.url ?? '/'}`, { method: req.method, headers });
10
+ }
11
+ export async function sendResponse(res, response) {
12
+ res.statusCode = response.status;
13
+ response.headers.forEach((value, key) => res.setHeader(key, value));
14
+ res.end(Buffer.from(await response.arrayBuffer()));
15
+ }
@@ -0,0 +1,4 @@
1
+ import { type Plugin } from 'vite';
2
+ /** Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. */
3
+ export declare function clientUrlFor(root: string, file: string): string;
4
+ export default function clarusjs(): Plugin;
@@ -0,0 +1,169 @@
1
+ // The clarusjs Vite plugin: a thin adapter around the compiler.
2
+ // Server environment gets render(), client environment gets attach(). Dev requests go through the fetch handler.
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { isAbsolute, relative, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { isRunnableDevEnvironment } from 'vite';
7
+ import { compile, ClarusError } from '../compiler/index.js';
8
+ import { findClarusFiles, prerender } from './build.js';
9
+ import { sendResponse, toRequest } from './node.js';
10
+ // From src/ (workspace, tests) our siblings are .ts files; from the published dist/ they are .js.
11
+ const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
12
+ const here = (path) => fileURLToPath(new URL(path + ext, import.meta.url));
13
+ const ENTRY = 'virtual:clarusjs/server-entry';
14
+ /** Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. */
15
+ export function clientUrlFor(root, file) {
16
+ const rel = relative(root, file);
17
+ return rel.startsWith('..') || isAbsolute(rel) ? `/@fs${file}?import` : `/${rel}?import`;
18
+ }
19
+ const LOADER_ENTRY = 'cl-loader';
20
+ const CLIENT_OUT = 'dist/client';
21
+ const SERVER_OUT = 'dist/server';
22
+ const entryName = (root, file) => relative(root, file).replace(/\.clarus$/, '');
23
+ export default function clarusjs() {
24
+ let root = process.cwd();
25
+ let command = 'serve';
26
+ let base = '/';
27
+ // `vite build` only: client entry name (see entryName) → public URL of its hashed chunk.
28
+ // Read from the client manifest on disk, because Vite resolves config (and so creates a new plugin instance) per
29
+ // environment: the server build cannot see state set during the client build.
30
+ let built;
31
+ const builtUrls = () => {
32
+ if (command !== 'build')
33
+ return undefined;
34
+ if (built)
35
+ return built;
36
+ const manifestFile = resolve(root, CLIENT_OUT, '.vite/manifest.json');
37
+ if (!existsSync(manifestFile)) {
38
+ throw new Error(`clarusjs: client manifest not found at ${manifestFile}; the server build must run after the client build`);
39
+ }
40
+ const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
41
+ built = new Map();
42
+ for (const chunk of Object.values(manifest))
43
+ if (chunk.isEntry && chunk.name)
44
+ built.set(chunk.name, base + chunk.file);
45
+ return built;
46
+ };
47
+ return {
48
+ name: 'clarusjs',
49
+ config(userConfig, env) {
50
+ const config = {
51
+ appType: 'custom',
52
+ resolve: {
53
+ alias: [
54
+ { find: 'clarusjs/runtime/server', replacement: here('../runtime/server') },
55
+ { find: 'clarusjs/runtime', replacement: here('../runtime/index') },
56
+ ],
57
+ },
58
+ };
59
+ if (env.isPreview)
60
+ config.build = { outDir: CLIENT_OUT }; // preview serves the static site
61
+ if (env.command !== 'build')
62
+ return config;
63
+ if (userConfig.base !== undefined && !userConfig.base.startsWith('/') && !/^https?:\/\//.test(userConfig.base)) {
64
+ // Pages live at different depths and islands are imported from the loader, so URLs must not be relative.
65
+ throw new Error(`clarusjs: relative base "${userConfig.base}" is not supported; use an absolute base such as "/" or "/docs/"`);
66
+ }
67
+ // Client entries: the island loader plus every stateful component. Stateless components never reach the client.
68
+ const appRoot = resolve(userConfig.root ?? process.cwd());
69
+ const input = { [LOADER_ENTRY]: here('../runtime/loader') };
70
+ for (const file of findClarusFiles(resolve(appRoot, 'src'))) {
71
+ if (compile(readFileSync(file, 'utf8'), { file, target: 'client' }).stateful)
72
+ input[entryName(appRoot, file)] = file;
73
+ }
74
+ config.builder = {};
75
+ config.environments = {
76
+ // Island chunks are loaded with import() and must keep their `attach` export.
77
+ client: { build: { outDir: CLIENT_OUT, manifest: true, rolldownOptions: { input, preserveEntrySignatures: 'exports-only' } } },
78
+ // Always .mjs, so Node loads it as ESM whatever the app's package.json says.
79
+ ssr: { build: { outDir: SERVER_OUT, rolldownOptions: { input: { index: ENTRY }, output: { entryFileNames: '[name].mjs' } } } },
80
+ };
81
+ return config;
82
+ },
83
+ // Each build re-reads the client manifest: a builder can run buildApp() more than once.
84
+ buildStart() { built = undefined; },
85
+ configResolved(config) {
86
+ root = config.root;
87
+ command = config.command;
88
+ base = config.base;
89
+ },
90
+ // Order matters: the server build needs the client's hashed URLs, and prerendering needs the server build.
91
+ async buildApp(builder) {
92
+ const { client, ssr } = builder.environments;
93
+ if (!client || !ssr)
94
+ return;
95
+ await builder.build(client);
96
+ await builder.build(ssr);
97
+ await prerender(resolve(builder.config.root, SERVER_OUT, 'index.mjs'), resolve(builder.config.root, CLIENT_OUT));
98
+ },
99
+ resolveId(id) {
100
+ if (id === '/cl-loader.js')
101
+ return here('../runtime/loader');
102
+ if (id === ENTRY)
103
+ return '\0' + ENTRY;
104
+ },
105
+ load(id) {
106
+ if (id !== '\0' + ENTRY)
107
+ return;
108
+ const loaderUrl = builtUrls()?.get(LOADER_ENTRY) ?? '/cl-loader.js';
109
+ return `import { createHandler } from ${JSON.stringify(here('../server/handler'))}\n` +
110
+ `export default createHandler(import.meta.glob('/src/pages/**/*.clarus'), { loaderUrl: ${JSON.stringify(loaderUrl)} })\n`;
111
+ },
112
+ transform: {
113
+ filter: { id: /\.clarus(\?|$)/ },
114
+ handler(code, id) {
115
+ const file = id.replace(/\?.*$/, '');
116
+ const target = this.environment.config.consumer === 'server' ? 'server' : 'client';
117
+ // ponytail: ?import makes Vite's dev transform middleware serve .clarus as JS for the loader's dynamic import; build output uses hashed chunk URLs from the client manifest (stage 3)
118
+ const urls = target === 'server' ? builtUrls() : undefined;
119
+ const clientUrl = urls ? urls.get(entryName(root, file)) : clientUrlFor(root, file);
120
+ if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
121
+ this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
122
+ }
123
+ try {
124
+ return { code: compile(code, { file, target, clientUrl }).code, map: null };
125
+ }
126
+ catch (err) {
127
+ if (err instanceof ClarusError)
128
+ this.error(err.message);
129
+ throw err;
130
+ }
131
+ },
132
+ },
133
+ // The built site is static files: /guide/x is guide/x/index.html. appType 'custom' turns off Vite's own lookup.
134
+ configurePreviewServer(server) {
135
+ const outDir = resolve(server.config.root, server.config.build.outDir);
136
+ const base = server.config.base; // e.g. '/' or '/docs/'; Vite strips it after this middleware
137
+ server.middlewares.use((req, _res, next) => {
138
+ const url = decodeURIComponent((req.url ?? '/').split('?')[0]);
139
+ const inBase = url === base.slice(0, -1) ? '/' : url.startsWith(base) ? '/' + url.slice(base.length) : undefined;
140
+ if (inBase !== undefined) {
141
+ // A built page wins; anything else (assets, /x.css) falls through to Vite's static files.
142
+ const file = resolve(outDir, `.${inBase.replace(/\/?$/, '/')}index.html`);
143
+ if (file.startsWith(outDir) && existsSync(file))
144
+ req.url = base + file.slice(outDir.length + 1).replace(/\\/g, '/');
145
+ }
146
+ next();
147
+ });
148
+ },
149
+ configureServer(server) {
150
+ return () => {
151
+ server.middlewares.use(async (req, res, next) => {
152
+ try {
153
+ const env = server.environments.ssr;
154
+ if (!isRunnableDevEnvironment(env))
155
+ return next();
156
+ const app = await env.runner.import(ENTRY);
157
+ const response = await app.default.fetch(toRequest(req));
158
+ if (response.status === 404)
159
+ return next();
160
+ await sendResponse(res, response);
161
+ }
162
+ catch (err) {
163
+ next(err);
164
+ }
165
+ });
166
+ };
167
+ },
168
+ };
169
+ }
package/package.json CHANGED
@@ -1,12 +1,82 @@
1
1
  {
2
2
  "name": "clarusjs",
3
- "version": "0.0.1",
4
- "description": "Clear, compiled views: templates compiled to server HTML, with JavaScript only for interactive islands. Placeholder: not ready for use yet.",
5
- "keywords": ["clarusjs", "framework", "compiler", "templates", "ssr", "ssg", "islands", "signals", "vite"],
3
+ "version": "0.2.0",
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
+ "license": "MIT",
6
+ "keywords": [
7
+ "clarusjs",
8
+ "framework",
9
+ "compiler",
10
+ "templates",
11
+ "ssr",
12
+ "ssg",
13
+ "islands",
14
+ "partial-hydration",
15
+ "signals",
16
+ "vite",
17
+ "vite-plugin",
18
+ "html-first",
19
+ "typescript"
20
+ ],
6
21
  "homepage": "https://github.com/forinda/clarusjs#readme",
7
- "repository": { "type": "git", "url": "git+https://github.com/forinda/clarusjs.git" },
8
- "bugs": { "url": "https://github.com/forinda/clarusjs/issues" },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/forinda/clarusjs.git",
25
+ "directory": "packages/clarusjs"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/forinda/clarusjs/issues"
29
+ },
9
30
  "type": "module",
10
- "main": "index.js",
11
- "files": ["index.js", "README.md"]
12
- }
31
+ "exports": {
32
+ "./compiler": {
33
+ "types": "./dist/compiler/index.d.ts",
34
+ "default": "./dist/compiler/index.js"
35
+ },
36
+ "./runtime": {
37
+ "types": "./dist/runtime/index.d.ts",
38
+ "default": "./dist/runtime/index.js"
39
+ },
40
+ "./runtime/server": {
41
+ "types": "./dist/runtime/server.d.ts",
42
+ "default": "./dist/runtime/server.js"
43
+ },
44
+ "./server": {
45
+ "types": "./dist/server/handler.d.ts",
46
+ "default": "./dist/server/handler.js"
47
+ },
48
+ "./vite": {
49
+ "types": "./dist/vite/plugin.d.ts",
50
+ "default": "./dist/vite/plugin.js"
51
+ }
52
+ },
53
+ "files": [
54
+ "dist",
55
+ "LICENSE",
56
+ "README.md"
57
+ ],
58
+ "engines": {
59
+ "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
60
+ },
61
+ "dependencies": {
62
+ "acorn": "^8.19.0"
63
+ },
64
+ "peerDependencies": {
65
+ "vite": "^8.0.0"
66
+ },
67
+ "devDependencies": {
68
+ "@types/node": "^26.6.6",
69
+ "happy-dom": "^21.0.4",
70
+ "typescript": "^7.0.2",
71
+ "vite": "^8.3.8",
72
+ "vitest": "^5.1.1"
73
+ },
74
+ "publishConfig": {
75
+ "access": "public"
76
+ },
77
+ "scripts": {
78
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
79
+ "test": "vitest run",
80
+ "typecheck": "tsc --noEmit"
81
+ }
82
+ }
package/index.js DELETED
@@ -1 +0,0 @@
1
- throw new Error('clarusjs is not released yet. Follow https://github.com/forinda/clarusjs for the first version.')