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,223 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import zlib from 'node:zlib';
|
|
3
|
+
import { resolveHostLoginPath, SOMA_DEFAULT_LOGIN_PATH } from 'soma-core/server/host-assembly';
|
|
4
|
+
import { isStatusError } from '../../core/server/runtime-space/errors';
|
|
5
|
+
import { SomaPublishedPageError } from '../../core/server/host/published-page-assets';
|
|
6
|
+
|
|
7
|
+
export { SOMA_DEFAULT_LOGIN_PATH };
|
|
8
|
+
|
|
9
|
+
export function resolveLoginPath(
|
|
10
|
+
assembly?: { readonly login?: { readonly path?: string } } | null,
|
|
11
|
+
): string {
|
|
12
|
+
return resolveHostLoginPath(assembly);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface CacheableLoadedPage {
|
|
16
|
+
/** 绑定声明 cache: store 才为 true */
|
|
17
|
+
readonly cacheable: boolean;
|
|
18
|
+
readonly purpose?: 'access' | 'preview';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const VARY_DEFAULT = 'Cookie, Authorization';
|
|
22
|
+
const VARY_ENCODING = 'Cookie, Authorization, Accept-Encoding';
|
|
23
|
+
|
|
24
|
+
interface CachedPagePayload {
|
|
25
|
+
readonly utf8: Uint8Array;
|
|
26
|
+
readonly gzip: Uint8Array | null;
|
|
27
|
+
readonly etag: string;
|
|
28
|
+
readonly size: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const MAX_CACHE_ENTRIES = 256;
|
|
32
|
+
const MAX_CACHE_BYTES = 64 * 1024 * 1024; // 64MB
|
|
33
|
+
|
|
34
|
+
class PagePayloadBufferLRU {
|
|
35
|
+
private cache = new Map<string, CachedPagePayload>();
|
|
36
|
+
private totalBytes = 0;
|
|
37
|
+
|
|
38
|
+
get(key: string): CachedPagePayload | undefined {
|
|
39
|
+
const entry = this.cache.get(key);
|
|
40
|
+
if (!entry) return undefined;
|
|
41
|
+
// LRU refresh: re-insert to end
|
|
42
|
+
this.cache.delete(key);
|
|
43
|
+
this.cache.set(key, entry);
|
|
44
|
+
return entry;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
set(key: string, entry: CachedPagePayload): void {
|
|
48
|
+
if (this.cache.has(key)) {
|
|
49
|
+
const old = this.cache.get(key)!;
|
|
50
|
+
this.totalBytes -= old.size;
|
|
51
|
+
this.cache.delete(key);
|
|
52
|
+
}
|
|
53
|
+
while (
|
|
54
|
+
(this.cache.size >= MAX_CACHE_ENTRIES || this.totalBytes + entry.size > MAX_CACHE_BYTES) &&
|
|
55
|
+
this.cache.size > 0
|
|
56
|
+
) {
|
|
57
|
+
const firstKey = this.cache.keys().next().value;
|
|
58
|
+
if (firstKey !== undefined) {
|
|
59
|
+
const item = this.cache.get(firstKey);
|
|
60
|
+
if (item) this.totalBytes -= item.size;
|
|
61
|
+
this.cache.delete(firstKey);
|
|
62
|
+
} else {
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
this.cache.set(key, entry);
|
|
67
|
+
this.totalBytes += entry.size;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
clear(): void {
|
|
71
|
+
this.cache.clear();
|
|
72
|
+
this.totalBytes = 0;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
get size(): number {
|
|
76
|
+
return this.cache.size;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
get bytes(): number {
|
|
80
|
+
return this.totalBytes;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const PagePayloadBufferCache = new PagePayloadBufferLRU();
|
|
85
|
+
|
|
86
|
+
export function clearPagePayloadBufferCache(): void {
|
|
87
|
+
PagePayloadBufferCache.clear();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function weakEtag(body: string | Uint8Array): string {
|
|
91
|
+
return `W/"${createHash('sha1').update(body).digest('hex').slice(0, 20)}"`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function etagMatches(header: string | null | undefined, etag: string): boolean {
|
|
95
|
+
if (!header) return false;
|
|
96
|
+
return header.split(',').some((candidate) => {
|
|
97
|
+
const value = candidate.trim();
|
|
98
|
+
return value === '*' || value === etag || value.replace(/^W\//, '') === etag.replace(/^W\//, '');
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function acceptsGzip(header: string | null | undefined): boolean {
|
|
103
|
+
if (!header) return false;
|
|
104
|
+
return header.includes('gzip') || header.includes('*');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 成功响应。
|
|
109
|
+
* 绑定 cache 为 store 且用途是访问:`private, no-cache` + 弱 ETag。
|
|
110
|
+
* 支持可选 cacheKey 实现有界预序列化二进制缓冲与 Gzip 压缩短路。
|
|
111
|
+
*/
|
|
112
|
+
export function pageSuccessResponse(
|
|
113
|
+
page: CacheableLoadedPage,
|
|
114
|
+
body: unknown,
|
|
115
|
+
request?: { headers: { get(name: string): string | null } },
|
|
116
|
+
cacheKey?: string,
|
|
117
|
+
): Response {
|
|
118
|
+
const jsonType = 'application/json; charset=utf-8';
|
|
119
|
+
|
|
120
|
+
if (!page.cacheable || page.purpose === 'preview') {
|
|
121
|
+
const text = typeof body === 'string' ? body : JSON.stringify(body);
|
|
122
|
+
return new Response(text, {
|
|
123
|
+
status: 200,
|
|
124
|
+
headers: { 'content-type': jsonType, 'cache-control': 'no-store' },
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// 1. 若提供了 cacheKey,走高性能二进制缓冲池
|
|
129
|
+
if (cacheKey) {
|
|
130
|
+
let cached = PagePayloadBufferCache.get(cacheKey);
|
|
131
|
+
if (!cached) {
|
|
132
|
+
const text = typeof body === 'string' ? body : JSON.stringify(body);
|
|
133
|
+
const utf8 = Buffer.from(text, 'utf8');
|
|
134
|
+
const etag = weakEtag(utf8);
|
|
135
|
+
let gzip: Uint8Array | null = null;
|
|
136
|
+
if (utf8.byteLength >= 1024) {
|
|
137
|
+
try {
|
|
138
|
+
gzip = zlib.gzipSync(utf8);
|
|
139
|
+
} catch {
|
|
140
|
+
gzip = null;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const entrySize = utf8.byteLength + (gzip ? gzip.byteLength : 0);
|
|
144
|
+
cached = { utf8, gzip, etag, size: entrySize };
|
|
145
|
+
PagePayloadBufferCache.set(cacheKey, cached);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const ifNoneMatch = request?.headers?.get('if-none-match');
|
|
149
|
+
if (etagMatches(ifNoneMatch, cached.etag)) {
|
|
150
|
+
return new Response(null, {
|
|
151
|
+
status: 304,
|
|
152
|
+
headers: {
|
|
153
|
+
'cache-control': 'private, no-cache',
|
|
154
|
+
etag: cached.etag,
|
|
155
|
+
vary: VARY_DEFAULT,
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const clientAcceptsGzip = acceptsGzip(request?.headers?.get('accept-encoding'));
|
|
161
|
+
if (clientAcceptsGzip && cached.gzip) {
|
|
162
|
+
return new Response(cached.gzip as unknown as BodyInit, {
|
|
163
|
+
status: 200,
|
|
164
|
+
headers: {
|
|
165
|
+
'content-type': jsonType,
|
|
166
|
+
'content-encoding': 'gzip',
|
|
167
|
+
'cache-control': 'private, no-cache',
|
|
168
|
+
etag: cached.etag,
|
|
169
|
+
vary: VARY_ENCODING,
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return new Response(cached.utf8 as unknown as BodyInit, {
|
|
175
|
+
status: 200,
|
|
176
|
+
headers: {
|
|
177
|
+
'content-type': jsonType,
|
|
178
|
+
'cache-control': 'private, no-cache',
|
|
179
|
+
etag: cached.etag,
|
|
180
|
+
vary: VARY_DEFAULT,
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// 2. 未传 cacheKey,保持经典签名与头部兼容行为
|
|
186
|
+
const text = typeof body === 'string' ? body : JSON.stringify(body);
|
|
187
|
+
const etag = weakEtag(text);
|
|
188
|
+
const headers = { 'cache-control': 'private, no-cache', etag, vary: VARY_DEFAULT };
|
|
189
|
+
if (etagMatches(request?.headers.get('if-none-match') ?? null, etag)) {
|
|
190
|
+
return new Response(null, { status: 304, headers });
|
|
191
|
+
}
|
|
192
|
+
return new Response(text, { status: 200, headers: { 'content-type': jsonType, ...headers } });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 错误响应。
|
|
197
|
+
*/
|
|
198
|
+
export function pageErrorResponse(
|
|
199
|
+
error: unknown,
|
|
200
|
+
assembly?: { readonly login?: { readonly path?: string } } | null,
|
|
201
|
+
): Response {
|
|
202
|
+
const headers = { 'cache-control': 'no-store' };
|
|
203
|
+
if (error instanceof SomaPublishedPageError) {
|
|
204
|
+
return Response.json({ error: error.message, code: error.code }, { status: 500, headers });
|
|
205
|
+
}
|
|
206
|
+
if (isStatusError(error)) {
|
|
207
|
+
const textKey = (error as { textKey?: unknown }).textKey;
|
|
208
|
+
return Response.json(
|
|
209
|
+
{
|
|
210
|
+
error: error.message,
|
|
211
|
+
code: error.code,
|
|
212
|
+
...(typeof textKey === 'string' ? { textKey } : {}),
|
|
213
|
+
...(error.status === 401 ? { login: { path: resolveLoginPath(assembly) } } : {}),
|
|
214
|
+
},
|
|
215
|
+
{ status: error.status, headers },
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
219
|
+
return Response.json(
|
|
220
|
+
{ error: detail || 'Internal server error', code: 'SOMA_PAGE_ASSET_UNKNOWN' },
|
|
221
|
+
{ status: 500, headers },
|
|
222
|
+
);
|
|
223
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
|
|
6
|
+
function readJson(filePath) {
|
|
7
|
+
try {
|
|
8
|
+
if (!fs.existsSync(filePath)) return null;
|
|
9
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
10
|
+
} catch {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function isSafePackageChild(packageRoot, candidate) {
|
|
16
|
+
return candidate === packageRoot || candidate.startsWith(`${packageRoot}${path.sep}`);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function collectFiles(root) {
|
|
20
|
+
if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return [];
|
|
21
|
+
const files = [];
|
|
22
|
+
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
|
23
|
+
const fullPath = path.join(root, entry.name);
|
|
24
|
+
if (entry.isDirectory()) files.push(...collectFiles(fullPath));
|
|
25
|
+
else if (entry.isFile()) files.push(fullPath);
|
|
26
|
+
}
|
|
27
|
+
return files;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isSafeExportWildcardValue(value) {
|
|
31
|
+
return (
|
|
32
|
+
value.length > 0 &&
|
|
33
|
+
!path.isAbsolute(value) &&
|
|
34
|
+
value.split(/[\\/]/).every((segment) => segment !== '' && segment !== '.' && segment !== '..')
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function expandWildcardExportAliases(packageName, packageRoot, entry, target) {
|
|
39
|
+
if ((entry.match(/\*/g) ?? []).length !== 1 || (target.match(/\*/g) ?? []).length !== 1) return {};
|
|
40
|
+
const entryStar = entry.indexOf('*');
|
|
41
|
+
const targetStar = target.indexOf('*');
|
|
42
|
+
const entryPrefix = entry.slice(0, entryStar);
|
|
43
|
+
const entrySuffix = entry.slice(entryStar + 1);
|
|
44
|
+
const targetPrefix = target.slice(0, targetStar);
|
|
45
|
+
const targetSuffix = target.slice(targetStar + 1);
|
|
46
|
+
const sourceRoot = path.resolve(packageRoot, targetPrefix);
|
|
47
|
+
if (!isSafePackageChild(packageRoot, sourceRoot)) return {};
|
|
48
|
+
|
|
49
|
+
const aliases = {};
|
|
50
|
+
for (const filePath of collectFiles(sourceRoot)) {
|
|
51
|
+
const relative = path.relative(sourceRoot, filePath).split(path.sep).join('/');
|
|
52
|
+
if (!relative.endsWith(targetSuffix)) continue;
|
|
53
|
+
const wildcardValue = relative.slice(0, relative.length - targetSuffix.length);
|
|
54
|
+
if (!isSafeExportWildcardValue(wildcardValue)) continue;
|
|
55
|
+
const publicPath = `${entryPrefix.slice(2)}${wildcardValue}${entrySuffix}`;
|
|
56
|
+
if (!isSafeExportWildcardValue(publicPath)) continue;
|
|
57
|
+
aliases[`${packageName}/${publicPath}`] = filePath;
|
|
58
|
+
}
|
|
59
|
+
return aliases;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 枚举单个包 package.json 中的公开 exports 映射表。
|
|
64
|
+
* 返回 map: specifier -> resolvedFilePath
|
|
65
|
+
*/
|
|
66
|
+
function readPublicPackageAliases(packageName, packageRoot) {
|
|
67
|
+
const exportsMap = readJson(path.join(packageRoot, 'package.json'))?.exports;
|
|
68
|
+
if (!exportsMap || typeof exportsMap !== 'object') return {};
|
|
69
|
+
|
|
70
|
+
const exactAliases = {};
|
|
71
|
+
const wildcardAliases = {};
|
|
72
|
+
|
|
73
|
+
for (const [entry, descriptor] of Object.entries(exportsMap)) {
|
|
74
|
+
if (entry !== '.' && !entry.startsWith('./')) continue;
|
|
75
|
+
let target = null;
|
|
76
|
+
if (typeof descriptor === 'string') {
|
|
77
|
+
target = descriptor;
|
|
78
|
+
} else if (descriptor && typeof descriptor === 'object') {
|
|
79
|
+
target =
|
|
80
|
+
descriptor.import?.default ??
|
|
81
|
+
descriptor.import ??
|
|
82
|
+
descriptor.default ??
|
|
83
|
+
descriptor.require?.default ??
|
|
84
|
+
descriptor.require;
|
|
85
|
+
if (typeof target === 'object' && target !== null) {
|
|
86
|
+
target = target.default;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (typeof target !== 'string' || !target.startsWith('./')) continue;
|
|
90
|
+
|
|
91
|
+
const isWildcard = entry.includes('*') || target.includes('*');
|
|
92
|
+
if (entry.includes('*') !== target.includes('*')) continue;
|
|
93
|
+
if (isWildcard) {
|
|
94
|
+
Object.assign(
|
|
95
|
+
wildcardAliases,
|
|
96
|
+
expandWildcardExportAliases(packageName, packageRoot, entry, target),
|
|
97
|
+
);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const resolved = path.resolve(packageRoot, target);
|
|
102
|
+
if (!isSafePackageChild(packageRoot, resolved) || !fs.existsSync(resolved)) continue;
|
|
103
|
+
const publicPath = entry === '.' ? '' : entry.slice(2);
|
|
104
|
+
const specifier = publicPath ? `${packageName}/${publicPath}` : packageName;
|
|
105
|
+
exactAliases[specifier] = resolved;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return { ...wildcardAliases, ...exactAliases };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 扫描仓库/依赖中的全部 soma-* 包并生成完整的别名表
|
|
113
|
+
*/
|
|
114
|
+
function readAllSomaPublicAliases(hostDir, repoRoot, extraRoots = []) {
|
|
115
|
+
const aliases = {};
|
|
116
|
+
const searchRoots = [
|
|
117
|
+
repoRoot,
|
|
118
|
+
path.join(repoRoot, 'soma-core'),
|
|
119
|
+
path.join(repoRoot, 'soma-foundation'),
|
|
120
|
+
path.join(repoRoot, 'soma-ui'),
|
|
121
|
+
path.join(repoRoot, 'soma-lite'),
|
|
122
|
+
path.join(repoRoot, 'soma-kit'),
|
|
123
|
+
path.join(repoRoot, 'soma-ai'),
|
|
124
|
+
];
|
|
125
|
+
|
|
126
|
+
for (const r of extraRoots) {
|
|
127
|
+
if (r) searchRoots.unshift(r);
|
|
128
|
+
}
|
|
129
|
+
if (hostDir) {
|
|
130
|
+
searchRoots.unshift(hostDir);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const seenPackages = new Set();
|
|
134
|
+
|
|
135
|
+
for (const searchRoot of searchRoots) {
|
|
136
|
+
if (!fs.existsSync(searchRoot)) continue;
|
|
137
|
+
const pkgJsonPath = path.join(searchRoot, 'package.json');
|
|
138
|
+
const pkgJson = readJson(pkgJsonPath);
|
|
139
|
+
if (pkgJson?.name && pkgJson.name.startsWith('soma-') && !seenPackages.has(pkgJson.name)) {
|
|
140
|
+
seenPackages.add(pkgJson.name);
|
|
141
|
+
Object.assign(aliases, readPublicPackageAliases(pkgJson.name, searchRoot));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// 检查子目录或 node_modules
|
|
145
|
+
const nm = path.join(searchRoot, 'node_modules');
|
|
146
|
+
if (fs.existsSync(nm)) {
|
|
147
|
+
try {
|
|
148
|
+
for (const entry of fs.readdirSync(nm, { withFileTypes: true })) {
|
|
149
|
+
if (!entry.isDirectory()) continue;
|
|
150
|
+
if (entry.name.startsWith('soma-') && !seenPackages.has(entry.name)) {
|
|
151
|
+
const pkgPath = path.join(nm, entry.name);
|
|
152
|
+
seenPackages.add(entry.name);
|
|
153
|
+
Object.assign(aliases, readPublicPackageAliases(entry.name, pkgPath));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
} catch {}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return aliases;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
module.exports = {
|
|
164
|
+
readJson,
|
|
165
|
+
readPublicPackageAliases,
|
|
166
|
+
readAllSomaPublicAliases,
|
|
167
|
+
};
|
package/{host-next/app/api/soma-registry/[...path]/route.ts → host-native/src/registry-handler.ts}
RENAMED
|
@@ -1,13 +1,8 @@
|
|
|
1
|
-
import { NextRequest } from 'next/server';
|
|
2
1
|
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import type { IService } from '
|
|
4
|
-
import { resolveRegistryService } from '
|
|
5
|
-
import { invokeHostRequestHook } from '
|
|
6
|
-
import { withHostResponseHeaders } from '
|
|
7
|
-
|
|
8
|
-
// 注册中心内置端点(/api/soma-registry/*)。
|
|
9
|
-
// 比通用宿主服务路由(/api/[...path])更具体,Next 自动优先匹配——core 自带,宿主零接线。
|
|
10
|
-
// 鉴权分两层:宿主请求钩子先跑(应用决定谁可管理),端点内的主体鉴权再跑(平台底线)。
|
|
2
|
+
import type { IService } from '../../core/server/api/IService';
|
|
3
|
+
import { resolveRegistryService } from '../../core/server/registry/services/index';
|
|
4
|
+
import { invokeHostRequestHook } from '../../core/server/host/invoke-host-request-hook';
|
|
5
|
+
import { withHostResponseHeaders } from '../../core/server/host/host-response-headers';
|
|
11
6
|
|
|
12
7
|
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
13
8
|
|
|
@@ -15,14 +10,17 @@ function createHandler(method: HttpMethod) {
|
|
|
15
10
|
const methodKey = method.toLowerCase() as keyof IService;
|
|
16
11
|
|
|
17
12
|
async function dispatch(
|
|
18
|
-
req:
|
|
19
|
-
{ params }: { params: Promise<{ path: string[] }> },
|
|
13
|
+
req: any,
|
|
14
|
+
{ params }: { params: Promise<{ path: string[] }> | { path: string[] } },
|
|
20
15
|
): Promise<Response> {
|
|
21
|
-
const
|
|
16
|
+
const resolvedParams = await params;
|
|
17
|
+
const segments = resolvedParams.path || [];
|
|
18
|
+
const url = new URL(req.url, 'http://soma.local');
|
|
19
|
+
const pathname = req.nextUrl?.pathname || url.pathname;
|
|
22
20
|
|
|
23
21
|
const rejected = await invokeHostRequestHook(req, {
|
|
24
22
|
kind: 'api',
|
|
25
|
-
path:
|
|
23
|
+
path: pathname,
|
|
26
24
|
});
|
|
27
25
|
if (rejected) {
|
|
28
26
|
return rejected;
|
|
@@ -47,7 +45,6 @@ function createHandler(method: HttpMethod) {
|
|
|
47
45
|
try {
|
|
48
46
|
return await handlerFn.call(service, req);
|
|
49
47
|
} catch (e: unknown) {
|
|
50
|
-
// 未预期异常:细节只进服务端日志,回给调用方的只有事件号(不泄漏路径与部署形态)
|
|
51
48
|
const eventId = randomUUID().slice(0, 8);
|
|
52
49
|
console.error(
|
|
53
50
|
`[soma-core][注册中心] 事件 ${eventId} 未处理异常 ${method} /api/soma-registry/${segments.join('/')}:`,
|
|
@@ -60,14 +57,15 @@ function createHandler(method: HttpMethod) {
|
|
|
60
57
|
}
|
|
61
58
|
}
|
|
62
59
|
|
|
63
|
-
// 最终响应统一合并 Host 装配的响应头出口
|
|
64
60
|
return async function handler(
|
|
65
|
-
req:
|
|
66
|
-
context: { params: Promise<{ path: string[] }> },
|
|
61
|
+
req: any,
|
|
62
|
+
context: { params: Promise<{ path: string[] }> | { path: string[] } },
|
|
67
63
|
): Promise<Response> {
|
|
64
|
+
const url = new URL(req.url, 'http://soma.local');
|
|
65
|
+
const pathname = req.nextUrl?.pathname || url.pathname;
|
|
68
66
|
return withHostResponseHeaders(await dispatch(req, context), {
|
|
69
|
-
method: req.method,
|
|
70
|
-
pathname
|
|
67
|
+
method: req.method || method,
|
|
68
|
+
pathname,
|
|
71
69
|
});
|
|
72
70
|
};
|
|
73
71
|
}
|
|
@@ -1,14 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// 规则(Next App Router 约定):
|
|
5
|
-
// · 含 `page.*` 或 `route.*` 的目录才是路由;
|
|
6
|
-
// · 路由组 `(x)` 不进 URL;`_x` 私有目录与 `@x` 并行槽位不是路由,整棵跳过;
|
|
7
|
-
// · 遇到动态段 `[x]` / `[...x]` / `[[...x]]` 就截到它之前(`app/api/[...path]` → `/api`);
|
|
8
|
-
// 截完是空(根 `/` 与根级 catch-all `[...path]`)的不登记——那是 SOMA 页面入口本身,不是壳占用的地址;
|
|
9
|
-
// · 结果去重、排序,形状符合 core 对 `reservedRoutes` 的要求(`/` 起首、无空白 / `?` / `#` / `//`、≤ 256)。
|
|
10
|
-
// CJS:next.config.js 直接 require;测试经 createRequire。
|
|
11
|
-
|
|
2
|
+
// 壳路由枚举:从给定目录枚举壳自己占用的 URL,登记为宿主装配的 reservedRoutes。
|
|
12
3
|
const fs = require('node:fs');
|
|
13
4
|
const path = require('node:path');
|
|
14
5
|
|
|
@@ -17,12 +8,24 @@ const DYNAMIC_SEGMENT = /^\[.*\]$/;
|
|
|
17
8
|
const ROUTE_GROUP = /^\(.*\)$/;
|
|
18
9
|
const SHAPE_FORBIDDEN = /[\s?#]|\/\//;
|
|
19
10
|
|
|
11
|
+
const DEFAULT_NATIVE_SHELL_ROUTES = Object.freeze([
|
|
12
|
+
'/api',
|
|
13
|
+
'/soma',
|
|
14
|
+
'/soma-runtime',
|
|
15
|
+
'/_soma',
|
|
16
|
+
]);
|
|
17
|
+
|
|
20
18
|
function enumerateShellRoutes(appDir) {
|
|
21
19
|
const found = new Set();
|
|
22
20
|
if (!fs.existsSync(appDir) || !fs.statSync(appDir).isDirectory()) return [];
|
|
23
21
|
|
|
24
22
|
function walk(dir, segments, sawDynamic) {
|
|
25
|
-
|
|
23
|
+
let entries;
|
|
24
|
+
try {
|
|
25
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
26
|
+
} catch {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
26
29
|
if (entries.some((entry) => entry.isFile() && ROUTE_FILE.test(entry.name))) {
|
|
27
30
|
if (segments.length > 0) found.add('/' + segments.join('/'));
|
|
28
31
|
}
|
|
@@ -34,7 +37,6 @@ function enumerateShellRoutes(appDir) {
|
|
|
34
37
|
if (ROUTE_GROUP.test(name)) {
|
|
35
38
|
walk(child, segments, sawDynamic);
|
|
36
39
|
} else if (DYNAMIC_SEGMENT.test(name) || sawDynamic) {
|
|
37
|
-
// 动态段之下的路由都归它的静态前缀(已登记),只需继续看其子树里有没有路由文件以登记前缀本身
|
|
38
40
|
walk(child, segments, true);
|
|
39
41
|
} else {
|
|
40
42
|
walk(child, [...segments, name], false);
|
|
@@ -48,4 +50,12 @@ function enumerateShellRoutes(appDir) {
|
|
|
48
50
|
.sort();
|
|
49
51
|
}
|
|
50
52
|
|
|
51
|
-
|
|
53
|
+
function resolveNativeShellRoutes() {
|
|
54
|
+
return DEFAULT_NATIVE_SHELL_ROUTES;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
module.exports = {
|
|
58
|
+
enumerateShellRoutes,
|
|
59
|
+
resolveNativeShellRoutes,
|
|
60
|
+
DEFAULT_NATIVE_SHELL_ROUTES,
|
|
61
|
+
};
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import zlib from 'node:zlib';
|
|
5
|
+
import { resolveSomaRuntimeLayout } from '../../core/server/runtime-space/root';
|
|
6
|
+
|
|
7
|
+
const CONTENT_TYPES: Readonly<Record<string, string>> = {
|
|
8
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
9
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
10
|
+
'.map': 'application/json; charset=utf-8',
|
|
11
|
+
'.json': 'application/json; charset=utf-8',
|
|
12
|
+
'.css': 'text/css; charset=utf-8',
|
|
13
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
14
|
+
'.wasm': 'application/wasm',
|
|
15
|
+
'.svg': 'image/svg+xml',
|
|
16
|
+
'.png': 'image/png',
|
|
17
|
+
'.jpg': 'image/jpeg',
|
|
18
|
+
'.jpeg': 'image/jpeg',
|
|
19
|
+
'.webp': 'image/webp',
|
|
20
|
+
'.woff': 'font/woff',
|
|
21
|
+
'.woff2': 'font/woff2',
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** 文件名带内容哈希(`name-3fa9c0de.js`)才可 immutable;其余短缓存 + 条件请求 */
|
|
25
|
+
const HASHED_NAME = /[-.][0-9a-f]{8,}\.[a-z0-9]+$/i;
|
|
26
|
+
|
|
27
|
+
export type StaticResolution =
|
|
28
|
+
| { readonly ok: true; readonly file: string; readonly size: number; readonly mtimeMs: number }
|
|
29
|
+
| { readonly ok: false };
|
|
30
|
+
|
|
31
|
+
export function isSafeSegments(segments: readonly string[]): boolean {
|
|
32
|
+
return segments.length > 0 && segments.every((segment) => (
|
|
33
|
+
segment !== '' && !segment.startsWith('.') && !/[\\/]/.test(segment) && !/[\x00-\x1f]/.test(segment)
|
|
34
|
+
));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function resolveStaticFile(staticRoot: string, segments: readonly string[]): StaticResolution {
|
|
38
|
+
if (!isSafeSegments(segments)) return { ok: false };
|
|
39
|
+
try {
|
|
40
|
+
const rootReal = fs.realpathSync(staticRoot);
|
|
41
|
+
const candidate = path.join(rootReal, ...segments);
|
|
42
|
+
const real = fs.realpathSync(candidate);
|
|
43
|
+
if (real !== rootReal && !real.startsWith(rootReal + path.sep)) return { ok: false };
|
|
44
|
+
const stat = fs.statSync(real);
|
|
45
|
+
if (!stat.isFile()) return { ok: false };
|
|
46
|
+
return { ok: true, file: real, size: stat.size, mtimeMs: stat.mtimeMs };
|
|
47
|
+
} catch {
|
|
48
|
+
return { ok: false };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function staticRootOf(hostDir: string, env: Readonly<Record<string, string | undefined>> = process.env): string {
|
|
53
|
+
return resolveSomaRuntimeLayout(hostDir, env).dirs.static;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface CachedStaticPayload {
|
|
57
|
+
readonly raw: Uint8Array;
|
|
58
|
+
readonly gzip: Uint8Array | null;
|
|
59
|
+
readonly size: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const MAX_STATIC_CACHE_BYTES = 32 * 1024 * 1024; // 32MB
|
|
63
|
+
const MAX_SINGLE_FILE_BYTES = 4 * 1024 * 1024; // 4MB
|
|
64
|
+
const staticBufferCache = new Map<string, CachedStaticPayload>();
|
|
65
|
+
let currentStaticCacheBytes = 0;
|
|
66
|
+
|
|
67
|
+
export function clearStaticBufferCache(): void {
|
|
68
|
+
staticBufferCache.clear();
|
|
69
|
+
currentStaticCacheBytes = 0;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function getOrCacheStaticFile(filePath: string, size: number, mtimeMs: number): CachedStaticPayload | null {
|
|
73
|
+
if (size > MAX_SINGLE_FILE_BYTES) return null;
|
|
74
|
+
const key = `${filePath}:${size}:${mtimeMs}`;
|
|
75
|
+
const existing = staticBufferCache.get(key);
|
|
76
|
+
if (existing) {
|
|
77
|
+
// LRU touch
|
|
78
|
+
staticBufferCache.delete(key);
|
|
79
|
+
staticBufferCache.set(key, existing);
|
|
80
|
+
return existing;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
try {
|
|
84
|
+
const buffer = fs.readFileSync(filePath);
|
|
85
|
+
const raw = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
86
|
+
let gzip: Uint8Array | null = null;
|
|
87
|
+
if (raw.byteLength >= 1024) {
|
|
88
|
+
try {
|
|
89
|
+
gzip = zlib.gzipSync(raw);
|
|
90
|
+
} catch {
|
|
91
|
+
gzip = null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const entrySize = raw.byteLength + (gzip ? gzip.byteLength : 0);
|
|
95
|
+
while (currentStaticCacheBytes + entrySize > MAX_STATIC_CACHE_BYTES && staticBufferCache.size > 0) {
|
|
96
|
+
const firstKey = staticBufferCache.keys().next().value;
|
|
97
|
+
if (firstKey !== undefined) {
|
|
98
|
+
const item = staticBufferCache.get(firstKey);
|
|
99
|
+
if (item) currentStaticCacheBytes -= item.size;
|
|
100
|
+
staticBufferCache.delete(firstKey);
|
|
101
|
+
} else {
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const entry: CachedStaticPayload = { raw, gzip, size: entrySize };
|
|
106
|
+
staticBufferCache.set(key, entry);
|
|
107
|
+
currentStaticCacheBytes += entrySize;
|
|
108
|
+
return entry;
|
|
109
|
+
} catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function acceptsGzip(header: string | null | undefined): boolean {
|
|
115
|
+
if (!header) return false;
|
|
116
|
+
return header.includes('gzip') || header.includes('*');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function staticResponse(
|
|
120
|
+
segments: readonly string[],
|
|
121
|
+
request: { readonly method: string; readonly headers: { get(name: string): string | null } },
|
|
122
|
+
env: Readonly<Record<string, string | undefined>> = process.env,
|
|
123
|
+
): Response {
|
|
124
|
+
const notFound = () => new Response('Not found', { status: 404, headers: { 'cache-control': 'no-store', 'content-type': 'text/plain; charset=utf-8' } });
|
|
125
|
+
const hostDir = env.SOMA_HOST_DIR;
|
|
126
|
+
if (!hostDir) return notFound();
|
|
127
|
+
let root: string;
|
|
128
|
+
try {
|
|
129
|
+
root = staticRootOf(hostDir, env);
|
|
130
|
+
} catch {
|
|
131
|
+
return notFound();
|
|
132
|
+
}
|
|
133
|
+
const resolved = resolveStaticFile(root, segments);
|
|
134
|
+
if (!resolved.ok) return notFound();
|
|
135
|
+
|
|
136
|
+
const etag = `W/"${createHash('sha1').update(`${resolved.size}:${resolved.mtimeMs}`).digest('hex').slice(0, 20)}"`;
|
|
137
|
+
const hashed = HASHED_NAME.test(path.basename(resolved.file));
|
|
138
|
+
const headers: Record<string, string> = {
|
|
139
|
+
'content-type': CONTENT_TYPES[path.extname(resolved.file).toLowerCase()] ?? 'application/octet-stream',
|
|
140
|
+
'cache-control': hashed ? 'public, max-age=31536000, immutable' : 'public, max-age=300, must-revalidate',
|
|
141
|
+
etag,
|
|
142
|
+
'x-content-type-options': 'nosniff',
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
if (request.headers.get('if-none-match')?.split(',').some((value) => value.trim() === etag)) {
|
|
146
|
+
return new Response(null, { status: 304, headers });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (request.method.toUpperCase() === 'HEAD') {
|
|
150
|
+
headers['content-length'] = String(resolved.size);
|
|
151
|
+
return new Response(null, { status: 200, headers });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const cached = getOrCacheStaticFile(resolved.file, resolved.size, resolved.mtimeMs);
|
|
155
|
+
const clientAcceptsGzip = acceptsGzip(request.headers.get('accept-encoding'));
|
|
156
|
+
|
|
157
|
+
if (cached) {
|
|
158
|
+
if (clientAcceptsGzip && cached.gzip) {
|
|
159
|
+
headers['content-encoding'] = 'gzip';
|
|
160
|
+
headers['vary'] = 'Accept-Encoding';
|
|
161
|
+
headers['content-length'] = String(cached.gzip.byteLength);
|
|
162
|
+
return new Response(cached.gzip as unknown as BodyInit, { status: 200, headers });
|
|
163
|
+
}
|
|
164
|
+
headers['content-length'] = String(cached.raw.byteLength);
|
|
165
|
+
return new Response(cached.raw as unknown as BodyInit, { status: 200, headers });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// 大于 4MB 的文件回退到直接读取
|
|
169
|
+
const buf = fs.readFileSync(resolved.file);
|
|
170
|
+
headers['content-length'] = String(buf.length);
|
|
171
|
+
return new Response(buf, { status: 200, headers });
|
|
172
|
+
}
|