soma-core 2.1.5 → 2.2.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 +2 -2
- package/bin/soma.cjs +1 -1
- package/bin/soma.ts +64 -15
- package/core/build/compiler/soma-precompile.js +11 -1
- package/core/client/base/SomaHttpClient.ts +85 -12
- package/core/client/data/data-object-resolver.ts +12 -1
- package/core/client/engine/event-engine.ts +3 -3
- package/core/client/engine/soma-bootstrap.ts +30 -30
- package/core/client/host-bridge/load-host-domain-class.ts +74 -20
- package/core/client/host-bridge/resolve-host-bootstrap.ts +125 -23
- package/core/client/infra/http/IHttpClient.ts +3 -1
- package/core/client/infra/http/SomaHttpService.ts +15 -6
- package/core/client/parser/data-config-parser.ts +6 -1
- package/core/server/api/dispatch-service-api.ts +212 -0
- package/core/server/api/load-host-service.ts +230 -56
- package/core/server/api/service-path.ts +78 -14
- package/core/server/engines/style/candidate-guard.ts +57 -0
- package/core/server/engines/style/index.ts +1 -1
- package/core/server/engines/style/tailwind-adapter.ts +83 -16
- package/core/server/host/source-packages.cjs +96 -30
- package/core/server/host/source-packages.ts +12 -5
- package/core/server/index.ts +39 -17
- package/core/server/infra/cache/ServerFileCache.ts +138 -25
- package/core/server/node.ts +32 -8
- package/core/shared/registry-generated/error-codes.ts +5 -0
- package/core/shared/registry-generated/limits.ts +5 -0
- package/core/shared/types/data-config.types.ts +2 -0
- package/dist/browser/soma-runtime.js +197 -49
- package/dist/cli/soma.js +68 -14
- package/dist/core/index.cjs +284 -64
- package/dist/host-native/aot-builder.cjs +850 -0
- package/dist/host-native/native-server.cjs +15338 -0
- package/dist/lsp/component-tree.cjs +11 -1
- package/dist/types/client/base/SomaHttpClient.d.ts +1 -8
- package/dist/types/client/data/data-object-resolver.d.ts +1 -0
- package/dist/types/client/engine/event-engine.d.ts +2 -2
- package/dist/types/client/engine/soma-bootstrap.d.ts +3 -2
- package/dist/types/client/host-bridge/load-host-domain-class.d.ts +1 -0
- package/dist/types/client/host-bridge/resolve-host-bootstrap.d.ts +20 -0
- package/dist/types/client/infra/http/IHttpClient.d.ts +2 -0
- package/dist/types/server/api/dispatch-service-api.d.ts +18 -0
- package/dist/types/server/api/load-host-service.d.ts +7 -2
- package/dist/types/server/api/service-path.d.ts +21 -1
- package/dist/types/server/engines/style/candidate-guard.d.ts +10 -0
- package/dist/types/server/engines/style/index.d.ts +1 -1
- package/dist/types/server/engines/style/tailwind-adapter.d.ts +12 -0
- package/dist/types/server/host/source-packages.d.cts +13 -1
- package/dist/types/server/host/source-packages.d.ts +7 -4
- package/dist/types/server/index.d.ts +18 -17
- package/dist/types/server/infra/cache/ServerFileCache.d.ts +28 -5
- package/dist/types/server/node.d.ts +10 -7
- package/dist/types/shared/registry-generated/error-codes.d.ts +4 -0
- package/dist/types/shared/registry-generated/limits.d.ts +4 -0
- package/dist/types/shared/types/data-config.types.d.ts +2 -0
- package/host-native/bin/host-native.cjs +204 -0
- package/host-native/client/browser-entry.ts +499 -0
- package/{host-next/app → host-native/client}/page-access.ts +12 -0
- package/host-native/client/router-bridge.ts +120 -0
- package/host-native/src/aot-builder.ts +486 -0
- package/host-native/src/csp-headers.ts +75 -0
- package/host-native/src/host-prepare.ts +123 -0
- package/{host-next/app/soma/manifest/route.ts → host-native/src/manifest-http.ts} +10 -10
- package/host-native/src/native-server.ts +691 -0
- package/host-native/src/page-http.ts +223 -0
- package/host-native/src/public-packages.cjs +167 -0
- package/{host-next/app/api/soma-registry/[...path]/route.ts → host-native/src/registry-handler.ts} +17 -19
- package/{host-next → host-native}/src/shell-routes.cjs +23 -13
- package/host-native/src/static-file.ts +172 -0
- package/host-native/src/workspace.ts +185 -0
- package/{host-next/app → host-native/styles}/globals.css +2 -2
- package/package.json +13 -32
- package/tsconfig.json +1 -1
- package/host-next/app/SomaPageClient.tsx +0 -359
- package/host-next/app/[...path]/page.tsx +0 -22
- package/host-next/app/api/[...path]/route.ts +0 -98
- package/host-next/app/components/SomaHostPage.tsx +0 -128
- package/host-next/app/components/SomaHydrationShell.tsx +0 -20
- package/host-next/app/components/SomaPageClientBoundary.tsx +0 -13
- package/host-next/app/components/SomaPageForbidden.tsx +0 -19
- package/host-next/app/favicon.ico/route.ts +0 -13
- package/host-next/app/layout.tsx +0 -27
- package/host-next/app/page.tsx +0 -9
- package/host-next/app/router-bridge.ts +0 -42
- package/host-next/app/soma/[...path]/route.ts +0 -9
- package/host-next/app/soma/_shared/host-prepare.ts +0 -33
- package/host-next/app/soma/_shared/page-http.ts +0 -86
- package/host-next/app/soma/page/route.ts +0 -36
- package/host-next/app/soma/route.ts +0 -9
- package/host-next/app/soma-runtime/[...file]/route.ts +0 -21
- package/host-next/app/soma-runtime/_shared/static-file.ts +0 -89
- package/host-next/bin/host-next.cjs +0 -60
- package/host-next/instrumentation.ts +0 -18
- package/host-next/next-env.d.ts +0 -7
- package/host-next/next.config.js +0 -410
- package/host-next/proxy.ts +0 -43
- package/host-next/src/workspace.ts +0 -543
|
@@ -45,3 +45,15 @@ export function loginRedirectTarget(loginPath: string | undefined, pagePath: str
|
|
|
45
45
|
if (pagePath === loginPath) return null;
|
|
46
46
|
return `${loginPath}?next=${encodeURIComponent(routerPath)}`;
|
|
47
47
|
}
|
|
48
|
+
|
|
49
|
+
import {
|
|
50
|
+
SOMA_PAGE_FORBIDDEN_TEXT_EN,
|
|
51
|
+
SOMA_PAGE_FORBIDDEN_TEXT_ZH,
|
|
52
|
+
} from '../../core/shared/page-access-text';
|
|
53
|
+
|
|
54
|
+
export function forbiddenText(locale?: string): string {
|
|
55
|
+
if (locale && (locale.toLowerCase().startsWith('en') || locale === 'en-US')) {
|
|
56
|
+
return SOMA_PAGE_FORBIDDEN_TEXT_EN;
|
|
57
|
+
}
|
|
58
|
+
return SOMA_PAGE_FORBIDDEN_TEXT_ZH;
|
|
59
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// SomaRouter → 原生浏览器 History API 导航桥接:按 core 给的落历史方式选 push / replace。
|
|
2
|
+
//
|
|
3
|
+
// core 的 `NAV_STATIC | … | replace`、`NAV_ACTION | … | replace` 与 Domain `router.navigate(url, { replace: true })`
|
|
4
|
+
// 都会在 `onNavigate` 回调里带 `{ replace: true }`。
|
|
5
|
+
|
|
6
|
+
export interface NextRouterLike {
|
|
7
|
+
push(href: string): void;
|
|
8
|
+
replace(href: string): void;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface SomaNavigateInfoLike {
|
|
12
|
+
readonly replace?: boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type SomaShellNavigate = (url: string, info?: SomaNavigateInfoLike) => void;
|
|
16
|
+
|
|
17
|
+
/** 兼容与单测接口:基于 NextRouterLike 对象的包装 */
|
|
18
|
+
export function createNextNavigate(router: NextRouterLike): SomaShellNavigate {
|
|
19
|
+
return (url, info) => {
|
|
20
|
+
if (info?.replace === true) router.replace(url);
|
|
21
|
+
else router.push(url);
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 纯原生浏览器导航桥接:直接操作 window.history */
|
|
26
|
+
export function createBrowserNavigate(
|
|
27
|
+
onRouteChange?: (url: string, info?: SomaNavigateInfoLike) => void,
|
|
28
|
+
): SomaShellNavigate {
|
|
29
|
+
return (url: string, info?: SomaNavigateInfoLike) => {
|
|
30
|
+
if (typeof window === 'undefined') return;
|
|
31
|
+
if (info?.replace === true) {
|
|
32
|
+
window.history.replaceState(null, '', url);
|
|
33
|
+
} else {
|
|
34
|
+
window.history.pushState(null, '', url);
|
|
35
|
+
}
|
|
36
|
+
onRouteChange?.(url, info);
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 内存路由的结构(`SomaRouter`):`getHistory` 可选 */
|
|
41
|
+
export interface SomaRouterLike {
|
|
42
|
+
getCurrentPath(): string;
|
|
43
|
+
getHistory?(): readonly string[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 挂载期(`onMount` 里)发生、桥接注册之前的那次导航怎么落历史:内存路由轨迹只有一条
|
|
48
|
+
* (初始路径被替换掉了)说明它是 replace;有两条及以上说明压过栈,按 push。
|
|
49
|
+
* 没有 `getHistory` 的路由给不出依据,按 push。
|
|
50
|
+
*/
|
|
51
|
+
export function pendingNavigateInfo(router: SomaRouterLike): SomaNavigateInfoLike {
|
|
52
|
+
const history = typeof router.getHistory === 'function' ? router.getHistory() : null;
|
|
53
|
+
return { replace: history !== null && history.length === 1 };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 拦截站内同源 `<a>` 标签点击,实现零整页刷新的极速 SPA 跳转 */
|
|
57
|
+
export function setupLinkInterceptor(navigate: SomaShellNavigate): () => void {
|
|
58
|
+
if (typeof window === 'undefined') return () => undefined;
|
|
59
|
+
|
|
60
|
+
const handleClick = (event: MouseEvent) => {
|
|
61
|
+
if (
|
|
62
|
+
event.defaultPrevented ||
|
|
63
|
+
event.button !== 0 ||
|
|
64
|
+
event.metaKey ||
|
|
65
|
+
event.ctrlKey ||
|
|
66
|
+
event.shiftKey ||
|
|
67
|
+
event.altKey
|
|
68
|
+
) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const anchor = (event.target as Element | null)?.closest('a');
|
|
73
|
+
if (!anchor || !(anchor instanceof HTMLAnchorElement)) return;
|
|
74
|
+
if (anchor.target && anchor.target !== '_self') return;
|
|
75
|
+
if (anchor.hasAttribute('download')) return;
|
|
76
|
+
|
|
77
|
+
const href = anchor.getAttribute('href');
|
|
78
|
+
if (!href || href.startsWith('#') || href.startsWith('javascript:')) return;
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
const url = new URL(anchor.href, window.location.href);
|
|
82
|
+
if (url.origin !== window.location.origin) return;
|
|
83
|
+
|
|
84
|
+
const pathname = url.pathname;
|
|
85
|
+
if (
|
|
86
|
+
pathname.startsWith('/api') ||
|
|
87
|
+
pathname.startsWith('/soma') ||
|
|
88
|
+
pathname.startsWith('/_soma')
|
|
89
|
+
) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
event.preventDefault();
|
|
94
|
+
const target = url.pathname + url.search + url.hash;
|
|
95
|
+
navigate(target);
|
|
96
|
+
} catch {
|
|
97
|
+
// 忽略无法解析的非法 URL,走浏览器默认行为
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
document.addEventListener('click', handleClick);
|
|
102
|
+
return () => {
|
|
103
|
+
document.removeEventListener('click', handleClick);
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 监听浏览器前进后退事件并触发路由回调 */
|
|
108
|
+
export function setupPopstateListener(onPop: (url: string) => void): () => void {
|
|
109
|
+
if (typeof window === 'undefined') return () => undefined;
|
|
110
|
+
|
|
111
|
+
const handlePopstate = () => {
|
|
112
|
+
const current = window.location.pathname + window.location.search + window.location.hash;
|
|
113
|
+
onPop(current);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
window.addEventListener('popstate', handlePopstate);
|
|
117
|
+
return () => {
|
|
118
|
+
window.removeEventListener('popstate', handlePopstate);
|
|
119
|
+
};
|
|
120
|
+
}
|
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import esbuild, { type BuildContext, type Plugin } from 'esbuild';
|
|
5
|
+
import { readAllSomaPublicAliases } from './public-packages.cjs';
|
|
6
|
+
import { toPascalCase } from '../../core/server/api/service-path';
|
|
7
|
+
import { getSomaHostSourceRoot, getSomaHostApiRoot } from '../../core/server/host/source-packages.cjs';
|
|
8
|
+
|
|
9
|
+
export interface BuildBrowserClientOptions {
|
|
10
|
+
readonly hostDir: string;
|
|
11
|
+
readonly webRoot?: string;
|
|
12
|
+
readonly outDir: string;
|
|
13
|
+
readonly dev: boolean;
|
|
14
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface BrowserClientBuildResult {
|
|
18
|
+
readonly entryUrl: string;
|
|
19
|
+
readonly cssUrl: string;
|
|
20
|
+
readonly cssText: string;
|
|
21
|
+
rebuild(): Promise<void>;
|
|
22
|
+
dispose(): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface BuildServerAotOptions {
|
|
26
|
+
readonly hostDir: string;
|
|
27
|
+
readonly webRoot?: string;
|
|
28
|
+
readonly apiRoot?: string;
|
|
29
|
+
readonly outDir: string;
|
|
30
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ServerAotManifest {
|
|
34
|
+
readonly hostDir: string;
|
|
35
|
+
readonly webRoot: string;
|
|
36
|
+
readonly apiRoot: string;
|
|
37
|
+
readonly builtAt: string;
|
|
38
|
+
readonly routes: Record<string, string>;
|
|
39
|
+
readonly hostAppCompiledPath?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
function resolveModuleFile(baseDir: string, subpath: string): string {
|
|
44
|
+
const target = subpath ? path.resolve(baseDir, subpath) : path.resolve(baseDir);
|
|
45
|
+
for (const ext of ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']) {
|
|
46
|
+
const candidate = target + ext;
|
|
47
|
+
if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
|
|
48
|
+
return candidate;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
|
|
52
|
+
for (const index of ['index.ts', 'index.tsx', 'index.js', 'index.mjs', 'index.cjs']) {
|
|
53
|
+
const candidate = path.join(target, index);
|
|
54
|
+
if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
|
|
55
|
+
return candidate;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return target;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const coreRoot = path.resolve(__dirname, '../..');
|
|
63
|
+
const hostNativeRoot = path.join(coreRoot, 'host-native');
|
|
64
|
+
const repoRoot = path.resolve(coreRoot, '..');
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 客户端专属 esbuild 插件:
|
|
68
|
+
* 1. 严禁 import 'server-only';
|
|
69
|
+
* 2. 映射 @soma-host/* 虚拟/可选模块;
|
|
70
|
+
* 3. 映射 soma-* 公开子路径。
|
|
71
|
+
*/
|
|
72
|
+
function createBrowserClientPlugin(options: {
|
|
73
|
+
hostDir: string;
|
|
74
|
+
webRoot: string;
|
|
75
|
+
}): Plugin {
|
|
76
|
+
const { hostDir, webRoot } = options;
|
|
77
|
+
const publicAliases = readAllSomaPublicAliases(hostDir, repoRoot, [webRoot, coreRoot]) as Record<string, string>;
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
name: 'soma-browser-client-plugin',
|
|
81
|
+
setup(build) {
|
|
82
|
+
// 1. 硬拦截 server-only
|
|
83
|
+
build.onResolve({ filter: /^server-only$/ }, (args) => {
|
|
84
|
+
throw new Error(
|
|
85
|
+
`[soma] Client bundle must not import 'server-only'! Boundary violation detected from ${args.importer}`,
|
|
86
|
+
);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// 2. @soma-host/bootstrap/soma-bootstrap
|
|
90
|
+
build.onResolve({ filter: /^@soma-host\/bootstrap\/soma-bootstrap$/ }, () => {
|
|
91
|
+
const candidateHostFile = path.resolve(webRoot, 'bootstrap/soma-bootstrap');
|
|
92
|
+
for (const ext of ['.ts', '.js', '.mjs']) {
|
|
93
|
+
if (fs.existsSync(candidateHostFile + ext)) {
|
|
94
|
+
return { path: candidateHostFile + ext };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (fs.existsSync(path.resolve(webRoot, 'soma.app.ts'))) {
|
|
98
|
+
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-from-app.ts') };
|
|
99
|
+
}
|
|
100
|
+
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-host.stub.ts') };
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
// 3. @soma-host/bootstrap/soma-domain-loaders
|
|
104
|
+
build.onResolve({ filter: /^@soma-host\/bootstrap\/soma-domain-loaders$/ }, () => {
|
|
105
|
+
const candidateLoader = path.resolve(webRoot, 'bootstrap/soma-domain-loaders');
|
|
106
|
+
for (const ext of ['.ts', '.js', '.mjs']) {
|
|
107
|
+
if (fs.existsSync(candidateLoader + ext)) {
|
|
108
|
+
return { path: candidateLoader + ext };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-domain-loaders.stub.ts') };
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// 4. @soma-host/domain/ui/*Class.ts 按需动态分片加载或缺失抛错
|
|
115
|
+
build.onResolve({ filter: /^@soma-host\/domain\/ui\/.*Class\.ts$/ }, (args) => {
|
|
116
|
+
const baseName = path.basename(args.path);
|
|
117
|
+
const diskFile = path.resolve(webRoot, 'domain/ui', baseName);
|
|
118
|
+
if (fs.existsSync(diskFile)) {
|
|
119
|
+
return { path: diskFile };
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
path: args.path,
|
|
123
|
+
namespace: 'soma-absent-domain',
|
|
124
|
+
};
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
build.onLoad({ filter: /.*/, namespace: 'soma-absent-domain' }, (args) => {
|
|
128
|
+
return {
|
|
129
|
+
contents: `
|
|
130
|
+
const err = new Error("Cannot find module '${args.path}'");
|
|
131
|
+
err.code = "MODULE_NOT_FOUND";
|
|
132
|
+
throw err;
|
|
133
|
+
`,
|
|
134
|
+
loader: 'js',
|
|
135
|
+
};
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
// 5. 其他 @soma-host/* 解析到 webRoot
|
|
139
|
+
build.onResolve({ filter: /^@soma-host(?:\/.*)?$/ }, (args) => {
|
|
140
|
+
const subpath = args.path.replace(/^@soma-host\/?/, '');
|
|
141
|
+
const target = path.resolve(webRoot, subpath);
|
|
142
|
+
for (const ext of ['', '.ts', '.tsx', '.js', '.jsx', '.mjs']) {
|
|
143
|
+
if (fs.existsSync(target + ext) && fs.statSync(target + ext).isFile()) {
|
|
144
|
+
return { path: target + ext };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
|
|
148
|
+
for (const index of ['index.ts', 'index.tsx', 'index.js', 'index.jsx']) {
|
|
149
|
+
if (fs.existsSync(path.join(target, index))) {
|
|
150
|
+
return { path: path.join(target, index) };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return { path: target };
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// 6. 拦截内部 engine 模块私有深导入(RT4 守卫)
|
|
158
|
+
build.onResolve({ filter: /core\/client\/engine\// }, (args) => {
|
|
159
|
+
if (!args.importer.includes('soma-core')) {
|
|
160
|
+
throw new Error(
|
|
161
|
+
`[soma] Deep import forbidden: '${args.path}' from '${args.importer}'. Import from 'soma-core/runtime' instead.`,
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
return undefined;
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
// 7. soma-* 公开子路径解析
|
|
168
|
+
build.onResolve({ filter: /^soma-[a-z0-9-]+(?:\/.*)?$/ }, (args) => {
|
|
169
|
+
const direct = publicAliases[args.path];
|
|
170
|
+
if (direct && fs.existsSync(direct)) {
|
|
171
|
+
return { path: direct };
|
|
172
|
+
}
|
|
173
|
+
return undefined;
|
|
174
|
+
});
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* 客户端 AOT 预编译打包:输出浏览器 ESM 分片与 globals.css
|
|
181
|
+
*/
|
|
182
|
+
export async function buildBrowserClient(
|
|
183
|
+
options: BuildBrowserClientOptions,
|
|
184
|
+
): Promise<BrowserClientBuildResult> {
|
|
185
|
+
const hostDir = path.resolve(options.hostDir);
|
|
186
|
+
const webRoot = path.resolve(options.webRoot || getSomaHostSourceRoot(hostDir, options.env));
|
|
187
|
+
const outDir = path.resolve(options.outDir);
|
|
188
|
+
const clientOutDir = path.join(outDir, 'client');
|
|
189
|
+
fs.mkdirSync(clientOutDir, { recursive: true });
|
|
190
|
+
|
|
191
|
+
const clientEntry = path.join(hostNativeRoot, 'client/browser-entry.ts');
|
|
192
|
+
const plugin = createBrowserClientPlugin({ hostDir, webRoot });
|
|
193
|
+
|
|
194
|
+
// 编译并输出 CSS
|
|
195
|
+
const cssSourcePath = path.join(hostNativeRoot, 'styles/globals.css');
|
|
196
|
+
let rawCss = '';
|
|
197
|
+
try {
|
|
198
|
+
rawCss = fs.readFileSync(cssSourcePath, 'utf8');
|
|
199
|
+
} catch {
|
|
200
|
+
rawCss = '/* soma globals */\n';
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
let finalCss = rawCss;
|
|
204
|
+
if (!options.dev) {
|
|
205
|
+
const minifiedCss = await esbuild.transform(rawCss, {
|
|
206
|
+
loader: 'css',
|
|
207
|
+
minify: true,
|
|
208
|
+
});
|
|
209
|
+
finalCss = minifiedCss.code;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
let cssFileName = 'globals.css';
|
|
213
|
+
if (!options.dev) {
|
|
214
|
+
const hash = createHash('sha256').update(finalCss).digest('hex').slice(0, 8);
|
|
215
|
+
cssFileName = `globals-${hash}.css`;
|
|
216
|
+
}
|
|
217
|
+
fs.writeFileSync(path.join(clientOutDir, cssFileName), finalCss, 'utf8');
|
|
218
|
+
const cssUrl = `/_soma/client/${cssFileName}`;
|
|
219
|
+
|
|
220
|
+
const buildOptions: esbuild.BuildOptions = {
|
|
221
|
+
entryPoints: {
|
|
222
|
+
'browser-entry': clientEntry,
|
|
223
|
+
},
|
|
224
|
+
outdir: clientOutDir,
|
|
225
|
+
bundle: true,
|
|
226
|
+
format: 'esm',
|
|
227
|
+
splitting: true,
|
|
228
|
+
platform: 'browser',
|
|
229
|
+
target: ['es2022'],
|
|
230
|
+
minify: !options.dev,
|
|
231
|
+
sourcemap: options.dev ? 'inline' : false,
|
|
232
|
+
entryNames: options.dev ? '[name]' : '[name]-[hash]',
|
|
233
|
+
chunkNames: options.dev ? 'chunks/[name]' : 'chunks/[name]-[hash]',
|
|
234
|
+
nodePaths: [path.join(webRoot, 'node_modules'), path.join(hostDir, 'node_modules'), path.join(coreRoot, 'node_modules')].filter((d) => fs.existsSync(d)),
|
|
235
|
+
plugins: [plugin],
|
|
236
|
+
define: {
|
|
237
|
+
'process.env.NODE_ENV': JSON.stringify(options.dev ? 'development' : 'production'),
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
let ctx: BuildContext | null = null;
|
|
242
|
+
let entryUrl = '/_soma/client/browser-entry.js';
|
|
243
|
+
|
|
244
|
+
if (options.dev) {
|
|
245
|
+
ctx = await esbuild.context(buildOptions);
|
|
246
|
+
await ctx.rebuild();
|
|
247
|
+
entryUrl = '/_soma/client/browser-entry.js';
|
|
248
|
+
} else {
|
|
249
|
+
const result = await esbuild.build({
|
|
250
|
+
...buildOptions,
|
|
251
|
+
metafile: true,
|
|
252
|
+
});
|
|
253
|
+
if (result.metafile) {
|
|
254
|
+
for (const [outputPath, meta] of Object.entries(result.metafile.outputs)) {
|
|
255
|
+
if (
|
|
256
|
+
meta.entryPoint &&
|
|
257
|
+
(meta.entryPoint.endsWith('browser-entry.ts') || path.basename(outputPath).startsWith('browser-entry')) &&
|
|
258
|
+
outputPath.endsWith('.js')
|
|
259
|
+
) {
|
|
260
|
+
const fileName = path.basename(outputPath);
|
|
261
|
+
entryUrl = `/_soma/client/${fileName}`;
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (!options.dev) {
|
|
269
|
+
fs.writeFileSync(
|
|
270
|
+
path.join(clientOutDir, 'client-manifest.json'),
|
|
271
|
+
JSON.stringify({ entryUrl, cssUrl, cssText: finalCss }, null, 2) + '\n',
|
|
272
|
+
'utf8',
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
return {
|
|
277
|
+
entryUrl,
|
|
278
|
+
cssUrl,
|
|
279
|
+
cssText: finalCss,
|
|
280
|
+
rebuild: async () => {
|
|
281
|
+
if (ctx) {
|
|
282
|
+
await ctx.rebuild();
|
|
283
|
+
}
|
|
284
|
+
},
|
|
285
|
+
dispose: async () => {
|
|
286
|
+
if (ctx) {
|
|
287
|
+
await ctx.dispose();
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* 后端 AOT 预编译:扫描后端服务源文件及 soma.app.ts,内联编译成 Node CJS 极速产物并生成 aot-manifest.json
|
|
295
|
+
*/
|
|
296
|
+
export async function buildServerAot(
|
|
297
|
+
options: BuildServerAotOptions,
|
|
298
|
+
): Promise<ServerAotManifest> {
|
|
299
|
+
const hostDir = path.resolve(options.hostDir);
|
|
300
|
+
const webRoot = path.resolve(options.webRoot || getSomaHostSourceRoot(hostDir, options.env));
|
|
301
|
+
const apiRoot = path.resolve(options.apiRoot || getSomaHostApiRoot(hostDir, options.env));
|
|
302
|
+
const outDir = path.resolve(options.outDir);
|
|
303
|
+
const aotServerDir = path.join(outDir, 'aot-server');
|
|
304
|
+
fs.mkdirSync(aotServerDir, { recursive: true });
|
|
305
|
+
|
|
306
|
+
const serviceFiles = scanServiceFiles(apiRoot, webRoot);
|
|
307
|
+
const entryPoints: Record<string, string> = {};
|
|
308
|
+
const routes: Record<string, string> = {};
|
|
309
|
+
|
|
310
|
+
for (const item of serviceFiles) {
|
|
311
|
+
const entryName = `services/${item.routeKey.replace(/\//g, '_')}`;
|
|
312
|
+
entryPoints[entryName] = item.filePath;
|
|
313
|
+
routes[item.routeKey] = `${entryName}.cjs`;
|
|
314
|
+
|
|
315
|
+
// 支持不同大小写路由键
|
|
316
|
+
const segments = item.routeKey.split('/');
|
|
317
|
+
const pascalKey = segments.slice(0, -1).concat(toPascalCase(segments[segments.length - 1])).join('/');
|
|
318
|
+
if (pascalKey !== item.routeKey) {
|
|
319
|
+
routes[pascalKey] = `${entryName}.cjs`;
|
|
320
|
+
}
|
|
321
|
+
const lowerKey = item.routeKey.toLowerCase();
|
|
322
|
+
if (lowerKey !== item.routeKey) {
|
|
323
|
+
routes[lowerKey] = `${entryName}.cjs`;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// 扫描 soma.app.ts
|
|
328
|
+
let hostAppCompiledPath: string | undefined;
|
|
329
|
+
const hostAppPath = path.resolve(webRoot, 'soma.app.ts');
|
|
330
|
+
if (fs.existsSync(hostAppPath)) {
|
|
331
|
+
entryPoints['host-app'] = hostAppPath;
|
|
332
|
+
hostAppCompiledPath = 'host-app.cjs';
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (Object.keys(entryPoints).length > 0) {
|
|
336
|
+
await esbuild.build({
|
|
337
|
+
entryPoints,
|
|
338
|
+
outdir: aotServerDir,
|
|
339
|
+
bundle: true,
|
|
340
|
+
platform: 'node',
|
|
341
|
+
format: 'cjs',
|
|
342
|
+
target: 'node20',
|
|
343
|
+
packages: 'external',
|
|
344
|
+
nodePaths: [path.join(apiRoot, 'node_modules'), path.join(webRoot, 'node_modules'), path.join(hostDir, 'node_modules'), path.join(coreRoot, 'node_modules')].filter((d) => fs.existsSync(d)),
|
|
345
|
+
outExtension: { '.js': '.cjs' },
|
|
346
|
+
plugins: [
|
|
347
|
+
{
|
|
348
|
+
name: 'soma-server-aot-plugin',
|
|
349
|
+
setup(build) {
|
|
350
|
+
const publicAliases = readAllSomaPublicAliases(hostDir, repoRoot, [webRoot, apiRoot, coreRoot]) as Record<string, string>;
|
|
351
|
+
build.onResolve({ filter: /^server-only$/ }, () => {
|
|
352
|
+
return { path: path.resolve(coreRoot, 'core/server/host/server-only-noop.cjs') };
|
|
353
|
+
});
|
|
354
|
+
build.onResolve({ filter: /^@core(?:\/.*)?$/ }, (args) => {
|
|
355
|
+
const subpath = args.path.replace(/^@core\/?/, '');
|
|
356
|
+
return { path: resolveModuleFile(path.resolve(coreRoot, 'core'), subpath) };
|
|
357
|
+
});
|
|
358
|
+
build.onResolve({ filter: /^@soma-host\/bootstrap\/soma-bootstrap$/ }, () => {
|
|
359
|
+
const candidateHostFile = path.resolve(webRoot, 'bootstrap/soma-bootstrap');
|
|
360
|
+
for (const ext of ['.ts', '.js', '.mjs']) {
|
|
361
|
+
if (fs.existsSync(candidateHostFile + ext)) {
|
|
362
|
+
return { path: candidateHostFile + ext };
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
if (fs.existsSync(path.resolve(webRoot, 'soma.app.ts'))) {
|
|
366
|
+
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-from-app.ts') };
|
|
367
|
+
}
|
|
368
|
+
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-host.stub.ts') };
|
|
369
|
+
});
|
|
370
|
+
build.onResolve({ filter: /^@soma-host\/bootstrap\/soma-domain-loaders$/ }, () => {
|
|
371
|
+
const candidateLoader = path.resolve(webRoot, 'bootstrap/soma-domain-loaders');
|
|
372
|
+
for (const ext of ['.ts', '.js', '.mjs']) {
|
|
373
|
+
if (fs.existsSync(candidateLoader + ext)) {
|
|
374
|
+
return { path: candidateLoader + ext };
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-domain-loaders.stub.ts') };
|
|
378
|
+
});
|
|
379
|
+
build.onResolve({ filter: /^@soma-host\/domain\/ui\/.*Class\.ts$/ }, (args) => {
|
|
380
|
+
const baseName = path.basename(args.path);
|
|
381
|
+
const diskFile = path.resolve(webRoot, 'domain/ui', baseName);
|
|
382
|
+
if (fs.existsSync(diskFile)) {
|
|
383
|
+
return { path: diskFile };
|
|
384
|
+
}
|
|
385
|
+
return { path: args.path, namespace: 'soma-absent-domain' };
|
|
386
|
+
});
|
|
387
|
+
build.onLoad({ filter: /.*/, namespace: 'soma-absent-domain' }, (args) => ({
|
|
388
|
+
contents: `const err = new Error("Cannot find module '${args.path}'"); err.code = "MODULE_NOT_FOUND"; throw err;`,
|
|
389
|
+
loader: 'js',
|
|
390
|
+
}));
|
|
391
|
+
build.onResolve({ filter: /^@soma-host(?:\/.*)?$/ }, (args) => {
|
|
392
|
+
const subpath = args.path.replace(/^@soma-host\/?/, '');
|
|
393
|
+
return { path: resolveModuleFile(webRoot, subpath) };
|
|
394
|
+
});
|
|
395
|
+
build.onResolve({ filter: /^@soma-api(?:\/.*)?$/ }, (args) => {
|
|
396
|
+
const subpath = args.path.replace(/^@soma-api\/?/, '');
|
|
397
|
+
return { path: resolveModuleFile(apiRoot, subpath) };
|
|
398
|
+
});
|
|
399
|
+
build.onResolve({ filter: /^soma-[a-z0-9-]+(?:\/.*)?$/ }, (args) => {
|
|
400
|
+
const direct = publicAliases[args.path];
|
|
401
|
+
if (direct && fs.existsSync(direct)) {
|
|
402
|
+
return { path: direct };
|
|
403
|
+
}
|
|
404
|
+
return undefined;
|
|
405
|
+
});
|
|
406
|
+
},
|
|
407
|
+
},
|
|
408
|
+
],
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const manifest: ServerAotManifest = {
|
|
413
|
+
hostDir,
|
|
414
|
+
webRoot,
|
|
415
|
+
apiRoot,
|
|
416
|
+
builtAt: new Date().toISOString(),
|
|
417
|
+
routes,
|
|
418
|
+
...(hostAppCompiledPath ? { hostAppCompiledPath } : {}),
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
const manifestPath = path.join(aotServerDir, 'aot-manifest.json');
|
|
422
|
+
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n', 'utf8');
|
|
423
|
+
|
|
424
|
+
return manifest;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
interface ScannedServiceItem {
|
|
428
|
+
readonly routeKey: string;
|
|
429
|
+
readonly filePath: string;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function scanServiceFiles(apiRoot: string, webRoot: string): ScannedServiceItem[] {
|
|
433
|
+
const items: ScannedServiceItem[] = [];
|
|
434
|
+
const scannedPaths = new Set<string>();
|
|
435
|
+
|
|
436
|
+
const baseCandidates = [
|
|
437
|
+
{ base: path.join(apiRoot, 'api', 'service'), isDirect: false },
|
|
438
|
+
{ base: path.join(apiRoot, 'service'), isDirect: false },
|
|
439
|
+
];
|
|
440
|
+
if (apiRoot !== webRoot) {
|
|
441
|
+
baseCandidates.push({ base: apiRoot, isDirect: true });
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
for (const { base, isDirect } of baseCandidates) {
|
|
445
|
+
if (!fs.existsSync(base)) continue;
|
|
446
|
+
walk(base, base, isDirect);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function walk(currentDir: string, baseDir: string, isDirect: boolean) {
|
|
450
|
+
let entries: fs.Dirent[] = [];
|
|
451
|
+
try {
|
|
452
|
+
entries = fs.readdirSync(currentDir, { withFileTypes: true });
|
|
453
|
+
} catch {
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
for (const entry of entries) {
|
|
458
|
+
const name = entry.name;
|
|
459
|
+
if (name.startsWith('.') || name.startsWith('_')) continue;
|
|
460
|
+
if (name === 'node_modules' || name === 'dist' || name === '.soma' || name === '.next') continue;
|
|
461
|
+
|
|
462
|
+
const fullPath = path.join(currentDir, name);
|
|
463
|
+
if (entry.isDirectory()) {
|
|
464
|
+
walk(fullPath, baseDir, isDirect);
|
|
465
|
+
} else if (entry.isFile()) {
|
|
466
|
+
if (!/\.(?:ts|js|mjs|cjs)$/.test(name)) continue;
|
|
467
|
+
if (name.endsWith('.d.ts') || name.includes('.test.') || name.includes('.spec.')) continue;
|
|
468
|
+
|
|
469
|
+
if (scannedPaths.has(fullPath)) continue;
|
|
470
|
+
scannedPaths.add(fullPath);
|
|
471
|
+
|
|
472
|
+
const rel = path.relative(baseDir, fullPath).replace(/\\/g, '/');
|
|
473
|
+
const segments = rel.replace(/\.[^.]+$/, '').split('/');
|
|
474
|
+
// 末段类名转换:如果文件名是 PascalCase(如 Hello),转成 kebab/camel(如 hello)
|
|
475
|
+
const last = segments[segments.length - 1];
|
|
476
|
+
const lowerLast = last.charAt(0).toLowerCase() + last.slice(1);
|
|
477
|
+
segments[segments.length - 1] = lowerLast;
|
|
478
|
+
|
|
479
|
+
const routeKey = segments.join('/');
|
|
480
|
+
items.push({ routeKey, filePath: fullPath });
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
return items;
|
|
486
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createSomaCspHeader,
|
|
3
|
+
resolveSomaCspOptionsFromEnv,
|
|
4
|
+
SOMA_CSP_NONCE_HEADER,
|
|
5
|
+
} from '../../core/server/host/content-security-policy';
|
|
6
|
+
import { resolveHostResponseHeaders } from '../../core/server/host/host-response-headers';
|
|
7
|
+
import { somaCspNonceMetadataAsync } from '../../core/server/host/csp-nonce-metadata';
|
|
8
|
+
|
|
9
|
+
export { createSomaCspHeader, resolveSomaCspOptionsFromEnv, SOMA_CSP_NONCE_HEADER };
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 为响应追加 Host 装配自定义头与 SOMA CSP 安全头
|
|
13
|
+
*/
|
|
14
|
+
export async function applyHostAndCspHeaders(
|
|
15
|
+
response: Response,
|
|
16
|
+
options: { readonly method: string; readonly pathname: string },
|
|
17
|
+
env: Readonly<Record<string, string | undefined>> = process.env,
|
|
18
|
+
): Promise<Response> {
|
|
19
|
+
const csp = createSomaCspHeader(resolveSomaCspOptionsFromEnv(env));
|
|
20
|
+
if (csp) {
|
|
21
|
+
response.headers.set(csp.name, csp.value);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const extra = await resolveHostResponseHeaders({
|
|
25
|
+
method: options.method,
|
|
26
|
+
pathname: options.pathname,
|
|
27
|
+
});
|
|
28
|
+
if (extra !== undefined) {
|
|
29
|
+
for (const [name, value] of Object.entries(extra)) {
|
|
30
|
+
response.headers.set(name, value);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return response;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 宿主 CSP 中间件(纯原生 Web Request / Response 实现,兼容测试与服务层)
|
|
39
|
+
*/
|
|
40
|
+
export async function proxy(
|
|
41
|
+
request: { readonly url: string; readonly method?: string; readonly headers?: HeadersInit },
|
|
42
|
+
env: Readonly<Record<string, string | undefined>> = process.env,
|
|
43
|
+
): Promise<Response> {
|
|
44
|
+
const csp = createSomaCspHeader(resolveSomaCspOptionsFromEnv(env));
|
|
45
|
+
const responseHeaders = new Headers();
|
|
46
|
+
|
|
47
|
+
if (csp) {
|
|
48
|
+
responseHeaders.set(csp.name, csp.value);
|
|
49
|
+
// 供请求层及测试使用的规范回显头
|
|
50
|
+
responseHeaders.set('x-middleware-request-content-security-policy', csp.value);
|
|
51
|
+
if (csp.nonce) {
|
|
52
|
+
responseHeaders.set(`x-middleware-request-${SOMA_CSP_NONCE_HEADER}`, csp.nonce);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const response = new Response(null, { status: 200, headers: responseHeaders });
|
|
57
|
+
const url = new URL(request.url);
|
|
58
|
+
const extra = await resolveHostResponseHeaders({
|
|
59
|
+
method: request.method || 'GET',
|
|
60
|
+
pathname: url.pathname,
|
|
61
|
+
});
|
|
62
|
+
if (extra !== undefined) {
|
|
63
|
+
for (const [name, value] of Object.entries(extra)) {
|
|
64
|
+
response.headers.set(name, value);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return response;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function readCspNonceMeta(nonce: string | undefined, env: Record<string, string | undefined> = process.env): Promise<string | undefined> {
|
|
71
|
+
const meta = await somaCspNonceMetadataAsync(async () => ({
|
|
72
|
+
get: (name: string) => (name === SOMA_CSP_NONCE_HEADER ? (nonce ?? null) : null),
|
|
73
|
+
}), env);
|
|
74
|
+
return meta.other?.['csp-nonce'];
|
|
75
|
+
}
|