clarusjs 0.14.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.
Files changed (45) hide show
  1. package/dist/check/generate.d.ts +2 -5
  2. package/dist/check/generate.js +106 -5
  3. package/dist/cli/check.d.ts +4 -0
  4. package/dist/cli/check.js +3 -1
  5. package/dist/cli/mapper.js +19 -1
  6. package/dist/cli/project.d.ts +4 -0
  7. package/dist/cli/project.js +1 -1
  8. package/dist/compiler/class-style.js +2 -2
  9. package/dist/compiler/components.d.ts +32 -0
  10. package/dist/compiler/components.js +63 -0
  11. package/dist/compiler/emit-client.js +18 -3
  12. package/dist/compiler/emit-server.js +11 -8
  13. package/dist/compiler/html-expr.d.ts +2 -1
  14. package/dist/compiler/html-expr.js +15 -9
  15. package/dist/compiler/index.d.ts +13 -1
  16. package/dist/compiler/index.js +54 -1
  17. package/dist/compiler/ir.d.ts +20 -0
  18. package/dist/compiler/ir.js +78 -11
  19. package/dist/compiler/parse.d.ts +20 -0
  20. package/dist/compiler/parse.js +27 -10
  21. package/dist/compiler/script.d.ts +11 -0
  22. package/dist/compiler/script.js +41 -0
  23. package/dist/compiler/shared.d.ts +6 -0
  24. package/dist/compiler/shared.js +14 -0
  25. package/dist/forms/index.js +15 -3
  26. package/dist/runtime/attrs.d.ts +6 -0
  27. package/dist/runtime/attrs.js +16 -0
  28. package/dist/runtime/dom.d.ts +33 -1
  29. package/dist/runtime/dom.js +128 -23
  30. package/dist/runtime/html.d.ts +6 -0
  31. package/dist/runtime/html.js +12 -0
  32. package/dist/runtime/index.d.ts +1 -1
  33. package/dist/runtime/index.js +1 -1
  34. package/dist/runtime/loader.js +32 -6
  35. package/dist/runtime/router.d.ts +6 -1
  36. package/dist/runtime/router.js +1 -1
  37. package/dist/runtime/server.d.ts +8 -2
  38. package/dist/runtime/server.js +14 -7
  39. package/dist/server/handler.d.ts +28 -1
  40. package/dist/server/handler.js +44 -1
  41. package/dist/server/modes.d.ts +2 -0
  42. package/dist/server/modes.js +5 -1
  43. package/dist/vite/plugin.d.ts +19 -0
  44. package/dist/vite/plugin.js +46 -12
  45. package/package.json +1 -1
@@ -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;
@@ -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 = folder !== undefined ? route === (folder || '/') || route.startsWith(`${folder}/`) : route === pattern;
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 };
@@ -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. */
@@ -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.find(resolve(root, 'src/pages'))) {
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.find(resolve(appRoot, 'src/pages'))) {
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.find(resolve(builder.config.root, 'src/pages')).map((f) => routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`)));
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.find(resolve(builder.config.root, 'src/pages')).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
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
- ` endpoints: import.meta.glob(['/src/pages/**/*.ts', '!/src/pages/**/*.load.ts', '!/src/pages/**/*.d.ts']),\n` +
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` +
@@ -578,7 +611,7 @@ export default function clarusjs(options = {}) {
578
611
  const clientUrl = urls
579
612
  ? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/')) ?? urls.get(real(file))
580
613
  : command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
581
- 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) {
582
615
  this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
583
616
  }
584
617
  let parsed;
@@ -602,7 +635,8 @@ export default function clarusjs(options = {}) {
602
635
  const collapseWhitespace = command === 'build' && options.collapseWhitespace !== false;
603
636
  const loader = componentLoaderOf(root, file) ? relative(root, file).split(sep).join('/') : undefined;
604
637
  const hot = command === 'serve' && target === 'client' ? '/cl-hot.js' : undefined;
605
- const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot, icon: iconsFor(file) });
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) });
606
640
  if (consumer === 'server' && !renderQuery)
607
641
  for (const w of out.warnings)
608
642
  this.warn(w.message);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clarusjs",
3
- "version": "0.14.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": [