soma-core 1.0.2 → 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.
Files changed (93) hide show
  1. package/app/SomaPageClient.tsx +11 -20
  2. package/app/[...path]/page.tsx +21 -0
  3. package/app/api/[...path]/route.ts +86 -77
  4. package/app/components/SomaHostPage.tsx +133 -0
  5. package/app/components/SomaHydrationShell.tsx +1 -1
  6. package/app/favicon.ico/route.ts +13 -0
  7. package/app/layout.tsx +10 -6
  8. package/app/page.tsx +7 -18
  9. package/app/soma/[...path]/route.ts +9 -0
  10. package/app/{api/soma-manifest → soma/manifest}/route.ts +3 -3
  11. package/app/soma/page/route.ts +29 -0
  12. package/app/soma/page-object/route.ts +158 -0
  13. package/app/soma/route.ts +9 -0
  14. package/bin/soma-mock.mjs +38 -0
  15. package/bin/soma.cjs +1 -1
  16. package/core/api/load-host-service.ts +5 -2
  17. package/core/base/SomaHttpClient.ts +5 -3
  18. package/core/compiler/full-manifest-builder.ts +84 -69
  19. package/core/compiler/host-config-sync.cjs +32 -6
  20. package/core/compiler/page-base-resolver.ts +3 -0
  21. package/core/compiler/soma-manifest-webpack-plugin.js +160 -10
  22. package/core/engine/dom-renderer.ts +160 -24
  23. package/core/engine/soma-headless-page.ts +86 -0
  24. package/core/host/app-config-composer.ts +90 -0
  25. package/core/host/app-config.stub.ts +2 -0
  26. package/core/host/host-config-paths.cjs +100 -0
  27. package/core/host/host-config-paths.ts +132 -0
  28. package/core/host/invoke-host-request-hook.ts +37 -0
  29. package/core/host/load-host-domain-class.ts +87 -0
  30. package/core/host/locale.stub.ts +2 -0
  31. package/core/host/page-response-mode.cjs +96 -0
  32. package/core/host/page-response-request.ts +35 -0
  33. package/core/host/request-origin.ts +18 -0
  34. package/core/host/resolve-host-request-hook.ts +29 -0
  35. package/core/host/server-page-assets.ts +193 -0
  36. package/core/host/soma-domain-loaders.stub.ts +6 -0
  37. package/core/host/soma-domain-loaders.ts +69 -0
  38. package/core/host/soma-request-hook-host.stub.ts +4 -0
  39. package/core/host/source-packages.ts +153 -0
  40. package/core/index.ts +22 -0
  41. package/core/infra/http/SomaHttpService.ts +23 -14
  42. package/core/infra/http/soma-server-request-context.ts +126 -0
  43. package/core/mock/node/catch-all.mjs +35 -0
  44. package/core/mock/node/cli.d.mts +58 -0
  45. package/core/mock/node/cli.mjs +243 -0
  46. package/core/mock/node/context.mjs +167 -0
  47. package/core/mock/node/environment-policy.mjs +52 -0
  48. package/core/mock/node/plugin-loader.mjs +212 -0
  49. package/core/mock/node/preload.mjs +91 -0
  50. package/core/mock/node/process-lifecycle.mjs +236 -0
  51. package/core/mock/node/public.d.mts +110 -0
  52. package/core/mock/node/public.mjs +4 -0
  53. package/core/mock/node/registry.mjs +336 -0
  54. package/core/mock/node/schema-generator.mjs +1310 -0
  55. package/core/mock/testing/host-harness.d.mts +66 -0
  56. package/core/mock/testing/host-harness.mjs +276 -0
  57. package/core/mock/testing/host-runtime.mjs +48 -0
  58. package/core/runtime/SomaRuntimeServices.ts +5 -1
  59. package/core/runtime/serialize-page-state.ts +152 -0
  60. package/dist/cli/soma.js +375 -4
  61. package/dist/core/index.cjs +2957 -2387
  62. package/dist/tsconfig.types.tsbuildinfo +1 -1
  63. package/dist/types/base/SomaHttpClient.d.ts +2 -0
  64. package/dist/types/compiler/full-manifest-builder.d.ts +2 -0
  65. package/dist/types/engine/dom-renderer.d.ts +6 -0
  66. package/dist/types/engine/soma-headless-page.d.ts +10 -0
  67. package/dist/types/host/app-config-composer.d.ts +6 -0
  68. package/dist/types/host/app-config.stub.d.ts +3 -0
  69. package/dist/types/host/host-config-paths.d.ts +23 -0
  70. package/dist/types/host/invoke-host-request-hook.d.ts +8 -0
  71. package/dist/types/host/load-host-domain-class.d.ts +12 -0
  72. package/dist/types/host/locale.stub.d.ts +3 -0
  73. package/dist/types/host/page-response-request.d.ts +9 -0
  74. package/dist/types/host/request-origin.d.ts +1 -0
  75. package/dist/types/host/resolve-host-request-hook.d.ts +16 -0
  76. package/dist/types/host/server-page-assets.d.ts +29 -0
  77. package/dist/types/host/soma-domain-loaders.d.ts +19 -0
  78. package/dist/types/host/soma-domain-loaders.stub.d.ts +4 -0
  79. package/dist/types/host/soma-request-hook-host.stub.d.ts +2 -0
  80. package/dist/types/host/source-packages.d.ts +12 -0
  81. package/dist/types/index.d.ts +3 -0
  82. package/dist/types/infra/http/SomaHttpService.d.ts +2 -0
  83. package/dist/types/infra/http/soma-server-request-context.d.ts +5 -0
  84. package/dist/types/runtime/serialize-page-state.d.ts +10 -0
  85. 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
  86. package/global.d.ts +74 -33
  87. package/middleware.ts +33 -0
  88. package/next.config.js +166 -16
  89. package/package.json +47 -13
  90. package/tailwind.config.ts +21 -17
  91. package/tsconfig.json +1 -5
  92. package/app/api/page/route.ts +0 -99
  93. package/app/loading.tsx +0 -5
@@ -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
+ }
@@ -0,0 +1,4 @@
1
+ import type { SomaRequestHook } from './resolve-host-request-hook';
2
+
3
+ export const somaRequestHook: SomaRequestHook | undefined = undefined;
4
+
@@ -0,0 +1,153 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { getSomaHostConfigRoot } from './host-config-paths';
4
+
5
+ export interface SomaAssetSource {
6
+ type: 'host' | 'package';
7
+ name: string;
8
+ assetRoot: string;
9
+ codeRoot: string;
10
+ configRoot: string;
11
+ packageName?: string;
12
+ }
13
+
14
+ interface PackageJson {
15
+ dependencies?: Record<string, string>;
16
+ devDependencies?: Record<string, string>;
17
+ soma?: {
18
+ source?: boolean;
19
+ hostRoot?: string;
20
+ configRoot?: string;
21
+ };
22
+ }
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
+
34
+ function readJson<T>(filePath: string): T | null {
35
+ try {
36
+ if (!fs.existsSync(filePath)) {
37
+ return null;
38
+ }
39
+ return JSON.parse(fs.readFileSync(filePath, 'utf8')) as T;
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ function packagePathInNodeModules(hostDir: string, packageName: string): string {
46
+ return path.join(hostDir, 'node_modules', ...packageName.split('/'));
47
+ }
48
+
49
+ function resolvePackageRoot(hostDir: string, packageName: string, version?: string): string | null {
50
+ const nodeModulesPath = packagePathInNodeModules(hostDir, packageName);
51
+ if (fs.existsSync(nodeModulesPath)) {
52
+ return nodeModulesPath;
53
+ }
54
+
55
+ if (version?.startsWith('file:')) {
56
+ const fileRoot = path.resolve(hostDir, version.slice('file:'.length));
57
+ if (fs.existsSync(fileRoot)) {
58
+ return fileRoot;
59
+ }
60
+ }
61
+
62
+ return null;
63
+ }
64
+
65
+ function readExplicitSourcePackages(): string[] {
66
+ return String(process.env.SOMA_SOURCE_PACKAGES ?? '')
67
+ .split(',')
68
+ .map((item) => item.trim())
69
+ .filter(Boolean);
70
+ }
71
+
72
+ function readHostDependencies(hostDir: string): Record<string, string> {
73
+ const packageJson = readJson<PackageJson>(path.join(hostDir, 'package.json'));
74
+ return {
75
+ ...(packageJson?.dependencies ?? {}),
76
+ ...(packageJson?.devDependencies ?? {}),
77
+ };
78
+ }
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
+
101
+ function isSomaSourcePackage(packageRoot: string, explicit: boolean): boolean {
102
+ if (explicit) {
103
+ return true;
104
+ }
105
+ const packageJson = readJson<PackageJson>(path.join(packageRoot, 'package.json'));
106
+ return packageJson?.soma?.source === true || fs.existsSync(path.join(packageRoot, 'shell', 'html'));
107
+ }
108
+
109
+ function toPackageSource(packageName: string, packageRoot: string): SomaAssetSource {
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');
114
+ return {
115
+ type: 'package',
116
+ name: packageName,
117
+ packageName,
118
+ assetRoot: fs.existsSync(path.join(shellRoot, 'html')) ? shellRoot : codeRoot,
119
+ codeRoot,
120
+ configRoot,
121
+ };
122
+ }
123
+
124
+ export function getSomaAssetSources(hostDir: string): SomaAssetSource[] {
125
+ const normalizedHostDir = path.resolve(hostDir);
126
+ const hostSourceRoot = getSomaHostSourceRoot(normalizedHostDir);
127
+ const dependencies = readHostDependencies(normalizedHostDir);
128
+ const explicitPackages = new Set(readExplicitSourcePackages());
129
+ const packageNames = new Set([
130
+ ...Object.keys(dependencies),
131
+ ...explicitPackages,
132
+ ]);
133
+
134
+ const sources: SomaAssetSource[] = [
135
+ {
136
+ type: 'host',
137
+ name: 'host',
138
+ assetRoot: hostSourceRoot,
139
+ codeRoot: hostSourceRoot,
140
+ configRoot: getSomaHostConfigRoot(normalizedHostDir),
141
+ },
142
+ ];
143
+
144
+ for (const packageName of packageNames) {
145
+ const packageRoot = resolvePackageRoot(normalizedHostDir, packageName, dependencies[packageName]);
146
+ if (!packageRoot || !isSomaSourcePackage(packageRoot, explicitPackages.has(packageName))) {
147
+ continue;
148
+ }
149
+ sources.push(toPackageSource(packageName, packageRoot));
150
+ }
151
+
152
+ return sources;
153
+ }
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.client = new SomaHttpClient(config);
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
- ...config?.headers,
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;