@celljs/vite 4.2.0 → 4.4.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 (105) hide show
  1. package/README.md +2 -1
  2. package/lib/builder/cell-builder.spec.js +27 -21
  3. package/lib/builder/cell-builder.spec.js.map +1 -1
  4. package/lib/builder/pages.spec.d.ts +2 -0
  5. package/lib/builder/pages.spec.d.ts.map +1 -0
  6. package/lib/builder/pages.spec.js +96 -0
  7. package/lib/builder/pages.spec.js.map +1 -0
  8. package/lib/constants.d.ts +0 -2
  9. package/lib/constants.d.ts.map +1 -1
  10. package/lib/constants.js +0 -2
  11. package/lib/constants.js.map +1 -1
  12. package/lib/dev/cell-dev-server.d.ts +4 -2
  13. package/lib/dev/cell-dev-server.d.ts.map +1 -1
  14. package/lib/dev/cell-dev-server.js +32 -2
  15. package/lib/dev/cell-dev-server.js.map +1 -1
  16. package/lib/dev/cell-dev-server.spec.js +1 -1
  17. package/lib/dev/cell-dev-server.spec.js.map +1 -1
  18. package/lib/expression/expression-evaluator.d.ts +11 -2
  19. package/lib/expression/expression-evaluator.d.ts.map +1 -1
  20. package/lib/expression/expression-evaluator.js +6 -2
  21. package/lib/expression/expression-evaluator.js.map +1 -1
  22. package/lib/expression/expression-evaluator.spec.js +3 -3
  23. package/lib/expression/expression-evaluator.spec.js.map +1 -1
  24. package/lib/generator/config-generator.d.ts +4 -3
  25. package/lib/generator/config-generator.d.ts.map +1 -1
  26. package/lib/generator/config-generator.js +7 -5
  27. package/lib/generator/config-generator.js.map +1 -1
  28. package/lib/generator/generator.spec.js +20 -5
  29. package/lib/generator/generator.spec.js.map +1 -1
  30. package/lib/generator/html-generator.js +3 -3
  31. package/lib/generator/html-generator.js.map +1 -1
  32. package/lib/generator/route-generator.d.ts +13 -0
  33. package/lib/generator/route-generator.d.ts.map +1 -0
  34. package/lib/generator/route-generator.js +34 -0
  35. package/lib/generator/route-generator.js.map +1 -0
  36. package/lib/index.d.ts +1 -0
  37. package/lib/index.d.ts.map +1 -1
  38. package/lib/index.js +1 -0
  39. package/lib/index.js.map +1 -1
  40. package/lib/output/output-writer.d.ts +4 -0
  41. package/lib/output/output-writer.d.ts.map +1 -1
  42. package/lib/output/output-writer.js +10 -0
  43. package/lib/output/output-writer.js.map +1 -1
  44. package/lib/plugin/cell-plugin.d.ts +11 -1
  45. package/lib/plugin/cell-plugin.d.ts.map +1 -1
  46. package/lib/plugin/cell-plugin.js +49 -3
  47. package/lib/plugin/cell-plugin.js.map +1 -1
  48. package/lib/plugin/class-name-util.d.ts +14 -0
  49. package/lib/plugin/class-name-util.d.ts.map +1 -0
  50. package/lib/plugin/class-name-util.js +82 -0
  51. package/lib/plugin/class-name-util.js.map +1 -0
  52. package/lib/plugin/class-name-util.spec.d.ts +2 -0
  53. package/lib/plugin/class-name-util.spec.d.ts.map +1 -0
  54. package/lib/plugin/class-name-util.spec.js +37 -0
  55. package/lib/plugin/class-name-util.spec.js.map +1 -0
  56. package/lib/project/config-loader.d.ts +6 -6
  57. package/lib/project/config-loader.d.ts.map +1 -1
  58. package/lib/project/config-loader.js +16 -22
  59. package/lib/project/config-loader.js.map +1 -1
  60. package/lib/project/config-schema.d.ts +107 -0
  61. package/lib/project/config-schema.d.ts.map +1 -0
  62. package/lib/project/config-schema.js +522 -0
  63. package/lib/project/config-schema.js.map +1 -0
  64. package/lib/project/config-schema.spec.d.ts +2 -0
  65. package/lib/project/config-schema.spec.d.ts.map +1 -0
  66. package/lib/project/config-schema.spec.js +248 -0
  67. package/lib/project/config-schema.spec.js.map +1 -0
  68. package/lib/project/env-overrides.d.ts +14 -10
  69. package/lib/project/env-overrides.d.ts.map +1 -1
  70. package/lib/project/env-overrides.js +28 -19
  71. package/lib/project/env-overrides.js.map +1 -1
  72. package/lib/project/env-overrides.spec.js +23 -13
  73. package/lib/project/env-overrides.spec.js.map +1 -1
  74. package/lib/project/page-scanner.d.ts +26 -0
  75. package/lib/project/page-scanner.d.ts.map +1 -0
  76. package/lib/project/page-scanner.js +102 -0
  77. package/lib/project/page-scanner.js.map +1 -0
  78. package/lib/project/page-scanner.spec.d.ts +2 -0
  79. package/lib/project/page-scanner.spec.d.ts.map +1 -0
  80. package/lib/project/page-scanner.spec.js +68 -0
  81. package/lib/project/page-scanner.spec.js.map +1 -0
  82. package/lib/project/project-loader.d.ts +32 -3
  83. package/lib/project/project-loader.d.ts.map +1 -1
  84. package/lib/project/project-loader.js +70 -15
  85. package/lib/project/project-loader.js.map +1 -1
  86. package/lib/project/project-loader.spec.js +78 -56
  87. package/lib/project/project-loader.spec.js.map +1 -1
  88. package/lib/testing/test-app.spec.js +3 -3
  89. package/lib/testing/test-app.spec.js.map +1 -1
  90. package/package.json +7 -7
  91. package/src/constants.ts +0 -3
  92. package/src/dev/cell-dev-server.ts +39 -5
  93. package/src/expression/expression-evaluator.ts +16 -3
  94. package/src/generator/config-generator.ts +7 -5
  95. package/src/generator/html-generator.ts +3 -3
  96. package/src/generator/route-generator.ts +34 -0
  97. package/src/index.ts +1 -0
  98. package/src/output/output-writer.ts +12 -0
  99. package/src/plugin/cell-plugin.ts +52 -3
  100. package/src/plugin/class-name-util.ts +85 -0
  101. package/src/project/config-loader.ts +18 -23
  102. package/src/project/config-schema.ts +596 -0
  103. package/src/project/env-overrides.ts +33 -22
  104. package/src/project/page-scanner.ts +105 -0
  105. package/src/project/project-loader.ts +82 -17
@@ -8,10 +8,13 @@ import { ExpressionEvaluator } from '../expression/expression-evaluator.js';
8
8
  import { ConfigGenerator } from '../generator/config-generator.js';
9
9
  import { ContainerGenerator } from '../generator/container-generator.js';
10
10
  import { HtmlGenerator } from '../generator/html-generator.js';
11
+ import { RouteGenerator } from '../generator/route-generator.js';
11
12
  import { AssetEmbedder } from '../output/asset-embedder.js';
12
13
  import { OutputWriter } from '../output/output-writer.js';
14
+ import { PageScanner } from '../project/page-scanner.js';
13
15
  import { ProjectLoader, type ProjectLoaderOptions } from '../project/project-loader.js';
14
16
  import { TsconfigUtil } from '../utils/tsconfig-util.js';
17
+ import { ClassNameUtil } from './class-name-util.js';
15
18
  import { NodePolyfills } from './node-polyfills.js';
16
19
 
17
20
  export interface CellPluginOptions extends ProjectLoaderOptions {
@@ -45,6 +48,7 @@ type ResolveContext = { resolve(id: string, importer?: string, options?: { skipS
45
48
  */
46
49
  export class CellPlugin {
47
50
  protected model: ProjectModel;
51
+ protected loader: ProjectLoader;
48
52
  protected root: string;
49
53
  protected coreDir: string;
50
54
  protected output: OutputWriter;
@@ -75,7 +79,8 @@ export class CellPlugin {
75
79
  },
76
80
  transform(code, id) {
77
81
  if (self.command === 'build') {
78
- return CellPlugin.withoutRequireShim(code);
82
+ const named = ClassNameUtil.applies(id, self.componentNames) ? ClassNameUtil.preserve(code, id) : undefined;
83
+ return CellPlugin.withoutRequireShim(named ?? code) ?? named ?? null;
79
84
  }
80
85
  // In development Node runs the files: Cell packages keep their require shim, sources get one.
81
86
  return this.environment.name === 'server' ? CellPlugin.withRequire(code, id) : null;
@@ -228,12 +233,14 @@ export class CellPlugin {
228
233
  this.command = env.command;
229
234
  this.root = realpathSync(resolve(userConfig.root ?? this.options.root ?? process.cwd()));
230
235
  const mode = this.options.mode ?? [env.command === 'build' ? 'production' : 'development'];
231
- this.model = new ProjectLoader({ ...this.options, root: this.root, mode }).load();
236
+ this.loader = new ProjectLoader({ ...this.options, root: this.root, mode });
237
+ this.model = this.loader.load();
232
238
  this.coreDir = this.resolveCoreDir();
233
239
  this.output = new OutputWriter(this.model, resolve(this.root, this.options.outDir ?? '.cell/output'), this.format, this.options.preset);
234
240
  this.evaluator = new ExpressionEvaluator(this.root);
235
241
  this.polyfills = new NodePolyfills(this.root);
236
242
  this.output.writeGenerated('project.json', `${JSON.stringify(this.model, null, 2)}\n`);
243
+ this.output.writeSchema(this.loader.schema);
237
244
  const nodeEnv = JSON.stringify(env.command === 'build' ? 'production' : 'development');
238
245
  if (env.command === 'serve') {
239
246
  return this.devConfig(nodeEnv);
@@ -398,10 +405,15 @@ export class CellPlugin {
398
405
  this.output.writeGenerated(`${target}/container.js`, code);
399
406
  return code;
400
407
  }
408
+ if (target === 'frontend' && this.isReactRoutesFile(id)) {
409
+ const code = new RouteGenerator(this.root).generate(targetModel.routes ?? []);
410
+ this.output.writeGenerated('frontend/routes.js', code);
411
+ return code;
412
+ }
401
413
  if (this.isCoreFile(id, 'common/config/dynamic-config.js')) {
402
414
  this.output.writeGenerated(`${target}/config.json`, `${JSON.stringify(targetModel.config, null, 2)}\n`);
403
415
  const outputDir = this.command === 'serve' ? resolve(this.root, this.options.outDir ?? '.cell/output') : undefined;
404
- return new ConfigGenerator(target, this.format, outputDir).generate(targetModel.config);
416
+ return new ConfigGenerator(target, this.format, outputDir).generate(targetModel.config, targetModel.configTypes);
405
417
  }
406
418
  return null;
407
419
  }
@@ -459,6 +471,43 @@ export class CellPlugin {
459
471
  return file.startsWith(this.coreDir) && (file.endsWith(`/esm/${path}`) || file.endsWith(`/lib/${path}`));
460
472
  }
461
473
 
474
+ /** The file of @celljs/react that the routes of `src/browser/pages` replace. */
475
+ static readonly ROUTES_FILE = 'browser/router/dynamic-routes.js';
476
+
477
+ protected reactDir?: string | null;
478
+
479
+ protected isReactRoutesFile(id: string): boolean {
480
+ const file = id.split('?')[0].replace(/\\/g, '/');
481
+ if (!file.endsWith(`/esm/${CellPlugin.ROUTES_FILE}`) && !file.endsWith(`/lib/${CellPlugin.ROUTES_FILE}`)) {
482
+ return false;
483
+ }
484
+ if (this.reactDir === undefined) {
485
+ try {
486
+ const manifest = createRequire(join(this.root, 'package.json')).resolve('@celljs/react/package.json');
487
+ this.reactDir = realpathSync(dirname(manifest)).replace(/\\/g, '/');
488
+ } catch {
489
+ this.reactDir = null;
490
+ }
491
+ }
492
+ return this.reactDir !== null && file.startsWith(`${this.reactDir}/`);
493
+ }
494
+
495
+ /**
496
+ * Scans `src/browser/pages` again (`cell dev` after a page was added or removed). Returns whether
497
+ * the routes changed; the caller reloads the module of {@link ROUTES_FILE}.
498
+ */
499
+ refreshRoutes(): boolean {
500
+ const frontend = this.model.frontend;
501
+ if (!frontend) {
502
+ return false;
503
+ }
504
+ const routes = new PageScanner(this.root).scan();
505
+ const changed = JSON.stringify(routes) !== JSON.stringify(frontend.routes ?? []);
506
+ frontend.routes = routes;
507
+ this.output.writeGenerated('project.json', `${JSON.stringify(this.model, null, 2)}\n`);
508
+ return changed;
509
+ }
510
+
462
511
  protected resolveCoreDir(): string {
463
512
  try {
464
513
  const manifest = createRequire(join(this.root, 'package.json')).resolve('@celljs/core/package.json');
@@ -0,0 +1,85 @@
1
+ import { parseAst } from 'vite';
2
+
3
+ type Node = { type: string; start: number; end: number; [key: string]: any };
4
+
5
+ /**
6
+ * Bundling renames classes whose names collide (`class Context$1`) and minification shortens them
7
+ * (`class Qn`), and the bundler's `keepNames` misses classes of lazily initialized modules (the ones the
8
+ * generated container imports). Cell uses class names in logs, errors, default security resources,
9
+ * OpenAPI names and `on<Event>` handlers of aggregates, so `cell build` gives every named class of the
10
+ * project and its components a static block that defines its source name, before anything renames it.
11
+ */
12
+ export namespace ClassNameUtil {
13
+ const SOURCE = /\.([cm]?[jt]sx?)$/;
14
+
15
+ /** Sources of the project and of Cell packages and components; other dependencies are left alone. */
16
+ export function applies(id: string, componentNames: string[]): boolean {
17
+ const file = id.split('?')[0];
18
+ if (!SOURCE.test(file) || file.includes('\0') || file.endsWith('.d.ts')) {
19
+ return false;
20
+ }
21
+ const index = file.lastIndexOf('/node_modules/');
22
+ if (index < 0) {
23
+ return true;
24
+ }
25
+ const rest = file.slice(index + '/node_modules/'.length);
26
+ return rest.startsWith('@celljs/') || componentNames.some(name => rest.startsWith(`${name}/`));
27
+ }
28
+
29
+ /** The code with a name-defining static block in each named class, or `undefined` if it has none. */
30
+ export function preserve(code: string, id: string): string | undefined {
31
+ if (!/\bclass\b/.test(code)) {
32
+ return undefined;
33
+ }
34
+ const file = id.split('?')[0];
35
+ const ext = SOURCE.exec(file)?.[1] ?? 'js';
36
+ const lang = ext.includes('t') ? (ext.endsWith('x') ? 'tsx' : 'ts') : ext.endsWith('x') ? 'jsx' : 'js';
37
+ let program: Node;
38
+ try {
39
+ program = parseAst(code, { lang }, file) as unknown as Node;
40
+ } catch {
41
+ return undefined;
42
+ }
43
+ const inserts: { at: number; text: string }[] = [];
44
+ walk(program, node => {
45
+ if ((node.type === 'ClassDeclaration' || node.type === 'ClassExpression') && node.id?.name && !node.declare && !definesName(node)) {
46
+ inserts.push({ at: node.body.end - 1, text: staticBlock(node.id.name) });
47
+ }
48
+ });
49
+ if (inserts.length === 0) {
50
+ return undefined;
51
+ }
52
+ let result = code;
53
+ for (const { at, text } of inserts.sort((a, b) => b.at - a.at)) {
54
+ result = result.slice(0, at) + text + result.slice(at);
55
+ }
56
+ return result;
57
+ }
58
+
59
+ function staticBlock(name: string): string {
60
+ return ` static { Object.defineProperty(this, 'name', { value: ${JSON.stringify(name)}, configurable: true }); }`;
61
+ }
62
+
63
+ /** A class with its own static `name` member keeps it. */
64
+ function definesName(node: Node): boolean {
65
+ return node.body.body.some((member: Node) => member.static && !member.computed && (member.key?.name === 'name' || member.key?.value === 'name'));
66
+ }
67
+
68
+ function walk(node: unknown, visit: (node: Node) => void): void {
69
+ if (Array.isArray(node)) {
70
+ for (const child of node) {
71
+ walk(child, visit);
72
+ }
73
+ return;
74
+ }
75
+ if (!node || typeof node !== 'object' || typeof (node as Node).type !== 'string') {
76
+ return;
77
+ }
78
+ visit(node as Node);
79
+ for (const [key, value] of Object.entries(node)) {
80
+ if (key !== 'type' && value && typeof value === 'object') {
81
+ walk(value, visit);
82
+ }
83
+ }
84
+ }
85
+ }
@@ -1,53 +1,48 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { CellError, type Target } from '@celljs/kit';
3
+ import { CellError } from '@celljs/kit';
4
4
  import yaml from 'js-yaml';
5
- import { TOOLING_KEYS } from '../constants.js';
6
5
  import { ConfigUtil } from '../utils/config-util.js';
7
6
  import type { Component } from './component-collector.js';
7
+ import type { ConfigLayerFile } from './config-schema.js';
8
8
 
9
9
  /**
10
- * Merges the configuration layers of all components: for each component in order, `cell.yml` then
10
+ * Reads the configuration layers of all components: for each component in order, `cell.yml` then
11
11
  * `cell.<mode>.yml` for every active mode. Records the files it read on each component.
12
12
  */
13
13
  export class ConfigLoader {
14
14
  constructor(protected readonly mode: string[]) {}
15
15
 
16
- load(components: Component[]): Record<string, any> {
17
- const merged: Record<string, any> = {};
16
+ read(components: Component[]): ConfigLayerFile[] {
17
+ const layers: ConfigLayerFile[] = [];
18
18
  for (const component of components) {
19
19
  for (const file of this.layerFiles(component)) {
20
20
  component.configFiles.push(file);
21
- ConfigUtil.merge(merged, this.readYaml(file));
21
+ const text = readFileSync(file, 'utf8');
22
+ layers.push({ component: component.name, file, text, doc: this.parse(file, text) });
22
23
  }
23
24
  }
24
- return merged;
25
+ return layers;
25
26
  }
26
27
 
27
- /** Application configuration of one target: shared keys, then the target section, without tooling keys. */
28
- forTarget(merged: Record<string, any>, target: Target): Record<string, unknown> {
29
- const config: Record<string, any> = {};
30
- for (const [key, value] of Object.entries(merged)) {
31
- if (!TOOLING_KEYS.includes(key)) {
32
- config[key] = structuredClone(value);
33
- }
34
- }
35
- ConfigUtil.merge(config, structuredClone(merged[target] ?? {}));
36
- for (const key of TOOLING_KEYS) {
37
- delete config[key];
28
+ /** The layers merged in order: objects merge, arrays and scalars replace; `mode` is the active modes. */
29
+ merge(layers: ConfigLayerFile[]): Record<string, any> {
30
+ const merged: Record<string, any> = {};
31
+ for (const layer of layers) {
32
+ ConfigUtil.merge(merged, structuredClone(layer.doc));
38
33
  }
39
- config.mode = [...this.mode];
40
- return config;
34
+ merged.mode = [...this.mode];
35
+ return merged;
41
36
  }
42
37
 
43
38
  protected layerFiles(component: Component): string[] {
44
39
  return ['cell.yml', ...this.mode.map(m => `cell.${m}.yml`)].map(name => join(component.dir, name)).filter(existsSync);
45
40
  }
46
41
 
47
- protected readYaml(file: string): Record<string, any> {
42
+ protected parse(file: string, text: string): Record<string, any> {
48
43
  let value: unknown;
49
44
  try {
50
- value = yaml.load(readFileSync(file, 'utf8'));
45
+ value = yaml.load(text);
51
46
  } catch (cause) {
52
47
  const mark = (cause as { mark?: { line: number; column: number } }).mark;
53
48
  throw new CellError({
@@ -69,7 +64,7 @@ export class ConfigLoader {
69
64
  message: `${file} must contain a YAML mapping at the top level.`,
70
65
  file,
71
66
  line: 1,
72
- hint: 'Start the file with keys such as `cell:` or `backend:`.',
67
+ hint: 'Start the file with configuration keys such as `server:` or `app:`.',
73
68
  });
74
69
  }
75
70
  return value;