@celljs/vite 4.3.0 → 4.4.1

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 (116) 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 +23 -2
  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 +17 -2
  45. package/lib/plugin/cell-plugin.d.ts.map +1 -1
  46. package/lib/plugin/cell-plugin.js +63 -5
  47. package/lib/plugin/cell-plugin.js.map +1 -1
  48. package/lib/plugin/cell-plugin.spec.js +15 -0
  49. package/lib/plugin/cell-plugin.spec.js.map +1 -1
  50. package/lib/plugin/class-name-util.d.ts +14 -0
  51. package/lib/plugin/class-name-util.d.ts.map +1 -0
  52. package/lib/plugin/class-name-util.js +82 -0
  53. package/lib/plugin/class-name-util.js.map +1 -0
  54. package/lib/plugin/class-name-util.spec.d.ts +2 -0
  55. package/lib/plugin/class-name-util.spec.d.ts.map +1 -0
  56. package/lib/plugin/class-name-util.spec.js +37 -0
  57. package/lib/plugin/class-name-util.spec.js.map +1 -0
  58. package/lib/project/browser-dependency-scanner.d.ts +29 -0
  59. package/lib/project/browser-dependency-scanner.d.ts.map +1 -0
  60. package/lib/project/browser-dependency-scanner.js +96 -0
  61. package/lib/project/browser-dependency-scanner.js.map +1 -0
  62. package/lib/project/browser-dependency-scanner.spec.d.ts +2 -0
  63. package/lib/project/browser-dependency-scanner.spec.d.ts.map +1 -0
  64. package/lib/project/browser-dependency-scanner.spec.js +41 -0
  65. package/lib/project/browser-dependency-scanner.spec.js.map +1 -0
  66. package/lib/project/config-loader.d.ts +6 -6
  67. package/lib/project/config-loader.d.ts.map +1 -1
  68. package/lib/project/config-loader.js +16 -22
  69. package/lib/project/config-loader.js.map +1 -1
  70. package/lib/project/config-schema.d.ts +107 -0
  71. package/lib/project/config-schema.d.ts.map +1 -0
  72. package/lib/project/config-schema.js +522 -0
  73. package/lib/project/config-schema.js.map +1 -0
  74. package/lib/project/config-schema.spec.d.ts +2 -0
  75. package/lib/project/config-schema.spec.d.ts.map +1 -0
  76. package/lib/project/config-schema.spec.js +248 -0
  77. package/lib/project/config-schema.spec.js.map +1 -0
  78. package/lib/project/env-overrides.d.ts +14 -10
  79. package/lib/project/env-overrides.d.ts.map +1 -1
  80. package/lib/project/env-overrides.js +28 -19
  81. package/lib/project/env-overrides.js.map +1 -1
  82. package/lib/project/env-overrides.spec.js +23 -13
  83. package/lib/project/env-overrides.spec.js.map +1 -1
  84. package/lib/project/page-scanner.d.ts +26 -0
  85. package/lib/project/page-scanner.d.ts.map +1 -0
  86. package/lib/project/page-scanner.js +102 -0
  87. package/lib/project/page-scanner.js.map +1 -0
  88. package/lib/project/page-scanner.spec.d.ts +2 -0
  89. package/lib/project/page-scanner.spec.d.ts.map +1 -0
  90. package/lib/project/page-scanner.spec.js +68 -0
  91. package/lib/project/page-scanner.spec.js.map +1 -0
  92. package/lib/project/project-loader.d.ts +32 -3
  93. package/lib/project/project-loader.d.ts.map +1 -1
  94. package/lib/project/project-loader.js +70 -15
  95. package/lib/project/project-loader.js.map +1 -1
  96. package/lib/project/project-loader.spec.js +78 -56
  97. package/lib/project/project-loader.spec.js.map +1 -1
  98. package/lib/testing/test-app.spec.js +3 -3
  99. package/lib/testing/test-app.spec.js.map +1 -1
  100. package/package.json +7 -7
  101. package/src/constants.ts +0 -3
  102. package/src/dev/cell-dev-server.ts +39 -5
  103. package/src/expression/expression-evaluator.ts +16 -3
  104. package/src/generator/config-generator.ts +7 -5
  105. package/src/generator/html-generator.ts +3 -3
  106. package/src/generator/route-generator.ts +34 -0
  107. package/src/index.ts +1 -0
  108. package/src/output/output-writer.ts +12 -0
  109. package/src/plugin/cell-plugin.ts +68 -6
  110. package/src/plugin/class-name-util.ts +85 -0
  111. package/src/project/browser-dependency-scanner.ts +102 -0
  112. package/src/project/config-loader.ts +18 -23
  113. package/src/project/config-schema.ts +596 -0
  114. package/src/project/env-overrides.ts +33 -22
  115. package/src/project/page-scanner.ts +105 -0
  116. package/src/project/project-loader.ts +82 -17
@@ -2,16 +2,20 @@ import { existsSync, readFileSync, realpathSync, rmSync } from 'node:fs';
2
2
  import { createRequire } from 'node:module';
3
3
  import { dirname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { CellError, type ModuleRef, type ProjectModel, type ServerRuntime, type Target } from '@celljs/kit';
5
- import type { ConfigEnv, Plugin, UserConfig, ViteBuilder } from 'vite';
5
+ import type { ConfigEnv, Plugin, Rolldown, UserConfig, ViteBuilder } from 'vite';
6
6
  import { ASSETS_ID, ENTRY_URL, ENVIRONMENT_OF, SINGLE_ENTRY_ID, TARGET_OF, WORKERD_SERVER_FILE } from '../constants.js';
7
7
  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 { BrowserDependencyScanner } from '../project/browser-dependency-scanner.js';
15
+ import { PageScanner } from '../project/page-scanner.js';
13
16
  import { ProjectLoader, type ProjectLoaderOptions } from '../project/project-loader.js';
14
17
  import { TsconfigUtil } from '../utils/tsconfig-util.js';
18
+ import { ClassNameUtil } from './class-name-util.js';
15
19
  import { NodePolyfills } from './node-polyfills.js';
16
20
 
17
21
  export interface CellPluginOptions extends ProjectLoaderOptions {
@@ -45,6 +49,7 @@ type ResolveContext = { resolve(id: string, importer?: string, options?: { skipS
45
49
  */
46
50
  export class CellPlugin {
47
51
  protected model: ProjectModel;
52
+ protected loader: ProjectLoader;
48
53
  protected root: string;
49
54
  protected coreDir: string;
50
55
  protected output: OutputWriter;
@@ -75,7 +80,8 @@ export class CellPlugin {
75
80
  },
76
81
  transform(code, id) {
77
82
  if (self.command === 'build') {
78
- return CellPlugin.withoutRequireShim(code);
83
+ const named = ClassNameUtil.applies(id, self.componentNames) ? ClassNameUtil.preserve(code, id) : undefined;
84
+ return CellPlugin.withoutRequireShim(named ?? code) ?? named ?? null;
79
85
  }
80
86
  // In development Node runs the files: Cell packages keep their require shim, sources get one.
81
87
  return this.environment.name === 'server' ? CellPlugin.withRequire(code, id) : null;
@@ -228,12 +234,14 @@ export class CellPlugin {
228
234
  this.command = env.command;
229
235
  this.root = realpathSync(resolve(userConfig.root ?? this.options.root ?? process.cwd()));
230
236
  const mode = this.options.mode ?? [env.command === 'build' ? 'production' : 'development'];
231
- this.model = new ProjectLoader({ ...this.options, root: this.root, mode }).load();
237
+ this.loader = new ProjectLoader({ ...this.options, root: this.root, mode });
238
+ this.model = this.loader.load();
232
239
  this.coreDir = this.resolveCoreDir();
233
240
  this.output = new OutputWriter(this.model, resolve(this.root, this.options.outDir ?? '.cell/output'), this.format, this.options.preset);
234
241
  this.evaluator = new ExpressionEvaluator(this.root);
235
242
  this.polyfills = new NodePolyfills(this.root);
236
243
  this.output.writeGenerated('project.json', `${JSON.stringify(this.model, null, 2)}\n`);
244
+ this.output.writeSchema(this.loader.schema);
237
245
  const nodeEnv = JSON.stringify(env.command === 'build' ? 'production' : 'development');
238
246
  if (env.command === 'serve') {
239
247
  return this.devConfig(nodeEnv);
@@ -250,7 +258,7 @@ export class CellPlugin {
250
258
  outDir: this.output.publicDir,
251
259
  emptyOutDir: true,
252
260
  sourcemap: this.options.sourcemap ?? false,
253
- rolldownOptions: { input: { index: this.htmlFile } },
261
+ rolldownOptions: { input: { index: this.htmlFile }, onLog: CellPlugin.onLog },
254
262
  },
255
263
  },
256
264
  server: {
@@ -268,6 +276,7 @@ export class CellPlugin {
268
276
  target: 'node20',
269
277
  rolldownOptions: {
270
278
  external: (id: string) => this.isExternal(id),
279
+ onLog: CellPlugin.onLog,
271
280
  output: { format: this.format, entryFileNames: this.output.serverEntry, codeSplitting: false },
272
281
  },
273
282
  },
@@ -292,7 +301,7 @@ export class CellPlugin {
292
301
  environments: {
293
302
  client: {
294
303
  define: { 'process.env.NODE_ENV': nodeEnv, global: 'globalThis' },
295
- optimizeDeps: { exclude: ['@celljs/core', ...this.componentNames] },
304
+ optimizeDeps: { exclude: ['@celljs/core', ...this.componentNames], include: new BrowserDependencyScanner(this.model).scan() },
296
305
  },
297
306
  server: {
298
307
  consumer: 'server',
@@ -303,6 +312,17 @@ export class CellPlugin {
303
312
  };
304
313
  }
305
314
 
315
+ /**
316
+ * Drops the warning about `"use client"` / `"use server"` (React Server Components) that every
317
+ * bundled package marked with them gives: Cell bundles no server components, so it means nothing here.
318
+ */
319
+ static readonly onLog: NonNullable<Rolldown.InputOptions['onLog']> = (level, log, handler) => {
320
+ if (log.code === 'MODULE_LEVEL_DIRECTIVE' && /"use (client|server)"/.test(log.message)) {
321
+ return;
322
+ }
323
+ handler(level, log);
324
+ };
325
+
306
326
  /** Components of the project other than itself. */
307
327
  protected get componentNames(): string[] {
308
328
  return this.model.components.filter(c => !c.root).map(c => c.name);
@@ -398,10 +418,15 @@ export class CellPlugin {
398
418
  this.output.writeGenerated(`${target}/container.js`, code);
399
419
  return code;
400
420
  }
421
+ if (target === 'frontend' && this.isReactRoutesFile(id)) {
422
+ const code = new RouteGenerator(this.root).generate(targetModel.routes ?? []);
423
+ this.output.writeGenerated('frontend/routes.js', code);
424
+ return code;
425
+ }
401
426
  if (this.isCoreFile(id, 'common/config/dynamic-config.js')) {
402
427
  this.output.writeGenerated(`${target}/config.json`, `${JSON.stringify(targetModel.config, null, 2)}\n`);
403
428
  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);
429
+ return new ConfigGenerator(target, this.format, outputDir).generate(targetModel.config, targetModel.configTypes);
405
430
  }
406
431
  return null;
407
432
  }
@@ -459,6 +484,43 @@ export class CellPlugin {
459
484
  return file.startsWith(this.coreDir) && (file.endsWith(`/esm/${path}`) || file.endsWith(`/lib/${path}`));
460
485
  }
461
486
 
487
+ /** The file of @celljs/react that the routes of `src/browser/pages` replace. */
488
+ static readonly ROUTES_FILE = 'browser/router/dynamic-routes.js';
489
+
490
+ protected reactDir?: string | null;
491
+
492
+ protected isReactRoutesFile(id: string): boolean {
493
+ const file = id.split('?')[0].replace(/\\/g, '/');
494
+ if (!file.endsWith(`/esm/${CellPlugin.ROUTES_FILE}`) && !file.endsWith(`/lib/${CellPlugin.ROUTES_FILE}`)) {
495
+ return false;
496
+ }
497
+ if (this.reactDir === undefined) {
498
+ try {
499
+ const manifest = createRequire(join(this.root, 'package.json')).resolve('@celljs/react/package.json');
500
+ this.reactDir = realpathSync(dirname(manifest)).replace(/\\/g, '/');
501
+ } catch {
502
+ this.reactDir = null;
503
+ }
504
+ }
505
+ return this.reactDir !== null && file.startsWith(`${this.reactDir}/`);
506
+ }
507
+
508
+ /**
509
+ * Scans `src/browser/pages` again (`cell dev` after a page was added or removed). Returns whether
510
+ * the routes changed; the caller reloads the module of {@link ROUTES_FILE}.
511
+ */
512
+ refreshRoutes(): boolean {
513
+ const frontend = this.model.frontend;
514
+ if (!frontend) {
515
+ return false;
516
+ }
517
+ const routes = new PageScanner(this.root).scan();
518
+ const changed = JSON.stringify(routes) !== JSON.stringify(frontend.routes ?? []);
519
+ frontend.routes = routes;
520
+ this.output.writeGenerated('project.json', `${JSON.stringify(this.model, null, 2)}\n`);
521
+ return changed;
522
+ }
523
+
462
524
  protected resolveCoreDir(): string {
463
525
  try {
464
526
  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
+ }
@@ -0,0 +1,102 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import type { ComponentInfo, ProjectModel } from '@celljs/kit';
4
+ import { ComponentCollector } from './component-collector.js';
5
+
6
+ /**
7
+ * Finds what the components of the frontend import from third-party packages, as `optimizeDeps.include`
8
+ * entries of `cell dev` (`'@celljs/react > react-router'`).
9
+ *
10
+ * Components are excluded from pre-bundling (they must see the generated container and share one
11
+ * @celljs/core), and Vite discovers no dependency imported from a file under node_modules. Installed
12
+ * components therefore served their imports raw: an ES module importing CommonJS (react-router importing
13
+ * react) then fails in the browser. Listing the imports up front pre-bundles them before the first page.
14
+ */
15
+ export class BrowserDependencyScanner {
16
+ protected static readonly IMPORT = /(?:^|[^\w$.])(?:import|export)\s*(?:[\w$*{}\s,]+\s*from\s*)?\(?\s*['"]([^'"\n]+)['"]/g;
17
+ protected static readonly SKIPPED_DIRS = new Set(['node_modules', 'node', 'src', 'test', '__tests__']);
18
+
19
+ protected readonly components: Map<string, ComponentInfo>;
20
+
21
+ constructor(protected readonly model: ProjectModel) {
22
+ this.components = new Map(model.components.filter(c => !c.root).map(c => [c.name, c]));
23
+ }
24
+
25
+ /** Sorted `<component> > <specifier>` entries, each import once. */
26
+ scan(): string[] {
27
+ const includes = new Set<string>();
28
+ for (const component of this.frontendComponents()) {
29
+ const dependencies = this.thirdPartyDependencies(component);
30
+ if (dependencies.size === 0) {
31
+ continue;
32
+ }
33
+ for (const specifier of this.imports(component.dir)) {
34
+ if (dependencies.has(BrowserDependencyScanner.packageName(specifier))) {
35
+ includes.add(`${component.name} > ${specifier}`);
36
+ }
37
+ }
38
+ }
39
+ return [...includes].sort();
40
+ }
41
+
42
+ /** Components with frontend modules, and the components they depend on. */
43
+ protected frontendComponents(): ComponentInfo[] {
44
+ const frontend = this.model.frontend;
45
+ if (!frontend) {
46
+ return [];
47
+ }
48
+ const pending = [...frontend.staticModules, ...frontend.modules].map(m => m.component);
49
+ if (frontend.entryComponent) {
50
+ pending.push(frontend.entryComponent);
51
+ }
52
+ const found = new Map<string, ComponentInfo>();
53
+ for (let name = pending.pop(); name !== undefined; name = pending.pop()) {
54
+ const component = this.components.get(name);
55
+ if (!component || found.has(name)) {
56
+ continue;
57
+ }
58
+ found.set(name, component);
59
+ pending.push(...Object.keys(this.packageJson(component).dependencies ?? {}));
60
+ }
61
+ return [...found.values()];
62
+ }
63
+
64
+ /** Dependencies that are neither components (excluded from pre-bundling) nor type packages. */
65
+ protected thirdPartyDependencies(component: ComponentInfo): Set<string> {
66
+ return new Set(Object.keys(this.packageJson(component).dependencies ?? {}).filter(name => !this.components.has(name) && !name.startsWith('@types/')));
67
+ }
68
+
69
+ protected packageJson(component: ComponentInfo) {
70
+ return ComponentCollector.readPackageJson(join(component.dir, 'package.json'));
71
+ }
72
+
73
+ /** Bare specifiers imported by the ES modules of a package, leaving out node-only and test files. */
74
+ protected imports(dir: string): Set<string> {
75
+ const specifiers = new Set<string>();
76
+ const visit = (current: string) => {
77
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
78
+ if (entry.isDirectory()) {
79
+ if (!entry.name.startsWith('.') && !BrowserDependencyScanner.SKIPPED_DIRS.has(entry.name)) {
80
+ visit(join(current, entry.name));
81
+ }
82
+ } else if (/\.m?js$/.test(entry.name) && !/\.(spec|test)\.m?js$/.test(entry.name)) {
83
+ for (const match of readFileSync(join(current, entry.name), 'utf8').matchAll(BrowserDependencyScanner.IMPORT)) {
84
+ if (!/^[./]/.test(match[1]) && !match[1].includes(':')) {
85
+ specifiers.add(match[1]);
86
+ }
87
+ }
88
+ }
89
+ }
90
+ };
91
+ if (existsSync(dir)) {
92
+ visit(dir);
93
+ }
94
+ return specifiers;
95
+ }
96
+
97
+ /** `react-dom/client` → `react-dom`, `@scope/pkg/sub` → `@scope/pkg`. */
98
+ static packageName(specifier: string): string {
99
+ const parts = specifier.split('/');
100
+ return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
101
+ }
102
+ }
@@ -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;