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
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const fs = require('node:fs');
|
|
6
|
+
const { spawn } = require('node:child_process');
|
|
7
|
+
|
|
8
|
+
const args = process.argv.slice(2);
|
|
9
|
+
const command = args[0];
|
|
10
|
+
|
|
11
|
+
if (!['dev', 'build', 'start'].includes(command)) {
|
|
12
|
+
console.error('用法: host-native.cjs <dev|build|start> [选项]');
|
|
13
|
+
console.error('选项:');
|
|
14
|
+
console.error(' -p, --port <n> 端口号 (默认 3000)');
|
|
15
|
+
console.error(' -H, --hostname <host> 监听地址 (默认 0.0.0.0)');
|
|
16
|
+
console.error(' --web-dir <dir> 前端静态根目录');
|
|
17
|
+
console.error(' --api-dir <dir> 后端服务根目录');
|
|
18
|
+
process.exit(1);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// 1. 自适应 V8 堆内存收束 (防止内存无限暴涨,生产态默认 512MB,开发态默认 1024MB)
|
|
22
|
+
if (!process.env.SOMA_NATIVE_HEAP_APPLIED && !process.env.SOMA_DISABLE_HEAP_CAP) {
|
|
23
|
+
const hasHeapArg = process.execArgv.some((arg) => arg.includes('--max-old-space-size'));
|
|
24
|
+
if (!hasHeapArg) {
|
|
25
|
+
const defaultMb = command === 'dev' ? 1024 : 512;
|
|
26
|
+
const maxOldSpace = process.env.SOMA_MAX_OLD_SPACE_MB
|
|
27
|
+
? parseInt(process.env.SOMA_MAX_OLD_SPACE_MB, 10)
|
|
28
|
+
: defaultMb;
|
|
29
|
+
|
|
30
|
+
const child = spawn(
|
|
31
|
+
process.execPath,
|
|
32
|
+
[`--max-old-space-size=${maxOldSpace}`, __filename, ...args],
|
|
33
|
+
{
|
|
34
|
+
stdio: 'inherit',
|
|
35
|
+
env: {
|
|
36
|
+
...process.env,
|
|
37
|
+
SOMA_NATIVE_HEAP_APPLIED: '1',
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
const forward = (sig) => { try { child.kill(sig); } catch {} };
|
|
43
|
+
process.on('SIGINT', () => forward('SIGINT'));
|
|
44
|
+
process.on('SIGTERM', () => forward('SIGTERM'));
|
|
45
|
+
child.on('exit', (code, signal) => {
|
|
46
|
+
process.exit(code ?? (signal ? 0 : 0));
|
|
47
|
+
});
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// 2. 参数解析
|
|
53
|
+
let port;
|
|
54
|
+
let hostname;
|
|
55
|
+
let webDir;
|
|
56
|
+
let apiDir;
|
|
57
|
+
|
|
58
|
+
for (let i = 1; i < args.length; i++) {
|
|
59
|
+
const arg = args[i];
|
|
60
|
+
if (arg === '-p' || arg === '--port') {
|
|
61
|
+
port = parseInt(args[++i], 10);
|
|
62
|
+
} else if (arg.startsWith('--port=')) {
|
|
63
|
+
port = parseInt(arg.slice('--port='.length), 10);
|
|
64
|
+
} else if (arg === '-H' || arg === '--hostname') {
|
|
65
|
+
hostname = args[++i];
|
|
66
|
+
} else if (arg.startsWith('--hostname=')) {
|
|
67
|
+
hostname = arg.slice('--hostname='.length);
|
|
68
|
+
} else if (arg === '--web-dir') {
|
|
69
|
+
webDir = args[++i];
|
|
70
|
+
} else if (arg.startsWith('--web-dir=')) {
|
|
71
|
+
webDir = arg.slice('--web-dir='.length);
|
|
72
|
+
} else if (arg === '--api-dir') {
|
|
73
|
+
apiDir = args[++i];
|
|
74
|
+
} else if (arg.startsWith('--api-dir=')) {
|
|
75
|
+
apiDir = arg.slice('--api-dir='.length);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const hostDir = path.resolve(
|
|
80
|
+
process.env.SOMA_HOST_DIR && process.env.SOMA_HOST_DIR.trim() !== ''
|
|
81
|
+
? process.env.SOMA_HOST_DIR
|
|
82
|
+
: process.cwd(),
|
|
83
|
+
);
|
|
84
|
+
process.env.SOMA_HOST_DIR = hostDir;
|
|
85
|
+
if (webDir) process.env.SOMA_WEB_DIR = path.resolve(hostDir, webDir);
|
|
86
|
+
if (apiDir) process.env.SOMA_API_DIR = path.resolve(hostDir, apiDir);
|
|
87
|
+
|
|
88
|
+
// 3. 准备运行时目录与静态分片同步
|
|
89
|
+
const { resolveSomaRuntimeLayout } = require('../../core/server/runtime-space/root.cjs');
|
|
90
|
+
const layout = resolveSomaRuntimeLayout(hostDir, process.env);
|
|
91
|
+
for (const dir of Object.values(layout.dirs)) {
|
|
92
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 同步浏览器核心运行包到 static/
|
|
96
|
+
const distBrowserDir = path.resolve(__dirname, '../../dist/browser');
|
|
97
|
+
if (fs.existsSync(distBrowserDir)) {
|
|
98
|
+
for (const file of fs.readdirSync(distBrowserDir)) {
|
|
99
|
+
const src = path.join(distBrowserDir, file);
|
|
100
|
+
const dst = path.join(layout.dirs.static, file);
|
|
101
|
+
if (fs.statSync(src).isFile()) {
|
|
102
|
+
fs.copyFileSync(src, dst);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// 默认壳路由设置
|
|
108
|
+
if (!process.env.SOMA_SHELL_ROUTES) {
|
|
109
|
+
process.env.SOMA_SHELL_ROUTES = JSON.stringify(['/api', '/soma', '/soma-runtime', '/_soma']);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const { getSomaHostSourceRoot, getSomaHostApiRoot } = require('../../core/server/host/source-packages.cjs');
|
|
113
|
+
|
|
114
|
+
function loadJiti() {
|
|
115
|
+
const createJiti = require('jiti');
|
|
116
|
+
return createJiti(__filename, { interopDefault: true });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function run() {
|
|
120
|
+
if (command === 'start' && !process.env.NODE_ENV) {
|
|
121
|
+
process.env.NODE_ENV = 'production';
|
|
122
|
+
}
|
|
123
|
+
const webRoot = getSomaHostSourceRoot(hostDir, process.env);
|
|
124
|
+
const apiRoot = getSomaHostApiRoot(hostDir, process.env);
|
|
125
|
+
|
|
126
|
+
if (command === 'build') {
|
|
127
|
+
const startTime = Date.now();
|
|
128
|
+
console.log('[soma-native] 开始执行 AOT 全量预编译...');
|
|
129
|
+
const jiti = loadJiti();
|
|
130
|
+
const aotBuilder = jiti(path.resolve(__dirname, '../src/aot-builder.ts'));
|
|
131
|
+
const hostPrepare = jiti(path.resolve(__dirname, '../src/host-prepare.ts'));
|
|
132
|
+
|
|
133
|
+
await hostPrepare.prewarmHostPages(hostDir, process.env);
|
|
134
|
+
|
|
135
|
+
await aotBuilder.buildBrowserClient({
|
|
136
|
+
hostDir,
|
|
137
|
+
webRoot,
|
|
138
|
+
outDir: layout.dirs.static,
|
|
139
|
+
dev: false,
|
|
140
|
+
env: process.env,
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
await aotBuilder.buildServerAot({
|
|
144
|
+
hostDir,
|
|
145
|
+
webRoot,
|
|
146
|
+
apiRoot,
|
|
147
|
+
outDir: layout.dirs.root,
|
|
148
|
+
env: process.env,
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
const elapsed = Date.now() - startTime;
|
|
152
|
+
console.log(`[soma-native] AOT 预编译完成!客户端与服务端产物已就绪 (耗时 ${elapsed}ms)`);
|
|
153
|
+
process.exit(0);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (command === 'start' || command === 'dev') {
|
|
157
|
+
const isDev = command === 'dev';
|
|
158
|
+
const precompiledServerPath = path.resolve(__dirname, '../../dist/host-native/native-server.cjs');
|
|
159
|
+
const nativeServer = (!isDev && fs.existsSync(precompiledServerPath))
|
|
160
|
+
? require(precompiledServerPath)
|
|
161
|
+
: loadJiti()(path.resolve(__dirname, '../src/native-server.ts'));
|
|
162
|
+
|
|
163
|
+
if (isDev) {
|
|
164
|
+
const hostPrepare = loadJiti()(path.resolve(__dirname, '../src/host-prepare.ts'));
|
|
165
|
+
try {
|
|
166
|
+
await hostPrepare.prewarmHostPages(hostDir, process.env);
|
|
167
|
+
} catch (e) {
|
|
168
|
+
console.warn('[soma-native] 初始预热执行异常:', e);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const instance = await nativeServer.createNativeServer({
|
|
173
|
+
hostDir,
|
|
174
|
+
webRoot,
|
|
175
|
+
apiRoot,
|
|
176
|
+
port,
|
|
177
|
+
hostname,
|
|
178
|
+
dev: isDev,
|
|
179
|
+
env: process.env,
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
const { url, port: actualPort } = await instance.start();
|
|
183
|
+
const modeText = isDev ? '开发态 (增量热更新)' : '生产态 (极速 AOT)';
|
|
184
|
+
|
|
185
|
+
console.log(`\n SOMA 极速原生内核已就绪 [${modeText}]`);
|
|
186
|
+
console.log(` > 本地地址: ${url}`);
|
|
187
|
+
console.log(` > 前端目录: ${webRoot}`);
|
|
188
|
+
console.log(` > 后端目录: ${apiRoot}\n`);
|
|
189
|
+
|
|
190
|
+
const cleanup = async () => {
|
|
191
|
+
console.log('\n[soma-native] 正在安全停止内核...');
|
|
192
|
+
await instance.close();
|
|
193
|
+
process.exit(0);
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
process.on('SIGINT', cleanup);
|
|
197
|
+
process.on('SIGTERM', cleanup);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
run().catch((err) => {
|
|
202
|
+
console.error('[soma-native] 进程启动失败:', err);
|
|
203
|
+
process.exit(1);
|
|
204
|
+
});
|
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
// 纯原生 DOM 极速客户端入口:零 React,零 Next,体积小、性能快
|
|
2
|
+
import { PageAccessError, readPageAccessError, loginRedirectTarget } from './page-access';
|
|
3
|
+
import {
|
|
4
|
+
createBrowserNavigate,
|
|
5
|
+
pendingNavigateInfo,
|
|
6
|
+
setupLinkInterceptor,
|
|
7
|
+
setupPopstateListener,
|
|
8
|
+
type SomaShellNavigate,
|
|
9
|
+
} from './router-bridge';
|
|
10
|
+
import type {
|
|
11
|
+
ComponentTreeRuntimeEnvelope,
|
|
12
|
+
SomaBootstrap as SomaBootstrapType,
|
|
13
|
+
SomaPageAssets,
|
|
14
|
+
SomaRuntimeServices,
|
|
15
|
+
} from 'soma-core/runtime';
|
|
16
|
+
import { assertRuntimeArtifact, maybeStartBootTimings, readBootTimings, SomaBootstrap } from 'soma-core/runtime';
|
|
17
|
+
import { loadHostDomainClass, resolveHostBootstrapOptions } from 'soma-core/host-bridge';
|
|
18
|
+
import { designChunkLoadBackoffMs } from 'soma-foundation/layout';
|
|
19
|
+
import {
|
|
20
|
+
SOMA_PAGE_FORBIDDEN_I18N_KEY,
|
|
21
|
+
SOMA_PAGE_FORBIDDEN_TEXT_EN,
|
|
22
|
+
SOMA_PAGE_FORBIDDEN_TEXT_ZH,
|
|
23
|
+
} from '../../core/shared/page-access-text';
|
|
24
|
+
|
|
25
|
+
declare global {
|
|
26
|
+
interface Window {
|
|
27
|
+
__SOMA_READY__?: boolean;
|
|
28
|
+
__SOMA_DEV_SSE__?: boolean;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const isDev = process.env.NODE_ENV !== 'production';
|
|
33
|
+
|
|
34
|
+
export function forbiddenText(language?: string): string {
|
|
35
|
+
return language && language.toLowerCase().startsWith('en')
|
|
36
|
+
? SOMA_PAGE_FORBIDDEN_TEXT_EN
|
|
37
|
+
: SOMA_PAGE_FORBIDDEN_TEXT_ZH;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function escapeHtml(str: string): string {
|
|
41
|
+
return str
|
|
42
|
+
.replace(/&/g, '&')
|
|
43
|
+
.replace(/</g, '<')
|
|
44
|
+
.replace(/>/g, '>')
|
|
45
|
+
.replace(/"/g, '"')
|
|
46
|
+
.replace(/'/g, ''');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function urlPathToPageBase(urlPath: string): string {
|
|
50
|
+
const clean = urlPath.replace(/^\//, '').replace(/\.html$/i, '');
|
|
51
|
+
return clean || 'index';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
type PagePayload = ComponentTreeRuntimeEnvelope & {
|
|
55
|
+
base: string;
|
|
56
|
+
sourcePackage?: string | null;
|
|
57
|
+
html: string;
|
|
58
|
+
ui: string;
|
|
59
|
+
event: string;
|
|
60
|
+
styleYaml?: string;
|
|
61
|
+
dataYaml?: string;
|
|
62
|
+
includes?: Record<string, string>;
|
|
63
|
+
localeYaml: string;
|
|
64
|
+
appConfigYaml: string;
|
|
65
|
+
compiledStyles?: SomaPageAssets['compiledStyles'];
|
|
66
|
+
colorScheme?: SomaPageAssets['colorScheme'];
|
|
67
|
+
params?: SomaPageAssets['pageParams'];
|
|
68
|
+
query?: SomaPageAssets['pageQuery'];
|
|
69
|
+
queryContract?: SomaPageAssets['queryContract'];
|
|
70
|
+
nav?: SomaPageAssets['nav'];
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
type PrecompiledAssets = Pick<
|
|
74
|
+
SomaPageAssets,
|
|
75
|
+
| 'html'
|
|
76
|
+
| 'sourceMarkup'
|
|
77
|
+
| 'artifact'
|
|
78
|
+
| 'uiConfig'
|
|
79
|
+
| 'eventConfig'
|
|
80
|
+
| 'triggerConfig'
|
|
81
|
+
| 'timerConfig'
|
|
82
|
+
| 'styleConfig'
|
|
83
|
+
| 'locale'
|
|
84
|
+
| 'appConfig'
|
|
85
|
+
| 'dataConfig'
|
|
86
|
+
| 'compiledStyles'
|
|
87
|
+
>;
|
|
88
|
+
|
|
89
|
+
const pageAssetCache = new Map<string, PagePayload>();
|
|
90
|
+
|
|
91
|
+
async function loadPrecompiledFromManifest(
|
|
92
|
+
path: string,
|
|
93
|
+
current: ComponentTreeRuntimeEnvelope,
|
|
94
|
+
): Promise<PrecompiledAssets | null> {
|
|
95
|
+
try {
|
|
96
|
+
const res = await fetch(`/soma/manifest?path=${encodeURIComponent(path)}`);
|
|
97
|
+
if (!res.ok) return null;
|
|
98
|
+
const data: PrecompiledAssets & {
|
|
99
|
+
triggers?: SomaPageAssets['triggerConfig'];
|
|
100
|
+
timers?: SomaPageAssets['timerConfig'];
|
|
101
|
+
} = await res.json();
|
|
102
|
+
assertRuntimeArtifact(data);
|
|
103
|
+
if ((data.sourceMarkup ?? 'legacy-html') !== (current.sourceMarkup ?? 'legacy-html')) return null;
|
|
104
|
+
if (
|
|
105
|
+
current.sourceMarkup === 'component-tree' &&
|
|
106
|
+
data.artifact?.artifactDigest !== current.artifact?.artifactDigest
|
|
107
|
+
) {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
if (typeof data.html !== 'string') return null;
|
|
111
|
+
return {
|
|
112
|
+
sourceMarkup: data.sourceMarkup,
|
|
113
|
+
html: data.html,
|
|
114
|
+
artifact: data.artifact,
|
|
115
|
+
uiConfig: data.uiConfig,
|
|
116
|
+
eventConfig: data.eventConfig,
|
|
117
|
+
triggerConfig: data.triggers ?? [],
|
|
118
|
+
timerConfig: data.timers ?? [],
|
|
119
|
+
styleConfig: data.styleConfig,
|
|
120
|
+
locale: data.locale ?? {},
|
|
121
|
+
appConfig: data.appConfig ?? null,
|
|
122
|
+
dataConfig: data.dataConfig ?? undefined,
|
|
123
|
+
...(data.compiledStyles !== undefined ? { compiledStyles: data.compiledStyles } : {}),
|
|
124
|
+
};
|
|
125
|
+
} catch {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
class NativePageClient {
|
|
131
|
+
private bootstrap: SomaBootstrapType | null = null;
|
|
132
|
+
private routerBridgeUnsub: (() => void) | null = null;
|
|
133
|
+
private currentRunId = 0;
|
|
134
|
+
private appRoot: HTMLElement;
|
|
135
|
+
private hydrationShell: HTMLElement;
|
|
136
|
+
private containerEl: HTMLElement;
|
|
137
|
+
private statusEl: HTMLElement;
|
|
138
|
+
private navigate: SomaShellNavigate;
|
|
139
|
+
|
|
140
|
+
constructor(appRoot: HTMLElement) {
|
|
141
|
+
this.appRoot = appRoot;
|
|
142
|
+
|
|
143
|
+
// 寻找现有的 hydration shell 或新建
|
|
144
|
+
const existingShell = appRoot.querySelector('.soma-hydration-shell') as HTMLElement | null;
|
|
145
|
+
if (existingShell) {
|
|
146
|
+
this.hydrationShell = existingShell;
|
|
147
|
+
} else {
|
|
148
|
+
this.hydrationShell = document.createElement('div');
|
|
149
|
+
this.hydrationShell.className = 'soma-hydration-shell';
|
|
150
|
+
this.hydrationShell.setAttribute('role', 'status');
|
|
151
|
+
this.hydrationShell.setAttribute('aria-live', 'polite');
|
|
152
|
+
this.hydrationShell.setAttribute('aria-busy', 'true');
|
|
153
|
+
this.hydrationShell.setAttribute('data-soma-hydration', 'pending');
|
|
154
|
+
this.hydrationShell.innerHTML = `
|
|
155
|
+
<div class="soma-hydration-shell__content">
|
|
156
|
+
<div class="soma-hydration-shell__spinner" aria-hidden="true"></div>
|
|
157
|
+
<p class="soma-hydration-shell__label">Loading page…</p>
|
|
158
|
+
</div>
|
|
159
|
+
`;
|
|
160
|
+
this.appRoot.appendChild(this.hydrationShell);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
this.containerEl = document.createElement('div');
|
|
164
|
+
this.containerEl.className = 'soma-page-container soma-hidden';
|
|
165
|
+
this.appRoot.appendChild(this.containerEl);
|
|
166
|
+
|
|
167
|
+
this.statusEl = document.createElement('div');
|
|
168
|
+
this.statusEl.className = 'soma-status-panel soma-hidden';
|
|
169
|
+
this.appRoot.appendChild(this.statusEl);
|
|
170
|
+
|
|
171
|
+
this.navigate = createBrowserNavigate((nextUrl) => {
|
|
172
|
+
void this.renderPage(nextUrl);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
setupLinkInterceptor((url, info) => {
|
|
176
|
+
this.navigate(url, info);
|
|
177
|
+
void this.renderPage(url);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
setupPopstateListener((url) => {
|
|
181
|
+
void this.renderPage(url);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
this.setupDevHmr();
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private setupDevHmr() {
|
|
188
|
+
if (typeof window === 'undefined' || !window.__SOMA_DEV_SSE__) return;
|
|
189
|
+
let es: EventSource | null = null;
|
|
190
|
+
const connectHmr = () => {
|
|
191
|
+
try {
|
|
192
|
+
es = new EventSource('/_soma/hmr');
|
|
193
|
+
es.addEventListener('reload', () => {
|
|
194
|
+
pageAssetCache.clear();
|
|
195
|
+
const cur = window.location.pathname + window.location.search;
|
|
196
|
+
void this.renderPage(cur);
|
|
197
|
+
});
|
|
198
|
+
es.onerror = () => {
|
|
199
|
+
es?.close();
|
|
200
|
+
setTimeout(connectHmr, 2000);
|
|
201
|
+
};
|
|
202
|
+
} catch {
|
|
203
|
+
setTimeout(connectHmr, 3000);
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
connectHmr();
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private showHydration() {
|
|
210
|
+
this.hydrationShell.classList.remove('soma-hidden');
|
|
211
|
+
this.containerEl.classList.add('soma-hidden');
|
|
212
|
+
this.statusEl.classList.add('soma-hidden');
|
|
213
|
+
this.statusEl.innerHTML = '';
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private showContainer() {
|
|
217
|
+
this.hydrationShell.classList.add('soma-hidden');
|
|
218
|
+
this.containerEl.classList.remove('soma-hidden');
|
|
219
|
+
this.statusEl.classList.add('soma-hidden');
|
|
220
|
+
this.statusEl.innerHTML = '';
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
private showForbidden(textKey?: string) {
|
|
224
|
+
this.hydrationShell.classList.add('soma-hidden');
|
|
225
|
+
this.containerEl.classList.add('soma-hidden');
|
|
226
|
+
this.statusEl.classList.remove('soma-hidden');
|
|
227
|
+
const key = textKey === SOMA_PAGE_FORBIDDEN_I18N_KEY ? textKey : SOMA_PAGE_FORBIDDEN_I18N_KEY;
|
|
228
|
+
const language = typeof navigator !== 'undefined' ? navigator.language : undefined;
|
|
229
|
+
this.statusEl.innerHTML = `
|
|
230
|
+
<main class="soma-page-forbidden" role="alert" data-soma-page-forbidden="${escapeHtml(key)}">
|
|
231
|
+
<p class="soma-page-forbidden__message">${escapeHtml(forbiddenText(language))}</p>
|
|
232
|
+
</main>
|
|
233
|
+
`;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private showError(errorMessage: string) {
|
|
237
|
+
this.hydrationShell.classList.add('soma-hidden');
|
|
238
|
+
this.containerEl.classList.add('soma-hidden');
|
|
239
|
+
this.statusEl.classList.remove('soma-hidden');
|
|
240
|
+
this.statusEl.innerHTML = `
|
|
241
|
+
<div class="soma-page-error">
|
|
242
|
+
<p class="soma-page-error__title">Page failed to load</p>
|
|
243
|
+
<p class="soma-page-error__message">${escapeHtml(errorMessage)}</p>
|
|
244
|
+
</div>
|
|
245
|
+
`;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async renderPage(targetUrl: string) {
|
|
249
|
+
const runId = ++this.currentRunId;
|
|
250
|
+
|
|
251
|
+
const parsed = new URL(targetUrl, window.location.href);
|
|
252
|
+
const pagePath = parsed.pathname;
|
|
253
|
+
const routerPath = parsed.search ? `${pagePath}${parsed.search}` : pagePath;
|
|
254
|
+
|
|
255
|
+
try {
|
|
256
|
+
maybeStartBootTimings();
|
|
257
|
+
this.showHydration();
|
|
258
|
+
|
|
259
|
+
const res = await fetch(`/soma/page?path=${encodeURIComponent(pagePath)}`);
|
|
260
|
+
if (!res.ok) throw await readPageAccessError(res);
|
|
261
|
+
const data: PagePayload = await res.json();
|
|
262
|
+
assertRuntimeArtifact(data);
|
|
263
|
+
|
|
264
|
+
if (runId !== this.currentRunId) return;
|
|
265
|
+
|
|
266
|
+
const base = (data.base as string) || urlPathToPageBase(pagePath);
|
|
267
|
+
const sourcePackage = typeof data.sourcePackage === 'string' ? data.sourcePackage : null;
|
|
268
|
+
const DomainClass = await loadHostDomainClass({ base, sourcePackage });
|
|
269
|
+
const routeAssets = {
|
|
270
|
+
routerPath,
|
|
271
|
+
...(data.params !== undefined ? { pageParams: data.params } : {}),
|
|
272
|
+
...(data.query !== undefined ? { pageQuery: data.query } : {}),
|
|
273
|
+
...(data.queryContract !== undefined ? { queryContract: data.queryContract } : {}),
|
|
274
|
+
...(data.nav !== undefined ? { nav: data.nav } : {}),
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
if (!isDev) {
|
|
278
|
+
const precompiled = await loadPrecompiledFromManifest(pagePath, data);
|
|
279
|
+
if (precompiled && runId === this.currentRunId) {
|
|
280
|
+
await this.mountInto(
|
|
281
|
+
DomainClass,
|
|
282
|
+
{ ...precompiled, ...routeAssets },
|
|
283
|
+
precompiled.html,
|
|
284
|
+
undefined,
|
|
285
|
+
routerPath,
|
|
286
|
+
runId,
|
|
287
|
+
);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const cached = pageAssetCache.get(routerPath);
|
|
292
|
+
if (
|
|
293
|
+
cached &&
|
|
294
|
+
(cached.sourceMarkup ?? 'legacy-html') === (data.sourceMarkup ?? 'legacy-html') &&
|
|
295
|
+
(data.sourceMarkup !== 'component-tree' ||
|
|
296
|
+
cached.artifact?.artifactDigest === data.artifact?.artifactDigest)
|
|
297
|
+
) {
|
|
298
|
+
const CachedClass = await loadHostDomainClass({
|
|
299
|
+
base: cached.base,
|
|
300
|
+
sourcePackage: cached.sourcePackage,
|
|
301
|
+
});
|
|
302
|
+
if (runId === this.currentRunId) {
|
|
303
|
+
await this.mountInto(
|
|
304
|
+
CachedClass,
|
|
305
|
+
{
|
|
306
|
+
uiYaml: cached.ui,
|
|
307
|
+
eventYaml: cached.event,
|
|
308
|
+
styleYaml: cached.styleYaml,
|
|
309
|
+
dataYaml: cached.dataYaml,
|
|
310
|
+
locale: cached.localeYaml ?? '',
|
|
311
|
+
appConfigYaml: cached.appConfigYaml ?? '',
|
|
312
|
+
sourceMarkup: cached.sourceMarkup,
|
|
313
|
+
artifact: cached.artifact,
|
|
314
|
+
...(cached.compiledStyles !== undefined ? { compiledStyles: cached.compiledStyles } : {}),
|
|
315
|
+
...routeAssets,
|
|
316
|
+
},
|
|
317
|
+
cached.html,
|
|
318
|
+
cached.includes,
|
|
319
|
+
routerPath,
|
|
320
|
+
runId,
|
|
321
|
+
);
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const payload: PagePayload = {
|
|
328
|
+
base,
|
|
329
|
+
sourcePackage,
|
|
330
|
+
sourceMarkup: data.sourceMarkup,
|
|
331
|
+
artifact: data.artifact,
|
|
332
|
+
html: data.html,
|
|
333
|
+
ui: data.ui,
|
|
334
|
+
event: data.event,
|
|
335
|
+
styleYaml: data.styleYaml ?? '',
|
|
336
|
+
dataYaml: typeof data.dataYaml === 'string' ? data.dataYaml : undefined,
|
|
337
|
+
includes: data.includes,
|
|
338
|
+
localeYaml: data.localeYaml ?? '',
|
|
339
|
+
appConfigYaml: data.appConfigYaml ?? '',
|
|
340
|
+
compiledStyles: data.compiledStyles,
|
|
341
|
+
colorScheme: data.colorScheme,
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
if (!isDev) {
|
|
345
|
+
pageAssetCache.set(routerPath, payload);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
if (runId !== this.currentRunId) return;
|
|
349
|
+
|
|
350
|
+
await this.mountInto(
|
|
351
|
+
DomainClass,
|
|
352
|
+
{
|
|
353
|
+
uiYaml: payload.ui,
|
|
354
|
+
eventYaml: payload.event,
|
|
355
|
+
styleYaml: payload.styleYaml,
|
|
356
|
+
dataYaml: payload.dataYaml,
|
|
357
|
+
locale: payload.localeYaml ?? '',
|
|
358
|
+
appConfigYaml: payload.appConfigYaml ?? '',
|
|
359
|
+
sourceMarkup: payload.sourceMarkup,
|
|
360
|
+
artifact: payload.artifact,
|
|
361
|
+
...(payload.compiledStyles !== undefined ? { compiledStyles: payload.compiledStyles } : {}),
|
|
362
|
+
...routeAssets,
|
|
363
|
+
},
|
|
364
|
+
payload.html,
|
|
365
|
+
payload.includes,
|
|
366
|
+
routerPath,
|
|
367
|
+
runId,
|
|
368
|
+
);
|
|
369
|
+
} catch (err: unknown) {
|
|
370
|
+
if (runId !== this.currentRunId) return;
|
|
371
|
+
if (err instanceof PageAccessError && err.status === 401) {
|
|
372
|
+
const target = loginRedirectTarget(err.loginPath, pagePath, routerPath);
|
|
373
|
+
if (target !== null) {
|
|
374
|
+
window.location.assign(target);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
if (err instanceof PageAccessError && err.status === 403) {
|
|
379
|
+
this.showForbidden(err.textKey);
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
383
|
+
this.showError(message);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
private async mountInto(
|
|
388
|
+
DomainClass: any,
|
|
389
|
+
assets: Omit<SomaPageAssets, 'html' | 'includes' | 'DomainClass'>,
|
|
390
|
+
html: string,
|
|
391
|
+
includes: Record<string, string> | undefined,
|
|
392
|
+
routerPath: string,
|
|
393
|
+
runId: number,
|
|
394
|
+
) {
|
|
395
|
+
if (this.bootstrap) {
|
|
396
|
+
await this.bootstrap.unmount();
|
|
397
|
+
this.bootstrap = null;
|
|
398
|
+
}
|
|
399
|
+
if (runId !== this.currentRunId) return;
|
|
400
|
+
|
|
401
|
+
const getServices = () =>
|
|
402
|
+
this.bootstrap?.getDomainInstance()?._services as SomaRuntimeServices | undefined;
|
|
403
|
+
|
|
404
|
+
const hostBootstrapOptions = await resolveHostBootstrapOptions(getServices, {
|
|
405
|
+
chunkLoadBackoffMs: designChunkLoadBackoffMs(),
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
const bs = new SomaBootstrap(hostBootstrapOptions);
|
|
409
|
+
this.bootstrap = bs;
|
|
410
|
+
|
|
411
|
+
await bs.mount(this.containerEl, {
|
|
412
|
+
html,
|
|
413
|
+
includes,
|
|
414
|
+
DomainClass,
|
|
415
|
+
...assets,
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
await bs.whenSettled();
|
|
419
|
+
if (runId !== this.currentRunId) return;
|
|
420
|
+
|
|
421
|
+
this.showContainer();
|
|
422
|
+
|
|
423
|
+
if (typeof window !== 'undefined') {
|
|
424
|
+
window.__SOMA_DIAGNOSTICS__ = {
|
|
425
|
+
isSettled: () => bs.isSettled(),
|
|
426
|
+
getDomainValue: (path: string) => bs.getDomainValue(path),
|
|
427
|
+
getRegisteredSomaIds: () => bs.getRegisteredSomaIds(),
|
|
428
|
+
getCspNonceChain: () => ({
|
|
429
|
+
meta: document.querySelector('meta[name="csp-nonce"]')?.getAttribute('content')?.trim() ?? '',
|
|
430
|
+
styles: Array.from(document.head.querySelectorAll('style'))
|
|
431
|
+
.map((style) => (style as HTMLStyleElement).nonce ?? '')
|
|
432
|
+
.filter(Boolean),
|
|
433
|
+
}),
|
|
434
|
+
};
|
|
435
|
+
window.__SOMA_READY__ = bs.isInitialized();
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
this.routerBridgeUnsub?.();
|
|
439
|
+
this.routerBridgeUnsub = null;
|
|
440
|
+
|
|
441
|
+
const domain = bs.getDomainInstance() as {
|
|
442
|
+
_services?: {
|
|
443
|
+
router: {
|
|
444
|
+
getCurrentPath: () => string;
|
|
445
|
+
getHistory?: () => readonly string[];
|
|
446
|
+
onNavigate: (cb: (p: string, info?: { readonly replace?: boolean }) => void) => () => void;
|
|
447
|
+
};
|
|
448
|
+
};
|
|
449
|
+
} | null;
|
|
450
|
+
|
|
451
|
+
if (domain?._services?.router) {
|
|
452
|
+
const somaRouter = domain._services.router;
|
|
453
|
+
this.routerBridgeUnsub = somaRouter.onNavigate((nextPath, info) => {
|
|
454
|
+
if (nextPath !== routerPath) {
|
|
455
|
+
this.navigate(nextPath, info);
|
|
456
|
+
void this.renderPage(nextPath);
|
|
457
|
+
}
|
|
458
|
+
});
|
|
459
|
+
const pending = somaRouter.getCurrentPath();
|
|
460
|
+
if (pending !== routerPath) {
|
|
461
|
+
this.navigate(pending, pendingNavigateInfo(somaRouter));
|
|
462
|
+
void this.renderPage(pending);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
if (isDev && typeof window !== 'undefined') {
|
|
467
|
+
window.__SOMA__ = {
|
|
468
|
+
getDiagnosticsSnapshot: () => bs.getDiagnosticsSnapshot(),
|
|
469
|
+
getTelemetrySnapshot: () => bs.getTelemetrySnapshot(),
|
|
470
|
+
getBootTimings: () => readBootTimings(),
|
|
471
|
+
getDomainInstance: () => bs.getDomainInstance(),
|
|
472
|
+
captureSnapshot: () => bs.captureSnapshot(),
|
|
473
|
+
restoreSnapshot: (id: number) => bs.restoreSnapshot(id),
|
|
474
|
+
setLocale: (locale: string) => bs.setLocale(locale),
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
export function initSomaNativeApp() {
|
|
481
|
+
if (typeof document === 'undefined') return;
|
|
482
|
+
let root = document.getElementById('soma-app-root');
|
|
483
|
+
if (!root) {
|
|
484
|
+
root = document.createElement('div');
|
|
485
|
+
root.id = 'soma-app-root';
|
|
486
|
+
document.body.appendChild(root);
|
|
487
|
+
}
|
|
488
|
+
const client = new NativePageClient(root);
|
|
489
|
+
const initialUrl = window.location.pathname + window.location.search + window.location.hash;
|
|
490
|
+
void client.renderPage(initialUrl);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
if (typeof document !== 'undefined') {
|
|
494
|
+
if (document.readyState === 'loading') {
|
|
495
|
+
document.addEventListener('DOMContentLoaded', () => initSomaNativeApp());
|
|
496
|
+
} else {
|
|
497
|
+
initSomaNativeApp();
|
|
498
|
+
}
|
|
499
|
+
}
|