soma-core 1.0.3 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/SomaPageClient.tsx +8 -45
- package/app/[...path]/page.tsx +21 -0
- package/app/api/[...path]/route.ts +86 -77
- package/app/components/SomaHostPage.tsx +133 -0
- package/app/components/SomaHydrationShell.tsx +1 -1
- package/app/layout.tsx +10 -6
- package/app/page.tsx +7 -18
- package/app/soma/[...path]/route.ts +9 -0
- package/app/{api/soma-manifest → soma/manifest}/route.ts +3 -3
- package/app/soma/page/route.ts +29 -0
- package/app/soma/page-object/route.ts +158 -0
- package/app/soma/route.ts +9 -0
- package/bin/soma-mock.mjs +38 -0
- package/core/base/SomaHttpClient.ts +5 -3
- package/core/compiler/full-manifest-builder.ts +84 -69
- package/core/compiler/host-config-sync.cjs +32 -6
- package/core/compiler/soma-manifest-webpack-plugin.js +41 -7
- package/core/engine/soma-headless-page.ts +86 -0
- package/core/host/app-config-composer.ts +90 -0
- package/core/host/host-config-paths.cjs +100 -0
- package/core/host/host-config-paths.ts +132 -0
- package/core/host/invoke-host-request-hook.ts +37 -0
- package/core/host/load-host-domain-class.ts +87 -0
- package/core/host/page-response-mode.cjs +96 -0
- package/core/host/page-response-request.ts +35 -0
- package/core/host/request-origin.ts +18 -0
- package/core/host/resolve-host-request-hook.ts +29 -0
- package/core/host/server-page-assets.ts +193 -0
- package/core/host/soma-domain-loaders.stub.ts +6 -0
- package/core/host/soma-domain-loaders.ts +69 -0
- package/core/host/soma-request-hook-host.stub.ts +4 -0
- package/core/host/source-packages.ts +46 -5
- package/core/index.ts +22 -0
- package/core/infra/http/SomaHttpService.ts +23 -14
- package/core/infra/http/soma-server-request-context.ts +126 -0
- package/core/mock/node/catch-all.mjs +35 -0
- package/core/mock/node/cli.d.mts +58 -0
- package/core/mock/node/cli.mjs +243 -0
- package/core/mock/node/context.mjs +167 -0
- package/core/mock/node/environment-policy.mjs +52 -0
- package/core/mock/node/plugin-loader.mjs +212 -0
- package/core/mock/node/preload.mjs +91 -0
- package/core/mock/node/process-lifecycle.mjs +236 -0
- package/core/mock/node/public.d.mts +110 -0
- package/core/mock/node/public.mjs +4 -0
- package/core/mock/node/registry.mjs +336 -0
- package/core/mock/node/schema-generator.mjs +1310 -0
- package/core/mock/testing/host-harness.d.mts +66 -0
- package/core/mock/testing/host-harness.mjs +276 -0
- package/core/mock/testing/host-runtime.mjs +48 -0
- package/core/runtime/SomaRuntimeServices.ts +5 -1
- package/core/runtime/serialize-page-state.ts +152 -0
- package/dist/cli/soma.js +374 -3
- package/dist/core/index.cjs +2861 -2388
- package/dist/tsconfig.types.tsbuildinfo +1 -1
- package/dist/types/base/SomaHttpClient.d.ts +2 -0
- package/dist/types/compiler/full-manifest-builder.d.ts +2 -0
- package/dist/types/engine/soma-headless-page.d.ts +10 -0
- package/dist/types/host/app-config-composer.d.ts +6 -0
- package/dist/types/host/host-config-paths.d.ts +23 -0
- package/dist/types/host/invoke-host-request-hook.d.ts +8 -0
- package/dist/types/host/load-host-domain-class.d.ts +12 -0
- package/dist/types/host/page-response-request.d.ts +9 -0
- package/dist/types/host/request-origin.d.ts +1 -0
- package/dist/types/host/resolve-host-request-hook.d.ts +16 -0
- package/dist/types/host/server-page-assets.d.ts +29 -0
- package/dist/types/host/soma-domain-loaders.d.ts +19 -0
- package/dist/types/host/soma-domain-loaders.stub.d.ts +4 -0
- package/dist/types/host/soma-request-hook-host.stub.d.ts +2 -0
- package/dist/types/host/source-packages.d.ts +4 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/infra/http/SomaHttpService.d.ts +2 -0
- package/dist/types/infra/http/soma-server-request-context.d.ts +5 -0
- package/dist/types/runtime/serialize-page-state.d.ts +10 -0
- package/docs//351/241/265/351/235/242JSON/346/250/241/345/274/217/346/216/245/345/205/245/346/214/207/345/215/227.md +141 -0
- package/global.d.ts +67 -26
- package/middleware.ts +33 -0
- package/next.config.js +109 -23
- package/package.json +39 -9
- package/tsconfig.json +1 -5
- package/app/api/page/route.ts +0 -119
- package/app/loading.tsx +0 -5
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
3
|
+
import { isSafePageBase, urlPathToCandidates } from '../compiler/page-base-resolver';
|
|
4
|
+
import { ServerFileCache } from '../infra/cache/ServerFileCache';
|
|
5
|
+
import { composeAppConfigYaml } from './app-config-composer';
|
|
6
|
+
import {
|
|
7
|
+
resolveAppConfigPath,
|
|
8
|
+
resolveHostAppConfigPath,
|
|
9
|
+
} from './host-config-paths';
|
|
10
|
+
import {
|
|
11
|
+
getSomaAssetSources,
|
|
12
|
+
type SomaAssetSource,
|
|
13
|
+
} from './source-packages';
|
|
14
|
+
|
|
15
|
+
export type SomaPageAssetLoadProfile = 'render' | 'headless';
|
|
16
|
+
|
|
17
|
+
export interface SomaServerPageAssets {
|
|
18
|
+
base: string;
|
|
19
|
+
sourceType: SomaAssetSource['type'];
|
|
20
|
+
sourcePackage: string | null;
|
|
21
|
+
html?: string;
|
|
22
|
+
ui: string;
|
|
23
|
+
event: string;
|
|
24
|
+
styleYaml: string;
|
|
25
|
+
localeYaml: string;
|
|
26
|
+
appConfigYaml: string;
|
|
27
|
+
includes?: Record<string, string>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class SomaPageAssetError extends Error {
|
|
31
|
+
readonly code: string;
|
|
32
|
+
readonly status: number;
|
|
33
|
+
|
|
34
|
+
constructor(code: string, status: number, message: string) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.name = 'SomaPageAssetError';
|
|
37
|
+
this.code = code;
|
|
38
|
+
this.status = status;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const cache = ServerFileCache.getInstance();
|
|
43
|
+
const watchedRoots = new Set<string>();
|
|
44
|
+
|
|
45
|
+
function ensureWatch(root: string): void {
|
|
46
|
+
if (watchedRoots.has(root)) return;
|
|
47
|
+
watchedRoots.add(root);
|
|
48
|
+
cache.watchAndInvalidate(root);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function resolveSomaPageSource(
|
|
52
|
+
sources: SomaAssetSource[],
|
|
53
|
+
urlPath: string,
|
|
54
|
+
): { source: SomaAssetSource; base: string } | null {
|
|
55
|
+
for (const candidate of urlPathToCandidates(urlPath)) {
|
|
56
|
+
if (!isSafePageBase(candidate)) continue;
|
|
57
|
+
for (const source of sources) {
|
|
58
|
+
const htmlPath = join(source.assetRoot, 'html', candidate + '.html');
|
|
59
|
+
if (existsSync(htmlPath)) {
|
|
60
|
+
return { source, base: candidate };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function collectIncludes(sources: SomaAssetSource[]): Record<string, string> {
|
|
68
|
+
const includes: Record<string, string> = {};
|
|
69
|
+
const ordered = [
|
|
70
|
+
...sources.filter((source) => source.type === 'package'),
|
|
71
|
+
...sources.filter((source) => source.type === 'host'),
|
|
72
|
+
];
|
|
73
|
+
for (const source of ordered) {
|
|
74
|
+
const sharedDir = join(source.assetRoot, 'html', 'shared');
|
|
75
|
+
try {
|
|
76
|
+
const files = cache.readDirFiles(sharedDir, '.html');
|
|
77
|
+
const names = cache.readDirNames(sharedDir, '.html');
|
|
78
|
+
for (let index = 0; index < names.length; index += 1) {
|
|
79
|
+
includes['shared/' + names[index]] = files[index];
|
|
80
|
+
}
|
|
81
|
+
} catch {
|
|
82
|
+
// A source package does not need a shared directory.
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return includes;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function assertContainedHtmlPath(source: SomaAssetSource, base: string): string {
|
|
89
|
+
const htmlRoot = resolve(source.assetRoot, 'html');
|
|
90
|
+
const htmlPath = resolve(htmlRoot, base + '.html');
|
|
91
|
+
const childPath = relative(htmlRoot, htmlPath);
|
|
92
|
+
if (!childPath || childPath.startsWith('..') || isAbsolute(childPath)) {
|
|
93
|
+
throw new SomaPageAssetError(
|
|
94
|
+
'SOMA_PAGE_PATH_INVALID',
|
|
95
|
+
400,
|
|
96
|
+
'Invalid page path',
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
return htmlPath;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function loadSomaServerPageAssets(options: {
|
|
103
|
+
hostDir: string | undefined;
|
|
104
|
+
urlPath: string;
|
|
105
|
+
profile?: SomaPageAssetLoadProfile;
|
|
106
|
+
watch?: boolean;
|
|
107
|
+
}): SomaServerPageAssets {
|
|
108
|
+
const { hostDir, urlPath } = options;
|
|
109
|
+
if (!hostDir) {
|
|
110
|
+
throw new SomaPageAssetError(
|
|
111
|
+
'SOMA_HOST_DIR_MISSING',
|
|
112
|
+
503,
|
|
113
|
+
'SOMA_HOST_DIR is not set. Run: npx soma dev from your app root.',
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const profile = options.profile ?? 'render';
|
|
118
|
+
const sources = getSomaAssetSources(hostDir);
|
|
119
|
+
const hostSource = sources.find((source) => source.type === 'host');
|
|
120
|
+
const hostConfigRoot = hostSource?.configRoot ?? hostDir;
|
|
121
|
+
if (options.watch !== false) {
|
|
122
|
+
for (const source of sources) {
|
|
123
|
+
ensureWatch(source.assetRoot);
|
|
124
|
+
if (source.codeRoot !== source.assetRoot) {
|
|
125
|
+
ensureWatch(source.codeRoot);
|
|
126
|
+
}
|
|
127
|
+
if (existsSync(source.configRoot)) {
|
|
128
|
+
ensureWatch(source.configRoot);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const resolvedPage = resolveSomaPageSource(sources, urlPath);
|
|
134
|
+
if (!resolvedPage) {
|
|
135
|
+
throw new SomaPageAssetError(
|
|
136
|
+
'SOMA_PAGE_NOT_FOUND',
|
|
137
|
+
404,
|
|
138
|
+
'Page not found: ' + urlPath,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const { source, base } = resolvedPage;
|
|
143
|
+
const htmlPath = assertContainedHtmlPath(source, base);
|
|
144
|
+
try {
|
|
145
|
+
const ui = cache.tryReadFile(join(source.assetRoot, 'ui', base + '_ui.yaml'));
|
|
146
|
+
const localeYaml = cache.tryReadFile(join(hostConfigRoot, 'locale.yaml'));
|
|
147
|
+
const hostAppConfigPath = resolveHostAppConfigPath(hostDir);
|
|
148
|
+
const hostAppConfigYaml = hostAppConfigPath
|
|
149
|
+
? cache.tryReadFile(hostAppConfigPath)
|
|
150
|
+
: '';
|
|
151
|
+
const sourceAppConfigPath = resolveAppConfigPath(source.configRoot);
|
|
152
|
+
const sourceAppConfigYaml = sourceAppConfigPath
|
|
153
|
+
? cache.tryReadFile(sourceAppConfigPath)
|
|
154
|
+
: '';
|
|
155
|
+
const appConfigYaml = source.type === 'host'
|
|
156
|
+
? hostAppConfigYaml
|
|
157
|
+
: composeAppConfigYaml(sourceAppConfigYaml, hostAppConfigYaml);
|
|
158
|
+
|
|
159
|
+
if (profile === 'headless') {
|
|
160
|
+
return {
|
|
161
|
+
base,
|
|
162
|
+
sourceType: source.type,
|
|
163
|
+
sourcePackage: source.packageName ?? null,
|
|
164
|
+
ui,
|
|
165
|
+
event: '',
|
|
166
|
+
styleYaml: '',
|
|
167
|
+
localeYaml,
|
|
168
|
+
appConfigYaml,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
base,
|
|
174
|
+
sourceType: source.type,
|
|
175
|
+
sourcePackage: source.packageName ?? null,
|
|
176
|
+
html: cache.readFile(htmlPath),
|
|
177
|
+
ui,
|
|
178
|
+
event: cache.tryReadFile(join(source.assetRoot, 'event', base + '_event.yaml')),
|
|
179
|
+
styleYaml: cache.tryReadFile(join(source.assetRoot, 'ui', base + '_style.yaml')),
|
|
180
|
+
localeYaml,
|
|
181
|
+
appConfigYaml,
|
|
182
|
+
includes: collectIncludes(sources),
|
|
183
|
+
};
|
|
184
|
+
} catch (error) {
|
|
185
|
+
if (error instanceof SomaPageAssetError) throw error;
|
|
186
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
187
|
+
throw new SomaPageAssetError(
|
|
188
|
+
'SOMA_PAGE_ASSET_READ_FAILED',
|
|
189
|
+
500,
|
|
190
|
+
'Asset read error: ' + detail,
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
export type SomaDomainModule = { default?: unknown; [key: string]: unknown };
|
|
2
|
+
|
|
3
|
+
export interface SomaDomainLoadContext {
|
|
4
|
+
base: string;
|
|
5
|
+
sourcePackage?: string | null;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export type SomaDomainLoader = (
|
|
9
|
+
ctx: SomaDomainLoadContext,
|
|
10
|
+
) => SomaDomainModule | Promise<SomaDomainModule>;
|
|
11
|
+
|
|
12
|
+
export type SomaDomainLoaderMap = Record<string, SomaDomainLoader>;
|
|
13
|
+
|
|
14
|
+
export type SomaDomainModuleResolver = (
|
|
15
|
+
ctx: SomaDomainLoadContext,
|
|
16
|
+
) => SomaDomainModule | null | undefined | Promise<SomaDomainModule | null | undefined>;
|
|
17
|
+
|
|
18
|
+
export interface SomaDomainLoaderModule {
|
|
19
|
+
loadSomaDomainModule?: SomaDomainModuleResolver;
|
|
20
|
+
somaDomainLoaders?: SomaDomainLoaderMap;
|
|
21
|
+
default?: SomaDomainLoaderMap | SomaDomainModuleResolver;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function createSomaDomainLoaderKey(sourcePackage: string | null | undefined, base: string): string {
|
|
25
|
+
return sourcePackage ? `${sourcePackage}:${base}` : `host:${base}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function findSomaDomainLoader(
|
|
29
|
+
loaders: SomaDomainLoaderMap | null | undefined,
|
|
30
|
+
ctx: SomaDomainLoadContext,
|
|
31
|
+
): SomaDomainLoader | null {
|
|
32
|
+
if (!loaders) return null;
|
|
33
|
+
|
|
34
|
+
const keys = ctx.sourcePackage
|
|
35
|
+
? [
|
|
36
|
+
createSomaDomainLoaderKey(ctx.sourcePackage, ctx.base),
|
|
37
|
+
`${ctx.sourcePackage}/${ctx.base}`,
|
|
38
|
+
]
|
|
39
|
+
: [
|
|
40
|
+
createSomaDomainLoaderKey(null, ctx.base),
|
|
41
|
+
ctx.base,
|
|
42
|
+
];
|
|
43
|
+
|
|
44
|
+
for (const key of keys) {
|
|
45
|
+
const loader = loaders[key];
|
|
46
|
+
if (loader) return loader;
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function loadSomaDomainModuleFromRegistry(
|
|
52
|
+
registry: SomaDomainLoaderModule | null | undefined,
|
|
53
|
+
ctx: SomaDomainLoadContext,
|
|
54
|
+
): Promise<SomaDomainModule | null> {
|
|
55
|
+
if (!registry) return null;
|
|
56
|
+
|
|
57
|
+
if (typeof registry.loadSomaDomainModule === 'function') {
|
|
58
|
+
return await registry.loadSomaDomainModule(ctx) ?? null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (typeof registry.default === 'function') {
|
|
62
|
+
return await registry.default(ctx) ?? null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const defaultLoaders = typeof registry.default === 'object' ? registry.default : null;
|
|
66
|
+
const loader = findSomaDomainLoader(registry.somaDomainLoaders, ctx)
|
|
67
|
+
?? findSomaDomainLoader(defaultLoaders, ctx);
|
|
68
|
+
return loader ? await loader(ctx) : null;
|
|
69
|
+
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
+
import { getSomaHostConfigRoot } from './host-config-paths';
|
|
3
4
|
|
|
4
5
|
export interface SomaAssetSource {
|
|
5
6
|
type: 'host' | 'package';
|
|
6
7
|
name: string;
|
|
7
8
|
assetRoot: string;
|
|
8
9
|
codeRoot: string;
|
|
10
|
+
configRoot: string;
|
|
9
11
|
packageName?: string;
|
|
10
12
|
}
|
|
11
13
|
|
|
@@ -14,9 +16,21 @@ interface PackageJson {
|
|
|
14
16
|
devDependencies?: Record<string, string>;
|
|
15
17
|
soma?: {
|
|
16
18
|
source?: boolean;
|
|
19
|
+
hostRoot?: string;
|
|
20
|
+
configRoot?: string;
|
|
17
21
|
};
|
|
18
22
|
}
|
|
19
23
|
|
|
24
|
+
export {
|
|
25
|
+
getSomaHostConfigRoot,
|
|
26
|
+
normalizeSomaEnv,
|
|
27
|
+
readSomaEnv,
|
|
28
|
+
resolveAppConfigPath,
|
|
29
|
+
resolveHostAppConfigPath,
|
|
30
|
+
resolveHostConfigRoot,
|
|
31
|
+
} from './host-config-paths';
|
|
32
|
+
export type { SomaEnvName } from './host-config-paths';
|
|
33
|
+
|
|
20
34
|
function readJson<T>(filePath: string): T | null {
|
|
21
35
|
try {
|
|
22
36
|
if (!fs.existsSync(filePath)) {
|
|
@@ -63,6 +77,27 @@ function readHostDependencies(hostDir: string): Record<string, string> {
|
|
|
63
77
|
};
|
|
64
78
|
}
|
|
65
79
|
|
|
80
|
+
function resolveSafeChildRoot(parent: string, relativePath: string | undefined): string {
|
|
81
|
+
const trimmed = relativePath?.trim();
|
|
82
|
+
if (!trimmed) {
|
|
83
|
+
return parent;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const resolved = path.resolve(parent, trimmed);
|
|
87
|
+
const normalizedParent = path.resolve(parent);
|
|
88
|
+
if (resolved === normalizedParent || resolved.startsWith(`${normalizedParent}${path.sep}`)) {
|
|
89
|
+
return fs.existsSync(resolved) ? resolved : normalizedParent;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return normalizedParent;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function getSomaHostSourceRoot(hostDir: string): string {
|
|
96
|
+
const normalizedHostDir = path.resolve(hostDir);
|
|
97
|
+
const packageJson = readJson<PackageJson>(path.join(normalizedHostDir, 'package.json'));
|
|
98
|
+
return resolveSafeChildRoot(normalizedHostDir, packageJson?.soma?.hostRoot);
|
|
99
|
+
}
|
|
100
|
+
|
|
66
101
|
function isSomaSourcePackage(packageRoot: string, explicit: boolean): boolean {
|
|
67
102
|
if (explicit) {
|
|
68
103
|
return true;
|
|
@@ -72,18 +107,23 @@ function isSomaSourcePackage(packageRoot: string, explicit: boolean): boolean {
|
|
|
72
107
|
}
|
|
73
108
|
|
|
74
109
|
function toPackageSource(packageName: string, packageRoot: string): SomaAssetSource {
|
|
75
|
-
const
|
|
110
|
+
const packageJson = readJson<PackageJson>(path.join(packageRoot, 'package.json'));
|
|
111
|
+
const codeRoot = resolveSafeChildRoot(packageRoot, packageJson?.soma?.hostRoot);
|
|
112
|
+
const configRoot = resolveSafeChildRoot(packageRoot, packageJson?.soma?.configRoot);
|
|
113
|
+
const shellRoot = path.join(codeRoot, 'shell');
|
|
76
114
|
return {
|
|
77
115
|
type: 'package',
|
|
78
116
|
name: packageName,
|
|
79
117
|
packageName,
|
|
80
|
-
assetRoot: fs.existsSync(path.join(shellRoot, 'html')) ? shellRoot :
|
|
81
|
-
codeRoot
|
|
118
|
+
assetRoot: fs.existsSync(path.join(shellRoot, 'html')) ? shellRoot : codeRoot,
|
|
119
|
+
codeRoot,
|
|
120
|
+
configRoot,
|
|
82
121
|
};
|
|
83
122
|
}
|
|
84
123
|
|
|
85
124
|
export function getSomaAssetSources(hostDir: string): SomaAssetSource[] {
|
|
86
125
|
const normalizedHostDir = path.resolve(hostDir);
|
|
126
|
+
const hostSourceRoot = getSomaHostSourceRoot(normalizedHostDir);
|
|
87
127
|
const dependencies = readHostDependencies(normalizedHostDir);
|
|
88
128
|
const explicitPackages = new Set(readExplicitSourcePackages());
|
|
89
129
|
const packageNames = new Set([
|
|
@@ -95,8 +135,9 @@ export function getSomaAssetSources(hostDir: string): SomaAssetSource[] {
|
|
|
95
135
|
{
|
|
96
136
|
type: 'host',
|
|
97
137
|
name: 'host',
|
|
98
|
-
assetRoot:
|
|
99
|
-
codeRoot:
|
|
138
|
+
assetRoot: hostSourceRoot,
|
|
139
|
+
codeRoot: hostSourceRoot,
|
|
140
|
+
configRoot: getSomaHostConfigRoot(normalizedHostDir),
|
|
100
141
|
},
|
|
101
142
|
];
|
|
102
143
|
|
package/core/index.ts
CHANGED
|
@@ -38,3 +38,25 @@ export { createPermissionMiddleware } from './middleware/createPermissionMiddlew
|
|
|
38
38
|
export type { SomaEventMiddlewareContext } from './engine/event-engine';
|
|
39
39
|
export type { SomaBootstrapConfigurator } from './host/resolve-host-bootstrap';
|
|
40
40
|
export { resolveHostBootstrapOptions } from './host/resolve-host-bootstrap';
|
|
41
|
+
export type {
|
|
42
|
+
SomaHostRequestContext,
|
|
43
|
+
SomaHostRequestKind,
|
|
44
|
+
SomaRequestHook,
|
|
45
|
+
} from './host/resolve-host-request-hook';
|
|
46
|
+
// The resolver is server-entry-only. Keep its types in the public root API,
|
|
47
|
+
// but do not re-export the runtime from the browser-facing root module: the
|
|
48
|
+
// resolver dynamically loads the Host request hook and may include Node-only
|
|
49
|
+
// dependencies from that hook in a Next client bundle.
|
|
50
|
+
export type {
|
|
51
|
+
SomaDomainLoadContext,
|
|
52
|
+
SomaDomainLoader,
|
|
53
|
+
SomaDomainLoaderMap,
|
|
54
|
+
SomaDomainLoaderModule,
|
|
55
|
+
SomaDomainModule,
|
|
56
|
+
SomaDomainModuleResolver,
|
|
57
|
+
} from './host/soma-domain-loaders';
|
|
58
|
+
export {
|
|
59
|
+
createSomaDomainLoaderKey,
|
|
60
|
+
findSomaDomainLoader,
|
|
61
|
+
loadSomaDomainModuleFromRegistry,
|
|
62
|
+
} from './host/soma-domain-loaders';
|
|
@@ -8,16 +8,18 @@ import { IHttpClient, HttpRequestConfig, UploadOptions } from './IHttpClient';
|
|
|
8
8
|
* - per-request headers, query params, timeout, and external AbortSignal
|
|
9
9
|
* - file upload via fetch with Blob body
|
|
10
10
|
*/
|
|
11
|
-
export class SomaHttpService implements IHttpClient {
|
|
12
|
-
private client: SomaHttpClient;
|
|
13
|
-
private baseURL: string;
|
|
11
|
+
export class SomaHttpService implements IHttpClient {
|
|
12
|
+
private client: SomaHttpClient;
|
|
13
|
+
private baseURL: string;
|
|
14
|
+
private defaultHeaders: Record<string, string> | (() => Record<string, string>);
|
|
14
15
|
private abortControllers: Set<AbortController> = new Set();
|
|
15
16
|
private onHttpError: ((status: number, message: string) => void) | null = null;
|
|
16
17
|
|
|
17
|
-
constructor(config: SomaHttpClientConfig) {
|
|
18
|
-
this.baseURL = config.baseURL;
|
|
19
|
-
this.
|
|
20
|
-
|
|
18
|
+
constructor(config: SomaHttpClientConfig) {
|
|
19
|
+
this.baseURL = config.baseURL;
|
|
20
|
+
this.defaultHeaders = config.defaultHeaders ?? {};
|
|
21
|
+
this.client = new SomaHttpClient(config);
|
|
22
|
+
}
|
|
21
23
|
|
|
22
24
|
/** 注册 HTTP 错误回调(401/403/422 等统一处理) */
|
|
23
25
|
setErrorHandler(handler: (status: number, message: string) => void): void {
|
|
@@ -70,7 +72,7 @@ export class SomaHttpService implements IHttpClient {
|
|
|
70
72
|
this.abortControllers.add(controller);
|
|
71
73
|
|
|
72
74
|
try {
|
|
73
|
-
const res = await fetch(fullUrl, { method: 'POST', body: form, signal: controller.signal });
|
|
75
|
+
const res = await fetch(fullUrl, { method: 'POST', body: form, signal: controller.signal });
|
|
74
76
|
if (!res.ok) {
|
|
75
77
|
this.onHttpError?.(res.status, res.statusText);
|
|
76
78
|
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
|
|
@@ -165,10 +167,11 @@ export class SomaHttpService implements IHttpClient {
|
|
|
165
167
|
fullUrl += (fullUrl.includes('?') ? '&' : '?') + qs;
|
|
166
168
|
}
|
|
167
169
|
|
|
168
|
-
const headers: Record<string, string> = {
|
|
169
|
-
'Content-Type': 'application/json',
|
|
170
|
-
...
|
|
171
|
-
|
|
170
|
+
const headers: Record<string, string> = {
|
|
171
|
+
'Content-Type': 'application/json',
|
|
172
|
+
...this.resolveDefaultHeaders(),
|
|
173
|
+
...config?.headers,
|
|
174
|
+
};
|
|
172
175
|
|
|
173
176
|
const options: RequestInit = {
|
|
174
177
|
method,
|
|
@@ -195,5 +198,11 @@ export class SomaHttpService implements IHttpClient {
|
|
|
195
198
|
clearTimeout(timeoutId);
|
|
196
199
|
this.abortControllers.delete(controller);
|
|
197
200
|
}
|
|
198
|
-
}
|
|
199
|
-
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private resolveDefaultHeaders(): Record<string, string> {
|
|
204
|
+
return typeof this.defaultHeaders === 'function'
|
|
205
|
+
? this.defaultHeaders()
|
|
206
|
+
: { ...this.defaultHeaders };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
|
|
3
|
+
export interface SomaServerRequestContextOptions {
|
|
4
|
+
fetchImpl?: typeof fetch;
|
|
5
|
+
pageHref?: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface SomaServerRequestContext {
|
|
9
|
+
origin: string;
|
|
10
|
+
requestHeaders: Headers;
|
|
11
|
+
pageHref: string;
|
|
12
|
+
fetchImpl: typeof fetch;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface SomaServerFetchState {
|
|
16
|
+
storage: AsyncLocalStorage<SomaServerRequestContext>;
|
|
17
|
+
baseFetch: typeof fetch;
|
|
18
|
+
wrapper: typeof fetch;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const STATE_KEY = Symbol.for('soma.server.request.fetch-state');
|
|
22
|
+
const FORWARDED_HEADERS = [
|
|
23
|
+
'accept-language',
|
|
24
|
+
'authorization',
|
|
25
|
+
'baggage',
|
|
26
|
+
'traceparent',
|
|
27
|
+
'tracestate',
|
|
28
|
+
'x-request-id',
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
function getStateRecord(): Record<PropertyKey, unknown> {
|
|
32
|
+
return globalThis as unknown as Record<PropertyKey, unknown>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function mergeSameOriginHeaders(
|
|
36
|
+
context: SomaServerRequestContext,
|
|
37
|
+
input: RequestInfo | URL,
|
|
38
|
+
init: RequestInit | undefined,
|
|
39
|
+
): Headers {
|
|
40
|
+
const headers = new Headers(input instanceof Request ? input.headers : undefined);
|
|
41
|
+
new Headers(init?.headers).forEach((value, key) => headers.set(key, value));
|
|
42
|
+
|
|
43
|
+
for (const name of FORWARDED_HEADERS) {
|
|
44
|
+
const value = context.requestHeaders.get(name);
|
|
45
|
+
if (value && !headers.has(name)) {
|
|
46
|
+
headers.set(name, value);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const credentials = init?.credentials
|
|
51
|
+
?? (input instanceof Request ? input.credentials : 'same-origin');
|
|
52
|
+
const cookie = context.requestHeaders.get('cookie');
|
|
53
|
+
if (credentials !== 'omit' && cookie && !headers.has('cookie')) {
|
|
54
|
+
headers.set('cookie', cookie);
|
|
55
|
+
}
|
|
56
|
+
if (!headers.has('x-soma-page-href')) {
|
|
57
|
+
headers.set('x-soma-page-href', context.pageHref);
|
|
58
|
+
}
|
|
59
|
+
return headers;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function inputUrl(input: RequestInfo | URL, origin: string): URL {
|
|
63
|
+
if (input instanceof Request) return new URL(input.url);
|
|
64
|
+
if (input instanceof URL) return input;
|
|
65
|
+
return new URL(input, origin);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function fetchWithContext(
|
|
69
|
+
context: SomaServerRequestContext,
|
|
70
|
+
input: RequestInfo | URL,
|
|
71
|
+
init?: RequestInit,
|
|
72
|
+
): Promise<Response> {
|
|
73
|
+
const target = inputUrl(input, context.origin);
|
|
74
|
+
if (target.origin !== context.origin) {
|
|
75
|
+
return context.fetchImpl(input, init);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const headers = mergeSameOriginHeaders(context, input, init);
|
|
79
|
+
const requestInit: RequestInit = {
|
|
80
|
+
...init,
|
|
81
|
+
headers,
|
|
82
|
+
cache: init?.cache ?? 'no-store',
|
|
83
|
+
};
|
|
84
|
+
if (input instanceof Request) {
|
|
85
|
+
return context.fetchImpl(new Request(new Request(target, input), requestInit));
|
|
86
|
+
}
|
|
87
|
+
return context.fetchImpl(target, requestInit);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function getOrCreateFetchState(): SomaServerFetchState {
|
|
91
|
+
const record = getStateRecord();
|
|
92
|
+
const existing = record[STATE_KEY] as SomaServerFetchState | undefined;
|
|
93
|
+
if (existing) return existing;
|
|
94
|
+
|
|
95
|
+
if (typeof globalThis.fetch !== 'function') {
|
|
96
|
+
throw new Error('Global fetch is required for SOMA headless page requests');
|
|
97
|
+
}
|
|
98
|
+
const storage = new AsyncLocalStorage<SomaServerRequestContext>();
|
|
99
|
+
const baseFetch = globalThis.fetch.bind(globalThis);
|
|
100
|
+
const wrapper: typeof fetch = async (input, init) => {
|
|
101
|
+
const context = storage.getStore();
|
|
102
|
+
return context
|
|
103
|
+
? fetchWithContext(context, input, init)
|
|
104
|
+
: baseFetch(input, init);
|
|
105
|
+
};
|
|
106
|
+
const state = { storage, baseFetch, wrapper };
|
|
107
|
+
record[STATE_KEY] = state;
|
|
108
|
+
globalThis.fetch = wrapper;
|
|
109
|
+
return state;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function withSomaServerRequestContext<T>(
|
|
113
|
+
request: Request,
|
|
114
|
+
task: () => T,
|
|
115
|
+
options: SomaServerRequestContextOptions = {},
|
|
116
|
+
): T {
|
|
117
|
+
const state = getOrCreateFetchState();
|
|
118
|
+
const requestUrl = new URL(request.url);
|
|
119
|
+
const context: SomaServerRequestContext = {
|
|
120
|
+
origin: requestUrl.origin,
|
|
121
|
+
requestHeaders: new Headers(request.headers),
|
|
122
|
+
pageHref: options.pageHref ?? requestUrl.pathname + requestUrl.search,
|
|
123
|
+
fetchImpl: options.fetchImpl ?? state.baseFetch,
|
|
124
|
+
};
|
|
125
|
+
return state.storage.run(context, task);
|
|
126
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { http, HttpResponse } from 'msw';
|
|
2
|
+
|
|
3
|
+
function safeRequestUrl(value) {
|
|
4
|
+
const url = new URL(value);
|
|
5
|
+
url.username = '';
|
|
6
|
+
url.password = '';
|
|
7
|
+
return `${url.origin}${url.pathname}`;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Last handler in the chain: every unregistered outbound HTTP request fails
|
|
12
|
+
* closed. This guarantees that enabling the mock cannot silently reach a real
|
|
13
|
+
* service or the public Internet.
|
|
14
|
+
*/
|
|
15
|
+
export function createCatchAllHandler(context) {
|
|
16
|
+
return http.all('*', async ({ request }) => {
|
|
17
|
+
const url = safeRequestUrl(request.url);
|
|
18
|
+
const journalEntry = context.journal.record({
|
|
19
|
+
scope: 'unregistered',
|
|
20
|
+
method: request.method,
|
|
21
|
+
url,
|
|
22
|
+
status: 501,
|
|
23
|
+
code: 'ERR-MOCK-SCHEMA-MISSING',
|
|
24
|
+
});
|
|
25
|
+
return HttpResponse.json({
|
|
26
|
+
code: 'ERR-MOCK-SCHEMA-MISSING',
|
|
27
|
+
message: `No server mock is registered for ${request.method} ${url}`,
|
|
28
|
+
data: { method: request.method, url },
|
|
29
|
+
traceId: `mock_unregistered_${journalEntry.sequence}`,
|
|
30
|
+
}, {
|
|
31
|
+
status: 501,
|
|
32
|
+
headers: { 'x-soma-mock-source': 'catch-all' },
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ChildProcess,
|
|
3
|
+
StdioOptions,
|
|
4
|
+
spawn,
|
|
5
|
+
spawnSync,
|
|
6
|
+
} from 'node:child_process';
|
|
7
|
+
import type { EventEmitter } from 'node:events';
|
|
8
|
+
|
|
9
|
+
export interface SomaMockLifecycleDelegate {
|
|
10
|
+
executable: string;
|
|
11
|
+
argsPrefix?: string[];
|
|
12
|
+
cwd?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface MockProcessLifecycleOptions {
|
|
16
|
+
detached?: boolean;
|
|
17
|
+
killProcess?: typeof process.kill;
|
|
18
|
+
killWaitMs?: number;
|
|
19
|
+
platform?: NodeJS.Platform;
|
|
20
|
+
termGraceMs?: number;
|
|
21
|
+
windowsCommandRunner?: typeof spawnSync;
|
|
22
|
+
windowsTreeHasExited?: (child: ChildProcess) => boolean;
|
|
23
|
+
windowsTreeKill?: (pid: number, signal: NodeJS.Signals) => boolean | void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface RunSomaMockLifecycleOptions extends MockProcessLifecycleOptions {
|
|
27
|
+
enabled: boolean;
|
|
28
|
+
appRoot?: string;
|
|
29
|
+
env?: NodeJS.ProcessEnv;
|
|
30
|
+
delegate: SomaMockLifecycleDelegate;
|
|
31
|
+
providerModuleUrls?: string[];
|
|
32
|
+
providerPackageRoot?: string;
|
|
33
|
+
providerEnvironmentKeys?: string[];
|
|
34
|
+
commandName?: string;
|
|
35
|
+
preloadUrl?: string;
|
|
36
|
+
nodeVersion?: string;
|
|
37
|
+
spawnImpl?: typeof spawn;
|
|
38
|
+
stdio?: StdioOptions;
|
|
39
|
+
signalSource?: EventEmitter;
|
|
40
|
+
stdout?: Pick<NodeJS.WritableStream, 'write'>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class SomaMockCliError extends Error {
|
|
44
|
+
readonly code: string;
|
|
45
|
+
constructor(code: string, message: string);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function withNodePreload(nodeOptions?: string, preloadUrl?: string): string;
|
|
49
|
+
export function withoutNodePreload(nodeOptions?: string, preloadUrl?: string): string;
|
|
50
|
+
export function terminateMockChild(
|
|
51
|
+
child: ChildProcess,
|
|
52
|
+
options?: MockProcessLifecycleOptions,
|
|
53
|
+
): Promise<void>;
|
|
54
|
+
export function runSomaMockCli(
|
|
55
|
+
argv: string[] | undefined,
|
|
56
|
+
options: RunSomaMockLifecycleOptions,
|
|
57
|
+
): Promise<number>;
|
|
58
|
+
export const SOMA_MOCK_PRELOAD_URL: string;
|