@celljs/vite 0.0.0-stage → 4.1.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.
- package/README.md +29 -2
- package/assets/favicon.ico +0 -0
- package/lib/builder/cell-builder.d.ts +19 -0
- package/lib/builder/cell-builder.d.ts.map +1 -0
- package/lib/builder/cell-builder.js +59 -0
- package/lib/builder/cell-builder.js.map +1 -0
- package/lib/builder/cell-builder.spec.d.ts +2 -0
- package/lib/builder/cell-builder.spec.d.ts.map +1 -0
- package/lib/builder/cell-builder.spec.js +280 -0
- package/lib/builder/cell-builder.spec.js.map +1 -0
- package/lib/constants.d.ts +24 -0
- package/lib/constants.d.ts.map +1 -0
- package/lib/constants.js +23 -0
- package/lib/constants.js.map +1 -0
- package/lib/dev/cell-dev-server.d.ts +113 -0
- package/lib/dev/cell-dev-server.d.ts.map +1 -0
- package/lib/dev/cell-dev-server.js +307 -0
- package/lib/dev/cell-dev-server.js.map +1 -0
- package/lib/dev/cell-dev-server.spec.d.ts +2 -0
- package/lib/dev/cell-dev-server.spec.d.ts.map +1 -0
- package/lib/dev/cell-dev-server.spec.js +188 -0
- package/lib/dev/cell-dev-server.spec.js.map +1 -0
- package/lib/expression/expression-evaluator.d.ts +28 -0
- package/lib/expression/expression-evaluator.d.ts.map +1 -0
- package/lib/expression/expression-evaluator.js +91 -0
- package/lib/expression/expression-evaluator.js.map +1 -0
- package/lib/expression/expression-evaluator.spec.d.ts +2 -0
- package/lib/expression/expression-evaluator.spec.d.ts.map +1 -0
- package/lib/expression/expression-evaluator.spec.js +48 -0
- package/lib/expression/expression-evaluator.spec.js.map +1 -0
- package/lib/generator/config-generator.d.ts +18 -0
- package/lib/generator/config-generator.d.ts.map +1 -0
- package/lib/generator/config-generator.js +45 -0
- package/lib/generator/config-generator.js.map +1 -0
- package/lib/generator/container-generator.d.ts +13 -0
- package/lib/generator/container-generator.d.ts.map +1 -0
- package/lib/generator/container-generator.js +41 -0
- package/lib/generator/container-generator.js.map +1 -0
- package/lib/generator/generator.spec.d.ts +2 -0
- package/lib/generator/generator.spec.d.ts.map +1 -0
- package/lib/generator/generator.spec.js +61 -0
- package/lib/generator/generator.spec.js.map +1 -0
- package/lib/generator/html-generator.d.ts +13 -0
- package/lib/generator/html-generator.d.ts.map +1 -0
- package/lib/generator/html-generator.js +42 -0
- package/lib/generator/html-generator.js.map +1 -0
- package/lib/index.d.ts +21 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +21 -0
- package/lib/index.js.map +1 -0
- package/lib/output/asset-embedder.d.ts +19 -0
- package/lib/output/asset-embedder.d.ts.map +1 -0
- package/lib/output/asset-embedder.js +35 -0
- package/lib/output/asset-embedder.js.map +1 -0
- package/lib/output/externals-copier.d.ts +20 -0
- package/lib/output/externals-copier.d.ts.map +1 -0
- package/lib/output/externals-copier.js +62 -0
- package/lib/output/externals-copier.js.map +1 -0
- package/lib/output/externals-copier.spec.d.ts +2 -0
- package/lib/output/externals-copier.spec.d.ts.map +1 -0
- package/lib/output/externals-copier.spec.js +30 -0
- package/lib/output/externals-copier.spec.js.map +1 -0
- package/lib/output/output-writer.d.ts +39 -0
- package/lib/output/output-writer.d.ts.map +1 -0
- package/lib/output/output-writer.js +102 -0
- package/lib/output/output-writer.js.map +1 -0
- package/lib/output/output-writer.spec.d.ts +2 -0
- package/lib/output/output-writer.spec.d.ts.map +1 -0
- package/lib/output/output-writer.spec.js +34 -0
- package/lib/output/output-writer.spec.js.map +1 -0
- package/lib/plugin/cell-plugin.d.ts +134 -0
- package/lib/plugin/cell-plugin.d.ts.map +1 -0
- package/lib/plugin/cell-plugin.js +429 -0
- package/lib/plugin/cell-plugin.js.map +1 -0
- package/lib/plugin/cell-plugin.spec.d.ts +2 -0
- package/lib/plugin/cell-plugin.spec.d.ts.map +1 -0
- package/lib/plugin/cell-plugin.spec.js +74 -0
- package/lib/plugin/cell-plugin.spec.js.map +1 -0
- package/lib/plugin/node-polyfills.d.ts +13 -0
- package/lib/plugin/node-polyfills.d.ts.map +1 -0
- package/lib/plugin/node-polyfills.js +55 -0
- package/lib/plugin/node-polyfills.js.map +1 -0
- package/lib/plugin/node-polyfills.spec.d.ts +2 -0
- package/lib/plugin/node-polyfills.spec.d.ts.map +1 -0
- package/lib/plugin/node-polyfills.spec.js +16 -0
- package/lib/plugin/node-polyfills.spec.js.map +1 -0
- package/lib/project/component-collector.d.ts +32 -0
- package/lib/project/component-collector.d.ts.map +1 -0
- package/lib/project/component-collector.js +93 -0
- package/lib/project/component-collector.js.map +1 -0
- package/lib/project/config-loader.d.ts +16 -0
- package/lib/project/config-loader.d.ts.map +1 -0
- package/lib/project/config-loader.js +76 -0
- package/lib/project/config-loader.js.map +1 -0
- package/lib/project/env-overrides.d.ts +23 -0
- package/lib/project/env-overrides.d.ts.map +1 -0
- package/lib/project/env-overrides.js +48 -0
- package/lib/project/env-overrides.js.map +1 -0
- package/lib/project/env-overrides.spec.d.ts +2 -0
- package/lib/project/env-overrides.spec.d.ts.map +1 -0
- package/lib/project/env-overrides.spec.js +41 -0
- package/lib/project/env-overrides.spec.js.map +1 -0
- package/lib/project/module-resolver.d.ts +15 -0
- package/lib/project/module-resolver.d.ts.map +1 -0
- package/lib/project/module-resolver.js +32 -0
- package/lib/project/module-resolver.js.map +1 -0
- package/lib/project/project-loader.d.ts +54 -0
- package/lib/project/project-loader.d.ts.map +1 -0
- package/lib/project/project-loader.js +117 -0
- package/lib/project/project-loader.js.map +1 -0
- package/lib/project/project-loader.spec.d.ts +2 -0
- package/lib/project/project-loader.spec.d.ts.map +1 -0
- package/lib/project/project-loader.spec.js +178 -0
- package/lib/project/project-loader.spec.js.map +1 -0
- package/lib/test/fixture-project.d.ts +17 -0
- package/lib/test/fixture-project.d.ts.map +1 -0
- package/lib/test/fixture-project.js +43 -0
- package/lib/test/fixture-project.js.map +1 -0
- package/lib/testing/memory-http.d.ts +82 -0
- package/lib/testing/memory-http.d.ts.map +1 -0
- package/lib/testing/memory-http.js +210 -0
- package/lib/testing/memory-http.js.map +1 -0
- package/lib/testing/test-app.d.ts +54 -0
- package/lib/testing/test-app.d.ts.map +1 -0
- package/lib/testing/test-app.js +132 -0
- package/lib/testing/test-app.js.map +1 -0
- package/lib/testing/test-app.spec.d.ts +2 -0
- package/lib/testing/test-app.spec.d.ts.map +1 -0
- package/lib/testing/test-app.spec.js +115 -0
- package/lib/testing/test-app.spec.js.map +1 -0
- package/lib/utils/config-util.d.ts +6 -0
- package/lib/utils/config-util.d.ts.map +1 -0
- package/lib/utils/config-util.js +25 -0
- package/lib/utils/config-util.js.map +1 -0
- package/lib/utils/config-util.spec.d.ts +2 -0
- package/lib/utils/config-util.spec.d.ts.map +1 -0
- package/lib/utils/config-util.spec.js +22 -0
- package/lib/utils/config-util.spec.js.map +1 -0
- package/lib/utils/tsconfig-util.d.ts +5 -0
- package/lib/utils/tsconfig-util.d.ts.map +1 -0
- package/lib/utils/tsconfig-util.js +21 -0
- package/lib/utils/tsconfig-util.js.map +1 -0
- package/package.json +50 -4
- package/src/builder/cell-builder.ts +72 -0
- package/src/constants.ts +30 -0
- package/src/dev/cell-dev-server.ts +387 -0
- package/src/expression/expression-evaluator.ts +99 -0
- package/src/generator/config-generator.ts +45 -0
- package/src/generator/container-generator.ts +41 -0
- package/src/generator/html-generator.ts +43 -0
- package/src/index.ts +20 -0
- package/src/output/asset-embedder.ts +42 -0
- package/src/output/externals-copier.ts +64 -0
- package/src/output/output-writer.ts +113 -0
- package/src/plugin/cell-plugin.ts +481 -0
- package/src/plugin/node-polyfills.ts +57 -0
- package/src/project/component-collector.ts +107 -0
- package/src/project/config-loader.ts +77 -0
- package/src/project/env-overrides.ts +55 -0
- package/src/project/module-resolver.ts +39 -0
- package/src/project/project-loader.ts +153 -0
- package/src/test/fixture-project.ts +50 -0
- package/src/testing/memory-http.ts +238 -0
- package/src/testing/test-app.ts +155 -0
- package/src/utils/config-util.ts +21 -0
- package/src/utils/tsconfig-util.ts +19 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
export var TsconfigUtil;
|
|
4
|
+
(function (TsconfigUtil) {
|
|
5
|
+
/** JSX runtime implied by the project's tsconfig (following relative `extends`). */
|
|
6
|
+
function jsxRuntime(root) {
|
|
7
|
+
let file = join(root, 'tsconfig.json');
|
|
8
|
+
for (let depth = 0; file && existsSync(file) && depth < 8; depth++) {
|
|
9
|
+
const text = readFileSync(file, 'utf8');
|
|
10
|
+
const jsx = /"jsx"\s*:\s*"([^"]+)"/.exec(text)?.[1];
|
|
11
|
+
if (jsx) {
|
|
12
|
+
return jsx === 'react' ? 'classic' : 'automatic';
|
|
13
|
+
}
|
|
14
|
+
const parent = /"extends"\s*:\s*"([^"]+)"/.exec(text)?.[1];
|
|
15
|
+
file = parent?.startsWith('.') ? resolve(dirname(file), parent.endsWith('.json') ? parent : `${parent}.json`) : undefined;
|
|
16
|
+
}
|
|
17
|
+
return 'automatic';
|
|
18
|
+
}
|
|
19
|
+
TsconfigUtil.jsxRuntime = jsxRuntime;
|
|
20
|
+
})(TsconfigUtil || (TsconfigUtil = {}));
|
|
21
|
+
//# sourceMappingURL=tsconfig-util.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tsconfig-util.js","sourceRoot":"","sources":["../../src/utils/tsconfig-util.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEnD,MAAM,KAAW,YAAY,CAe5B;AAfD,WAAiB,YAAY;IACzB,oFAAoF;IACpF,SAAgB,UAAU,CAAC,IAAY;QACnC,IAAI,IAAI,GAAuB,IAAI,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;QAC3D,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,IAAI,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;YACjE,MAAM,IAAI,GAAW,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;YAChD,MAAM,GAAG,GAAG,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YACpD,IAAI,GAAG,EAAE,CAAC;gBACN,OAAO,GAAG,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC;YACrD,CAAC;YACD,MAAM,MAAM,GAAuB,2BAA2B,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC/E,IAAI,GAAG,MAAM,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC9H,CAAC;QACD,OAAO,WAAW,CAAC;IACvB,CAAC;IAZe,aAAA,UAAU,aAYzB,CAAA;AACL,CAAC,EAfgB,YAAY,KAAZ,YAAY,QAe5B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@celljs/vite",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "4.1.0",
|
|
4
|
+
"description": "Vite plugin that builds Cell applications: component graph, DI container, configuration and single-file server output.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"homepage": "https://github.com/cellbang/cell",
|
|
7
|
+
"bugs": {
|
|
8
|
+
"url": "https://github.com/cellbang/cell/issues"
|
|
9
|
+
},
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "https://github.com/cellbang/cell.git"
|
|
13
|
+
},
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": "^20.19.0 || >=22.12.0"
|
|
17
|
+
},
|
|
18
|
+
"main": "lib/index.js",
|
|
19
|
+
"types": "lib/index.d.ts",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./lib/index.d.ts",
|
|
23
|
+
"default": "./lib/index.js"
|
|
24
|
+
},
|
|
25
|
+
"./package.json": "./package.json"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"lib",
|
|
29
|
+
"src",
|
|
30
|
+
"assets",
|
|
31
|
+
"!src/**/*.spec.ts"
|
|
32
|
+
],
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsc -b",
|
|
35
|
+
"clean": "rm -rf lib *.tsbuildinfo",
|
|
36
|
+
"test": "bun test ./lib",
|
|
37
|
+
"watch": "tsc -b -w --preserveWatchOutput"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@celljs/kit": "4.1.0",
|
|
41
|
+
"js-yaml": "^4.1.1",
|
|
42
|
+
"vite": "^8.3.6"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@celljs/core": "4.1.0",
|
|
46
|
+
"@celljs/express-adapter": "4.1.0",
|
|
47
|
+
"@celljs/http": "4.1.0",
|
|
48
|
+
"@celljs/mvc": "4.1.0",
|
|
49
|
+
"@celljs/web": "4.1.0",
|
|
50
|
+
"@types/js-yaml": "^4.0.9"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { stripVTControlCharacters } from 'node:util';
|
|
2
|
+
import { CellError, type ProjectModel } from '@celljs/kit';
|
|
3
|
+
import type { InlineConfig, PluginOption, UserConfig } from 'vite';
|
|
4
|
+
import { CellPlugin, type CellPluginOptions } from '../plugin/cell-plugin.js';
|
|
5
|
+
|
|
6
|
+
export interface CellBuilderOptions extends CellPluginOptions {
|
|
7
|
+
logLevel?: 'info' | 'warn' | 'error' | 'silent';
|
|
8
|
+
/** Merged into the Vite configuration (the `vite` field of cell.config.ts). */
|
|
9
|
+
vite?: UserConfig;
|
|
10
|
+
/** Plugins of toolchain modules, after the Cell plugin. */
|
|
11
|
+
plugins?: PluginOption[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface BundlerError extends Error {
|
|
15
|
+
id?: string;
|
|
16
|
+
loc?: { file?: string; line?: number; column?: number };
|
|
17
|
+
plugin?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Builds every target of a project; the programmatic form of `cell build`. */
|
|
21
|
+
export class CellBuilder {
|
|
22
|
+
constructor(protected readonly options: CellBuilderOptions = {}) {}
|
|
23
|
+
|
|
24
|
+
async build(): Promise<ProjectModel> {
|
|
25
|
+
const { createBuilder, mergeConfig } = await import('vite');
|
|
26
|
+
const plugin = new CellPlugin(this.options);
|
|
27
|
+
try {
|
|
28
|
+
const config: InlineConfig = {
|
|
29
|
+
root: this.options.root ?? process.cwd(),
|
|
30
|
+
configFile: false,
|
|
31
|
+
logLevel: this.options.logLevel ?? 'warn',
|
|
32
|
+
plugins: [plugin.toVitePlugin(), ...(this.options.plugins ?? [])],
|
|
33
|
+
};
|
|
34
|
+
const builder = await createBuilder(this.options.vite ? mergeConfig(config, this.options.vite) : config, null);
|
|
35
|
+
await builder.buildApp();
|
|
36
|
+
} catch (error) {
|
|
37
|
+
throw CellBuilder.toCellError(error);
|
|
38
|
+
}
|
|
39
|
+
return plugin.project;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Bundler failures become `CELL_BUILD_FAILED` with the failing file; Cell errors pass through. */
|
|
43
|
+
static toCellError(error: unknown): CellError {
|
|
44
|
+
const cause = (error as { cause?: unknown })?.cause;
|
|
45
|
+
if (CellError.is(error)) {
|
|
46
|
+
return error;
|
|
47
|
+
}
|
|
48
|
+
if (CellError.is(cause)) {
|
|
49
|
+
return cause;
|
|
50
|
+
}
|
|
51
|
+
const e = error as BundlerError;
|
|
52
|
+
const errors = (error as { errors?: BundlerError[] }).errors;
|
|
53
|
+
const first = errors?.[0] ?? e;
|
|
54
|
+
const lines = stripVTControlCharacters(String(first?.message ?? error)).split('\n');
|
|
55
|
+
const summary = lines.find(line => line.trim() && !/^Build failed/.test(line)) ?? String(error);
|
|
56
|
+
// Rolldown wraps plugin failures as "plugin X threw an error" and puts the reason under "Caused by:".
|
|
57
|
+
const causedBy = lines.findIndex(line => /^\s*Caused by:/.test(line));
|
|
58
|
+
const reason = causedBy >= 0 ? lines.slice(causedBy + 1).find(line => line.trim()) : undefined;
|
|
59
|
+
const message = reason ? `${reason.trim()} (${summary.replace(/ threw an error$/, '').trim()})` : summary;
|
|
60
|
+
return new CellError({
|
|
61
|
+
code: 'CELL_BUILD_FAILED',
|
|
62
|
+
message: message.trim(),
|
|
63
|
+
file: first?.loc?.file ?? first?.id,
|
|
64
|
+
line: first?.loc?.line,
|
|
65
|
+
column: first?.loc?.column,
|
|
66
|
+
hint: first?.plugin
|
|
67
|
+
? `The ${first.plugin} step failed; fix the reported file, or check that its dependencies are installed.`
|
|
68
|
+
: 'Fix the reported file, or check that its dependencies are installed.',
|
|
69
|
+
cause: error,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
}
|
package/src/constants.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Target } from '@celljs/kit';
|
|
2
|
+
|
|
3
|
+
export const TARGETS: Target[] = ['frontend', 'backend'];
|
|
4
|
+
|
|
5
|
+
/** Application entry used when neither the options nor a preset choose one. */
|
|
6
|
+
export const DEFAULT_ENTRY = '@celljs/core/lib/common/application/application-entry';
|
|
7
|
+
|
|
8
|
+
/** Vite environment that builds each target, and the reverse mapping. */
|
|
9
|
+
export const ENVIRONMENT_OF: Record<Target, string> = { frontend: 'client', backend: 'server' };
|
|
10
|
+
export const TARGET_OF: Record<string, Target> = { client: 'frontend', server: 'backend' };
|
|
11
|
+
|
|
12
|
+
/** Keys of the merged cell.yml that are not application configuration as such: the target sections and the mode. */
|
|
13
|
+
export const TOOLING_KEYS = ['mode', 'frontend', 'backend'];
|
|
14
|
+
|
|
15
|
+
/** Directory of the frontend output inside the output directory; the backend default of `paths.public`. */
|
|
16
|
+
export const PUBLIC_DIR = 'public';
|
|
17
|
+
|
|
18
|
+
/** URL of the frontend entry inside the generated HTML page. */
|
|
19
|
+
export const ENTRY_URL = '/@cell/entry.js';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Where the server bundle pretends to be on Cloudflare Workers, which has no `import.meta.url`:
|
|
23
|
+
* workerd runs the modules from `/bundle` (its working directory).
|
|
24
|
+
*/
|
|
25
|
+
export const WORKERD_SERVER_FILE = '/bundle/server/index.mjs';
|
|
26
|
+
/** Key of the global under which a `--single` server bundle registers its embedded frontend files (read by @celljs/serve-static). */
|
|
27
|
+
export const EMBEDDED_ASSETS_KEY = '@celljs/serve-static/assets';
|
|
28
|
+
/** Entry of a `--single` server bundle: the embedded frontend files, then the backend entry. */
|
|
29
|
+
export const SINGLE_ENTRY_ID = 'virtual:cell/single-entry';
|
|
30
|
+
export const ASSETS_ID = 'virtual:cell/assets';
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
3
|
+
import { basename, dirname, extname, join, sep } from 'node:path';
|
|
4
|
+
import { CellError, type ProjectModel } from '@celljs/kit';
|
|
5
|
+
import type { InlineConfig, Logger, Plugin, PluginOption, UserConfig, ViteDevServer } from 'vite';
|
|
6
|
+
import { CellPlugin, type CellPluginOptions } from '../plugin/cell-plugin.js';
|
|
7
|
+
import { EnvOverrides } from '../project/env-overrides.js';
|
|
8
|
+
|
|
9
|
+
/** What a backend entry hands to the host (`ApplicationHost` of @celljs/core). */
|
|
10
|
+
export interface StartedApplication {
|
|
11
|
+
container: unknown;
|
|
12
|
+
handler?: (req: IncomingMessage, res: ServerResponse, next?: (error?: unknown) => void) => void;
|
|
13
|
+
stop(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const HOST_KEY = Symbol.for('@celljs/core/application-host');
|
|
17
|
+
|
|
18
|
+
/** A request the backend answered in `cell dev` (frontend modules and assets are left out). */
|
|
19
|
+
export interface DevRequestRecord {
|
|
20
|
+
time: string;
|
|
21
|
+
method: string;
|
|
22
|
+
url: string;
|
|
23
|
+
status: number;
|
|
24
|
+
durationMs: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface CellDevServerOptions extends CellPluginOptions {
|
|
28
|
+
/** Port of the one server for frontend and backend. Default: `cell.server.port` of the backend, else 3000. */
|
|
29
|
+
port?: number;
|
|
30
|
+
/** Interface to listen on. Default: `cell.server.host` of the backend, else 127.0.0.1. */
|
|
31
|
+
host?: string;
|
|
32
|
+
logLevel?: 'info' | 'warn' | 'error' | 'silent';
|
|
33
|
+
/** Vite logger, e.g. one that writes to stderr for `--json`. */
|
|
34
|
+
logger?: Logger;
|
|
35
|
+
/** Merged into the Vite configuration (the `vite` field of cell.config.ts). */
|
|
36
|
+
vite?: UserConfig;
|
|
37
|
+
/** Plugins of toolchain modules, after the Cell plugin. */
|
|
38
|
+
plugins?: PluginOption[];
|
|
39
|
+
/** Handlers of toolchain modules by path prefix, before the backend. */
|
|
40
|
+
devHandlers?: { path: string; handler: (req: IncomingMessage, res: ServerResponse, next: (error?: unknown) => void) => void }[];
|
|
41
|
+
/** More files whose change restarts with a new toolchain (`cell.addWatchFile`). */
|
|
42
|
+
watchFiles?: string[];
|
|
43
|
+
/**
|
|
44
|
+
* Listen on a port and watch files. Default `true`; `false` runs in-process only (`createTestApp`):
|
|
45
|
+
* requests go through {@link CellDevServer.handler}.
|
|
46
|
+
*/
|
|
47
|
+
listen?: boolean;
|
|
48
|
+
/** Start the backend entry. Default `true`; `false` only loads modules on request ({@link CellDevServer.import}), as `cell check` does. */
|
|
49
|
+
backend?: boolean;
|
|
50
|
+
/** How long the backend may take to start. Default 60s. */
|
|
51
|
+
startTimeout?: number;
|
|
52
|
+
/** Files changed that the project model depends on (cell*.yml, package.json, cell.config.*): restart with a new toolchain. */
|
|
53
|
+
onRestart?(files: string[]): void;
|
|
54
|
+
/** The backend was reloaded after `files` changed; `error` when it failed to start again. */
|
|
55
|
+
onReload?(files: string[], error?: CellError): void;
|
|
56
|
+
/** A request reached the backend and was answered. */
|
|
57
|
+
onRequest?(record: DevRequestRecord): void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* `cell dev` on one port (docs/design/architecture.md §6): Vite serves the frontend with HMR, and
|
|
62
|
+
* the backend runs in the `server` environment's module runner. Its entry hands the request handler
|
|
63
|
+
* over through `ApplicationHost` instead of listening; when one of its files changes, the old
|
|
64
|
+
* application is stopped, the runner forgets every module and the entry is imported again.
|
|
65
|
+
*/
|
|
66
|
+
export class CellDevServer {
|
|
67
|
+
static readonly DEFAULT_PORT = 3000;
|
|
68
|
+
static readonly DEFAULT_HOST = '127.0.0.1';
|
|
69
|
+
static readonly CONTENT_TYPES: Record<string, string> = {
|
|
70
|
+
'.css': 'text/css; charset=utf-8',
|
|
71
|
+
'.gif': 'image/gif',
|
|
72
|
+
'.html': 'text/html; charset=utf-8',
|
|
73
|
+
'.ico': 'image/x-icon',
|
|
74
|
+
'.jpeg': 'image/jpeg',
|
|
75
|
+
'.jpg': 'image/jpeg',
|
|
76
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
77
|
+
'.json': 'application/json',
|
|
78
|
+
'.png': 'image/png',
|
|
79
|
+
'.svg': 'image/svg+xml',
|
|
80
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
81
|
+
'.webp': 'image/webp',
|
|
82
|
+
'.woff': 'font/woff',
|
|
83
|
+
'.woff2': 'font/woff2',
|
|
84
|
+
};
|
|
85
|
+
static readonly CONFIG_FILE = /^(cell(\.[\w-]+)?\.ya?ml|cell\.config\.[cm]?[jt]s|package\.json)$/;
|
|
86
|
+
|
|
87
|
+
protected vite: ViteDevServer;
|
|
88
|
+
protected plugin: CellPlugin;
|
|
89
|
+
protected backend?: StartedApplication;
|
|
90
|
+
protected backendError?: CellError;
|
|
91
|
+
protected loading: Promise<void> = Promise.resolve();
|
|
92
|
+
protected pending = new Set<string>();
|
|
93
|
+
protected timer?: ReturnType<typeof setTimeout>;
|
|
94
|
+
protected closed = false;
|
|
95
|
+
|
|
96
|
+
constructor(protected readonly options: CellDevServerOptions = {}) {}
|
|
97
|
+
|
|
98
|
+
get project(): ProjectModel {
|
|
99
|
+
return this.plugin.project;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
get url(): string {
|
|
103
|
+
const { port, host } = this.address;
|
|
104
|
+
return `http://${host.includes(':') ? `[${host}]` : host}:${port}`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
get address(): { host: string; port: number } {
|
|
108
|
+
const address = this.vite.httpServer?.address();
|
|
109
|
+
const host = this.vite.config.server.host;
|
|
110
|
+
return {
|
|
111
|
+
host: typeof host === 'string' ? host : CellDevServer.DEFAULT_HOST,
|
|
112
|
+
port: typeof address === 'object' && address ? address.port : (this.vite.config.server.port ?? CellDevServer.DEFAULT_PORT),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The running backend: its DI container and request handler. */
|
|
117
|
+
get application(): StartedApplication | undefined {
|
|
118
|
+
return this.backend;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The last error of the backend, until it starts again. */
|
|
122
|
+
get error(): CellError | undefined {
|
|
123
|
+
return this.backendError;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async start(): Promise<this> {
|
|
127
|
+
const { createServer, createRunnableDevEnvironment, mergeConfig } = await import('vite');
|
|
128
|
+
this.plugin = new CellPlugin(this.options);
|
|
129
|
+
const config: InlineConfig = {
|
|
130
|
+
root: this.options.root ?? process.cwd(),
|
|
131
|
+
configFile: false,
|
|
132
|
+
logLevel: this.options.logLevel ?? 'info',
|
|
133
|
+
customLogger: this.options.logger,
|
|
134
|
+
clearScreen: false,
|
|
135
|
+
...(this.options.listen === false ? { server: { middlewareMode: true, hmr: false, ws: false, watch: null } } : {}),
|
|
136
|
+
plugins: [this.plugin.toVitePlugin(), this.devPlugin(), ...(this.options.plugins ?? [])],
|
|
137
|
+
environments: {
|
|
138
|
+
// The runner's own HMR would re-run the entry on every change; reloads are done here instead.
|
|
139
|
+
server: { dev: { createEnvironment: (name, resolved) => createRunnableDevEnvironment(name, resolved, { runnerOptions: { hmr: false } }) } },
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
try {
|
|
143
|
+
this.vite = await createServer(this.options.vite ? mergeConfig(config, this.options.vite) : config);
|
|
144
|
+
if (this.options.listen !== false) {
|
|
145
|
+
await this.vite.listen();
|
|
146
|
+
}
|
|
147
|
+
} catch (error) {
|
|
148
|
+
await this.vite?.close();
|
|
149
|
+
throw CellDevServer.toCellError(error, 'CELL_DEV_FAILED');
|
|
150
|
+
}
|
|
151
|
+
if (this.options.listen !== false) {
|
|
152
|
+
this.vite.watcher.on('all', (event, file) => this.onFileChange(event, file));
|
|
153
|
+
}
|
|
154
|
+
if (this.project.backend && this.options.backend !== false) {
|
|
155
|
+
await this.reload([]);
|
|
156
|
+
}
|
|
157
|
+
return this;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Imports a module into the backend's module runner (with the generated container and configuration). */
|
|
161
|
+
import<T = Record<string, unknown>>(specifier: string): Promise<T> {
|
|
162
|
+
return this.serverEnvironment.runner.import(specifier) as Promise<T>;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Every request handler of the server in one: Vite, the frontend page, module handlers, the backend. */
|
|
166
|
+
get handler(): (req: IncomingMessage, res: ServerResponse) => void {
|
|
167
|
+
return this.vite.middlewares;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async close(): Promise<void> {
|
|
171
|
+
this.closed = true;
|
|
172
|
+
clearTimeout(this.timer);
|
|
173
|
+
await this.loading;
|
|
174
|
+
await this.stopBackend();
|
|
175
|
+
await this.vite?.close();
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Files whose change makes a new project model: the component's cell*.yml and package.json, and the project's cell.config.*. */
|
|
179
|
+
get configFiles(): string[] {
|
|
180
|
+
return [...new Set([...this.project.components.flatMap(c => [...c.configFiles, join(c.dir, 'package.json')]), ...(this.options.watchFiles ?? [])])];
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Stops the running backend and starts it again from fresh modules. */
|
|
184
|
+
reload(files: string[]): Promise<void> {
|
|
185
|
+
this.loading = this.loading.then(async () => {
|
|
186
|
+
if (this.closed) {
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
await this.stopBackend();
|
|
190
|
+
const environment = this.serverEnvironment;
|
|
191
|
+
environment.moduleGraph.invalidateAll();
|
|
192
|
+
environment.runner.clearCache();
|
|
193
|
+
try {
|
|
194
|
+
this.backend = await this.importBackend();
|
|
195
|
+
this.backendError = undefined;
|
|
196
|
+
} catch (error) {
|
|
197
|
+
this.backendError = CellDevServer.toCellError(error, 'CELL_DEV_BACKEND_FAILED');
|
|
198
|
+
}
|
|
199
|
+
if (files.length > 0 || this.backendError) {
|
|
200
|
+
this.options.onReload?.(files, this.backendError);
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
return this.loading;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
protected get serverEnvironment() {
|
|
207
|
+
return this.vite.environments.server as ViteDevServer['environments'][string] & {
|
|
208
|
+
runner: { import(url: string): Promise<unknown>; clearCache(): void };
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
protected async importBackend(): Promise<StartedApplication> {
|
|
213
|
+
const entry = this.project.backend?.entry ?? '';
|
|
214
|
+
const timeout = this.options.startTimeout ?? 60000;
|
|
215
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
216
|
+
const started = new Promise<StartedApplication>((resolvePromise, reject) => {
|
|
217
|
+
(globalThis as Record<symbol, unknown>)[HOST_KEY] = { server: this.vite.httpServer, started: resolvePromise, failed: reject };
|
|
218
|
+
timer = setTimeout(
|
|
219
|
+
() =>
|
|
220
|
+
reject(
|
|
221
|
+
new CellError({
|
|
222
|
+
code: 'CELL_DEV_START_TIMEOUT',
|
|
223
|
+
message: `The backend entry ${entry} did not start within ${timeout / 1000}s.`,
|
|
224
|
+
hint: 'Check Application.start() and lifecycle onStart hooks for work that never finishes; an entry of its own must report to ApplicationHost.get().',
|
|
225
|
+
}),
|
|
226
|
+
),
|
|
227
|
+
timeout,
|
|
228
|
+
);
|
|
229
|
+
});
|
|
230
|
+
try {
|
|
231
|
+
await this.serverEnvironment.runner.import(entry);
|
|
232
|
+
return await started;
|
|
233
|
+
} finally {
|
|
234
|
+
clearTimeout(timer);
|
|
235
|
+
(globalThis as Record<symbol, unknown>)[HOST_KEY] = undefined;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
protected async stopBackend(): Promise<void> {
|
|
240
|
+
const backend = this.backend;
|
|
241
|
+
this.backend = undefined;
|
|
242
|
+
try {
|
|
243
|
+
await backend?.stop();
|
|
244
|
+
} catch (error) {
|
|
245
|
+
this.vite.config.logger.error(`[cell] The backend did not stop cleanly: ${(error as Error)?.message ?? error}`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
protected onFileChange(event: string, file: string): void {
|
|
250
|
+
if (this.closed) {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const name = basename(file);
|
|
254
|
+
const projectFile = dirname(file) === this.project.root && CellDevServer.CONFIG_FILE.test(name);
|
|
255
|
+
if (projectFile || (event === 'change' && this.configFiles.includes(file))) {
|
|
256
|
+
this.options.onRestart?.([file]);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (!this.project.backend || file.split(sep).includes('node_modules')) {
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
// A failed start may not have reached the file yet, so any source change is worth a retry.
|
|
263
|
+
const used = (this.serverEnvironment.moduleGraph.getModulesByFile(file)?.size ?? 0) > 0;
|
|
264
|
+
if (used || this.backendError) {
|
|
265
|
+
this.pending.add(file);
|
|
266
|
+
clearTimeout(this.timer);
|
|
267
|
+
this.timer = setTimeout(() => {
|
|
268
|
+
const files = [...this.pending];
|
|
269
|
+
this.pending.clear();
|
|
270
|
+
void this.reload(files);
|
|
271
|
+
}, 50);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
protected devPlugin(): Plugin {
|
|
276
|
+
return {
|
|
277
|
+
name: 'cell:dev',
|
|
278
|
+
config: () => (this.options.listen === false ? {} : { server: { ...this.listenOptions(), strictPort: true } }),
|
|
279
|
+
configureServer: server => {
|
|
280
|
+
server.watcher?.add([join(this.project.root, 'cell.config.*'), ...(this.options.watchFiles ?? [])]);
|
|
281
|
+
// After Vite's own middlewares: modules and assets of the frontend come first.
|
|
282
|
+
return () => {
|
|
283
|
+
server.middlewares.use((req, res, next) => {
|
|
284
|
+
this.handle(req, res, next).catch(next);
|
|
285
|
+
});
|
|
286
|
+
};
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
protected listenOptions(): { port: number; host: string } {
|
|
292
|
+
const backend = this.project.backend;
|
|
293
|
+
const server = { port: undefined as unknown, host: undefined as unknown };
|
|
294
|
+
if (backend) {
|
|
295
|
+
const config = structuredClone(backend.config) as { cell?: { server?: { port?: unknown; host?: unknown } } };
|
|
296
|
+
new EnvOverrides(this.project.root, this.options.env ?? process.env).apply('backend', config);
|
|
297
|
+
Object.assign(server, config.cell?.server ?? {});
|
|
298
|
+
}
|
|
299
|
+
return {
|
|
300
|
+
port: this.options.port ?? (typeof server.port === 'number' ? server.port : CellDevServer.DEFAULT_PORT),
|
|
301
|
+
host: this.options.host ?? (typeof server.host === 'string' && !server.host.includes('${') ? server.host : CellDevServer.DEFAULT_HOST),
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
protected async handle(req: IncomingMessage, res: ServerResponse, next: (error?: unknown) => void): Promise<void> {
|
|
306
|
+
const path = (req.url ?? '/').split('?')[0];
|
|
307
|
+
// The page of the frontend, as serve-static gives it in production.
|
|
308
|
+
if (this.project.frontend && (req.method === 'GET' || req.method === 'HEAD') && (path === '/' || path === '/index.html')) {
|
|
309
|
+
const html = await this.vite.transformIndexHtml(req.url ?? '/', this.plugin.renderHtml(), (req as { originalUrl?: string }).originalUrl);
|
|
310
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
311
|
+
res.end(html);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
const devHandler = this.options.devHandlers?.find(
|
|
315
|
+
({ path: prefix }) => path === prefix || path.startsWith(prefix.endsWith('/') ? prefix : `${prefix}/`),
|
|
316
|
+
);
|
|
317
|
+
if (devHandler) {
|
|
318
|
+
devHandler.handler(req, res, next);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
const file = this.project.frontend && (req.method === 'GET' || req.method === 'HEAD') ? this.plugin.frontendFile(decodeURIComponent(path)) : undefined;
|
|
322
|
+
if (file) {
|
|
323
|
+
res.setHeader('Content-Type', CellDevServer.CONTENT_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream');
|
|
324
|
+
res.end(req.method === 'HEAD' ? undefined : readFileSync(file));
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (!this.project.backend) {
|
|
328
|
+
next();
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
this.record(req, res);
|
|
332
|
+
await this.loading;
|
|
333
|
+
if (this.backendError) {
|
|
334
|
+
res.statusCode = 500;
|
|
335
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
336
|
+
res.end(`${this.backendError.format()}\n\nThe backend starts again when a file changes.\n`);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (!this.backend?.handler) {
|
|
340
|
+
next();
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
this.backend.handler(req, res, next);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
protected record(req: IncomingMessage, res: ServerResponse): void {
|
|
347
|
+
const onRequest = this.options.onRequest;
|
|
348
|
+
if (!onRequest) {
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
const started = performance.now();
|
|
352
|
+
const url = (req as { originalUrl?: string }).originalUrl ?? req.url ?? '/';
|
|
353
|
+
res.once('finish', () =>
|
|
354
|
+
onRequest({
|
|
355
|
+
time: new Date().toISOString(),
|
|
356
|
+
method: req.method ?? 'GET',
|
|
357
|
+
url,
|
|
358
|
+
status: res.statusCode,
|
|
359
|
+
durationMs: Math.round(performance.now() - started),
|
|
360
|
+
}),
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
static toCellError(error: unknown, code: string): CellError {
|
|
365
|
+
if (CellError.is(error)) {
|
|
366
|
+
return error;
|
|
367
|
+
}
|
|
368
|
+
const e = error as Error & { id?: string; loc?: { file?: string; line?: number; column?: number }; frame?: string };
|
|
369
|
+
// Vite and Oxc open with "Transform failed with 1 error:"; the reason is the next line.
|
|
370
|
+
const lines = String(e?.message ?? error)
|
|
371
|
+
.split('\n')
|
|
372
|
+
.filter(line => line.trim());
|
|
373
|
+
const message = lines.find(line => !/(failed|errors?):\s*$/i.test(line)) ?? lines[0] ?? String(error);
|
|
374
|
+
return new CellError({
|
|
375
|
+
code,
|
|
376
|
+
message: message.trim(),
|
|
377
|
+
file: e?.loc?.file ?? e?.id,
|
|
378
|
+
line: e?.loc?.line,
|
|
379
|
+
column: e?.loc?.column,
|
|
380
|
+
hint:
|
|
381
|
+
code === 'CELL_DEV_FAILED'
|
|
382
|
+
? 'Check the port and the vite field of cell.config.ts.'
|
|
383
|
+
: 'Fix the reported file; the backend starts again when it is saved.',
|
|
384
|
+
cause: error,
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { CellError } from '@celljs/kit';
|
|
4
|
+
|
|
5
|
+
/** What the build uses of `@celljs/core/el` (packages/core/src/common/el/expression-util.ts). */
|
|
6
|
+
interface ExpressionUtil {
|
|
7
|
+
evaluateText(text: string, context: object): unknown;
|
|
8
|
+
evaluateConfiguration(root: object): void;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Evaluates `${...}` expressions with the project's own @celljs/core (`@celljs/core/el`), so build-time
|
|
13
|
+
* and runtime evaluation are the same code: references between keys resolve in any order, and what an
|
|
14
|
+
* expression returns (an environment variable, for instance) is never evaluated again.
|
|
15
|
+
*/
|
|
16
|
+
export class ExpressionEvaluator {
|
|
17
|
+
protected static readonly utils = new Map<string, ExpressionUtil>();
|
|
18
|
+
|
|
19
|
+
protected readonly util: ExpressionUtil;
|
|
20
|
+
|
|
21
|
+
constructor(root: string) {
|
|
22
|
+
this.util = ExpressionEvaluator.utilFor(root);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
protected static utilFor(root: string): ExpressionUtil {
|
|
26
|
+
let util = ExpressionEvaluator.utils.get(root);
|
|
27
|
+
if (!util) {
|
|
28
|
+
const require = createRequire(join(root, 'package.json'));
|
|
29
|
+
try {
|
|
30
|
+
util = require('@celljs/core/el').ExpressionUtil as ExpressionUtil;
|
|
31
|
+
} catch (cause) {
|
|
32
|
+
throw ExpressionEvaluator.loadError(require, root, cause);
|
|
33
|
+
}
|
|
34
|
+
ExpressionEvaluator.utils.set(root, util);
|
|
35
|
+
}
|
|
36
|
+
return util;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
protected static loadError(require: NodeJS.Require, root: string, cause: unknown): CellError {
|
|
40
|
+
let version: string | undefined;
|
|
41
|
+
try {
|
|
42
|
+
version = require('@celljs/core/package.json').version;
|
|
43
|
+
} catch {
|
|
44
|
+
return new CellError({
|
|
45
|
+
code: 'CELL_CORE_NOT_FOUND',
|
|
46
|
+
message: 'The project does not depend on @celljs/core.',
|
|
47
|
+
file: join(root, 'package.json'),
|
|
48
|
+
hint: 'Add @celljs/core to dependencies and install.',
|
|
49
|
+
cause,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
return new CellError({
|
|
53
|
+
code: 'CELL_CORE_EL_MISSING',
|
|
54
|
+
message: `The @celljs/core ${version} of this project has no @celljs/core/el entry, which the build evaluates configuration expressions with.`,
|
|
55
|
+
file: join(root, 'package.json'),
|
|
56
|
+
hint: 'Upgrade @celljs/core and the other @celljs/* packages to 4.1.0 or later.',
|
|
57
|
+
cause,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Evaluates `target` in place and returns it. The objects of `extra` (e.g. `env`) are visible to the
|
|
63
|
+
* expressions as they are, without being evaluated, and are removed afterwards.
|
|
64
|
+
*/
|
|
65
|
+
evaluate<T extends Record<string, unknown>>(target: T, extra: Record<string, object> = {}): T {
|
|
66
|
+
const root: Record<string, unknown> = target;
|
|
67
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
68
|
+
root[key] = { ...value, _ignoreEl: true };
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
this.util.evaluateConfiguration(root);
|
|
72
|
+
} catch (cause) {
|
|
73
|
+
throw this.error(cause, (cause as Error).message);
|
|
74
|
+
} finally {
|
|
75
|
+
for (const key of Object.keys(extra)) {
|
|
76
|
+
delete root[key];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return target;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Evaluates one text against `ctx`. */
|
|
83
|
+
evaluateText(text: string, ctx: Record<string, unknown>, path = 'value'): unknown {
|
|
84
|
+
try {
|
|
85
|
+
return this.util.evaluateText(text, ctx);
|
|
86
|
+
} catch (cause) {
|
|
87
|
+
throw this.error(cause, `Cannot evaluate ${path}: ${text} (${(cause as Error).message})`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
protected error(cause: unknown, message: string): CellError {
|
|
92
|
+
return new CellError({
|
|
93
|
+
code: 'CELL_CONFIG_EXPRESSION',
|
|
94
|
+
message,
|
|
95
|
+
hint: 'Expressions are jexl inside ${...} and see only configuration keys and `env`; check quotes, braces and key names.',
|
|
96
|
+
cause,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|