soma-core 2.1.6 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/bin/soma.cjs +1 -1
- package/bin/soma.ts +64 -15
- 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 +79 -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 +98 -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/dist/cli/soma.js +68 -14
- package/dist/host-native/aot-builder.cjs +852 -0
- package/dist/host-native/native-server.cjs +15341 -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/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 +12 -31
- 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
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
import { NextRequest } from 'next/server';
|
|
2
|
-
import type { IService } from '../../../core/server/api/IService';
|
|
3
|
-
import { loadHostService } from '../../../core/server/api/load-host-service';
|
|
4
|
-
import { invokeHostRequestHook } from '../../../core/server/host/invoke-host-request-hook';
|
|
5
|
-
import { withHostResponseHeaders } from '../../../core/server/host/host-response-headers';
|
|
6
|
-
|
|
7
|
-
// ─── HTTP 方法分发工厂 ─────────────────────────────────────
|
|
8
|
-
|
|
9
|
-
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
10
|
-
|
|
11
|
-
function createHandler(method: HttpMethod) {
|
|
12
|
-
const methodKey = method.toLowerCase() as keyof IService;
|
|
13
|
-
|
|
14
|
-
async function dispatch(
|
|
15
|
-
req: NextRequest,
|
|
16
|
-
{ params }: { params: Promise<{ path: string[] }> },
|
|
17
|
-
): Promise<Response> {
|
|
18
|
-
const segments = (await params).path || [];
|
|
19
|
-
|
|
20
|
-
const rejected = await invokeHostRequestHook(req, {
|
|
21
|
-
kind: 'api',
|
|
22
|
-
path: req.nextUrl.pathname,
|
|
23
|
-
});
|
|
24
|
-
if (rejected) {
|
|
25
|
-
return rejected;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
if (segments.length === 0) {
|
|
29
|
-
return Response.json(
|
|
30
|
-
{ error: 'Missing API path. Expected: /api/{module}/{action}' },
|
|
31
|
-
{ status: 400 },
|
|
32
|
-
);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
const service = loadHostService(segments);
|
|
36
|
-
|
|
37
|
-
if (!service) {
|
|
38
|
-
return Response.json(
|
|
39
|
-
{ error: `API not found: /api/${segments.join('/')}` },
|
|
40
|
-
{ status: 404 },
|
|
41
|
-
);
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const handlerFn = service[methodKey];
|
|
45
|
-
if (typeof handlerFn !== 'function') {
|
|
46
|
-
return Response.json(
|
|
47
|
-
{
|
|
48
|
-
error: `Method ${method} not allowed: /api/${segments.join('/')}`,
|
|
49
|
-
},
|
|
50
|
-
{
|
|
51
|
-
status: 405,
|
|
52
|
-
headers: { Allow: getAllowHeader(service) },
|
|
53
|
-
},
|
|
54
|
-
);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
try {
|
|
58
|
-
return await handlerFn.call(service, req);
|
|
59
|
-
} catch (e: unknown) {
|
|
60
|
-
const message = e instanceof Error ? e.message : String(e);
|
|
61
|
-
console.error(`[soma-core][接口] ${method} /api/${segments.join('/')}:`, message);
|
|
62
|
-
return Response.json(
|
|
63
|
-
{ error: message || 'Internal server error' },
|
|
64
|
-
{ status: 500 },
|
|
65
|
-
);
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// 最终响应(含请求钩子拒绝、404/405/500)统一合并 Host 装配的响应头出口
|
|
70
|
-
return async function handler(
|
|
71
|
-
req: NextRequest,
|
|
72
|
-
context: { params: Promise<{ path: string[] }> },
|
|
73
|
-
): Promise<Response> {
|
|
74
|
-
return withHostResponseHeaders(await dispatch(req, context), {
|
|
75
|
-
method: req.method,
|
|
76
|
-
pathname: req.nextUrl.pathname,
|
|
77
|
-
});
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** 生成 Allow 响应头 */
|
|
82
|
-
function getAllowHeader(service: IService): string {
|
|
83
|
-
const methods: string[] = [];
|
|
84
|
-
if (typeof service.get === 'function') methods.push('GET');
|
|
85
|
-
if (typeof service.post === 'function') methods.push('POST');
|
|
86
|
-
if (typeof service.put === 'function') methods.push('PUT');
|
|
87
|
-
if (typeof service.patch === 'function') methods.push('PATCH');
|
|
88
|
-
if (typeof service.delete === 'function') methods.push('DELETE');
|
|
89
|
-
return methods.join(', ');
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
// ─── 导出所有 HTTP 方法处理器 ───────────────────────────────
|
|
93
|
-
|
|
94
|
-
export const GET = createHandler('GET');
|
|
95
|
-
export const POST = createHandler('POST');
|
|
96
|
-
export const PUT = createHandler('PUT');
|
|
97
|
-
export const PATCH = createHandler('PATCH');
|
|
98
|
-
export const DELETE = createHandler('DELETE');
|
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
import { headers } from 'next/headers';
|
|
2
|
-
import { redirect } from 'next/navigation';
|
|
3
|
-
import { Suspense } from 'react';
|
|
4
|
-
import { invokeHostRequestHook } from '../../core/server/host/invoke-host-request-hook';
|
|
5
|
-
import { SomaHydrationShell } from './SomaHydrationShell';
|
|
6
|
-
import { SomaPageClientBoundary } from './SomaPageClientBoundary';
|
|
7
|
-
|
|
8
|
-
export type SomaPageSearchParams = Record<string, string | string[] | undefined>;
|
|
9
|
-
|
|
10
|
-
function firstForwardedValue(value: string | null): string {
|
|
11
|
-
return value?.split(',')[0]?.trim() ?? '';
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
function resolveRequestOrigin(requestHeaders: Headers): string {
|
|
15
|
-
const host = firstForwardedValue(requestHeaders.get('x-forwarded-host'))
|
|
16
|
-
|| firstForwardedValue(requestHeaders.get('host'))
|
|
17
|
-
|| 'localhost';
|
|
18
|
-
const closingBracket = host.indexOf(']');
|
|
19
|
-
const hostname = (host.startsWith('[') && closingBracket > 0
|
|
20
|
-
? host.slice(1, closingBracket)
|
|
21
|
-
: host.split(':')[0]).toLowerCase();
|
|
22
|
-
const forwardedProtocol = firstForwardedValue(requestHeaders.get('x-forwarded-proto'));
|
|
23
|
-
const protocol = forwardedProtocol === 'http' || forwardedProtocol === 'https'
|
|
24
|
-
? forwardedProtocol
|
|
25
|
-
: (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' ? 'http' : 'https');
|
|
26
|
-
return `${protocol}://${host}`;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function appendSearchParams(url: URL, searchParams: SomaPageSearchParams | undefined): void {
|
|
30
|
-
if (!searchParams) return;
|
|
31
|
-
for (const [key, rawValue] of Object.entries(searchParams)) {
|
|
32
|
-
if (Array.isArray(rawValue)) {
|
|
33
|
-
rawValue.forEach((value) => url.searchParams.append(key, value));
|
|
34
|
-
} else if (typeof rawValue === 'string') {
|
|
35
|
-
url.searchParams.set(key, rawValue);
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
async function readRejectedMessage(response: Response): Promise<string> {
|
|
41
|
-
try {
|
|
42
|
-
const payload = await response.clone().json() as { error?: unknown; message?: unknown };
|
|
43
|
-
const message = payload.error ?? payload.message;
|
|
44
|
-
if (typeof message === 'string' && message.trim()) {
|
|
45
|
-
return message.trim();
|
|
46
|
-
}
|
|
47
|
-
} catch {
|
|
48
|
-
// Fall through to text/status when the Host returned a non-JSON response.
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
try {
|
|
52
|
-
const text = await response.clone().text();
|
|
53
|
-
if (text.trim()) return text.trim();
|
|
54
|
-
} catch {
|
|
55
|
-
// Ignore unreadable rejection bodies.
|
|
56
|
-
}
|
|
57
|
-
return response.statusText || 'Request rejected';
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function isRedirectResponse(response: Response): boolean {
|
|
61
|
-
return response.status >= 300 && response.status < 400 && Boolean(response.headers.get('location'));
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function isHtmlRejectionResponse(response: Response): boolean {
|
|
65
|
-
return (response.headers.get('content-type') || '').toLowerCase().includes('text/html');
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** Prefer the document body when a Host Hook returns a full HTML rejection page. */
|
|
69
|
-
function extractHtmlBodyInner(html: string): string {
|
|
70
|
-
const match = html.match(/<body\b[^>]*>([\s\S]*)<\/body>/i);
|
|
71
|
-
return (match?.[1] ?? html).trim();
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
export async function SomaHostPage({
|
|
75
|
-
pathname,
|
|
76
|
-
searchParams,
|
|
77
|
-
}: {
|
|
78
|
-
pathname: string;
|
|
79
|
-
searchParams?: SomaPageSearchParams;
|
|
80
|
-
}) {
|
|
81
|
-
const incomingHeaders = await headers();
|
|
82
|
-
const requestHeaders = new Headers();
|
|
83
|
-
incomingHeaders.forEach((value, key) => requestHeaders.set(key, value));
|
|
84
|
-
|
|
85
|
-
const requestUrl = new URL(pathname, resolveRequestOrigin(requestHeaders));
|
|
86
|
-
appendSearchParams(requestUrl, searchParams);
|
|
87
|
-
const request = new Request(requestUrl, { method: 'GET', headers: requestHeaders });
|
|
88
|
-
const rejected = await invokeHostRequestHook(request, {
|
|
89
|
-
kind: 'page',
|
|
90
|
-
path: requestUrl.pathname,
|
|
91
|
-
pageHref: requestUrl.pathname,
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
if (rejected) {
|
|
95
|
-
if (isRedirectResponse(rejected)) {
|
|
96
|
-
redirect(new URL(rejected.headers.get('location')!, requestUrl).toString());
|
|
97
|
-
}
|
|
98
|
-
if (isHtmlRejectionResponse(rejected)) {
|
|
99
|
-
const html = await rejected.text();
|
|
100
|
-
return (
|
|
101
|
-
<div
|
|
102
|
-
data-soma-request-rejected={rejected.status}
|
|
103
|
-
data-soma-rejection-html="1"
|
|
104
|
-
dangerouslySetInnerHTML={{ __html: extractHtmlBodyInner(html) }}
|
|
105
|
-
/>
|
|
106
|
-
);
|
|
107
|
-
}
|
|
108
|
-
const message = await readRejectedMessage(rejected);
|
|
109
|
-
return (
|
|
110
|
-
<main
|
|
111
|
-
className="soma-request-rejected"
|
|
112
|
-
data-soma-request-rejected={rejected.status}
|
|
113
|
-
>
|
|
114
|
-
<section className="soma-request-rejected__panel">
|
|
115
|
-
<p className="soma-request-rejected__eyebrow">HTTP {rejected.status}</p>
|
|
116
|
-
<h1 className="soma-request-rejected__title">Request rejected</h1>
|
|
117
|
-
<p className="soma-request-rejected__message">{message}</p>
|
|
118
|
-
</section>
|
|
119
|
-
</main>
|
|
120
|
-
);
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
return (
|
|
124
|
-
<Suspense fallback={<SomaHydrationShell />}>
|
|
125
|
-
<SomaPageClientBoundary />
|
|
126
|
-
</Suspense>
|
|
127
|
-
);
|
|
128
|
-
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SSR 首屏占位 — SOMA 运行时仅在客户端 mount(8.4)
|
|
3
|
-
* 避免 hydration mismatch,同时提供可访问的加载态
|
|
4
|
-
*/
|
|
5
|
-
export function SomaHydrationShell() {
|
|
6
|
-
return (
|
|
7
|
-
<div
|
|
8
|
-
className="soma-hydration-shell"
|
|
9
|
-
role="status"
|
|
10
|
-
aria-live="polite"
|
|
11
|
-
aria-busy="true"
|
|
12
|
-
data-soma-hydration="pending"
|
|
13
|
-
>
|
|
14
|
-
<div className="soma-hydration-shell__content">
|
|
15
|
-
<div className="soma-hydration-shell__spinner" aria-hidden />
|
|
16
|
-
<p className="soma-hydration-shell__label">Loading page…</p>
|
|
17
|
-
</div>
|
|
18
|
-
</div>
|
|
19
|
-
);
|
|
20
|
-
}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
'use client';
|
|
2
|
-
|
|
3
|
-
import dynamic from 'next/dynamic';
|
|
4
|
-
import { SomaHydrationShell } from './SomaHydrationShell';
|
|
5
|
-
|
|
6
|
-
const SomaPageClient = dynamic(() => import('../SomaPageClient'), {
|
|
7
|
-
ssr: false,
|
|
8
|
-
loading: () => <SomaHydrationShell />,
|
|
9
|
-
});
|
|
10
|
-
|
|
11
|
-
export function SomaPageClientBoundary() {
|
|
12
|
-
return <SomaPageClient />;
|
|
13
|
-
}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
'use client';
|
|
2
|
-
|
|
3
|
-
import { SOMA_PAGE_FORBIDDEN_I18N_KEY, SOMA_PAGE_FORBIDDEN_TEXT_EN, SOMA_PAGE_FORBIDDEN_TEXT_ZH } from '../../core/shared/page-access-text';
|
|
4
|
-
|
|
5
|
-
/** 受控无权页(403):词条 `soma.page.forbidden`,文案不含任何权限细节;语言取浏览器首选,缺省 zh-CN */
|
|
6
|
-
export function forbiddenText(language: string | undefined): string {
|
|
7
|
-
return language && language.toLowerCase().startsWith('en') ? SOMA_PAGE_FORBIDDEN_TEXT_EN : SOMA_PAGE_FORBIDDEN_TEXT_ZH;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export function SomaPageForbidden({ textKey }: { textKey: string | undefined }) {
|
|
11
|
-
// 只认框架词条;未知键(不应出现)同样给无权文案,不回显任何服务端文字
|
|
12
|
-
const key = textKey === SOMA_PAGE_FORBIDDEN_I18N_KEY ? textKey : SOMA_PAGE_FORBIDDEN_I18N_KEY;
|
|
13
|
-
const language = typeof navigator !== 'undefined' ? navigator.language : undefined;
|
|
14
|
-
return (
|
|
15
|
-
<main className="soma-page-forbidden" role="alert" data-soma-page-forbidden={key}>
|
|
16
|
-
<p className="soma-page-forbidden__message">{forbiddenText(language)}</p>
|
|
17
|
-
</main>
|
|
18
|
-
);
|
|
19
|
-
}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
const faviconSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
|
2
|
-
<rect width="64" height="64" rx="14" fill="#1677ff"/>
|
|
3
|
-
<path d="M18 22h8l6 18 6-18h8L35 48h-6L18 22z" fill="#ffffff"/>
|
|
4
|
-
</svg>`;
|
|
5
|
-
|
|
6
|
-
export function GET(): Response {
|
|
7
|
-
return new Response(faviconSvg, {
|
|
8
|
-
headers: {
|
|
9
|
-
'content-type': 'image/svg+xml; charset=utf-8',
|
|
10
|
-
'cache-control': 'public, max-age=86400',
|
|
11
|
-
},
|
|
12
|
-
});
|
|
13
|
-
}
|
package/host-next/app/layout.tsx
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import { headers } from 'next/headers';
|
|
2
|
-
import './globals.css';
|
|
3
|
-
import { readHostAppDisplayName } from '../core/server/host/app-config-composer';
|
|
4
|
-
import { somaCspNonceMetadataAsync } from '../core/server/host/csp-nonce-metadata';
|
|
5
|
-
|
|
6
|
-
export async function generateMetadata() {
|
|
7
|
-
const displayName = readHostAppDisplayName();
|
|
8
|
-
return {
|
|
9
|
-
title: displayName || 'SOMA',
|
|
10
|
-
description: displayName || 'SOMA declarative UI runtime',
|
|
11
|
-
// CSP 开启时透出 `<meta name="csp-nonce">`,供 soma-ui 的运行期 `<style>` 注入器取用
|
|
12
|
-
// (作业单 D-5)。CSP 关(缺省)时展开的是空对象,headers() 也不会被调用,静态渲染不受影响。
|
|
13
|
-
...await somaCspNonceMetadataAsync(() => headers()),
|
|
14
|
-
};
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export default function RootLayout({
|
|
18
|
-
children,
|
|
19
|
-
}: {
|
|
20
|
-
children: React.ReactNode;
|
|
21
|
-
}) {
|
|
22
|
-
return (
|
|
23
|
-
<html lang="en">
|
|
24
|
-
<body>{children}</body>
|
|
25
|
-
</html>
|
|
26
|
-
);
|
|
27
|
-
}
|
package/host-next/app/page.tsx
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { SomaHostPage, type SomaPageSearchParams } from './components/SomaHostPage';
|
|
2
|
-
|
|
3
|
-
export default async function SomaRootPage({
|
|
4
|
-
searchParams,
|
|
5
|
-
}: {
|
|
6
|
-
searchParams?: Promise<SomaPageSearchParams>;
|
|
7
|
-
}) {
|
|
8
|
-
return <SomaHostPage pathname="/" searchParams={await searchParams} />;
|
|
9
|
-
}
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
// SomaRouter → Next 路由的桥(K1 ⑦):按 core 给的落历史方式选 push / replace。
|
|
2
|
-
//
|
|
3
|
-
// core 的 `NAV_STATIC | … | replace`、`NAV_ACTION | … | replace` 与 Domain `router.navigate(url, { replace: true })`
|
|
4
|
-
// 都会在 `onNavigate` 回调里带 `{ replace: true }`;壳此前一律 `router.push`,replace 声明在 Next 宿主里不兑现
|
|
5
|
-
// (历史条数照增、后退回到被替换的那一页)。这里是唯一的选择点。
|
|
6
|
-
|
|
7
|
-
/** Next `useRouter()` 返回值里用到的两个方法 */
|
|
8
|
-
export interface NextRouterLike {
|
|
9
|
-
push(href: string): void;
|
|
10
|
-
replace(href: string): void;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/** core `NavigateInfo` 的结构(壳不 import core 类型也能对上) */
|
|
14
|
-
export interface SomaNavigateInfoLike {
|
|
15
|
-
readonly replace?: boolean;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/** 壳侧导航函数:`replace` 为真走 `router.replace`(不入历史),否则 `router.push` */
|
|
19
|
-
export type SomaShellNavigate = (url: string, info?: SomaNavigateInfoLike) => void;
|
|
20
|
-
|
|
21
|
-
export function createNextNavigate(router: NextRouterLike): SomaShellNavigate {
|
|
22
|
-
return (url, info) => {
|
|
23
|
-
if (info?.replace === true) router.replace(url);
|
|
24
|
-
else router.push(url);
|
|
25
|
-
};
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/** 内存路由的结构(`SomaRouter`):`getHistory` 可选,旧实现没有它时按 push 处理 */
|
|
29
|
-
export interface SomaRouterLike {
|
|
30
|
-
getCurrentPath(): string;
|
|
31
|
-
getHistory?(): readonly string[];
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* 挂载期(`onMount` 里)发生、桥接注册之前的那次导航怎么落历史:内存路由轨迹只有一条
|
|
36
|
-
* (初始路径被替换掉了)说明它是 replace;有两条及以上说明压过栈,按 push。
|
|
37
|
-
* 没有 `getHistory` 的路由给不出依据,按 push(与旧行为一致)。
|
|
38
|
-
*/
|
|
39
|
-
export function pendingNavigateInfo(router: SomaRouterLike): SomaNavigateInfoLike {
|
|
40
|
-
const history = typeof router.getHistory === 'function' ? router.getHistory() : null;
|
|
41
|
-
return { replace: history !== null && history.length === 1 };
|
|
42
|
-
}
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
function somaRouteNotFound(): Response {
|
|
2
|
-
return Response.json({ error: 'SOMA internal endpoint not found' }, { status: 404 });
|
|
3
|
-
}
|
|
4
|
-
|
|
5
|
-
export const GET = somaRouteNotFound;
|
|
6
|
-
export const POST = somaRouteNotFound;
|
|
7
|
-
export const PUT = somaRouteNotFound;
|
|
8
|
-
export const PATCH = somaRouteNotFound;
|
|
9
|
-
export const DELETE = somaRouteNotFound;
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
// 页面入口的装配准备:等 soma.app.ts 的服务端面装配完,并向 core 登记壳路由(需求单 R-18 / R-24)。
|
|
2
|
-
//
|
|
3
|
-
// 壳路由由 next.config.js 在启动时从 `app/` 枚举(src/shell-routes.cjs),经环境变量 `SOMA_SHELL_ROUTES`(JSON 数组)带进来。
|
|
4
|
-
// 登记走 core 的 `registerShellRoutes` 登记口:core 把它与装配的 `reservedRoutes` 合并,首段并入保留首段,动态地址不得占用。
|
|
5
|
-
// 宿主壳不再改装配对象(装配可以是冻结的),也不再有「登记失败」这一返回值;登记幂等。
|
|
6
|
-
import { assertReservedRoutesShape, loadHostAssembly, registerShellRoutes as registerCoreShellRoutes } from 'soma-core/server/host-assembly';
|
|
7
|
-
|
|
8
|
-
export const SOMA_SHELL_ROUTES_ENV = 'SOMA_SHELL_ROUTES';
|
|
9
|
-
|
|
10
|
-
export function readShellRoutesFromEnv(env: Readonly<Record<string, string | undefined>> = process.env): readonly string[] {
|
|
11
|
-
const raw = env[SOMA_SHELL_ROUTES_ENV];
|
|
12
|
-
if (!raw) return [];
|
|
13
|
-
try {
|
|
14
|
-
const parsed: unknown = JSON.parse(raw);
|
|
15
|
-
assertReservedRoutesShape(parsed);
|
|
16
|
-
return Array.isArray(parsed) ? (parsed as string[]) : [];
|
|
17
|
-
} catch {
|
|
18
|
-
return [];
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** 登记壳路由(转调 core 登记口);环境里没有时什么也不做。返回登记后 core 已知的壳路由 */
|
|
23
|
-
export function registerShellRoutes(shellRoutes: readonly string[] = readShellRoutesFromEnv()): readonly string[] {
|
|
24
|
-
return shellRoutes.length === 0 ? [] : registerCoreShellRoutes(shellRoutes);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export async function prepareHostAssembly(hostDir: string | undefined) {
|
|
28
|
-
if (!hostDir) return null;
|
|
29
|
-
const assembly = await loadHostAssembly(hostDir);
|
|
30
|
-
// 无 soma.app.ts 时也登记:壳路由与装配无关,保留首段对动态注入同样生效
|
|
31
|
-
registerShellRoutes();
|
|
32
|
-
return assembly;
|
|
33
|
-
}
|
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
// /soma/page 的 HTTP 层:成功响应的缓存头、错误到状态码与受控字段的映射。
|
|
2
|
-
// 私有目录(`_shared`)不是路由;壳路由枚举(src/shell-routes.cjs)也跳过它。
|
|
3
|
-
// 判定只看 `loadPageByAddress` 的返回与错误形状(code / status / textKey),不认产生方,不读角色值。
|
|
4
|
-
import { createHash } from 'node:crypto';
|
|
5
|
-
import { resolveHostLoginPath, SOMA_DEFAULT_LOGIN_PATH } from 'soma-core/server/host-assembly';
|
|
6
|
-
import { isStatusError } from '../../../core/server/runtime-space/errors';
|
|
7
|
-
import { SomaPublishedPageError } from '../../../core/server/host/published-page-assets';
|
|
8
|
-
|
|
9
|
-
export { SOMA_DEFAULT_LOGIN_PATH };
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* 登录页路径(R-24):装配 `login.path`,缺省 `/login`。判定与形状校验归 core
|
|
13
|
-
* (`resolveHostLoginPath`),本壳不再自写。装配取自已加载的 Host 装配(`prepareHostAssembly` 的返回值),未加载时回缺省。
|
|
14
|
-
*/
|
|
15
|
-
export function resolveLoginPath(
|
|
16
|
-
assembly?: { readonly login?: { readonly path?: string } } | null,
|
|
17
|
-
): string {
|
|
18
|
-
return resolveHostLoginPath(assembly);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export interface CacheableLoadedPage {
|
|
22
|
-
/** 绑定声明 cache: store 才为 true */
|
|
23
|
-
readonly cacheable: boolean;
|
|
24
|
-
readonly purpose?: 'access' | 'preview';
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
const VARY = 'Cookie, Authorization';
|
|
28
|
-
|
|
29
|
-
function weakEtag(body: string): string {
|
|
30
|
-
return `W/"${createHash('sha1').update(body).digest('hex').slice(0, 20)}"`;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function etagMatches(header: string | null, etag: string): boolean {
|
|
34
|
-
if (header === null) return false;
|
|
35
|
-
return header.split(',').some((candidate) => {
|
|
36
|
-
const value = candidate.trim();
|
|
37
|
-
return value === '*' || value === etag || value.replace(/^W\//, '') === etag.replace(/^W\//, '');
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* 成功响应。绑定 cache 为 store 且用途是访问:`private, no-cache` + 弱 ETag(可条件请求,但绝不让共享缓存存:
|
|
43
|
-
* 响应里的导航目录与参数随身份变化);no-store 绑定与预览用途:`no-store`。
|
|
44
|
-
*/
|
|
45
|
-
export function pageSuccessResponse(page: CacheableLoadedPage, body: unknown, request?: { headers: { get(name: string): string | null } }): Response {
|
|
46
|
-
const text = JSON.stringify(body);
|
|
47
|
-
const jsonType = 'application/json; charset=utf-8';
|
|
48
|
-
if (!page.cacheable || page.purpose === 'preview') {
|
|
49
|
-
return new Response(text, { status: 200, headers: { 'content-type': jsonType, 'cache-control': 'no-store' } });
|
|
50
|
-
}
|
|
51
|
-
const etag = weakEtag(text);
|
|
52
|
-
const headers = { 'cache-control': 'private, no-cache', etag, vary: VARY };
|
|
53
|
-
if (etagMatches(request?.headers.get('if-none-match') ?? null, etag)) {
|
|
54
|
-
return new Response(null, { status: 304, headers });
|
|
55
|
-
}
|
|
56
|
-
return new Response(text, { status: 200, headers: { 'content-type': jsonType, ...headers } });
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* 错误响应。整页错误(主题整体解析失败等)500 + 诊断码;带 code / status 的地址与页面错误原状态码:
|
|
61
|
-
* 404 未命中 / 参数不合、409 同址冲突、401 未登录(附 `login.path`,交页面客户端跳转)、403 无权(附 `textKey`,客户端渲染受控无权页)。
|
|
62
|
-
* 响应里没有角色信息、内部路径与声明细节。
|
|
63
|
-
*/
|
|
64
|
-
export function pageErrorResponse(
|
|
65
|
-
error: unknown,
|
|
66
|
-
assembly?: { readonly login?: { readonly path?: string } } | null,
|
|
67
|
-
): Response {
|
|
68
|
-
const headers = { 'cache-control': 'no-store' };
|
|
69
|
-
if (error instanceof SomaPublishedPageError) {
|
|
70
|
-
return Response.json({ error: error.message, code: error.code }, { status: 500, headers });
|
|
71
|
-
}
|
|
72
|
-
if (isStatusError(error)) {
|
|
73
|
-
const textKey = (error as { textKey?: unknown }).textKey;
|
|
74
|
-
return Response.json(
|
|
75
|
-
{
|
|
76
|
-
error: error.message,
|
|
77
|
-
code: error.code,
|
|
78
|
-
...(typeof textKey === 'string' ? { textKey } : {}),
|
|
79
|
-
...(error.status === 401 ? { login: { path: resolveLoginPath(assembly) } } : {}),
|
|
80
|
-
},
|
|
81
|
-
{ status: error.status, headers },
|
|
82
|
-
);
|
|
83
|
-
}
|
|
84
|
-
const detail = error instanceof Error ? error.message : String(error);
|
|
85
|
-
return Response.json({ error: detail || 'Internal server error', code: 'SOMA_PAGE_ASSET_UNKNOWN' }, { status: 500, headers });
|
|
86
|
-
}
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { NextRequest } from 'next/server';
|
|
2
|
-
import { loadPageByAddress } from '../../../core/server/runtime-space';
|
|
3
|
-
import { pageErrorResponse, pageSuccessResponse } from '../_shared/page-http';
|
|
4
|
-
import { prepareHostAssembly } from '../_shared/host-prepare';
|
|
5
|
-
import { withHostResponseHeaders } from '../../../core/server/host/host-response-headers';
|
|
6
|
-
|
|
7
|
-
export const runtime = 'nodejs';
|
|
8
|
-
export const dynamic = 'force-dynamic';
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* SOMA internal page asset endpoint. Host request hooks must never run here.
|
|
12
|
-
* 只调 `loadPageByAddress`(runtime 空间的唯一取页入口):未命中 404,同址冲突 409,参数类型不合 404,
|
|
13
|
-
* 访问门 401(附登录路径,页面客户端跳转)/ 403(附词条键 `soma.page.forbidden`)。
|
|
14
|
-
* 响应在原运行时资产之上带 binding / params / query / nav / purpose;缓存头按绑定的 `cache` 设(见 `_shared/page-http.ts`)。
|
|
15
|
-
*/
|
|
16
|
-
export async function GET(request: NextRequest): Promise<Response> {
|
|
17
|
-
return withHostResponseHeaders(await loadPageResponse(request), {
|
|
18
|
-
method: request.method,
|
|
19
|
-
pathname: request.nextUrl.pathname,
|
|
20
|
-
});
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
async function loadPageResponse(request: NextRequest): Promise<Response> {
|
|
24
|
-
const pagePath = request.nextUrl.searchParams.get('path') || '/';
|
|
25
|
-
let assembly: Awaited<ReturnType<typeof prepareHostAssembly>> = null;
|
|
26
|
-
try {
|
|
27
|
-
// Host 请求钩子不在这里跑,但编译点同样依赖 soma.app.ts 的服务端面已装配完:先等它(装配失败即拒绝启动,原样 500)
|
|
28
|
-
assembly = await prepareHostAssembly(process.env.SOMA_HOST_DIR);
|
|
29
|
-
const page = await loadPageByAddress(pagePath, request, {
|
|
30
|
-
hostDir: process.env.SOMA_HOST_DIR,
|
|
31
|
-
});
|
|
32
|
-
return pageSuccessResponse(page, page, request);
|
|
33
|
-
} catch (error) {
|
|
34
|
-
return pageErrorResponse(error, assembly);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
function somaRouteNotFound(): Response {
|
|
2
|
-
return Response.json({ error: 'SOMA internal endpoint not found' }, { status: 404 });
|
|
3
|
-
}
|
|
4
|
-
|
|
5
|
-
export const GET = somaRouteNotFound;
|
|
6
|
-
export const POST = somaRouteNotFound;
|
|
7
|
-
export const PUT = somaRouteNotFound;
|
|
8
|
-
export const PATCH = somaRouteNotFound;
|
|
9
|
-
export const DELETE = somaRouteNotFound;
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { staticResponse } from '../_shared/static-file';
|
|
2
|
-
|
|
3
|
-
export const runtime = 'nodejs';
|
|
4
|
-
export const dynamic = 'force-dynamic';
|
|
5
|
-
|
|
6
|
-
/** GET|HEAD /soma-runtime/<文件> - 读 `<runtime 根>/static/` 下的静态文件(浏览器运行包等);其余方法 405 */
|
|
7
|
-
export async function GET(request: Request, context: { params: Promise<{ file: string[] }> }): Promise<Response> {
|
|
8
|
-
const { file } = await context.params;
|
|
9
|
-
return staticResponse(file ?? [], request);
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export const HEAD = GET;
|
|
13
|
-
|
|
14
|
-
function methodNotAllowed(): Response {
|
|
15
|
-
return new Response('Method not allowed', { status: 405, headers: { allow: 'GET, HEAD', 'cache-control': 'no-store' } });
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export const POST = methodNotAllowed;
|
|
19
|
-
export const PUT = methodNotAllowed;
|
|
20
|
-
export const PATCH = methodNotAllowed;
|
|
21
|
-
export const DELETE = methodNotAllowed;
|