soma-core 2.2.6 → 2.2.7

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 (59) hide show
  1. package/core/build/compiler/soma-precompile.js +66 -10
  2. package/core/client/container/IContainerAdapter.ts +4 -0
  3. package/core/client/container/SomaContainerAdapter.ts +43 -2
  4. package/core/client/data/data-object-resolver.ts +7 -3
  5. package/core/client/engine/event-engine.ts +28 -3
  6. package/core/client/engine/soma-bootstrap.ts +2 -1
  7. package/core/client/infra/notify/DefaultNotifyService.ts +2 -2
  8. package/core/client/parser/confirm-spec.ts +99 -6
  9. package/core/client/parser/data-config-parser.ts +1 -1
  10. package/core/client/parser/pipeline-parser.ts +2 -1
  11. package/core/client/render-ports/hide-transition.ts +9 -0
  12. package/core/client/render-ports/index.ts +4 -0
  13. package/core/client/render-ports/notify-renderer.ts +2 -1
  14. package/core/index.ts +16 -4
  15. package/core/server/api/load-host-service.ts +3 -0
  16. package/core/server/api/paged-list.ts +259 -0
  17. package/core/server/host/empty-host-bootstrap.mjs +3 -0
  18. package/core/server/host/host-assembly.ts +3 -0
  19. package/core/server/host/source-aliases.cjs +345 -0
  20. package/core/server/host/source-aliases.ts +32 -0
  21. package/core/server/host/source-packages.cjs +1 -0
  22. package/core/server/infra/cache/ServerFileCache.ts +4 -1
  23. package/core/server/node.ts +10 -0
  24. package/core/server/runtime-space/inject.ts +4 -1
  25. package/core/shared/core-diagnostic-codes.ts +6 -0
  26. package/core/shared/data-declaration-checks.ts +29 -3
  27. package/core/shared/registry-generated/diagnostic-registry-index.ts +5 -0
  28. package/core/shared/registry-generated/diagnostic-registry.ts +35 -0
  29. package/core/shared/registry-generated/limits.ts +18 -2
  30. package/core/shared/registry-generated/std-grammar.ts +1 -1
  31. package/core/shared/types/data-config.types.ts +3 -1
  32. package/core/shared/types/event.types.ts +9 -0
  33. package/dist/browser/soma-runtime.js +169 -19
  34. package/dist/core/index.cjs +190 -19
  35. package/dist/host-native/aot-builder.cjs +284 -0
  36. package/dist/host-native/native-server.cjs +344 -10
  37. package/dist/lsp/component-tree.cjs +66 -10
  38. package/dist/types/client/container/IContainerAdapter.d.ts +3 -0
  39. package/dist/types/client/container/SomaContainerAdapter.d.ts +5 -0
  40. package/dist/types/client/data/data-object-resolver.d.ts +2 -0
  41. package/dist/types/client/parser/confirm-spec.d.ts +27 -3
  42. package/dist/types/client/render-ports/hide-transition.d.ts +9 -0
  43. package/dist/types/client/render-ports/index.d.ts +4 -0
  44. package/dist/types/client/render-ports/notify-renderer.d.ts +2 -1
  45. package/dist/types/index.d.ts +4 -4
  46. package/dist/types/server/api/paged-list.d.ts +101 -0
  47. package/dist/types/server/host/source-aliases.d.cts +53 -0
  48. package/dist/types/server/host/source-aliases.d.ts +30 -0
  49. package/dist/types/server/host/source-packages.d.cts +2 -0
  50. package/dist/types/server/node.d.ts +1 -0
  51. package/dist/types/shared/core-diagnostic-codes.d.ts +1 -1
  52. package/dist/types/shared/registry-generated/diagnostic-registry.d.ts +30 -0
  53. package/dist/types/shared/registry-generated/limits.d.ts +14 -0
  54. package/dist/types/shared/registry-generated/std-grammar.d.ts +1 -1
  55. package/dist/types/shared/types/data-config.types.d.ts +3 -1
  56. package/dist/types/shared/types/event.types.d.ts +8 -0
  57. package/host-native/src/aot-builder.ts +23 -0
  58. package/host-native/styles/globals.css +30 -28
  59. package/package.json +13 -2
@@ -10,6 +10,7 @@ import {
10
10
  } from "../host/source-packages";
11
11
  import { ensureNodeServerOnlyInterop, getJitiFactory } from "../host/host-assembly";
12
12
  import { currentHostDir } from "../host/host-dir";
13
+ import { getSomaSourceRootAliases } from "../host/source-aliases";
13
14
 
14
15
  export type AotServiceResolver = (routeKey: string, segments: readonly string[]) => unknown | Promise<unknown>;
15
16
 
@@ -121,6 +122,8 @@ function getJitiLoader(
121
122
  moduleCache: !reload,
122
123
  requireCache: !reload,
123
124
  alias: {
125
+ // 源码根别名(soma.sourceRoots):jiti 只匹配带斜杠的整段前缀,不劫持裸名;固定别名在后,不可被覆盖
126
+ ...getSomaSourceRootAliases(normalizedHostDir),
124
127
  "@core": getCoreDir(),
125
128
  "@soma-host": normalizedWebRoot,
126
129
  "@soma-api": normalizedApiRoot,
@@ -0,0 +1,259 @@
1
+ // 服务端分页整形助手(协议中性、纯函数、无 node 依赖;服务端薄壳 / 手写 service 用,不进浏览器包)。
2
+ //
3
+ // 页面的列表数据读取约定:`GET ?pageNo=&pageSize=&<筛选字段>=…`(键名可用 pageKey / sizeKey 改,筛选字段名即字段名,空值不带),
4
+ // 期望响应 `{ rows, total }`。旧后台常见三种不一样,这里只做「响应形状翻译」,不碰业务、不发请求(请求由调用方的 load 函数发):
5
+ // 1 后端页码键叫 page / pageNum,页长叫 size / limit,筛选参数名与字段名不同 -> createPagedListAdapter 的 upstream* 与 filterMap;
6
+ // 2 响应是业务信封(失败判定 / 数据位置由调用方声明:failWhen / messagePath / dataPath),列表键与总数键不统一
7
+ // -> unwrapResponseEnvelope + 适配器的 rowsPath / totalPaths;
8
+ // 3 游标分页(cursor / limit / nextCursor),没有页码 -> cursorPageWindow(沿游标走到第 N 页)。
9
+ //
10
+ // 信封失败判定复用 `envelopeFailureOf`(与 `data:` 的 failWhen 同一份实现),不另写第二套谓词求值。
11
+
12
+ import { envelopeFailureOf, type SomaEnvelopeFailure } from '../../client/data/envelope-failure';
13
+ import { SOMA_PIPELINE_LIMITS } from '../../shared/registry-generated/limits';
14
+
15
+ type Rec = Record<string, unknown>;
16
+
17
+ const isRec = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v);
18
+
19
+ /** 缺省页长 / 页长上限(调用方可用 defaultPageSize / maxPageSize 覆盖);数字只在 design 真源 pipeline/limits.json 的 pagedList,经生成表读 */
20
+ export const SOMA_PAGED_LIST_LIMITS = {
21
+ pageSizeDefault: SOMA_PIPELINE_LIMITS.pagedList.pageSizeDefault,
22
+ pageSizeMax: SOMA_PIPELINE_LIMITS.pagedList.pageSizeMax,
23
+ } as const;
24
+
25
+ const DEFAULT_PAGE_KEY = 'pageNo';
26
+ const DEFAULT_SIZE_KEY = 'pageSize';
27
+ const RESERVED_EXTRA: readonly string[] = ['window', 'sort', 'order'];
28
+ const DEFAULT_ROW_KEYS: readonly string[] = ['list', 'records', 'rows', 'items', 'data'];
29
+ const DEFAULT_TOTAL_PATHS: readonly string[] = ['totalCount', 'total', 'count'];
30
+
31
+ function positiveInt(raw: unknown): number | null {
32
+ const n = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : Number.NaN;
33
+ return Number.isInteger(n) && n > 0 ? n : null;
34
+ }
35
+
36
+ function pathGet(root: unknown, path: string): unknown {
37
+ let cur = root;
38
+ for (const key of path.split('.')) {
39
+ if (!isRec(cur)) return undefined;
40
+ cur = cur[key];
41
+ }
42
+ return cur;
43
+ }
44
+
45
+ // ---------------------------------------------------------------- 业务信封
46
+
47
+ /** 响应信封声明:failWhen 为闭集谓词(命中 = 失败)、messagePath 为失败文案点路径、dataPath 为成功数据点路径(缺省不拆) */
48
+ export interface SomaResponseEnvelope {
49
+ failWhen?: Rec;
50
+ messagePath?: string;
51
+ dataPath?: string;
52
+ }
53
+
54
+ export type SomaUnwrappedEnvelope = { ok: true; data: unknown } | { ok: false; error: Rec };
55
+
56
+ /** 响应命中信封失败判定(没有声明 failWhen 一律不判失败) */
57
+ export function isResponseEnvelopeFailure(raw: unknown, env?: SomaResponseEnvelope): raw is Rec {
58
+ if (env?.failWhen === undefined) return false;
59
+ return envelopeFailureOf(raw, { failWhen: env.failWhen as unknown as SomaEnvelopeFailure['failWhen'] }, '') !== null;
60
+ }
61
+
62
+ /** 拆信封:失败信封原样放进 `error`;成功按 dataPath 取数据(没声明不拆) */
63
+ export function unwrapResponseEnvelope(raw: unknown, env?: SomaResponseEnvelope): SomaUnwrappedEnvelope {
64
+ if (isResponseEnvelopeFailure(raw, env)) return { ok: false, error: raw };
65
+ if (env?.dataPath === undefined) return { ok: true, data: raw };
66
+ return { ok: true, data: pathGet(raw, env.dataPath) };
67
+ }
68
+
69
+ // ---------------------------------------------------------------- 页码协议适配器
70
+
71
+ export interface PagedListAdapterOptions {
72
+ /** 请求里的页码键 / 页长键(缺省 pageNo / pageSize;其余键都当筛选) */
73
+ pageKey?: string;
74
+ sizeKey?: string;
75
+ /** 上游页码参数名(缺省 page) */
76
+ upstreamPage?: string;
77
+ /** 上游页长参数名(缺省 pageSize) */
78
+ upstreamSize?: string;
79
+ /** 响应里行数组的位置:点路径(相对拆信封后的 data),或候选键列表(取第一个数组);缺省 list / records / rows / items / data */
80
+ rowsPath?: string | readonly string[];
81
+ /** 总数的候选位置(相对拆信封后的 data);缺省 totalCount / total / count */
82
+ totalPaths?: readonly string[];
83
+ /** 筛选参数:字段名 -> 上游参数名;数组 = 同名透传的白名单;缺省收全部非保留参数同名透传 */
84
+ filterMap?: Readonly<Record<string, string>> | readonly string[];
85
+ /** 给行补主键 id:依次取这些键里第一个非空值(已有非空 id 不动) */
86
+ rowId?: string | readonly string[];
87
+ /** 缺省页长 / 页长上限(缺省 SOMA_PAGED_LIST_LIMITS) */
88
+ defaultPageSize?: number;
89
+ maxPageSize?: number;
90
+ /** 业务信封声明(由调用方显式传入;缺省按无信封处理,不读任何全局) */
91
+ envelope?: SomaResponseEnvelope;
92
+ }
93
+
94
+ export interface PagedQuery {
95
+ /** 从 1 起 */
96
+ page: number;
97
+ pageSize: number;
98
+ /** 字段名 -> 值(已去空白,空值不进) */
99
+ filters: Record<string, string>;
100
+ /** 可直接拼到上游请求的参数:页码、页长、已改名的筛选 */
101
+ upstream: Record<string, string | number>;
102
+ }
103
+
104
+ export interface PagedList {
105
+ rows: Rec[];
106
+ total: number;
107
+ }
108
+
109
+ export interface PagedListAdapter {
110
+ /** 请求里没有页码键 = 旧调用方(调用方可据此原样转交旧服务) */
111
+ hasPage(input: unknown): boolean;
112
+ readQuery(input: unknown): PagedQuery;
113
+ /** 上游响应 -> 列表;失败信封返回 { error } */
114
+ toList(raw: unknown, mapRow?: (row: Rec, index: number) => Rec): PagedList | { error: Rec };
115
+ }
116
+
117
+ function entriesOf(input: unknown): Array<[string, unknown]> {
118
+ if (input instanceof URLSearchParams) return [...input.entries()];
119
+ if (typeof input === 'string') return [...new URLSearchParams(input.includes('?') ? input.slice(input.indexOf('?') + 1) : input).entries()];
120
+ if (isRec(input)) return Object.entries(input);
121
+ return [];
122
+ }
123
+
124
+ function rowsOf(data: unknown, rowsPath: string | readonly string[] | undefined): Rec[] {
125
+ let list: unknown;
126
+ if (Array.isArray(data)) list = data;
127
+ else if (typeof rowsPath === 'string') list = pathGet(data, rowsPath);
128
+ else list = (rowsPath ?? DEFAULT_ROW_KEYS).map((key) => (isRec(data) ? data[key] : undefined)).find(Array.isArray);
129
+ return Array.isArray(list) ? list.filter(isRec) : [];
130
+ }
131
+
132
+ function totalOf(data: unknown, paths: readonly string[], fallback: number): number {
133
+ for (const path of paths) {
134
+ const v = pathGet(data, path);
135
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
136
+ if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) return Number(v);
137
+ }
138
+ return fallback;
139
+ }
140
+
141
+ /** 给行补主键:id 缺省时依次取 keys 里第一个非空值(字符串化),已有非空 id 不动 */
142
+ export function withRowId(row: Rec, keys: string | readonly string[]): Rec {
143
+ if (typeof row.id === 'string' && row.id !== '') return row;
144
+ if (typeof row.id === 'number') return { ...row, id: String(row.id) };
145
+ for (const key of typeof keys === 'string' ? [keys] : keys) {
146
+ const v = row[key];
147
+ if (typeof v === 'string' && v.trim() !== '') return { ...row, id: v.trim() };
148
+ if (typeof v === 'number') return { ...row, id: String(v) };
149
+ }
150
+ return { ...row, id: '' };
151
+ }
152
+
153
+ export function createPagedListAdapter(options: PagedListAdapterOptions = {}): PagedListAdapter {
154
+ const pageKey = options.pageKey ?? DEFAULT_PAGE_KEY;
155
+ const sizeKey = options.sizeKey ?? DEFAULT_SIZE_KEY;
156
+ const reserved = new Set<string>([pageKey, sizeKey, ...RESERVED_EXTRA]);
157
+ const upstreamPage = options.upstreamPage ?? 'page';
158
+ const upstreamSize = options.upstreamSize ?? 'pageSize';
159
+ const totalPaths = options.totalPaths ?? DEFAULT_TOTAL_PATHS;
160
+ const defaultSize = options.defaultPageSize ?? SOMA_PAGED_LIST_LIMITS.pageSizeDefault;
161
+ const maxSize = options.maxPageSize ?? SOMA_PAGED_LIST_LIMITS.pageSizeMax;
162
+ const filterMap = options.filterMap;
163
+ const filterName = (key: string): string | null => {
164
+ if (filterMap === undefined) return key;
165
+ if (Array.isArray(filterMap)) return filterMap.includes(key) ? key : null;
166
+ const mapped = (filterMap as Readonly<Record<string, string>>)[key];
167
+ return mapped === undefined ? null : mapped;
168
+ };
169
+
170
+ return {
171
+ hasPage(input) {
172
+ return entriesOf(input).some(([k, v]) => k === pageKey && positiveInt(v) !== null);
173
+ },
174
+ readQuery(input) {
175
+ const entries = entriesOf(input);
176
+ const pick = (key: string): number | null => {
177
+ const hit = entries.find(([k]) => k === key);
178
+ return hit === undefined ? null : positiveInt(hit[1]);
179
+ };
180
+ const page = pick(pageKey) ?? 1;
181
+ const pageSize = Math.min(pick(sizeKey) ?? defaultSize, maxSize);
182
+ const filters: Record<string, string> = {};
183
+ const upstream: Record<string, string | number> = { [upstreamPage]: page, [upstreamSize]: pageSize };
184
+ for (const [key, value] of entries) {
185
+ if (reserved.has(key) || value === undefined || value === null) continue;
186
+ const text = String(value).trim();
187
+ const target = filterName(key);
188
+ if (text === '' || target === null) continue;
189
+ filters[key] = text;
190
+ upstream[target] = text;
191
+ }
192
+ return { page, pageSize, filters, upstream };
193
+ },
194
+ toList(raw, mapRow) {
195
+ const unwrapped = unwrapResponseEnvelope(raw, options.envelope);
196
+ if (!unwrapped.ok) return { error: unwrapped.error };
197
+ let rows = rowsOf(unwrapped.data, options.rowsPath);
198
+ if (options.rowId !== undefined) rows = rows.map((r) => withRowId(r, options.rowId!));
199
+ if (mapRow !== undefined) rows = rows.map(mapRow);
200
+ return { rows, total: totalOf(unwrapped.data, totalPaths, rows.length) };
201
+ },
202
+ };
203
+ }
204
+
205
+ // ---------------------------------------------------------------- 游标分页
206
+
207
+ export type CursorLoader = (query: { cursor?: string; limit: number }) => Promise<unknown>;
208
+
209
+ export interface CursorPageOptions<T> {
210
+ load: CursorLoader;
211
+ /** 响应里行数组的键(缺省 rows) */
212
+ rowsKey?: string;
213
+ /** 响应里总数的键(缺省 total) */
214
+ totalKey?: string;
215
+ /** 响应里下一页游标的键(缺省 nextCursor) */
216
+ nextKey?: string;
217
+ parse?: (raw: unknown) => T;
218
+ /** 目标页(从 1 起)与页长 */
219
+ page: number;
220
+ pageSize: number;
221
+ /** 出错信息前缀(如「接口目录」) */
222
+ label: string;
223
+ }
224
+
225
+ export interface CursorPageResult<T> {
226
+ rows: T[];
227
+ total: number;
228
+ /** 最后一次取到的原始响应(调用方要读其它字段,如 snapshotVersion);页号超过末页时是末页那次的响应 */
229
+ raw: Rec | null;
230
+ }
231
+
232
+ /**
233
+ * 沿游标走到第 page 页,返回该页行与总数;页号超过末页返回空行(total 仍真实)。
234
+ * 响应结构非法(行不是数组、总数不是非负整数、行数超过页长)抛错,不静默截断;游标重复也抛错(防死循环)。
235
+ */
236
+ export async function cursorPageWindow<T = unknown>(options: CursorPageOptions<T>): Promise<CursorPageResult<T>> {
237
+ const { load, page, pageSize, label } = options;
238
+ const rowsKey = options.rowsKey ?? 'rows';
239
+ const totalKey = options.totalKey ?? 'total';
240
+ const nextKey = options.nextKey ?? 'nextCursor';
241
+ const parse = options.parse ?? ((raw: unknown) => raw as T);
242
+ let cursor: string | undefined;
243
+ const seen = new Set<string>();
244
+ let total = 0;
245
+ for (let current = 1; current <= page; current += 1) {
246
+ const response = await load({ ...(cursor !== undefined ? { cursor } : {}), limit: pageSize });
247
+ if (!isRec(response)) throw new Error(`${label}分页响应结构非法`);
248
+ const result: Rec = response;
249
+ const raw = result[rowsKey];
250
+ total = Number(result[totalKey]);
251
+ if (!Array.isArray(raw) || !Number.isSafeInteger(total) || total < 0 || raw.length > pageSize) throw new Error(`${label}分页响应结构非法`);
252
+ if (current === page) return { rows: raw.map(parse), total, raw: result };
253
+ const next = typeof result[nextKey] === 'string' ? (result[nextKey] as string).trim() : '';
254
+ if (next === '' || next === cursor || seen.has(next)) return { rows: [], total, raw: result };
255
+ seen.add(next);
256
+ cursor = next;
257
+ }
258
+ return { rows: [], total, raw: null };
259
+ }
@@ -0,0 +1,3 @@
1
+ // core 可选宿主引导模块的空实现:宿主没有 bootstrap/soma-bootstrap 时,vitest / vite 的别名指到这里(见 source-aliases.cjs 的 somaViteHostAliases)。
2
+ // 不导出 configureSomaBootstrap,与运行期「模块不存在 = 无宿主钩子」同形。
3
+ export {};
@@ -53,6 +53,7 @@ export function getJitiFactory(anchorDir?: string): JitiFactory {
53
53
  }
54
54
  import type { SomaHostAssembly } from '../../shared/types/host-assembly.types';
55
55
  import { getSomaHostSourceRoot } from './source-packages';
56
+ import { getSomaSourceRootAliases } from './source-aliases';
56
57
 
57
58
  /** Host 装配文件相对应用根的位置 */
58
59
  export const SOMA_HOST_ASSEMBLY_FILE = 'soma.app.ts';
@@ -290,6 +291,8 @@ function loadAppSync(appRoot: string): LoadedApp | null {
290
291
  moduleCache: false,
291
292
  requireCache: false,
292
293
  alias: {
294
+ // 源码根别名(soma.sourceRoots):与服务加载器同一实现;固定别名在后,不可被覆盖
295
+ ...getSomaSourceRootAliases(key),
293
296
  '@soma-host': hostRoot,
294
297
  '@core': coreDir,
295
298
  ...(serverOnlyEmpty !== undefined ? { 'server-only': serverOnlyEmpty } : {}),
@@ -0,0 +1,345 @@
1
+ // 源码根别名的唯一实现(`package.json#soma.sourceRoots`;《core 标准格式与 runtime 空间》P12 同族)。
2
+ //
3
+ // 为什么是 .cjs:构建期(esbuild 插件、host-native 内核、vitest 配置)是 CommonJS / 纯 Node 环境,运行期(TS)经 `source-aliases.ts`
4
+ // 带类型再导出同一份,不再各写一份。「哪些顶层目录是别名」「哪些名字不许占」「与已装包冲突怎么办」只在这里判定。
5
+ //
6
+ // 契约:
7
+ // 声明(`package.json#soma.sourceRoots`,缺省 = 完全不生效、返回空)
8
+ // "auto" → 以 apiRoot(`soma.apiRoot`,缺省回落 webRoot / hostRoot)为源码根
9
+ // "<相对目录>" | string[] → 每项是一个源码根(相对宿主目录,必须落在宿主目录内且存在)
10
+ // { "<别名>": "<相对目录>" } → 显式「别名 → 目录」,目录同样必须落在宿主目录内且存在
11
+ // 源码根形态下,其「一级子目录」各成一个别名:`<dir>/...` 解析到 `<源码根>/<dir>/...`(同 tsconfig `baseUrl` / vite 别名语义)。
12
+ // 只认带斜杠的子路径说明符:裸 `domain`、`kit`、npm 包名、`node:` 内置一概不劫持;没有子路径的 `domain` 仍走原解析。
13
+ // 前缀必须整段匹配(别名 `kit` 不匹配 `kitchen/x`)。
14
+ //
15
+ // 优先级(确定性,与 talent_graph 旧补丁里的 jiti 别名一致):声明的别名先于 node_modules 里的同名包。
16
+ // 宿主 `node_modules/<别名>` 存在且不是指向别名目录的软链 → 诊断 CORE-HOST-ALIAS-SHADOW(warning,别名仍生效,此时该包的
17
+ // `<别名>/...` 子路径说明符在宿主代码里读不到);指向别名目录的软链(旧补丁遗留)视为同一目录、不报。
18
+ // 多个源码根里同名别名:先声明者胜,后者 CORE-HOST-ALIAS-DUPLICATE(warning)。
19
+ //
20
+ // 诊断(error 级由 `getSomaSourceRootAliases` 抛出,不静默降级):
21
+ // CORE-HOST-ALIAS-INVALID error 声明形状不对 / 路径越界或不存在 / 别名名字非法
22
+ // CORE-HOST-ALIAS-RESERVED error 别名占了保留名:`soma` / `soma-*`、`server-only`、`node_modules`、以及带子路径的 Node 内置(`fs`、`path` ...)
23
+ // CORE-HOST-ALIAS-SHADOW warning 见上
24
+ // CORE-HOST-ALIAS-DUPLICATE warning 见上
25
+ // CORE-HOST-ALIAS-TSCONFIG-DRIFT warning tsconfig.json 的 baseUrl 与(auto / 数组形态的)第一个源码根不一致
26
+ //
27
+ // 与 core 的纪律:这里不出现任何 Host / 方言 / 外壳的名字;路径只经 `path.join / path.resolve` 对 hostDir 拼接(G100)。
28
+ const fs = require("node:fs");
29
+ const path = require("node:path");
30
+ const nodeModule = require("node:module");
31
+ const { getSomaHostApiRoot, getSomaHostSourceRoot, resolveSafeChildRoot } = require("./source-packages.cjs");
32
+
33
+ const CODE_INVALID = "CORE-HOST-ALIAS-INVALID";
34
+ const CODE_RESERVED = "CORE-HOST-ALIAS-RESERVED";
35
+ const CODE_SHADOW = "CORE-HOST-ALIAS-SHADOW";
36
+ const CODE_DUPLICATE = "CORE-HOST-ALIAS-DUPLICATE";
37
+ const CODE_TSCONFIG_DRIFT = "CORE-HOST-ALIAS-TSCONFIG-DRIFT";
38
+
39
+ /** 合法别名:字母数字下划线开头,之后允许 `.` `-`;不含斜杠、`@`、`:`、空白 */
40
+ const ALIAS_NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
41
+ const RESERVED_NAMES = new Set(["server-only", "node_modules", "soma"]);
42
+ const BUILTIN_WITH_SUBPATH = new Set(
43
+ nodeModule.builtinModules.filter((m) => m.includes("/")).map((m) => m.slice(0, m.indexOf("/"))),
44
+ );
45
+
46
+ // number-source: limits#/cache/sourceRootAliasCapacity
47
+ const MAX_CACHE = 64;
48
+ /** @type {Map<string, object>} */
49
+ const resolveCache = new Map();
50
+ const warned = new Set();
51
+
52
+ function clearSomaSourceRootCache() {
53
+ resolveCache.clear();
54
+ warned.clear();
55
+ }
56
+
57
+ function readJson(filePath) {
58
+ try {
59
+ if (!fs.existsSync(filePath)) return null;
60
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ /** tsconfig 允许注释与尾逗号:字符串感知地去掉再解析;失败返回 null(漂移检查直接跳过) */
67
+ function readTsconfig(filePath) {
68
+ let raw;
69
+ try {
70
+ raw = fs.readFileSync(filePath, "utf8");
71
+ } catch {
72
+ return null;
73
+ }
74
+ const stripped = raw
75
+ .replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_m, str) => str ?? "")
76
+ .replace(/,(\s*[}\]])/g, "$1");
77
+ try {
78
+ return JSON.parse(stripped);
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ function reservedReason(name) {
85
+ if (name === "soma" || name.startsWith("soma-")) return "与 soma 公开包名空间冲突";
86
+ if (RESERVED_NAMES.has(name)) return "是保留名";
87
+ if (BUILTIN_WITH_SUBPATH.has(name)) return `会劫持 Node 内置子路径(如 ${name}/...)`;
88
+ return null;
89
+ }
90
+
91
+ /** 目录是否真实落在宿主目录内(跟随软链,防越界软链) */
92
+ function realInside(parent, child) {
93
+ try {
94
+ const p = fs.realpathSync(parent);
95
+ const c = fs.realpathSync(child);
96
+ return c === p || c.startsWith(`${p}${path.sep}`);
97
+ } catch {
98
+ return false;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * 解析声明的源码根 → 别名表。纯函数式(只读文件系统),不抛、不打印;结果带诊断。
104
+ * @returns {{ declared: boolean, entries: Array<{ name: string, dir: string }>, aliases: Record<string, string>, diagnostics: Array<{ code: string, severity: "error" | "warning", message: string, name?: string }> }}
105
+ */
106
+ function resolveSomaSourceRoots(hostDir, env = process.env) {
107
+ let normalizedHostDir = path.resolve(hostDir);
108
+ // 传进来的可能是应用根(package 里的子目录,如 <工程>/src/kit)而不是工程根:声明在最近的上级 package.json 里,
109
+ // 向上找到它再解析(别名表属于工程,不属于某个子目录);一路没有 package.json 就按原目录处理(= 未声明)。
110
+ if (!fs.existsSync(path.join(normalizedHostDir, "package.json"))) {
111
+ for (let dir = path.dirname(normalizedHostDir); ; dir = path.dirname(dir)) {
112
+ if (fs.existsSync(path.join(dir, "package.json"))) { normalizedHostDir = dir; break; }
113
+ if (path.dirname(dir) === dir) break;
114
+ }
115
+ }
116
+ const packageJsonPath = path.join(normalizedHostDir, "package.json");
117
+ const stat = fs.statSync(packageJsonPath, { throwIfNoEntry: false });
118
+ const cacheKey = `${normalizedHostDir}\0${env?.SOMA_API_DIR ?? ""}\0${env?.SOMA_WEB_DIR ?? ""}\0${stat ? `${stat.mtimeMs}:${stat.size}` : "none"}`;
119
+ const cached = resolveCache.get(cacheKey);
120
+ if (cached) return cached;
121
+
122
+ const result = compute(normalizedHostDir, env, readJson(packageJsonPath));
123
+ if (resolveCache.size >= MAX_CACHE) resolveCache.delete(resolveCache.keys().next().value);
124
+ resolveCache.set(cacheKey, result);
125
+ return result;
126
+ }
127
+
128
+ function compute(hostDir, env, packageJson) {
129
+ const diagnostics = [];
130
+ const raw = packageJson?.soma?.sourceRoots;
131
+ const empty = { declared: false, entries: [], aliases: {}, diagnostics };
132
+ if (raw === undefined || raw === null) return empty;
133
+
134
+ const invalid = (message) => diagnostics.push({ code: CODE_INVALID, severity: "error", message: `soma.sourceRoots ${message}` });
135
+
136
+ /** 候选:{ name, dir, from } 按声明顺序 */
137
+ const candidates = [];
138
+ let firstRoot = null;
139
+
140
+ const addRoot = (rootDir) => {
141
+ if (firstRoot === null) firstRoot = rootDir;
142
+ let children;
143
+ try {
144
+ children = fs.readdirSync(rootDir, { withFileTypes: true });
145
+ } catch {
146
+ invalid(`的源码根不可读:${rootDir}`);
147
+ return;
148
+ }
149
+ for (const entry of children.sort((a, b) => a.name.localeCompare(b.name))) {
150
+ const full = path.join(rootDir, entry.name);
151
+ const isDir = entry.isDirectory() || (entry.isSymbolicLink() && fs.statSync(full, { throwIfNoEntry: false })?.isDirectory());
152
+ // 隐藏目录、node_modules 与不合法的名字在发现式声明里静默跳过(不是用户写进去的)
153
+ if (!isDir || entry.name.startsWith(".") || entry.name === "node_modules" || !ALIAS_NAME_RE.test(entry.name)) continue;
154
+ candidates.push({ name: entry.name, dir: full });
155
+ }
156
+ };
157
+
158
+ const safeRoot = (rel) => {
159
+ if (typeof rel !== "string" || !rel.trim() || rel.includes("\0")) {
160
+ invalid("的路径必须是非空字符串");
161
+ return null;
162
+ }
163
+ const resolved = path.resolve(hostDir, rel.trim());
164
+ const safe = resolveSafeChildRoot(hostDir, rel);
165
+ // resolveSafeChildRoot 对越界 / 不存在一律回落 parent;回落且并非本来就指向 parent → 拒绝
166
+ if (safe !== resolved || !fs.existsSync(safe) || !fs.statSync(safe).isDirectory() || !realInside(hostDir, safe)) {
167
+ invalid(`的路径 "${rel}" 必须是宿主目录内已存在的目录`);
168
+ return null;
169
+ }
170
+ return safe;
171
+ };
172
+
173
+ if (raw === "auto") {
174
+ const apiRoot = getSomaHostApiRoot(hostDir, env);
175
+ addRoot(apiRoot);
176
+ } else if (typeof raw === "string" || Array.isArray(raw)) {
177
+ for (const rel of Array.isArray(raw) ? raw : [raw]) {
178
+ const root = safeRoot(rel);
179
+ if (root) addRoot(root);
180
+ }
181
+ } else if (typeof raw === "object") {
182
+ for (const [name, rel] of Object.entries(raw)) {
183
+ if (!ALIAS_NAME_RE.test(name)) {
184
+ diagnostics.push({ code: CODE_INVALID, severity: "error", name, message: `别名 "${name}" 不合法(只允许字母数字 _ . -,且不含斜杠)` });
185
+ continue;
186
+ }
187
+ const dir = safeRoot(rel);
188
+ if (dir) candidates.push({ name, dir });
189
+ }
190
+ } else {
191
+ invalid('必须是 "auto"、目录字符串、字符串数组或「别名 → 目录」对象');
192
+ return { ...empty, declared: true };
193
+ }
194
+
195
+ const entries = [];
196
+ const taken = new Map();
197
+ for (const candidate of candidates) {
198
+ const reason = reservedReason(candidate.name);
199
+ if (reason) {
200
+ diagnostics.push({
201
+ code: CODE_RESERVED,
202
+ severity: "error",
203
+ name: candidate.name,
204
+ message: `源码根别名 "${candidate.name}" ${reason},请把该目录改名或移出源码根`,
205
+ });
206
+ continue;
207
+ }
208
+ if (taken.has(candidate.name)) {
209
+ diagnostics.push({
210
+ code: CODE_DUPLICATE,
211
+ severity: "warning",
212
+ name: candidate.name,
213
+ message: `源码根别名 "${candidate.name}" 同时出现在 ${taken.get(candidate.name)} 与 ${candidate.dir},先声明者生效`,
214
+ });
215
+ continue;
216
+ }
217
+ taken.set(candidate.name, candidate.dir);
218
+ entries.push(candidate);
219
+ }
220
+
221
+ for (const { name, dir } of entries) {
222
+ const installed = path.join(hostDir, "node_modules", name);
223
+ const installedStat = fs.lstatSync(installed, { throwIfNoEntry: false });
224
+ if (!installedStat) continue;
225
+ let same = false;
226
+ try {
227
+ same = fs.realpathSync(installed) === fs.realpathSync(dir);
228
+ } catch {
229
+ same = false;
230
+ }
231
+ if (!same) {
232
+ diagnostics.push({
233
+ code: CODE_SHADOW,
234
+ severity: "warning",
235
+ name,
236
+ message: `源码根别名 "${name}" 遮蔽了已安装的包 node_modules/${name}:宿主代码里的 "${name}/..." 一律解析到 ${dir}(声明的别名优先于已装包)`,
237
+ });
238
+ }
239
+ }
240
+
241
+ if (firstRoot !== null) {
242
+ const tsconfig = readTsconfig(path.join(hostDir, "tsconfig.json"));
243
+ const baseUrl = tsconfig?.compilerOptions?.baseUrl;
244
+ if (typeof baseUrl === "string" && path.resolve(hostDir, baseUrl) !== path.resolve(firstRoot)) {
245
+ diagnostics.push({
246
+ code: CODE_TSCONFIG_DRIFT,
247
+ severity: "warning",
248
+ message: `tsconfig.json 的 baseUrl(${baseUrl})与 soma.sourceRoots 的源码根(${path.relative(hostDir, firstRoot) || "."})不一致:编辑器与运行期会解析到不同目录`,
249
+ });
250
+ }
251
+ }
252
+
253
+ const aliases = {};
254
+ for (const { name, dir } of entries) aliases[name] = dir;
255
+ return { declared: true, entries, aliases, diagnostics };
256
+ }
257
+
258
+ function formatDiagnostic(d) {
259
+ return `[soma-core][${d.code}] ${d.message}`;
260
+ }
261
+
262
+ /**
263
+ * 运行期 / 构建期取别名表的统一入口:error 级诊断抛出(带 `code`),warning 级每个宿主每条只打一次。
264
+ * 未声明 → `{}`。
265
+ * @returns {Record<string, string>} 别名 → 绝对目录(无尾斜杠)
266
+ */
267
+ function getSomaSourceRootAliases(hostDir, env = process.env) {
268
+ const resolved = resolveSomaSourceRoots(hostDir, env);
269
+ const errors = resolved.diagnostics.filter((d) => d.severity === "error");
270
+ if (errors.length > 0) {
271
+ const error = new Error(errors.map(formatDiagnostic).join("\n"));
272
+ error.code = errors[0].code;
273
+ error.diagnostics = errors;
274
+ throw error;
275
+ }
276
+ for (const d of resolved.diagnostics) {
277
+ const key = `${path.resolve(hostDir)}\0${d.code}\0${d.name ?? ""}\0${d.message}`;
278
+ if (warned.has(key)) continue;
279
+ warned.add(key);
280
+ // 日志前缀 `[包名][事件域]`(verify:logs):事件域取「引擎」,诊断码跟在后面
281
+ console.warn(`[soma-core][引擎] ${d.code} ${d.message}`);
282
+ }
283
+ return { ...resolved.aliases };
284
+ }
285
+
286
+ /** 说明符 → `{ dir, subpath }`(只认带斜杠的整段前缀匹配);不匹配 → null。供 esbuild 等自己解析的构建器使用 */
287
+ function matchSomaSourceRoot(aliases, specifier) {
288
+ if (typeof specifier !== "string") return null;
289
+ const slash = specifier.indexOf("/");
290
+ if (slash <= 0) return null;
291
+ const name = specifier.slice(0, slash);
292
+ const dir = Object.prototype.hasOwnProperty.call(aliases, name) ? aliases[name] : undefined;
293
+ if (dir === undefined) return null;
294
+ return { name, dir, subpath: specifier.slice(slash + 1) };
295
+ }
296
+
297
+ /** esbuild `onResolve` 的 filter:`^(?:a|b)/`;无别名 → null(调用方不注册钩子,零开销) */
298
+ function somaSourceRootFilter(aliases) {
299
+ const names = Object.keys(aliases);
300
+ if (names.length === 0) return null;
301
+ return new RegExp(`^(?:${names.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})/`);
302
+ }
303
+
304
+ /** vitest / vite `resolve.alias` 数组:`[{ find: /^name\//, replacement: "<dir>/" }]`;未声明 → [] */
305
+ function somaViteAliases(hostDir, env = process.env) {
306
+ return Object.entries(getSomaSourceRootAliases(hostDir, env)).map(([name, dir]) => ({
307
+ find: new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`),
308
+ replacement: `${dir.split(path.sep).join("/")}/`,
309
+ }));
310
+ }
311
+
312
+ /** core 可选宿主引导模块的说明符(与 core/client/host-bridge/resolve-host-bootstrap.ts 的 HOST_BOOTSTRAP_MODULE 同值) */
313
+ const HOST_BOOTSTRAP_SPECIFIER = "@soma-host/bootstrap/soma-bootstrap";
314
+ const HOST_BOOTSTRAP_CANDIDATES = ["soma-bootstrap.ts", "soma-bootstrap.js", "soma-bootstrap.mjs"];
315
+
316
+ /**
317
+ * vitest / vite 用的完整宿主别名:源码根别名(`somaViteAliases`)+ 可选宿主引导模块。
318
+ * core 对 `@soma-host/bootstrap/soma-bootstrap` 做可选动态 import:原生 Node 下缺失会被捕获(按「无宿主钩子」处理),
319
+ * 但 vite 在转换期就要解析该说明符,宿主没有这个文件时测试直接失败——以前每个应用自己写一个空垫片。
320
+ * 这里统一给出:宿主源码根下有该文件就指向它,没有就指向 core 自带的空模块(与运行期「无钩子」同形)。
321
+ */
322
+ function somaViteHostAliases(hostDir, env = process.env) {
323
+ const sourceRoot = getSomaHostSourceRoot(path.resolve(hostDir), env);
324
+ const found = HOST_BOOTSTRAP_CANDIDATES.map((name) => path.join(sourceRoot, "bootstrap", name)).find((file) => fs.existsSync(file));
325
+ const target = found ?? path.join(__dirname, "empty-host-bootstrap.mjs");
326
+ return [
327
+ ...somaViteAliases(hostDir, env),
328
+ { find: new RegExp(`^${HOST_BOOTSTRAP_SPECIFIER}$`), replacement: target.split(path.sep).join("/") },
329
+ ];
330
+ }
331
+
332
+ module.exports = {
333
+ somaViteHostAliases,
334
+ CODE_INVALID,
335
+ CODE_RESERVED,
336
+ CODE_SHADOW,
337
+ CODE_DUPLICATE,
338
+ CODE_TSCONFIG_DRIFT,
339
+ clearSomaSourceRootCache,
340
+ resolveSomaSourceRoots,
341
+ getSomaSourceRootAliases,
342
+ matchSomaSourceRoot,
343
+ somaSourceRootFilter,
344
+ somaViteAliases,
345
+ };
@@ -0,0 +1,32 @@
1
+ import * as impl from "./source-aliases.cjs";
2
+
3
+ export interface SomaSourceRootDiagnostic {
4
+ readonly code: string;
5
+ readonly severity: "error" | "warning";
6
+ readonly message: string;
7
+ readonly name?: string;
8
+ }
9
+
10
+ export interface SomaSourceRootResolution {
11
+ readonly declared: boolean;
12
+ readonly entries: ReadonlyArray<{ readonly name: string; readonly dir: string }>;
13
+ readonly aliases: Readonly<Record<string, string>>;
14
+ readonly diagnostics: readonly SomaSourceRootDiagnostic[];
15
+ }
16
+
17
+ type Env = Readonly<Record<string, string | undefined>>;
18
+
19
+ /** 实现只有 `source-aliases.cjs` 一份(单实现);这里只补类型再导出,不另写第二份。 */
20
+ export const resolveSomaSourceRoots: (hostDir: string, env?: Env) => SomaSourceRootResolution =
21
+ impl.resolveSomaSourceRoots as never;
22
+
23
+ /** 别名 → 绝对目录;未声明 → `{}`;error 级诊断抛出(带 `code`) */
24
+ export const getSomaSourceRootAliases: (hostDir: string, env?: Env) => Record<string, string> =
25
+ impl.getSomaSourceRootAliases;
26
+
27
+ export const somaViteAliases: (hostDir: string, env?: Env) => Array<{ find: RegExp; replacement: string }> =
28
+ impl.somaViteAliases;
29
+
30
+ /** vitest / vite 的完整宿主别名:源码根别名 + 可选宿主引导模块(宿主没有该文件时指向 core 自带空模块) */
31
+ export const somaViteHostAliases: (hostDir: string, env?: Env) => Array<{ find: RegExp; replacement: string }> =
32
+ impl.somaViteHostAliases as never;