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.
Files changed (70) hide show
  1. package/README.md +2 -2
  2. package/bin/soma.cjs +1 -1
  3. package/bin/soma.ts +64 -15
  4. package/core/server/api/dispatch-service-api.ts +212 -0
  5. package/core/server/api/load-host-service.ts +230 -56
  6. package/core/server/api/service-path.ts +79 -14
  7. package/core/server/engines/style/candidate-guard.ts +57 -0
  8. package/core/server/engines/style/index.ts +1 -1
  9. package/core/server/engines/style/tailwind-adapter.ts +83 -16
  10. package/core/server/host/source-packages.cjs +98 -30
  11. package/core/server/host/source-packages.ts +12 -5
  12. package/core/server/index.ts +39 -17
  13. package/core/server/infra/cache/ServerFileCache.ts +138 -25
  14. package/core/server/node.ts +32 -8
  15. package/dist/cli/soma.js +68 -14
  16. package/dist/host-native/aot-builder.cjs +852 -0
  17. package/dist/host-native/native-server.cjs +15341 -0
  18. package/dist/types/server/api/dispatch-service-api.d.ts +18 -0
  19. package/dist/types/server/api/load-host-service.d.ts +7 -2
  20. package/dist/types/server/api/service-path.d.ts +21 -1
  21. package/dist/types/server/engines/style/candidate-guard.d.ts +10 -0
  22. package/dist/types/server/engines/style/index.d.ts +1 -1
  23. package/dist/types/server/engines/style/tailwind-adapter.d.ts +12 -0
  24. package/dist/types/server/host/source-packages.d.cts +13 -1
  25. package/dist/types/server/host/source-packages.d.ts +7 -4
  26. package/dist/types/server/index.d.ts +18 -17
  27. package/dist/types/server/infra/cache/ServerFileCache.d.ts +28 -5
  28. package/dist/types/server/node.d.ts +10 -7
  29. package/host-native/bin/host-native.cjs +204 -0
  30. package/host-native/client/browser-entry.ts +499 -0
  31. package/{host-next/app → host-native/client}/page-access.ts +12 -0
  32. package/host-native/client/router-bridge.ts +120 -0
  33. package/host-native/src/aot-builder.ts +486 -0
  34. package/host-native/src/csp-headers.ts +75 -0
  35. package/host-native/src/host-prepare.ts +123 -0
  36. package/{host-next/app/soma/manifest/route.ts → host-native/src/manifest-http.ts} +10 -10
  37. package/host-native/src/native-server.ts +691 -0
  38. package/host-native/src/page-http.ts +223 -0
  39. package/host-native/src/public-packages.cjs +167 -0
  40. package/{host-next/app/api/soma-registry/[...path]/route.ts → host-native/src/registry-handler.ts} +17 -19
  41. package/{host-next → host-native}/src/shell-routes.cjs +23 -13
  42. package/host-native/src/static-file.ts +172 -0
  43. package/host-native/src/workspace.ts +185 -0
  44. package/{host-next/app → host-native/styles}/globals.css +2 -2
  45. package/package.json +12 -31
  46. package/tsconfig.json +1 -1
  47. package/host-next/app/SomaPageClient.tsx +0 -359
  48. package/host-next/app/[...path]/page.tsx +0 -22
  49. package/host-next/app/api/[...path]/route.ts +0 -98
  50. package/host-next/app/components/SomaHostPage.tsx +0 -128
  51. package/host-next/app/components/SomaHydrationShell.tsx +0 -20
  52. package/host-next/app/components/SomaPageClientBoundary.tsx +0 -13
  53. package/host-next/app/components/SomaPageForbidden.tsx +0 -19
  54. package/host-next/app/favicon.ico/route.ts +0 -13
  55. package/host-next/app/layout.tsx +0 -27
  56. package/host-next/app/page.tsx +0 -9
  57. package/host-next/app/router-bridge.ts +0 -42
  58. package/host-next/app/soma/[...path]/route.ts +0 -9
  59. package/host-next/app/soma/_shared/host-prepare.ts +0 -33
  60. package/host-next/app/soma/_shared/page-http.ts +0 -86
  61. package/host-next/app/soma/page/route.ts +0 -36
  62. package/host-next/app/soma/route.ts +0 -9
  63. package/host-next/app/soma-runtime/[...file]/route.ts +0 -21
  64. package/host-next/app/soma-runtime/_shared/static-file.ts +0 -89
  65. package/host-next/bin/host-next.cjs +0 -60
  66. package/host-next/instrumentation.ts +0 -18
  67. package/host-next/next-env.d.ts +0 -7
  68. package/host-next/next.config.js +0 -410
  69. package/host-next/proxy.ts +0 -43
  70. package/host-next/src/workspace.ts +0 -543
@@ -1,543 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- /** Next 宿主壳目录(soma-core/host-next):源码在 src/ 下(上一级)。 */
5
- export const hostPackageRoot = path.resolve(__dirname, '..');
6
-
7
- /**
8
- * soma-core 包根:壳目录的上一级(壳与 core 同包)。
9
- * Next 工作区里链接它的 core/ 与 global.d.ts,壳代码对 `../core/...` 的相对引用照旧可用。
10
- */
11
- export const coreRoot = path.resolve(hostPackageRoot, '..');
12
-
13
- /** 工作区 node_modules 的来源:soma-core 包自己的 node_modules(依赖被提升时可能不存在,此时靠向上解析)。 */
14
- function resolvePackageNodeModules(): string | null {
15
- for (const root of [coreRoot]) {
16
- const candidate = path.join(root, 'node_modules');
17
- if (fs.existsSync(candidate)) return candidate;
18
- }
19
- return null;
20
- }
21
-
22
- function lstatIfPresent(filePath: string): fs.Stats | null {
23
- try {
24
- return fs.lstatSync(filePath);
25
- } catch (error) {
26
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
27
- throw error;
28
- }
29
- }
30
-
31
- function rejectWorkspaceSymlink(filePath: string): fs.Stats | null {
32
- const stat = lstatIfPresent(filePath);
33
- if (stat?.isSymbolicLink()) {
34
- throw new Error(`[soma] Refusing symbolic link inside the SOMA Next workspace: ${filePath}`);
35
- }
36
- return stat;
37
- }
38
-
39
- export function resolveNextBin(): string | null {
40
- const searchPaths = [hostPackageRoot, path.join(hostPackageRoot, '..'), path.join(hostPackageRoot, '../..'), coreRoot];
41
- for (const base of searchPaths) {
42
- try {
43
- return require.resolve('next/dist/bin/next', { paths: [base] });
44
- } catch {
45
- /* try next */
46
- }
47
- }
48
- return null;
49
- }
50
-
51
- function writeFileIfChanged(filePath: string, content: string): void {
52
- const stat = rejectWorkspaceSymlink(filePath);
53
- if (stat && fs.readFileSync(filePath, 'utf8') === content) {
54
- return;
55
- }
56
- fs.writeFileSync(filePath, content);
57
- }
58
-
59
- function linkOrCopy(targetPath: string, linkPath: string, type: 'dir' | 'file'): void {
60
- const existing = lstatIfPresent(linkPath);
61
- if (existing) {
62
- const stat = existing;
63
- if (stat.isSymbolicLink() && path.resolve(path.dirname(linkPath), fs.readlinkSync(linkPath)) === targetPath) {
64
- return;
65
- }
66
- if (stat.isSymbolicLink()) {
67
- throw new Error(`[soma] Refusing symbolic link inside the SOMA Next workspace: ${linkPath}`);
68
- }
69
- removeManaged(linkPath, { recursive: true, force: true });
70
- }
71
-
72
- try {
73
- fs.symlinkSync(targetPath, linkPath, process.platform === 'win32' && type === 'dir' ? 'junction' : type);
74
- } catch {
75
- rejectWorkspaceSymlink(linkPath);
76
- if (type === 'dir') {
77
- fs.cpSync(targetPath, linkPath, { recursive: true });
78
- } else {
79
- fs.copyFileSync(targetPath, linkPath);
80
- }
81
- }
82
- }
83
-
84
- /**
85
- * Copy a single framework-owned file into the workspace (no symlink). Used for files Next/webpack
86
- * resolves relative imports from: a symlink resolves to its real path, so `./core/...` would be
87
- * looked up beside the source instead of inside the workspace. Runs on every assembly, so source
88
- * changes are picked up (content compared, rewritten only when different). An existing symlink is
89
- * replaced only when it points at one of `ownedSources` (older workspaces linked these files);
90
- * any other symlink is refused.
91
- */
92
- function copyFileIntoWorkspace(sourcePath: string, destPath: string, ownedSources: readonly string[]): void {
93
- const existing = lstatIfPresent(destPath);
94
- if (existing?.isSymbolicLink()) {
95
- const linkedTarget = path.resolve(path.dirname(destPath), fs.readlinkSync(destPath));
96
- if (!ownedSources.some((owned) => path.resolve(owned) === linkedTarget)) {
97
- throw new Error(`[soma] Refusing symbolic link inside the SOMA Next workspace: ${destPath}`);
98
- }
99
- fs.unlinkSync(destPath);
100
- } else if (existing?.isDirectory()) {
101
- removeManaged(destPath, { recursive: true, force: true });
102
- }
103
- writeFileIfChanged(destPath, fs.readFileSync(sourcePath, 'utf8'));
104
- }
105
-
106
- function copyDirectory(targetPath: string, destPath: string): void {
107
- const existingDest = rejectWorkspaceSymlink(destPath);
108
- if (existingDest) {
109
- if (!existingDest.isDirectory()) {
110
- removeManaged(destPath, { recursive: true, force: true });
111
- }
112
- }
113
- fs.mkdirSync(destPath, { recursive: true });
114
-
115
- const sourceEntries = new Set<string>();
116
- for (const entry of fs.readdirSync(targetPath, { withFileTypes: true })) {
117
- sourceEntries.add(entry.name);
118
- const sourceEntry = path.join(targetPath, entry.name);
119
- const destEntry = path.join(destPath, entry.name);
120
- if (entry.isDirectory()) {
121
- copyDirectory(sourceEntry, destEntry);
122
- } else {
123
- const destStat = rejectWorkspaceSymlink(destEntry);
124
- if (destStat?.isDirectory()) {
125
- removeManaged(destEntry, { recursive: true, force: true });
126
- }
127
- fs.copyFileSync(sourceEntry, destEntry);
128
- }
129
- }
130
-
131
- for (const entry of fs.readdirSync(destPath, { withFileTypes: true })) {
132
- if (!sourceEntries.has(entry.name)) {
133
- const stalePath = path.join(destPath, entry.name);
134
- rejectWorkspaceSymlink(stalePath);
135
- removeManaged(stalePath, { recursive: true, force: true });
136
- }
137
- }
138
- }
139
-
140
- function listTopLevelPackageNames(nodeModulesDir: string): string[] {
141
- if (!fs.existsSync(nodeModulesDir)) {
142
- return [];
143
- }
144
-
145
- const names: string[] = [];
146
- for (const entry of fs.readdirSync(nodeModulesDir, { withFileTypes: true })) {
147
- if (entry.name.startsWith('.')) {
148
- continue;
149
- }
150
- if (entry.name.startsWith('@')) {
151
- const scopeDir = path.join(nodeModulesDir, entry.name);
152
- if (!entry.isDirectory()) {
153
- continue;
154
- }
155
- for (const scoped of fs.readdirSync(scopeDir)) {
156
- if (scoped.startsWith('.')) {
157
- continue;
158
- }
159
- names.push(`${entry.name}/${scoped}`);
160
- }
161
- continue;
162
- }
163
- names.push(entry.name);
164
- }
165
- return names;
166
- }
167
-
168
- function readPackageDependencyNames(): string[] {
169
- const names = new Set<string>();
170
- for (const root of [coreRoot]) {
171
- const packageJsonPath = path.join(root, 'package.json');
172
- if (!fs.existsSync(packageJsonPath)) continue;
173
- try {
174
- const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as {
175
- dependencies?: Record<string, string>;
176
- devDependencies?: Record<string, string>;
177
- peerDependencies?: Record<string, string>;
178
- };
179
- for (const name of Object.keys({
180
- ...(pkg.dependencies ?? {}),
181
- ...(pkg.devDependencies ?? {}),
182
- ...(pkg.peerDependencies ?? {}),
183
- })) names.add(name);
184
- } catch {
185
- /* unreadable package.json: skip */
186
- }
187
- }
188
- return [...names];
189
- }
190
-
191
- function toPosixRelative(fromDir: string, toPath: string): string {
192
- let rel = path.relative(fromDir, toPath).replace(/\\/g, '/');
193
- if (!rel.startsWith('.')) {
194
- rel = `./${rel}`;
195
- }
196
- return rel;
197
- }
198
-
199
- /** Symlink/junction only — never copy a full node_modules tree. */
200
- function symlinkDirOnly(targetPath: string, linkPath: string): boolean {
201
- if (!fs.existsSync(targetPath)) {
202
- return false;
203
- }
204
-
205
- const existing = lstatIfPresent(linkPath);
206
- if (existing) {
207
- const stat = existing;
208
- if (
209
- stat.isSymbolicLink() &&
210
- path.resolve(path.dirname(linkPath), fs.readlinkSync(linkPath)) === targetPath
211
- ) {
212
- return true;
213
- }
214
- if (stat.isSymbolicLink()) {
215
- throw new Error(`[soma] Refusing symbolic link inside the SOMA Next workspace: ${linkPath}`);
216
- }
217
- removeManaged(linkPath, { recursive: true, force: true });
218
- }
219
-
220
- try {
221
- fs.symlinkSync(targetPath, linkPath, process.platform === 'win32' ? 'junction' : 'dir');
222
- return true;
223
- } catch {
224
- return false;
225
- }
226
- }
227
-
228
- /** Fallback when linking the whole node_modules fails: per-package symlinks only. */
229
- function ensureShallowNodeModulesLinks(workspaceDir: string, packageNodeModules: string): boolean {
230
- const workspaceNodeModules = path.join(workspaceDir, 'node_modules');
231
- const existing = rejectWorkspaceSymlink(workspaceNodeModules);
232
- if (existing) {
233
- removeManaged(workspaceNodeModules, { recursive: true, force: true });
234
- }
235
- fs.mkdirSync(workspaceNodeModules, { recursive: true });
236
-
237
- let linked = 0;
238
- for (const name of listTopLevelPackageNames(packageNodeModules)) {
239
- const target = path.join(packageNodeModules, name);
240
- if (!fs.existsSync(target)) {
241
- continue;
242
- }
243
- const linkPath = path.join(workspaceNodeModules, name);
244
- fs.mkdirSync(path.dirname(linkPath), { recursive: true });
245
- try {
246
- fs.symlinkSync(target, linkPath, process.platform === 'win32' ? 'junction' : 'dir');
247
- linked += 1;
248
- } catch {
249
- /* skip packages that cannot be linked */
250
- }
251
- }
252
- return linked > 0;
253
- }
254
-
255
- function buildCoreDependencyPaths(workspaceDir: string): Record<string, string[]> {
256
- const paths: Record<string, string[]> = {};
257
- const nodeModulesDir = resolvePackageNodeModules();
258
- if (nodeModulesDir === null) {
259
- return paths;
260
- }
261
-
262
- const names = new Set([
263
- ...readPackageDependencyNames(),
264
- ...listTopLevelPackageNames(nodeModulesDir),
265
- ]);
266
-
267
- for (const name of names) {
268
- const target = path.join(nodeModulesDir, name);
269
- if (!fs.existsSync(target)) {
270
- continue;
271
- }
272
- const rel = toPosixRelative(workspaceDir, target);
273
- paths[name] = [rel];
274
- paths[`${name}/*`] = [`${rel}/*`];
275
- }
276
- return paths;
277
- }
278
-
279
- function buildNextWorkspaceTsconfig(
280
- workspaceDir: string,
281
- hasWorkspaceNodeModules: boolean,
282
- ): string {
283
- const paths: Record<string, string[]> = {
284
- '@core/*': ['./core/*'],
285
- '@/*': ['./*'],
286
- };
287
- const compilerOptions: Record<string, unknown> = {
288
- target: 'ES2020',
289
- lib: ['dom', 'dom.iterable', 'esnext'],
290
- allowJs: true,
291
- skipLibCheck: true,
292
- strict: true,
293
- noEmit: true,
294
- esModuleInterop: true,
295
- module: 'esnext',
296
- moduleResolution: 'bundler',
297
- resolveJsonModule: true,
298
- isolatedModules: true,
299
- jsx: 'preserve',
300
- incremental: true,
301
- experimentalDecorators: true,
302
- emitDecoratorMetadata: true,
303
- plugins: [{ name: 'next' }],
304
- baseUrl: '.',
305
- paths,
306
- };
307
-
308
- if (!hasWorkspaceNodeModules) {
309
- Object.assign(paths, buildCoreDependencyPaths(workspaceDir));
310
- const nodeModulesDir = resolvePackageNodeModules();
311
- const typesRoot = nodeModulesDir === null ? '' : path.join(nodeModulesDir, '@types');
312
- if (typesRoot && fs.existsSync(typesRoot)) {
313
- compilerOptions.typeRoots = [toPosixRelative(workspaceDir, typesRoot)];
314
- }
315
- }
316
-
317
- return `${JSON.stringify(
318
- {
319
- compilerOptions,
320
- include: [
321
- 'next-env.d.ts',
322
- 'global.d.ts',
323
- '**/*.ts',
324
- '**/*.tsx',
325
- '.next/types/**/*.ts',
326
- ],
327
- exclude: ['node_modules'],
328
- },
329
- null,
330
- 2,
331
- )}\n`;
332
- }
333
-
334
- function ensureWorkspaceNodeModules(workspaceDir: string): boolean {
335
- const packageNodeModules = resolvePackageNodeModules();
336
- const workspaceNodeModules = path.join(workspaceDir, 'node_modules');
337
-
338
- if (packageNodeModules === null) {
339
- const existing = rejectWorkspaceSymlink(workspaceNodeModules);
340
- if (existing) {
341
- removeManaged(workspaceNodeModules, { recursive: true, force: true });
342
- }
343
- return false;
344
- }
345
-
346
- if (symlinkDirOnly(packageNodeModules, workspaceNodeModules)) {
347
- return true;
348
- }
349
-
350
- return ensureShallowNodeModulesLinks(workspaceDir, packageNodeModules);
351
- }
352
-
353
- function canonicalizePotentialPath(filePath: string): string {
354
- const missingSegments: string[] = [];
355
- let existingPath = path.resolve(filePath);
356
- while (!fs.existsSync(existingPath)) {
357
- const parent = path.dirname(existingPath);
358
- if (parent === existingPath) break;
359
- missingSegments.unshift(path.basename(existingPath));
360
- existingPath = parent;
361
- }
362
- const canonicalBase = fs.existsSync(existingPath)
363
- ? fs.realpathSync(existingPath)
364
- : existingPath;
365
- return path.join(canonicalBase, ...missingSegments);
366
- }
367
-
368
- function pathsOverlap(left: string, right: string): boolean {
369
- const contains = (parent: string, child: string) => (
370
- child === parent || child.startsWith(`${parent}${path.sep}`)
371
- );
372
- return contains(left, right) || contains(right, left);
373
- }
374
-
375
- /**
376
- * runtime 根的保护(R-18):工作区重建(复制 / 链接 / 清理陈旧文件)是对工作区内框架自有路径的删除,
377
- * 任何会碰到 runtime 根(等于、在其内或包含它)的删除一律拒绝——runtime 根里是注入页、绑定、预热与静态产物,不是可重建的东西。
378
- * 根在 `ensureNextWorkspace` 入口解析一次(core 的唯一实现 root.cjs),解析失败(越界由 core 启动期拒绝)则不设保护。
379
- */
380
- let protectedRuntimeRoot: string | null = null;
381
-
382
- export function resolveRuntimeRootForGuard(hostDir: string, env: NodeJS.ProcessEnv = process.env): string | null {
383
- try {
384
- const { resolveSomaRuntimeRoot } = require(path.join(coreRoot, 'core/server/runtime-space/root.cjs')) as {
385
- resolveSomaRuntimeRoot(hostDir: string, env?: NodeJS.ProcessEnv): string;
386
- };
387
- return canonicalizePotentialPath(resolveSomaRuntimeRoot(hostDir, env));
388
- } catch {
389
- return null;
390
- }
391
- }
392
-
393
- /** 删除工作区内的框架自有路径;碰到 runtime 根即抛错,不删 */
394
- function removeManaged(target: string, options: fs.RmOptions): void {
395
- if (protectedRuntimeRoot !== null && pathsOverlap(canonicalizePotentialPath(target), protectedRuntimeRoot)) {
396
- throw new Error(`[soma] Refusing to remove ${target}: it overlaps the SOMA runtime root ${protectedRuntimeRoot}. Move SOMA_RUNTIME_DIR out of the Next workspace's framework-owned paths.`);
397
- }
398
- fs.rmSync(target, options);
399
- }
400
-
401
- /** 工作区里由框架重建的顶层路径;runtime 根不得与其中任何一个重叠 */
402
- const WORKSPACE_MANAGED_ENTRIES = ['app', 'core', 'public', 'node_modules', 'global.d.ts', 'proxy.ts', 'middleware.ts', 'instrumentation.ts', 'next.config.js', 'tsconfig.json', 'package.json'] as const;
403
-
404
- export function assertRuntimeRootOutsideManaged(workspaceDir: string, runtimeRoot: string | null): void {
405
- if (runtimeRoot === null) return;
406
- const canonicalRuntimeRoot = canonicalizePotentialPath(runtimeRoot);
407
- for (const name of WORKSPACE_MANAGED_ENTRIES) {
408
- if (pathsOverlap(canonicalizePotentialPath(path.join(workspaceDir, name)), canonicalRuntimeRoot)) {
409
- throw new Error(`[soma] SOMA runtime root ${runtimeRoot} overlaps the Next workspace path ${name}, which is rebuilt on every start. Set SOMA_RUNTIME_DIR to a directory outside the workspace's framework-owned paths (default: <host>/.soma/runtime).`);
410
- }
411
- }
412
- }
413
-
414
- function assertReusableWorkspaceDir(workspaceDir: string): void {
415
- const workspaceStat = rejectWorkspaceSymlink(workspaceDir);
416
- if (!workspaceStat) return;
417
- if (!workspaceStat.isDirectory()) {
418
- throw new Error('[soma] SOMA_NEXT_WORKSPACE_DIR must resolve to a directory.');
419
- }
420
- if (fs.readdirSync(workspaceDir).length === 0) return;
421
-
422
- let markerName: unknown;
423
- const markerPath = path.join(workspaceDir, 'package.json');
424
- const markerStat = rejectWorkspaceSymlink(markerPath);
425
- try {
426
- if (!markerStat?.isFile()) throw new Error('workspace marker is not a file');
427
- const marker = JSON.parse(fs.readFileSync(markerPath, 'utf8')) as {
428
- name?: unknown;
429
- };
430
- markerName = marker.name;
431
- } catch {
432
- markerName = undefined;
433
- }
434
- if (markerName !== 'soma-next-workspace') {
435
- throw new Error(
436
- '[soma] SOMA_NEXT_WORKSPACE_DIR points to a non-empty directory that is not a SOMA Next workspace.',
437
- );
438
- }
439
- }
440
-
441
- function assertDefaultWorkspacePath(hostDir: string, workspaceDir: string): void {
442
- let current = path.resolve(hostDir);
443
- for (const segment of ['.soma', 'next']) {
444
- current = path.join(current, segment);
445
- rejectWorkspaceSymlink(current);
446
- }
447
- const canonicalHostDir = canonicalizePotentialPath(hostDir);
448
- const expectedWorkspaceDir = path.join(canonicalHostDir, '.soma', 'next');
449
- if (canonicalizePotentialPath(workspaceDir) !== expectedWorkspaceDir) {
450
- throw new Error('[soma] Default SOMA Next workspace escaped SOMA_HOST_DIR.');
451
- }
452
- }
453
-
454
- function resolveNextWorkspaceDir(hostDir: string): string {
455
- const configured = process.env.SOMA_NEXT_WORKSPACE_DIR;
456
- const usesDefaultWorkspace = configured === undefined;
457
- if (!usesDefaultWorkspace && !configured.trim()) {
458
- throw new Error('[soma] SOMA_NEXT_WORKSPACE_DIR must be a non-empty path when set.');
459
- }
460
-
461
- const requestedWorkspaceDir = usesDefaultWorkspace
462
- ? path.resolve(hostDir, '.soma', 'next')
463
- : path.resolve(hostDir, configured);
464
- if (usesDefaultWorkspace) {
465
- assertDefaultWorkspacePath(hostDir, requestedWorkspaceDir);
466
- } else {
467
- rejectWorkspaceSymlink(requestedWorkspaceDir);
468
- }
469
- const workspaceDir = canonicalizePotentialPath(requestedWorkspaceDir);
470
- const canonicalWorkspaceDir = canonicalizePotentialPath(workspaceDir);
471
- const filesystemRoot = path.parse(canonicalWorkspaceDir).root;
472
- const canonicalHostDir = canonicalizePotentialPath(hostDir);
473
- const canonicalPackageRoots = [hostPackageRoot, coreRoot].map(canonicalizePotentialPath);
474
- if (canonicalWorkspaceDir === filesystemRoot) {
475
- throw new Error('[soma] SOMA Next workspace must not resolve to a filesystem root.');
476
- }
477
- if (!usesDefaultWorkspace && (
478
- pathsOverlap(canonicalWorkspaceDir, canonicalHostDir)
479
- || canonicalPackageRoots.some((root) => pathsOverlap(canonicalWorkspaceDir, root))
480
- )) {
481
- throw new Error(
482
- '[soma] SOMA_NEXT_WORKSPACE_DIR must be isolated from SOMA_HOST_DIR and the soma-core package.',
483
- );
484
- }
485
- assertReusableWorkspaceDir(workspaceDir);
486
- return workspaceDir;
487
- }
488
-
489
- /** Mount Host `public/` into the Next workspace so files are served at `/…`. */
490
- function ensureHostPublicAssets(hostDir: string, workspaceDir: string): void {
491
- const hostPublic = path.join(hostDir, 'public');
492
- const workspacePublic = path.join(workspaceDir, 'public');
493
- const hostPublicStat = lstatIfPresent(hostPublic);
494
- if (hostPublicStat?.isDirectory()) {
495
- linkOrCopy(hostPublic, workspacePublic, 'dir');
496
- return;
497
- }
498
- const existing = lstatIfPresent(workspacePublic);
499
- if (existing) {
500
- removeManaged(workspacePublic, { recursive: true, force: true });
501
- }
502
- }
503
-
504
- export function ensureNextWorkspace(hostDir: string): string {
505
- const workspaceDir = resolveNextWorkspaceDir(hostDir);
506
- const runtimeRoot = resolveRuntimeRootForGuard(hostDir);
507
- assertRuntimeRootOutsideManaged(workspaceDir, runtimeRoot);
508
- protectedRuntimeRoot = runtimeRoot;
509
- fs.mkdirSync(workspaceDir, { recursive: true });
510
- writeFileIfChanged(
511
- path.join(workspaceDir, 'package.json'),
512
- JSON.stringify({ private: true, name: 'soma-next-workspace' }, null, 2) + '\n',
513
- );
514
-
515
- copyDirectory(path.join(hostPackageRoot, 'app'), path.join(workspaceDir, 'app'));
516
- linkOrCopy(path.join(coreRoot, 'core'), path.join(workspaceDir, 'core'), 'dir');
517
- // proxy.ts imports `./core/...`; copied (not linked) so webpack resolves it inside the workspace.
518
- copyFileIntoWorkspace(path.join(hostPackageRoot, 'proxy.ts'), path.join(workspaceDir, 'proxy.ts'), [
519
- path.join(hostPackageRoot, 'proxy.ts'),
520
- path.join(coreRoot, 'proxy.ts'),
521
- ]);
522
- // instrumentation.ts(服务启动钩子入口)同理复制:它的 `./core/...` 相对引用要在工作区内解析。
523
- copyFileIntoWorkspace(
524
- path.join(hostPackageRoot, 'instrumentation.ts'),
525
- path.join(workspaceDir, 'instrumentation.ts'),
526
- [path.join(hostPackageRoot, 'instrumentation.ts')],
527
- );
528
- linkOrCopy(path.join(coreRoot, 'global.d.ts'), path.join(workspaceDir, 'global.d.ts'), 'file');
529
- ensureHostPublicAssets(hostDir, workspaceDir);
530
-
531
- const hasWorkspaceNodeModules = ensureWorkspaceNodeModules(workspaceDir);
532
-
533
- writeFileIfChanged(
534
- path.join(workspaceDir, 'next.config.js'),
535
- `module.exports = require(${JSON.stringify(path.join(hostPackageRoot, 'next.config.js'))});\n`,
536
- );
537
- writeFileIfChanged(
538
- path.join(workspaceDir, 'tsconfig.json'),
539
- buildNextWorkspaceTsconfig(workspaceDir, hasWorkspaceNodeModules),
540
- );
541
-
542
- return workspaceDir;
543
- }