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,243 @@
1
+ import { spawn } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import process from 'node:process';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import {
6
+ SomaMockCliError,
7
+ terminateMockChild,
8
+ waitForChild,
9
+ } from './process-lifecycle.mjs';
10
+ import { filterMockEnvironment } from './environment-policy.mjs';
11
+
12
+ const MOCK_COMMANDS = new Set(['dev', 'build', 'start']);
13
+ const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
14
+ const DEFAULT_PRELOAD_URL = pathToFileURL(path.join(PACKAGE_ROOT, 'core', 'mock', 'node', 'preload.mjs')).href;
15
+
16
+ export { SomaMockCliError, terminateMockChild };
17
+
18
+ function unquoteNodeOption(value) {
19
+ const source = String(value || '');
20
+ if (source.length >= 2) {
21
+ const first = source[0];
22
+ const last = source.at(-1);
23
+ if ((first === '"' || first === "'") && last === first) return source.slice(1, -1);
24
+ }
25
+ return source;
26
+ }
27
+
28
+ function nodeOptionTokens(nodeOptions) {
29
+ const source = String(nodeOptions || '').trim();
30
+ return source ? source.split(/\s+/u) : [];
31
+ }
32
+
33
+ function tokenImportsUrl(token, preloadUrl) {
34
+ const normalized = unquoteNodeOption(token);
35
+ if (!normalized.startsWith('--import=')) return false;
36
+ return unquoteNodeOption(normalized.slice('--import='.length)) === preloadUrl;
37
+ }
38
+
39
+ function hasNodePreload(nodeOptions, preloadUrl) {
40
+ const tokens = nodeOptionTokens(nodeOptions);
41
+ for (let index = 0; index < tokens.length; index += 1) {
42
+ if (tokenImportsUrl(tokens[index], preloadUrl)) return true;
43
+ if (
44
+ unquoteNodeOption(tokens[index]) === '--import'
45
+ && unquoteNodeOption(tokens[index + 1]) === preloadUrl
46
+ ) return true;
47
+ }
48
+ return false;
49
+ }
50
+
51
+ export function withNodePreload(nodeOptions, preloadUrl = DEFAULT_PRELOAD_URL) {
52
+ const current = String(nodeOptions || '').trim();
53
+ if (hasNodePreload(current, preloadUrl)) return current;
54
+ return [current, `--import=${preloadUrl}`].filter(Boolean).join(' ');
55
+ }
56
+
57
+ export function withoutNodePreload(nodeOptions, preloadUrl = DEFAULT_PRELOAD_URL) {
58
+ const tokens = nodeOptionTokens(nodeOptions);
59
+ const retained = [];
60
+ for (let index = 0; index < tokens.length; index += 1) {
61
+ if (tokenImportsUrl(tokens[index], preloadUrl)) continue;
62
+ if (
63
+ unquoteNodeOption(tokens[index]) === '--import'
64
+ && unquoteNodeOption(tokens[index + 1]) === preloadUrl
65
+ ) {
66
+ index += 1;
67
+ continue;
68
+ }
69
+ retained.push(tokens[index]);
70
+ }
71
+ return retained.join(' ');
72
+ }
73
+
74
+ function sanitizeMockEnvironment(environment, preloadUrl, options = {}) {
75
+ const sanitized = filterMockEnvironment(environment, options);
76
+ const nodeOptions = withoutNodePreload(sanitized.NODE_OPTIONS, preloadUrl);
77
+ if (nodeOptions) sanitized.NODE_OPTIONS = nodeOptions;
78
+ else delete sanitized.NODE_OPTIONS;
79
+ return sanitized;
80
+ }
81
+
82
+ function assertSupportedNode(version = process.versions.node) {
83
+ const [major, minor] = String(version).split('.').map(Number);
84
+ if (major < 18 || (major === 18 && minor < 18)) {
85
+ throw new SomaMockCliError(
86
+ 'NODE_VERSION_UNSUPPORTED',
87
+ `Server Mock preloading requires Node >=18.18; current version is ${version}`,
88
+ );
89
+ }
90
+ }
91
+
92
+ function printUsage(stdout, commandName) {
93
+ stdout.write([
94
+ `Usage: ${commandName} <dev|build|start> [...args]`,
95
+ '',
96
+ 'Runs the Host lifecycle with the generic SOMA MSW provider explicitly enabled.',
97
+ 'Environment policy belongs to the caller; Core only accepts an explicit boolean switch.',
98
+ '',
99
+ ].join('\n'));
100
+ }
101
+
102
+ function normalizeProviderModules(providerModuleUrls = [], providerPackageRoot) {
103
+ if (!Array.isArray(providerModuleUrls)) {
104
+ throw new TypeError('providerModuleUrls must be an array of file: URLs');
105
+ }
106
+ if (providerModuleUrls.length === 0) return [];
107
+ const packageRoot = typeof providerPackageRoot === 'string' ? providerPackageRoot.trim() : '';
108
+ if (!packageRoot) {
109
+ throw new TypeError('providerPackageRoot is required when providerModuleUrls is non-empty');
110
+ }
111
+ const resolvedRoot = path.resolve(packageRoot);
112
+ return providerModuleUrls.map((entry) => {
113
+ const value = String(entry || '').trim();
114
+ if (!value.startsWith('file:')) {
115
+ throw new TypeError(`providerModuleUrls entries must be file: URLs: ${entry}`);
116
+ }
117
+ return { url: value, packageRoot: resolvedRoot };
118
+ });
119
+ }
120
+
121
+ /**
122
+ * Generic Mock lifecycle launcher. Upper frameworks own the enablement switch
123
+ * and pass a Host lifecycle delegate plus optional trusted provider modules.
124
+ * Core does not enable Mock from the regular soma CLI.
125
+ *
126
+ * @param {string[]} [argv]
127
+ * @param {{
128
+ * enabled: boolean,
129
+ * appRoot?: string,
130
+ * env?: NodeJS.ProcessEnv,
131
+ * delegate: { executable: string, argsPrefix?: string[], cwd?: string },
132
+ * providerModuleUrls?: string[],
133
+ * providerPackageRoot?: string,
134
+ * providerEnvironmentKeys?: string[],
135
+ * commandName?: string,
136
+ * preloadUrl?: string,
137
+ * nodeVersion?: string,
138
+ * spawnImpl?: typeof spawn,
139
+ * detached?: boolean,
140
+ * stdio?: import('node:child_process').StdioOptions,
141
+ * signalSource?: NodeJS.EventEmitter,
142
+ * killProcess?: typeof process.kill,
143
+ * killWaitMs?: number,
144
+ * termGraceMs?: number,
145
+ * platform?: NodeJS.Platform,
146
+ * windowsCommandRunner?: typeof import('node:child_process').spawnSync,
147
+ * windowsTreeKill?: (pid: number, signal: NodeJS.Signals) => boolean | void,
148
+ * windowsTreeHasExited?: (child: import('node:child_process').ChildProcess) => boolean,
149
+ * stdout?: NodeJS.WritableStream,
150
+ * }} options
151
+ */
152
+ export async function runSomaMockCli(argv = process.argv.slice(2), options = {}) {
153
+ if (!options || typeof options !== 'object') {
154
+ throw new TypeError('runSomaMockCli requires options');
155
+ }
156
+ if (typeof options.enabled !== 'boolean') {
157
+ throw new TypeError('runSomaMockCli requires options.enabled to be a boolean');
158
+ }
159
+ if (!options.delegate) {
160
+ throw new TypeError('runSomaMockCli requires options.delegate');
161
+ }
162
+ const commandName = options.commandName || 'soma-mock';
163
+ const [rawCommand = 'dev', ...commandArguments] = argv;
164
+ const command = String(rawCommand).trim();
165
+ if (command === '--help' || command === '-h' || command === 'help') {
166
+ printUsage(options.stdout ?? process.stdout, commandName);
167
+ return 0;
168
+ }
169
+ if (!MOCK_COMMANDS.has(command)) {
170
+ throw new SomaMockCliError(
171
+ 'COMMAND_UNSUPPORTED',
172
+ `Unsupported Mock Host command ${JSON.stringify(command)}; expected dev, build or start`,
173
+ );
174
+ }
175
+
176
+ const env = options.env ?? process.env;
177
+ const appRoot = path.resolve(options.appRoot ?? process.cwd());
178
+ const preloadUrl = options.preloadUrl ?? DEFAULT_PRELOAD_URL;
179
+
180
+ let childEnvironment;
181
+ if (options.enabled) {
182
+ assertSupportedNode(options.nodeVersion);
183
+ const providerModules = normalizeProviderModules(
184
+ options.providerModuleUrls,
185
+ options.providerPackageRoot,
186
+ );
187
+ const sanitizedEnvironment = sanitizeMockEnvironment(env, preloadUrl, {
188
+ // The wrapper must not activate the preload using a stale parent Host.
189
+ // The delegated Host lifecycle owns rebuilding SOMA_HOST_DIR for Next.
190
+ removeRuntimeHostDir: true,
191
+ providerEnvironmentKeys: options.providerEnvironmentKeys,
192
+ });
193
+ childEnvironment = {
194
+ ...sanitizedEnvironment,
195
+ SOMA_MOCK_ENABLED: '1',
196
+ SOMA_MOCK_APP_ROOT: appRoot,
197
+ NODE_OPTIONS: withNodePreload(sanitizedEnvironment.NODE_OPTIONS, preloadUrl),
198
+ };
199
+ // Always rebuild provider list; never inherit parent SOMA_MOCK_PROVIDER_MODULES.
200
+ if (providerModules.length > 0) {
201
+ childEnvironment.SOMA_MOCK_PROVIDER_MODULES = JSON.stringify(providerModules);
202
+ } else {
203
+ delete childEnvironment.SOMA_MOCK_PROVIDER_MODULES;
204
+ }
205
+ } else {
206
+ childEnvironment = sanitizeMockEnvironment(env, preloadUrl, { removeAllMockKeys: true });
207
+ }
208
+
209
+ const delegate = options.delegate;
210
+ const executable = delegate.executable;
211
+ if (typeof executable !== 'string' || !executable.trim()) {
212
+ throw new TypeError('delegate.executable must be a non-empty string');
213
+ }
214
+ const argsPrefix = Array.isArray(delegate.argsPrefix) ? delegate.argsPrefix : [];
215
+ const cwd = path.resolve(delegate.cwd || appRoot);
216
+ const spawnImpl = options.spawnImpl ?? spawn;
217
+ const detached = options.detached ?? process.platform !== 'win32';
218
+ const child = spawnImpl(executable, [
219
+ ...argsPrefix,
220
+ command,
221
+ ...commandArguments,
222
+ ], {
223
+ cwd,
224
+ detached,
225
+ env: childEnvironment,
226
+ stdio: options.stdio ?? 'inherit',
227
+ });
228
+ if (!child || typeof child.once !== 'function' || typeof child.kill !== 'function') {
229
+ throw new SomaMockCliError('HOST_SPAWN_INVALID', `Unable to start Mock Host delegate: ${executable}`);
230
+ }
231
+ return waitForChild(child, options.signalSource ?? process, {
232
+ detached,
233
+ killProcess: options.killProcess,
234
+ killWaitMs: options.killWaitMs,
235
+ platform: options.platform,
236
+ termGraceMs: options.termGraceMs,
237
+ windowsCommandRunner: options.windowsCommandRunner,
238
+ windowsTreeHasExited: options.windowsTreeHasExited,
239
+ windowsTreeKill: options.windowsTreeKill,
240
+ });
241
+ }
242
+
243
+ export const SOMA_MOCK_PRELOAD_URL = DEFAULT_PRELOAD_URL;
@@ -0,0 +1,167 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { generateFromSchema } from './schema-generator.mjs';
4
+
5
+ const DEFAULT_JOURNAL_MAX_RECORDS = 1_000;
6
+ const MAX_JOURNAL_MAX_RECORDS = 100_000;
7
+ const REDACTED_JOURNAL_VALUE = '[REDACTED]';
8
+
9
+ function normalizedJournalKey(value) {
10
+ return String(value || '').replace(/[^a-z0-9]/giu, '').toLowerCase();
11
+ }
12
+
13
+ function isSensitiveJournalKey(key) {
14
+ const normalized = normalizedJournalKey(key);
15
+ return normalized.includes('authorization')
16
+ || [
17
+ 'cookie',
18
+ 'credential',
19
+ 'password',
20
+ 'passwd',
21
+ 'secret',
22
+ 'stoken',
23
+ 'token',
24
+ 'apikey',
25
+ 'privatekey',
26
+ ].some((name) => normalized === name || normalized.endsWith(name));
27
+ }
28
+
29
+ function isJournalUrlKey(key) {
30
+ const normalized = normalizedJournalKey(key);
31
+ return normalized === 'url' || normalized.endsWith('url')
32
+ || normalized === 'href' || normalized.endsWith('href');
33
+ }
34
+
35
+ function redactJournalUrl(value) {
36
+ if (typeof value !== 'string') return value;
37
+ try {
38
+ const url = new URL(value);
39
+ if (!['http:', 'https:'].includes(url.protocol)) return REDACTED_JOURNAL_VALUE;
40
+ return `${url.origin}${url.pathname}`;
41
+ } catch {
42
+ return value.replace(/[?#].*$/u, '');
43
+ }
44
+ }
45
+
46
+ /** Apply one privacy policy to every in-memory and JSONL journal entry. */
47
+ export function redactJournalValue(value) {
48
+ const seen = new WeakSet();
49
+ function visit(entry, key = '') {
50
+ if (typeof entry === 'boolean') return entry;
51
+ if (isSensitiveJournalKey(key)) return REDACTED_JOURNAL_VALUE;
52
+ if (isJournalUrlKey(key) && typeof entry === 'string') return redactJournalUrl(entry);
53
+ if (typeof entry === 'string' && normalizedJournalKey(key).endsWith('body')) {
54
+ return REDACTED_JOURNAL_VALUE;
55
+ }
56
+ if (!entry || typeof entry !== 'object') return entry;
57
+ if (seen.has(entry)) return '[Circular]';
58
+ seen.add(entry);
59
+ if (Array.isArray(entry)) return entry.map((item) => visit(item));
60
+ return Object.fromEntries(
61
+ Object.entries(entry).map(([entryKey, nested]) => [entryKey, visit(nested, entryKey)]),
62
+ );
63
+ }
64
+ return visit(value);
65
+ }
66
+
67
+ function normalizeJournalMaxRecords(value) {
68
+ const resolved = value === undefined || value === null || value === ''
69
+ ? DEFAULT_JOURNAL_MAX_RECORDS
70
+ : Number(value);
71
+ if (!Number.isInteger(resolved) || resolved < 1 || resolved > MAX_JOURNAL_MAX_RECORDS) {
72
+ throw new TypeError(
73
+ `MSW journal maxRecords must be an integer between 1 and ${MAX_JOURNAL_MAX_RECORDS}`,
74
+ );
75
+ }
76
+ return resolved;
77
+ }
78
+
79
+ function readJsonLines(filePath) {
80
+ if (!filePath || !fs.existsSync(filePath)) return [];
81
+ return fs.readFileSync(filePath, 'utf8')
82
+ .split(/\r?\n/)
83
+ .filter(Boolean)
84
+ .map((line, index) => {
85
+ try {
86
+ return JSON.parse(line);
87
+ } catch (error) {
88
+ throw new Error(`Invalid MSW journal JSON at ${filePath}:${index + 1}`, { cause: error });
89
+ }
90
+ });
91
+ }
92
+
93
+ export function createMockJournal(options = {}) {
94
+ const filePath = options.filePath ? path.resolve(options.filePath) : null;
95
+ const maxRecords = normalizeJournalMaxRecords(
96
+ options.maxRecords ?? process.env.SOMA_MOCK_JOURNAL_MAX_RECORDS,
97
+ );
98
+ const records = [];
99
+ let sequence = 0;
100
+
101
+ function record(entry) {
102
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
103
+ throw new TypeError('MSW journal entries must be objects');
104
+ }
105
+ const sanitizedEntry = redactJournalValue(entry);
106
+ const value = {
107
+ ...sanitizedEntry,
108
+ sequence: sequence += 1,
109
+ pid: process.pid,
110
+ timestamp: new Date().toISOString(),
111
+ };
112
+ records.push(value);
113
+ if (records.length > maxRecords) records.splice(0, records.length - maxRecords);
114
+ if (filePath) {
115
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
116
+ fs.appendFileSync(filePath, `${JSON.stringify(value)}\n`, 'utf8');
117
+ }
118
+ return value;
119
+ }
120
+
121
+ function list() {
122
+ return filePath ? readJsonLines(filePath) : records.map((entry) => structuredClone(entry));
123
+ }
124
+
125
+ function clear() {
126
+ records.length = 0;
127
+ sequence = 0;
128
+ if (filePath) {
129
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
130
+ fs.writeFileSync(filePath, '', 'utf8');
131
+ }
132
+ }
133
+
134
+ return Object.freeze({ filePath, maxRecords, record, list, clear });
135
+ }
136
+
137
+ export function createMockContext(options = {}) {
138
+ const hostDir = path.resolve(
139
+ options.hostDir
140
+ || process.env.SOMA_MOCK_APP_ROOT
141
+ || process.env.SOMA_HOST_DIR
142
+ || process.cwd(),
143
+ );
144
+ const runtimeHostDir = path.resolve(
145
+ options.runtimeHostDir || process.env.SOMA_HOST_DIR || hostDir,
146
+ );
147
+ const seed = String(options.seed ?? process.env.SOMA_MOCK_SEED ?? 'soma-mock');
148
+ const journal = options.journal || createMockJournal({
149
+ filePath: options.journalFile ?? process.env.SOMA_MOCK_JOURNAL_FILE,
150
+ });
151
+ const state = options.state || Object.create(null);
152
+
153
+ const context = {
154
+ hostDir,
155
+ runtimeHostDir,
156
+ seed,
157
+ state,
158
+ journal,
159
+ generateFromSchema(schema, generationOptions = {}) {
160
+ return generateFromSchema(schema, {
161
+ ...generationOptions,
162
+ seed: generationOptions.seed ?? seed,
163
+ });
164
+ },
165
+ };
166
+ return context;
167
+ }
@@ -0,0 +1,52 @@
1
+ const MOCK_CONTROL_PLANE_KEYS = new Set([
2
+ 'SOMA_MOCK_APP_ROOT',
3
+ 'SOMA_MOCK_ENABLED',
4
+ 'SOMA_MOCK_PROVIDER_MODULES',
5
+ ]);
6
+
7
+ const MOCK_DATA_PLANE_KEYS = new Set([
8
+ 'SOMA_MOCK_JOURNAL_FILE',
9
+ 'SOMA_MOCK_JOURNAL_MAX_RECORDS',
10
+ 'SOMA_MOCK_QUIET',
11
+ 'SOMA_MOCK_REGISTRY_FILE',
12
+ 'SOMA_MOCK_SEED',
13
+ ]);
14
+
15
+ function normalizeProviderEnvironmentKeys(keys = []) {
16
+ if (!Array.isArray(keys)) {
17
+ throw new TypeError('providerEnvironmentKeys must be an array of SOMA_MOCK_* environment keys');
18
+ }
19
+ const normalized = new Set();
20
+ for (const rawKey of keys) {
21
+ const key = String(rawKey || '').trim();
22
+ if (!/^SOMA_MOCK_[A-Z0-9_]+$/u.test(key)) {
23
+ throw new TypeError(`Invalid Mock provider environment key: ${rawKey}`);
24
+ }
25
+ if (MOCK_CONTROL_PLANE_KEYS.has(key)) {
26
+ throw new TypeError(`Mock provider environment key is reserved by Core: ${key}`);
27
+ }
28
+ normalized.add(key);
29
+ }
30
+ return normalized;
31
+ }
32
+
33
+ /**
34
+ * Rebuild the Mock data plane from an explicit key contract. Core control
35
+ * keys are always removed and undeclared extension keys never reach a child.
36
+ */
37
+ export function filterMockEnvironment(environment = {}, options = {}) {
38
+ const providerKeys = normalizeProviderEnvironmentKeys(options.providerEnvironmentKeys);
39
+ const allowedMockKeys = options.removeAllMockKeys
40
+ ? new Set()
41
+ : new Set([...MOCK_DATA_PLANE_KEYS, ...providerKeys]);
42
+ const filtered = {};
43
+
44
+ for (const [key, value] of Object.entries(environment)) {
45
+ if (options.removeRuntimeHostDir && key === 'SOMA_HOST_DIR') continue;
46
+ if (key.startsWith('SOMA_MOCK_')) {
47
+ if (MOCK_CONTROL_PLANE_KEYS.has(key) || !allowedMockKeys.has(key)) continue;
48
+ }
49
+ filtered[key] = value;
50
+ }
51
+ return filtered;
52
+ }
@@ -0,0 +1,212 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import { createCatchAllHandler } from './catch-all.mjs';
5
+ import { createRegistryHandlers } from './registry.mjs';
6
+
7
+ function isPathInside(root, target) {
8
+ const relative = path.relative(root, target);
9
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
10
+ }
11
+
12
+ async function handlersFrom(factory, context, name) {
13
+ const handlers = await factory(context);
14
+ if (!Array.isArray(handlers)) throw new TypeError(`${name} must return an array of MSW handlers`);
15
+ return handlers;
16
+ }
17
+
18
+ function resolveHostHandlersFile(context) {
19
+ const mockDirectory = path.resolve(context.hostDir, 'mock');
20
+ const handlersFile = path.join(mockDirectory, 'handlers.mjs');
21
+ if (!fs.existsSync(handlersFile)) return null;
22
+
23
+ const realHostDirectory = fs.realpathSync(context.hostDir);
24
+ const realMockDirectory = fs.realpathSync(mockDirectory);
25
+ const realHandlersFile = fs.realpathSync(handlersFile);
26
+ if (
27
+ !isPathInside(realHostDirectory, realMockDirectory)
28
+ || !isPathInside(realMockDirectory, realHandlersFile)
29
+ ) {
30
+ throw new TypeError(`Host Mock handlers must stay inside SOMA_MOCK_APP_ROOT/mock: ${handlersFile}`);
31
+ }
32
+ return realHandlersFile;
33
+ }
34
+
35
+ /**
36
+ * Load the current App's optional stateful handlers without introducing a
37
+ * dependency from the Mock engine to any business Host.
38
+ */
39
+ export async function loadHostMockHandlers(context) {
40
+ const handlersFile = resolveHostHandlersFile(context);
41
+ if (!handlersFile) return { filePath: null, handlers: [] };
42
+
43
+ const module = await import(pathToFileURL(handlersFile).href);
44
+ if (typeof module.createMockHandlers !== 'function') {
45
+ throw new TypeError(
46
+ `Host Mock plugin must export createMockHandlers(context): ${handlersFile}`,
47
+ );
48
+ }
49
+ return {
50
+ filePath: handlersFile,
51
+ handlers: await handlersFrom(
52
+ module.createMockHandlers,
53
+ context,
54
+ `${handlersFile}#createMockHandlers`,
55
+ ),
56
+ };
57
+ }
58
+
59
+ function parseProviderModuleEntries(raw) {
60
+ if (!raw) return [];
61
+ const text = String(raw).trim();
62
+ if (!text) return [];
63
+ let parsed;
64
+ try {
65
+ parsed = JSON.parse(text);
66
+ } catch (error) {
67
+ throw new TypeError(
68
+ 'SOMA_MOCK_PROVIDER_MODULES must be a JSON array of { url, packageRoot } entries',
69
+ { cause: error },
70
+ );
71
+ }
72
+ if (!Array.isArray(parsed)) {
73
+ throw new TypeError(
74
+ 'SOMA_MOCK_PROVIDER_MODULES must be a JSON array of { url, packageRoot } entries',
75
+ );
76
+ }
77
+ return parsed.map((entry, index) => {
78
+ if (typeof entry === 'string') {
79
+ throw new TypeError(
80
+ `SOMA_MOCK_PROVIDER_MODULES[${index}] must be an object with url and packageRoot (string URLs alone are rejected)`,
81
+ );
82
+ }
83
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
84
+ throw new TypeError(`SOMA_MOCK_PROVIDER_MODULES[${index}] must be an object`);
85
+ }
86
+ return {
87
+ url: String(entry.url || ''),
88
+ packageRoot: String(entry.packageRoot || ''),
89
+ };
90
+ });
91
+ }
92
+
93
+ /**
94
+ * Resolve a provider file: URL and prove it stays inside the declared package root
95
+ * via both lexical and realpath containment (Windows-safe via fileURLToPath).
96
+ */
97
+ export function resolveProviderModuleEntry(entry) {
98
+ const moduleUrl = String(entry?.url || '').trim();
99
+ const packageRootInput = String(entry?.packageRoot || '').trim();
100
+ if (!moduleUrl.startsWith('file:')) {
101
+ throw new TypeError(`Mock provider module must be a file: URL: ${moduleUrl || entry?.url}`);
102
+ }
103
+ if (!packageRootInput) {
104
+ throw new TypeError(`Mock provider packageRoot is required for ${moduleUrl}`);
105
+ }
106
+
107
+ let url;
108
+ try {
109
+ url = new URL(moduleUrl);
110
+ } catch (error) {
111
+ throw new TypeError(`Mock provider module must be a file: URL: ${moduleUrl}`, { cause: error });
112
+ }
113
+ if (url.protocol !== 'file:') {
114
+ throw new TypeError(`Mock provider module must be a file: URL: ${moduleUrl}`);
115
+ }
116
+
117
+ const filePath = path.resolve(fileURLToPath(url));
118
+ const packageRoot = path.resolve(packageRootInput);
119
+ if (!fs.existsSync(packageRoot) || !fs.statSync(packageRoot).isDirectory()) {
120
+ throw new Error(`Mock provider packageRoot does not exist: ${packageRoot}`);
121
+ }
122
+ if (!fs.existsSync(filePath)) {
123
+ throw new Error(`Mock provider module does not exist: ${filePath}`);
124
+ }
125
+ if (!isPathInside(packageRoot, filePath)) {
126
+ throw new TypeError(
127
+ `Mock provider module must stay inside packageRoot ${packageRoot}: ${filePath}`,
128
+ );
129
+ }
130
+
131
+ const realPackageRoot = fs.realpathSync(packageRoot);
132
+ const realFilePath = fs.realpathSync(filePath);
133
+ if (!isPathInside(realPackageRoot, realFilePath)) {
134
+ throw new TypeError(
135
+ `Mock provider module must stay inside packageRoot ${packageRoot}: ${filePath}`,
136
+ );
137
+ }
138
+
139
+ return {
140
+ href: pathToFileURL(realFilePath).href,
141
+ filePath: realFilePath,
142
+ packageRoot: realPackageRoot,
143
+ };
144
+ }
145
+
146
+ /**
147
+ * Load trusted upper-framework providers registered by the Mock launcher.
148
+ * Provider list is rebuilt by the launcher; inherited values are not trusted.
149
+ */
150
+ export async function loadProviderModules(context, options = {}) {
151
+ const moduleEntries = options.providerModules
152
+ ?? parseProviderModuleEntries(process.env.SOMA_MOCK_PROVIDER_MODULES);
153
+ const providers = [];
154
+ const names = new Set();
155
+
156
+ for (const entry of moduleEntries) {
157
+ const resolved = resolveProviderModuleEntry(entry);
158
+ const module = await import(resolved.href);
159
+ if (typeof module.createSomaMockProvider !== 'function') {
160
+ throw new TypeError(
161
+ `Mock provider must export createSomaMockProvider(context): ${resolved.filePath}`,
162
+ );
163
+ }
164
+ const provider = await module.createSomaMockProvider(context);
165
+ if (!provider || typeof provider !== 'object' || Array.isArray(provider)) {
166
+ throw new TypeError(`createSomaMockProvider must return a provider object: ${resolved.filePath}`);
167
+ }
168
+ const name = typeof provider.name === 'string' ? provider.name.trim() : '';
169
+ if (!name) {
170
+ throw new TypeError(`Mock provider name must be a non-empty string: ${resolved.filePath}`);
171
+ }
172
+ if (names.has(name)) {
173
+ throw new TypeError(`Duplicate Mock provider name: ${name}`);
174
+ }
175
+ names.add(name);
176
+ const handlers = Array.isArray(provider.handlers) ? provider.handlers : null;
177
+ if (!handlers) {
178
+ throw new TypeError(`Mock provider ${name} handlers must be an array`);
179
+ }
180
+ providers.push({
181
+ name,
182
+ filePath: resolved.filePath,
183
+ packageRoot: resolved.packageRoot,
184
+ handlers,
185
+ });
186
+ }
187
+
188
+ return providers;
189
+ }
190
+
191
+ /**
192
+ * Precedence is deliberate: runtime server.use overrides are prepended by MSW,
193
+ * registered providers win over App handlers, App handlers win over declarative
194
+ * JSON/Schema routes, and catch-all prevents accidental network.
195
+ */
196
+ export async function createMockHandlers(context, options = {}) {
197
+ const providers = await loadProviderModules(context, options);
198
+ const hostPlugin = await loadHostMockHandlers(context);
199
+ const registry = createRegistryHandlers(context);
200
+ return {
201
+ registry,
202
+ hostPlugin,
203
+ providers,
204
+ handlers: [
205
+ ...providers.flatMap((provider) => provider.handlers),
206
+ ...hostPlugin.handlers,
207
+ ...registry.jsonHandlers,
208
+ ...registry.schemaHandlers,
209
+ createCatchAllHandler(context),
210
+ ],
211
+ };
212
+ }