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.
@@ -1,12 +1,23 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
1
9
  // The clarusjs Vite plugin: a thin adapter around the compiler.
2
10
  // Server environment gets render(), client environment gets attach(). Dev requests go through the fetch handler.
3
11
  import { existsSync, readFileSync, rmSync } from 'node:fs';
4
- import { dirname, isAbsolute, relative, resolve } from 'node:path';
5
- import { fileURLToPath } from 'node:url';
12
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
13
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
14
  import { isRunnableDevEnvironment } from 'vite';
7
15
  import { compile, ClarusError } from '../compiler/index.js';
8
16
  import { findClarusFiles, prerender } from './build.js';
9
17
  import { writeManifest } from './manifest.js';
18
+ import { writeNetlifyFunction } from './netlify.js';
19
+ import { checkModes, modeFor } from '../server/modes.js';
20
+ import { routeFromFile } from '../server/handler.js';
10
21
  import { sendResponse, toRequest } from './node.js';
11
22
  // From src/ (workspace, tests) our siblings are .ts files; from the published dist/ they are .js.
12
23
  const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
@@ -18,12 +29,31 @@ export function clientUrlFor(root, file) {
18
29
  return rel.startsWith('..') || isAbsolute(rel) ? `/@fs${file}?import` : `/${rel}?import`;
19
30
  }
20
31
  const LOADER_ENTRY = 'cl-loader';
32
+ const ROUTER_ENTRY = 'cl-router';
33
+ const NAV_ENTRY = 'cl-nav';
34
+ // Client entry name of a client-mode page's browser render module.
35
+ const renderEntry = (name) => `render/${name}`;
21
36
  const CLIENT_OUT = 'dist/client';
22
37
  // Placeholder for a nested island's chunk URL in the client build, replaced once the bundle's file names are known.
23
38
  const CHUNK_TOKEN = '__CLARUS_CHUNK__';
24
39
  const SERVER_OUT = 'dist/server';
25
40
  const entryName = (root, file) => relative(root, file).replace(/\.tscl$/, '');
26
- export default function clarusjs() {
41
+ /** Client-mode pages: route (as the file names it) → absolute file. */
42
+ function clientPages(appRoot, modes) {
43
+ const pages = new Map();
44
+ for (const file of findClarusFiles(resolve(appRoot, 'src/pages'))) {
45
+ const route = routeFromFile(`/${relative(appRoot, file).split(sep).join('/')}`);
46
+ if (modeFor(route, modes) === 'client')
47
+ pages.set(route, file);
48
+ }
49
+ return pages;
50
+ }
51
+ export default function clarusjs(options = {}) {
52
+ const modes = options.routes ?? {};
53
+ checkModes(modes);
54
+ if (options.adapter !== undefined && options.adapter !== 'netlify') {
55
+ throw new Error(`clarusjs: adapter "${options.adapter}" is not supported; use 'netlify'`);
56
+ }
27
57
  let root = process.cwd();
28
58
  let command = 'serve';
29
59
  let base = '/';
@@ -42,9 +72,14 @@ export default function clarusjs() {
42
72
  }
43
73
  const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
44
74
  built = new Map();
45
- for (const chunk of Object.values(manifest))
46
- if (chunk.isEntry && chunk.name)
75
+ // By entry name, and by source key: names are sanitized ([id] → _id_), keys keep the real path.
76
+ for (const [key, chunk] of Object.entries(manifest)) {
77
+ if (!chunk.isEntry)
78
+ continue;
79
+ if (chunk.name)
47
80
  built.set(chunk.name, base + chunk.file);
81
+ built.set(key, base + chunk.file);
82
+ }
48
83
  return built;
49
84
  };
50
85
  return {
@@ -74,6 +109,14 @@ export default function clarusjs() {
74
109
  if (compile(readFileSync(file, 'utf8'), { file, target: 'client' }).stateful)
75
110
  input[entryName(appRoot, file)] = file;
76
111
  }
112
+ // Client routes: the router, and each page's render function for the browser.
113
+ const client = clientPages(appRoot, modes);
114
+ if (client.size)
115
+ input[ROUTER_ENTRY] = here('../runtime/router');
116
+ if (options.fragments)
117
+ input[NAV_ENTRY] = here('../runtime/fragments');
118
+ for (const file of client.values())
119
+ input[renderEntry(entryName(appRoot, file))] = `${file}?render`;
77
120
  config.builder = {};
78
121
  config.environments = {
79
122
  // Island chunks are loaded with import() and must keep their `attach` export.
@@ -90,9 +133,15 @@ export default function clarusjs() {
90
133
  if (this.environment.config.consumer !== 'client' || command !== 'build')
91
134
  return;
92
135
  const byName = new Map();
93
- for (const out of Object.values(bundle))
94
- if (out.type === 'chunk' && out.isEntry)
95
- byName.set(out.name, base + out.fileName);
136
+ // By sanitized name and by the raw entry name from the source path ([id] stays [id]).
137
+ for (const out of Object.values(bundle)) {
138
+ if (out.type !== 'chunk' || !out.isEntry)
139
+ continue;
140
+ byName.set(out.name, base + out.fileName);
141
+ // Only island chunks: a client page's ?render chunk would otherwise take its island's place.
142
+ if (out.facadeModuleId && !/[?&]render\b/.test(out.facadeModuleId))
143
+ byName.set(entryName(root, out.facadeModuleId.replace(/\?.*$/, '')), base + out.fileName);
144
+ }
96
145
  for (const out of Object.values(bundle)) {
97
146
  if (out.type !== 'chunk' || !out.code.includes(CHUNK_TOKEN))
98
147
  continue;
@@ -121,46 +170,81 @@ export default function clarusjs() {
121
170
  const dist = dirname(out);
122
171
  const manifestFile = resolve(dist, 'clarusjs-manifest.json');
123
172
  rmSync(manifestFile, { force: true }); // a page reading the manifest must never see the previous build's
124
- const { routes, readers } = await prerender(entry, out, manifestFile);
125
- writeManifest(dist, routes, builder.config.base);
173
+ const { routes, readers, loaded, server } = await prerender(entry, out, manifestFile);
174
+ writeManifest(dist, routes, builder.config.base, loaded, server);
126
175
  // Pages that read the manifest saw none on the first pass: render them again now that it exists.
127
176
  if (readers.length) {
128
177
  await prerender(entry, out, manifestFile, readers);
129
- writeManifest(dist, routes, builder.config.base);
178
+ writeManifest(dist, routes, builder.config.base, loaded, server);
130
179
  }
180
+ if (options.adapter === 'netlify')
181
+ writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true);
131
182
  },
132
183
  resolveId(id) {
133
184
  if (id === '/cl-loader.js')
134
185
  return here('../runtime/loader');
186
+ if (id === '/cl-router.js')
187
+ return here('../runtime/router');
188
+ if (id === '/cl-nav.js')
189
+ return here('../runtime/fragments');
135
190
  if (id === ENTRY)
136
191
  return '\0' + ENTRY;
137
192
  },
138
193
  load(id) {
139
194
  if (id !== '\0' + ENTRY)
140
195
  return;
141
- const loaderUrl = builtUrls()?.get(LOADER_ENTRY) ?? '/cl-loader.js';
196
+ const urls = builtUrls();
197
+ const loaderUrl = urls?.get(LOADER_ENTRY) ?? '/cl-loader.js';
198
+ const routerUrl = urls?.get(ROUTER_ENTRY) ?? '/cl-router.js';
199
+ const navUrl = urls?.get(NAV_ENTRY) ?? '/cl-nav.js';
200
+ // Built: hashed chunk URLs. Dev: the source, served as JS by Vite.
201
+ const client = {};
202
+ for (const [route, file] of clientPages(root, modes)) {
203
+ const key = `${relative(root, file).split(sep).join('/')}?render`;
204
+ const url = urls ? urls.get(key) : `${clientUrlFor(root, file).replace(/\?.*$/, '')}?render&import`;
205
+ if (!url)
206
+ throw new Error(`clarusjs: no client chunk for ${key}`);
207
+ client[route] = url;
208
+ }
142
209
  return `import { createHandler } from ${JSON.stringify(here('../server/handler'))}\n` +
143
- `export default createHandler(import.meta.glob('/src/pages/**/*.tscl'), { loaderUrl: ${JSON.stringify(loaderUrl)} })\n`;
210
+ `import { registerViews, render } from ${JSON.stringify(here('../server/views'))}\n` +
211
+ // Every view under src/, for render(name, props) in server code. Also exported for apps that import the build.
212
+ `registerViews(import.meta.glob('/src/**/*.tscl'))\n` +
213
+ `export { render }\n` +
214
+ `export default createHandler(import.meta.glob('/src/pages/**/*.tscl'), {\n` +
215
+ ` loaderUrl: ${JSON.stringify(loaderUrl)},\n` +
216
+ ` data: import.meta.glob('/src/pages/**/*.load.ts'),\n` +
217
+ ` modes: ${JSON.stringify(modes)},\n` +
218
+ ` routerUrl: ${JSON.stringify(routerUrl)},\n` +
219
+ ` client: ${JSON.stringify(client)},\n` +
220
+ ` base: ${JSON.stringify(base)},\n` +
221
+ ` fragments: ${options.fragments === true},\n` +
222
+ ` navUrl: ${JSON.stringify(navUrl)},\n` +
223
+ `})\n`;
144
224
  },
145
225
  transform: {
146
226
  filter: { id: /\.tscl(\?|$)/ },
147
227
  handler(code, id) {
148
228
  const file = id.replace(/\?.*$/, '');
149
229
  // ?render: a component's server render function, used in the browser to render children of islands.
150
- const target = this.environment.config.consumer === 'server' || /[?&]render\b/.test(id) ? 'server' : 'client';
230
+ const renderQuery = /[?&]render\b/.test(id);
231
+ const target = this.environment.config.consumer === 'server' || renderQuery ? 'server' : 'client';
151
232
  // ponytail: ?import makes Vite's dev transform middleware serve .tscl as JS for the loader's dynamic import; build output uses hashed chunk URLs from the client manifest (stage 3)
152
233
  const consumer = this.environment.config.consumer;
153
234
  // Server build: chunk URLs come from the client manifest. Client build (a ?render child): the chunk doesn't
154
235
  // exist yet, so write a placeholder that generateBundle swaps for the real file name. Dev: the source URL.
155
236
  const urls = consumer === 'server' ? builtUrls() : undefined;
237
+ // Built URLs by entry name, or by source key when the name was sanitized ([tag] → _tag_).
156
238
  const clientUrl = urls
157
- ? urls.get(entryName(root, file))
239
+ ? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/'))
158
240
  : command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
159
241
  if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
160
242
  this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
161
243
  }
162
244
  try {
163
- return { code: compile(code, { file, target, clientUrl }).code, map: null };
245
+ // A ?render module runs in the browser: its child components must be render modules too.
246
+ const renderImports = renderQuery && this.environment.config.consumer !== 'server';
247
+ return { code: compile(code, { file, target, clientUrl, renderImports }).code, map: null };
164
248
  }
165
249
  catch (err) {
166
250
  if (err instanceof ClarusError)
@@ -174,7 +258,13 @@ export default function clarusjs() {
174
258
  const outDir = resolve(server.config.root, server.config.build.outDir);
175
259
  const base = server.config.base; // e.g. '/' or '/docs/'; Vite strips it after this middleware
176
260
  server.middlewares.use((req, _res, next) => {
177
- const url = decodeURIComponent((req.url ?? '/').split('?')[0]);
261
+ let url;
262
+ try {
263
+ url = decodeURIComponent((req.url ?? '/').split('?')[0]);
264
+ }
265
+ catch {
266
+ return next(); // a malformed %-escape names no built page
267
+ }
178
268
  const inBase = url === base.slice(0, -1) ? '/' : url.startsWith(base) ? '/' + url.slice(base.length) : undefined;
179
269
  if (inBase !== undefined) {
180
270
  // A built page wins; anything else (assets, /x.css) falls through to Vite's static files.
@@ -184,6 +274,26 @@ export default function clarusjs() {
184
274
  }
185
275
  next();
186
276
  });
277
+ // Server routes go to the built handler, as they would in production; anything else that isn't a file is a 404.
278
+ return () => {
279
+ server.middlewares.use(async (req, res, next) => {
280
+ try {
281
+ const entry = resolve(server.config.root, SERVER_OUT, 'index.mjs');
282
+ if (!existsSync(entry))
283
+ return next();
284
+ const app = (await import(__rewriteRelativeImportExtension(pathToFileURL(entry).href)));
285
+ if (!app.default.isServerPath((req.url ?? '/').split('?')[0]))
286
+ return next();
287
+ const response = await app.default.fetch(toRequest(req));
288
+ if (response.status === 404)
289
+ return next();
290
+ await sendResponse(res, response);
291
+ }
292
+ catch (err) {
293
+ next(err);
294
+ }
295
+ });
296
+ };
187
297
  },
188
298
  configureServer(server) {
189
299
  return () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clarusjs",
3
- "version": "0.4.0",
3
+ "version": "0.6.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": [
@@ -52,6 +52,10 @@
52
52
  "./manifest": {
53
53
  "types": "./dist/server/manifest.d.ts",
54
54
  "default": "./dist/server/manifest.js"
55
+ },
56
+ "./views": {
57
+ "types": "./dist/server/views.d.ts",
58
+ "default": "./dist/server/views.js"
55
59
  }
56
60
  },
57
61
  "bin": {