soma-core 1.0.0 → 1.0.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.
@@ -0,0 +1,153 @@
1
+ import { NextRequest } from 'next/server';
2
+ import type { IService } from '@/core/api/IService';
3
+
4
+ // ─── 工具函数 ──────────────────────────────────────────────
5
+
6
+ /**
7
+ * 将 kebab-case / snake_case 转为 PascalCase
8
+ * @example "user-profile" → "UserProfile", "oauth_token" → "OauthToken"
9
+ */
10
+ function toPascalCase(str: string): string {
11
+ return str
12
+ .split(/[-_]/)
13
+ .map(s => s.charAt(0).toUpperCase() + s.slice(1))
14
+ .join('');
15
+ }
16
+
17
+ /**
18
+ * 从 path 片段构造服务文件路径并动态加载
19
+ * @example ["login"] → @soma-host/api/service/Login
20
+ * @example ["user", "profile"] → @soma-host/api/service/user/Profile
21
+ */
22
+ function buildImportPath(segments: string[]): string {
23
+ const fileName = toPascalCase(segments[segments.length - 1]);
24
+ const dirs = segments.slice(0, -1);
25
+ const dirPrefix = dirs.length > 0 ? `${dirs.join('/')}/` : '';
26
+ return `@soma-host/api/service/${dirPrefix}${fileName}`;
27
+ }
28
+
29
+ /**
30
+ * 检查对象是否为合法的 IService 实例
31
+ */
32
+ function isService(obj: any): obj is IService {
33
+ if (!obj || typeof obj !== 'object') return false;
34
+ const methods = ['get', 'post', 'put', 'patch', 'delete'];
35
+ return methods.some(m => typeof obj[m] === 'function');
36
+ }
37
+
38
+ // ─── 模块缓存(dev 模式下不缓存,确保热更新) ────────────────
39
+
40
+ const isDev = process.env.NODE_ENV !== 'production';
41
+ const moduleCache = new Map<string, { mod: any; mtime: number }>();
42
+
43
+ async function loadService(segments: string[]): Promise<IService | null> {
44
+ const importPath = buildImportPath(segments);
45
+
46
+ try {
47
+ // 动态导入服务模块(webpack 通过 @soma-host 别名解析到 app-demo)
48
+ const mod = await import(
49
+ /* webpackChunkName: "api-service" */
50
+ /* webpackMode: "lazy" */
51
+ /* webpackInclude: /api\/service\/.*\.ts$/ */
52
+ importPath
53
+ );
54
+
55
+ // 清除缓存以支持热更新(dev 模式)
56
+ if (isDev && moduleCache.has(importPath)) {
57
+ moduleCache.delete(importPath);
58
+ }
59
+
60
+ const ServiceClass = mod.default;
61
+ if (!ServiceClass || typeof ServiceClass !== 'function') {
62
+ console.warn(`[soma-api] ${importPath} 缺少 default export`);
63
+ return null;
64
+ }
65
+
66
+ const instance = new ServiceClass();
67
+ if (!isService(instance)) {
68
+ console.warn(`[soma-api] ${importPath} 未实现 IService 接口`);
69
+ return null;
70
+ }
71
+
72
+ return instance;
73
+ } catch (e: any) {
74
+ if (e.code === 'MODULE_NOT_FOUND' || e.code === 'ERR_MODULE_NOT_FOUND') {
75
+ return null; // 服务文件不存在
76
+ }
77
+ console.error(`[soma-api] 加载 ${importPath} 失败:`, e.message);
78
+ return null;
79
+ }
80
+ }
81
+
82
+ // ─── HTTP 方法分发工厂 ─────────────────────────────────────
83
+
84
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
85
+
86
+ function createHandler(method: HttpMethod) {
87
+ const methodKey = method.toLowerCase() as keyof IService;
88
+
89
+ return async function handler(
90
+ req: NextRequest,
91
+ { params }: { params: { path: string[] } },
92
+ ): Promise<Response> {
93
+ const segments = params.path || [];
94
+
95
+ if (segments.length === 0) {
96
+ return Response.json(
97
+ { error: '缺少 API 路径,格式: /api/{module}/{action}' },
98
+ { status: 400 },
99
+ );
100
+ }
101
+
102
+ const service = await loadService(segments);
103
+
104
+ if (!service) {
105
+ return Response.json(
106
+ { error: `API 不存在: /api/${segments.join('/')}` },
107
+ { status: 404 },
108
+ );
109
+ }
110
+
111
+ const handlerFn = service[methodKey];
112
+ if (typeof handlerFn !== 'function') {
113
+ return Response.json(
114
+ {
115
+ error: `不支持 ${method} 方法: /api/${segments.join('/')}`,
116
+ },
117
+ {
118
+ status: 405,
119
+ headers: { Allow: getAllowHeader(service) },
120
+ },
121
+ );
122
+ }
123
+
124
+ try {
125
+ return await handlerFn.call(service, req);
126
+ } catch (e: any) {
127
+ console.error(`[soma-api] ${method} /api/${segments.join('/')}:`, e);
128
+ return Response.json(
129
+ { error: e.message || '服务器内部错误' },
130
+ { status: 500 },
131
+ );
132
+ }
133
+ };
134
+ }
135
+
136
+ /** 生成 Allow 响应头 */
137
+ function getAllowHeader(service: IService): string {
138
+ const methods: string[] = [];
139
+ if (typeof service.get === 'function') methods.push('GET');
140
+ if (typeof service.post === 'function') methods.push('POST');
141
+ if (typeof service.put === 'function') methods.push('PUT');
142
+ if (typeof service.patch === 'function') methods.push('PATCH');
143
+ if (typeof service.delete === 'function') methods.push('DELETE');
144
+ return methods.join(', ');
145
+ }
146
+
147
+ // ─── 导出所有 HTTP 方法处理器 ───────────────────────────────
148
+
149
+ export const GET = createHandler('GET');
150
+ export const POST = createHandler('POST');
151
+ export const PUT = createHandler('PUT');
152
+ export const PATCH = createHandler('PATCH');
153
+ export const DELETE = createHandler('DELETE');
@@ -46,7 +46,7 @@ export async function GET(req: NextRequest) {
46
46
  const hostDir = getHostDir();
47
47
  if (!hostDir) {
48
48
  return Response.json(
49
- { error: 'SOMA_HOST_DIR 未设置。请在宿主应用根目录执行:npx soma dev。' },
49
+ { error: 'SOMA_HOST_DIR 未设置。请在业务应用根目录执行:npx soma dev。' },
50
50
  { status: 503 },
51
51
  );
52
52
  }
package/bin/soma.cjs CHANGED
@@ -1,2 +1,2 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
2
2
  require('../dist/cli/soma.js');
@@ -0,0 +1,33 @@
1
+ import { NextRequest } from 'next/server';
2
+
3
+ /**
4
+ * SOMA 后端服务接口 —— app-demo/api/service/ 下的服务类必须实现此接口。
5
+ *
6
+ * 实现约定:
7
+ * - 每个文件 default export 一个实现 IService 的类
8
+ * - 可选实现 get / post / put / patch / delete,对应 HTTP 方法
9
+ * - 未实现的方法请求会返回 405 Method Not Allowed
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * // app-demo/api/service/Login.ts
14
+ * import type { IService } from 'soma-core/core/api/IService';
15
+ *
16
+ * export default class LoginService implements IService {
17
+ * async post(req: NextRequest): Promise<Response> {
18
+ * const { username, password } = await req.json();
19
+ * if (username === 'admin') {
20
+ * return Response.json({ code: 0, token: 'xxx' });
21
+ * }
22
+ * return Response.json({ code: -1 }, { status: 401 });
23
+ * }
24
+ * }
25
+ * ```
26
+ */
27
+ export interface IService {
28
+ get?(req: NextRequest): Promise<Response>;
29
+ post?(req: NextRequest): Promise<Response>;
30
+ put?(req: NextRequest): Promise<Response>;
31
+ patch?(req: NextRequest): Promise<Response>;
32
+ delete?(req: NextRequest): Promise<Response>;
33
+ }
package/core/index.ts CHANGED
@@ -1,6 +1,9 @@
1
- /**
2
- * soma-core — 宿主通过 bundler 解析子路径时请使用 exports。
3
- */
4
- export * from './base/index';
5
-
6
- export type { SomaAppConfig, SomaPageRoot } from './types/domain.types';
1
+ /**
2
+ * soma-core — 业务应用通过 bundler 解析子路径时请使用 exports。
3
+ */
4
+ export * from './base/index';
5
+
6
+ export type { SomaAppConfig, SomaPageRoot } from './types/domain.types';
7
+
8
+ // 后端服务接口
9
+ export type { IService } from './api/IService';
@@ -1,465 +1,465 @@
1
- import type { SomaScopeResolver } from '../engine/scope-resolver';
2
- import type { ParsedEvent } from '../types/event.types';
3
- import type {
4
- ExtendedShowValue,
5
- NestedShowMapping,
6
- ShowMapping,
7
- UiConfig,
8
- } from '../types/ui-config.types';
9
- import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
10
-
11
- export interface SomaContractValidationInput {
12
- container: HTMLElement;
13
- uiConfig: UiConfig;
14
- eventConfig: ParsedEvent[];
15
- resolver: SomaScopeResolver;
16
- rootInstance: object;
17
- }
18
-
19
- export interface SomaContractReport {
20
- errors: string[];
21
- warnings: string[];
22
- anchorIds: string[];
23
- bindingCount: number;
24
- eventCount: number;
25
- }
26
-
27
- export class SomaContractError extends Error {
28
- readonly report: SomaContractReport;
29
-
30
- constructor(report: SomaContractReport) {
31
- const summary = report.errors[0] ?? 'SOMA contract validation failed';
32
- super(`[SOMA Contract] ${summary}`);
33
- this.name = 'SomaContractError';
34
- this.report = report;
35
- }
36
- }
37
-
38
- export class SomaContractValidator {
39
- private diagnostics: SomaDiagnostics | null;
40
-
41
- constructor(diagnostics?: SomaDiagnostics) {
42
- this.diagnostics = diagnostics ?? null;
43
- }
44
-
45
- validate(input: SomaContractValidationInput): SomaContractReport {
46
- const hostCount = input.container.querySelectorAll('[data-soma-host]').length;
47
- const { anchors, duplicates } = this.collectAnchorStats(input.container);
48
- const report: SomaContractReport = {
49
- errors: [],
50
- warnings: [],
51
- anchorIds: [...anchors].sort(),
52
- bindingCount: 0,
53
- eventCount: input.eventConfig.length,
54
- };
55
-
56
- if (hostCount === 0) {
57
- this.addError(report, 'container: 缺少 data-soma-host 边界');
58
- } else if (hostCount > 1) {
59
- this.addWarning(report, `container: 检测到 ${hostCount} 个 data-soma-host,建议每页仅保留一个宿主边界`);
60
- }
61
-
62
- for (const [somaId, count] of duplicates.entries()) {
63
- this.addError(report, `anchor.${somaId}: 检测到 ${count} 个重复的静态 data-soma-id,绑定会产生歧义`);
64
- }
65
-
66
- this.validateShowMapping(
67
- input.uiConfig.show,
68
- anchors,
69
- input.resolver,
70
- input.rootInstance,
71
- report,
72
- 'show',
73
- );
74
- this.validateEvents(
75
- input.eventConfig,
76
- anchors,
77
- input.resolver,
78
- input.rootInstance,
79
- report,
80
- );
81
-
82
- if (report.errors.length > 0) {
83
- throw new SomaContractError(report);
84
- }
85
-
86
- return report;
87
- }
88
-
89
- private collectAnchorStats(container: HTMLElement): {
90
- anchors: Set<string>;
91
- duplicates: Map<string, number>;
92
- } {
93
- const anchors = new Set<string>();
94
- const counts = new Map<string, number>();
95
-
96
- const scanNode = (root: HTMLElement | DocumentFragment) => {
97
- root.querySelectorAll<HTMLElement>('[data-soma-id]').forEach((element) => {
98
- const somaId = element.getAttribute('data-soma-id');
99
- if (somaId) {
100
- anchors.add(somaId);
101
- counts.set(somaId, (counts.get(somaId) ?? 0) + 1);
102
- }
103
- });
104
- // Also scan inside <template> elements whose content lives in a DocumentFragment
105
- root.querySelectorAll<HTMLTemplateElement>('template[data-soma-role]').forEach((tmpl) => {
106
- if (tmpl.content) {
107
- scanNode(tmpl.content);
108
- }
109
- });
110
- };
111
-
112
- scanNode(container);
113
-
114
- const duplicates = new Map<string, number>();
115
- for (const [somaId, count] of counts.entries()) {
116
- if (count > 1) {
117
- duplicates.set(somaId, count);
118
- }
119
- }
120
-
121
- return { anchors, duplicates };
122
- }
123
-
124
- private validateShowMapping(
125
- show: ShowMapping,
126
- anchors: Set<string>,
127
- resolver: SomaScopeResolver,
128
- rootInstance: object,
129
- report: SomaContractReport,
130
- basePath: string,
131
- ): void {
132
- for (const [rawKey, value] of Object.entries(show)) {
133
- report.bindingCount += 1;
134
- const currentPath = `${basePath}.${rawKey}`;
135
- const somaId = this.extractSomaId(rawKey);
136
-
137
- if (!anchors.has(somaId)) {
138
- this.addError(report, `${currentPath}: 缺少 data-soma-id="${somaId}"`);
139
- }
140
-
141
- if (typeof value === 'string') {
142
- this.validateReadablePath(value, currentPath, resolver, rootInstance, report);
143
- continue;
144
- }
145
-
146
- if (this.isNestedShowMapping(value)) {
147
- this.validateReadablePath(
148
- value.bind.obj,
149
- `${currentPath}.bind.obj`,
150
- resolver,
151
- rootInstance,
152
- report,
153
- );
154
- this.validateShowMapping(
155
- value.show,
156
- anchors,
157
- resolver,
158
- rootInstance,
159
- report,
160
- `${currentPath}.show`,
161
- );
162
- continue;
163
- }
164
-
165
- if (this.isExtendedShowValue(value)) {
166
- if (value.text) {
167
- this.validateReadablePath(
168
- value.text,
169
- `${currentPath}.text`,
170
- resolver,
171
- rootInstance,
172
- report,
173
- );
174
- }
175
- if (value.model) {
176
- this.validateReadablePath(
177
- value.model,
178
- `${currentPath}.model`,
179
- resolver,
180
- rootInstance,
181
- report,
182
- );
183
- }
184
- if (value.when) {
185
- this.validateReadablePath(
186
- value.when,
187
- `${currentPath}.when`,
188
- resolver,
189
- rootInstance,
190
- report,
191
- );
192
- }
193
- if (value.class) {
194
- for (const [className, expr] of Object.entries(value.class)) {
195
- this.validateReadablePath(
196
- expr,
197
- `${currentPath}.class.${className}`,
198
- resolver,
199
- rootInstance,
200
- report,
201
- );
202
- }
203
- }
204
- if (value.show) {
205
- this.validateShowMapping(
206
- value.show,
207
- anchors,
208
- resolver,
209
- rootInstance,
210
- report,
211
- `${currentPath}.show`,
212
- );
213
- }
214
- }
215
- }
216
- }
217
-
218
- private validateEvents(
219
- events: ParsedEvent[],
220
- anchors: Set<string>,
221
- resolver: SomaScopeResolver,
222
- rootInstance: object,
223
- report: SomaContractReport,
224
- ): void {
225
- const eventKeys = new Set<string>();
226
-
227
- for (const event of events) {
228
- const eventKey = `${event.domEvent}:${event.somaId}`;
229
- if (eventKeys.has(eventKey)) {
230
- this.addError(report, `event.${eventKey}: 重复声明的事件绑定`);
231
- } else {
232
- eventKeys.add(eventKey);
233
- }
234
-
235
- if (!anchors.has(event.somaId)) {
236
- this.addError(report, `event.${eventKey}: 缺少事件源 data-soma-id="${event.somaId}"`);
237
- }
238
-
239
- if (event.targetId && event.targetId !== 'self' && !anchors.has(event.targetId)) {
240
- this.addError(
241
- report,
242
- `event.${eventKey}: 缺少交互目标 data-soma-id="${event.targetId}"`,
243
- );
244
- }
245
-
246
- if (event.funcPath) {
247
- this.validateFunctionPath(
248
- event.funcPath,
249
- `event.${eventKey}.funcPath`,
250
- resolver,
251
- rootInstance,
252
- report,
253
- );
254
- }
255
- }
256
- }
257
-
258
- private validateReadablePath(
259
- rawPath: string,
260
- location: string,
261
- resolver: SomaScopeResolver,
262
- rootInstance: object,
263
- report: SomaContractReport,
264
- ): void {
265
- let path = rawPath.trim();
266
- if (!path) {
267
- this.addError(report, `${location}: 绑定路径不能为空`);
268
- return;
269
- }
270
-
271
- if (path.startsWith('!')) {
272
- path = path.slice(1);
273
- }
274
-
275
- const segments = path.split('.').filter(Boolean);
276
- if (segments.length === 0) {
277
- this.addError(report, `${location}: 绑定路径不能为空`);
278
- return;
279
- }
280
-
281
- const rootToken = segments[0];
282
-
283
- if (resolver.hasVar(rootToken)) {
284
- const varPath = resolver.getVarPath(rootToken);
285
- if (varPath === '') {
286
- this.validateSegments(rootInstance, segments.slice(1), location, report);
287
- }
288
- return;
289
- }
290
-
291
- this.validateSegments(rootInstance, segments, location, report);
292
- }
293
-
294
- private validateFunctionPath(
295
- funcPath: string,
296
- location: string,
297
- resolver: SomaScopeResolver,
298
- rootInstance: object,
299
- report: SomaContractReport,
300
- ): void {
301
- const segments = funcPath.split('.').filter(Boolean);
302
- if (segments.length < 2) {
303
- this.addError(report, `${location}: 函数路径至少需要 "对象.方法" 两段`);
304
- return;
305
- }
306
-
307
- const rootToken = segments[0];
308
- if (resolver.hasVar(rootToken)) {
309
- const varPath = resolver.getVarPath(rootToken);
310
- if (varPath === '') {
311
- try {
312
- resolver.resolveFunction(funcPath);
313
- } catch (error) {
314
- const message = error instanceof Error ? error.message : String(error);
315
- this.addError(report, `${location}: ${message}`);
316
- }
317
- return;
318
- }
319
-
320
- const sample = this.resolveAliasSample(rootToken, resolver, rootInstance);
321
- if (sample === undefined) {
322
- this.addWarning(
323
- report,
324
- `${location}: 别名 "${rootToken}" 当前缺少可验证样本,延迟到运行时校验`,
325
- );
326
- return;
327
- }
328
-
329
- this.validateFunctionOnTarget(sample, segments.slice(1), location, report, funcPath);
330
- return;
331
- }
332
-
333
- try {
334
- resolver.resolveFunction(funcPath);
335
- } catch (error) {
336
- const message = error instanceof Error ? error.message : String(error);
337
- this.addError(report, `${location}: ${message}`);
338
- }
339
- }
340
-
341
- private validateSegments(
342
- rootInstance: object,
343
- segments: string[],
344
- location: string,
345
- report: SomaContractReport,
346
- ): void {
347
- if (segments.length === 0) {
348
- return;
349
- }
350
-
351
- let current: any = rootInstance;
352
- for (let index = 0; index < segments.length; index++) {
353
- const segment = segments[index];
354
-
355
- if (current == null) {
356
- this.addWarning(
357
- report,
358
- `${location}: 在 "${segments.slice(0, index).join('.')}" 处遇到空值,延迟到运行时校验`,
359
- );
360
- return;
361
- }
362
-
363
- if (Array.isArray(current)) {
364
- this.addWarning(
365
- report,
366
- `${location}: "${segments.slice(0, index).join('.')}" 是集合,元素字段延迟到运行时校验`,
367
- );
368
- return;
369
- }
370
-
371
- if (!(segment in Object(current))) {
372
- const message = `${location}: 路径 "${segments.slice(0, index + 1).join('.')}" 不存在`;
373
- if (index === 0) {
374
- this.addError(report, message);
375
- } else {
376
- this.addWarning(report, message);
377
- }
378
- return;
379
- }
380
-
381
- current = current[segment];
382
- }
383
- }
384
-
385
- private validateFunctionOnTarget(
386
- target: any,
387
- segments: string[],
388
- location: string,
389
- report: SomaContractReport,
390
- funcPath: string,
391
- ): void {
392
- let current = target;
393
-
394
- for (let index = 0; index < segments.length; index++) {
395
- if (current == null) {
396
- this.addWarning(report, `${location}: "${funcPath}" 在运行时可能为空对象`);
397
- return;
398
- }
399
-
400
- if (Array.isArray(current)) {
401
- if (current.length === 0) {
402
- this.addWarning(report, `${location}: "${funcPath}" 对应集合为空,延迟到运行时校验`);
403
- return;
404
- }
405
- current = current[0];
406
- }
407
-
408
- const segment = segments[index];
409
- if (!(segment in Object(current))) {
410
- this.addError(
411
- report,
412
- `${location}: 函数路径 "${funcPath}" 缺少属性 "${segment}"`,
413
- );
414
- return;
415
- }
416
-
417
- const next = current[segment];
418
- if (index === segments.length - 1 && typeof next !== 'function') {
419
- this.addError(report, `${location}: "${funcPath}" 不是可调用函数`);
420
- return;
421
- }
422
-
423
- current = next;
424
- }
425
- }
426
-
427
- private resolveAliasSample(
428
- alias: string,
429
- resolver: SomaScopeResolver,
430
- rootInstance: object,
431
- ): any {
432
- const varPath = resolver.getVarPath(alias);
433
- if (varPath === undefined) return undefined;
434
- if (!varPath) return rootInstance;
435
-
436
- const resolved = resolver.readFromRoot(varPath);
437
- if (Array.isArray(resolved)) {
438
- return resolved[0];
439
- }
440
- return resolved;
441
- }
442
-
443
- private extractSomaId(rawKey: string): string {
444
- const [somaId] = rawKey.split('@');
445
- return somaId;
446
- }
447
-
448
- private isNestedShowMapping(value: unknown): value is NestedShowMapping {
449
- return typeof value === 'object' && value !== null && 'bind' in value && 'show' in value;
450
- }
451
-
452
- private isExtendedShowValue(value: unknown): value is ExtendedShowValue {
453
- return typeof value === 'object' && value !== null;
454
- }
455
-
456
- private addError(report: SomaContractReport, message: string): void {
457
- report.errors.push(message);
458
- this.diagnostics?.recordValidation('error', message);
459
- }
460
-
461
- private addWarning(report: SomaContractReport, message: string): void {
462
- report.warnings.push(message);
463
- this.diagnostics?.recordValidation('warning', message);
464
- }
465
- }
1
+ import type { SomaScopeResolver } from '../engine/scope-resolver';
2
+ import type { ParsedEvent } from '../types/event.types';
3
+ import type {
4
+ ExtendedShowValue,
5
+ NestedShowMapping,
6
+ ShowMapping,
7
+ UiConfig,
8
+ } from '../types/ui-config.types';
9
+ import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
10
+
11
+ export interface SomaContractValidationInput {
12
+ container: HTMLElement;
13
+ uiConfig: UiConfig;
14
+ eventConfig: ParsedEvent[];
15
+ resolver: SomaScopeResolver;
16
+ rootInstance: object;
17
+ }
18
+
19
+ export interface SomaContractReport {
20
+ errors: string[];
21
+ warnings: string[];
22
+ anchorIds: string[];
23
+ bindingCount: number;
24
+ eventCount: number;
25
+ }
26
+
27
+ export class SomaContractError extends Error {
28
+ readonly report: SomaContractReport;
29
+
30
+ constructor(report: SomaContractReport) {
31
+ const summary = report.errors[0] ?? 'SOMA contract validation failed';
32
+ super(`[SOMA Contract] ${summary}`);
33
+ this.name = 'SomaContractError';
34
+ this.report = report;
35
+ }
36
+ }
37
+
38
+ export class SomaContractValidator {
39
+ private diagnostics: SomaDiagnostics | null;
40
+
41
+ constructor(diagnostics?: SomaDiagnostics) {
42
+ this.diagnostics = diagnostics ?? null;
43
+ }
44
+
45
+ validate(input: SomaContractValidationInput): SomaContractReport {
46
+ const hostCount = input.container.querySelectorAll('[data-soma-host]').length;
47
+ const { anchors, duplicates } = this.collectAnchorStats(input.container);
48
+ const report: SomaContractReport = {
49
+ errors: [],
50
+ warnings: [],
51
+ anchorIds: [...anchors].sort(),
52
+ bindingCount: 0,
53
+ eventCount: input.eventConfig.length,
54
+ };
55
+
56
+ if (hostCount === 0) {
57
+ this.addError(report, 'container: 缺少 data-soma-host 边界');
58
+ } else if (hostCount > 1) {
59
+ this.addWarning(report, `container: 检测到 ${hostCount} 个 data-soma-host,建议每页仅保留一个业务应用边界`);
60
+ }
61
+
62
+ for (const [somaId, count] of duplicates.entries()) {
63
+ this.addError(report, `anchor.${somaId}: 检测到 ${count} 个重复的静态 data-soma-id,绑定会产生歧义`);
64
+ }
65
+
66
+ this.validateShowMapping(
67
+ input.uiConfig.show,
68
+ anchors,
69
+ input.resolver,
70
+ input.rootInstance,
71
+ report,
72
+ 'show',
73
+ );
74
+ this.validateEvents(
75
+ input.eventConfig,
76
+ anchors,
77
+ input.resolver,
78
+ input.rootInstance,
79
+ report,
80
+ );
81
+
82
+ if (report.errors.length > 0) {
83
+ throw new SomaContractError(report);
84
+ }
85
+
86
+ return report;
87
+ }
88
+
89
+ private collectAnchorStats(container: HTMLElement): {
90
+ anchors: Set<string>;
91
+ duplicates: Map<string, number>;
92
+ } {
93
+ const anchors = new Set<string>();
94
+ const counts = new Map<string, number>();
95
+
96
+ const scanNode = (root: HTMLElement | DocumentFragment) => {
97
+ root.querySelectorAll<HTMLElement>('[data-soma-id]').forEach((element) => {
98
+ const somaId = element.getAttribute('data-soma-id');
99
+ if (somaId) {
100
+ anchors.add(somaId);
101
+ counts.set(somaId, (counts.get(somaId) ?? 0) + 1);
102
+ }
103
+ });
104
+ // Also scan inside <template> elements whose content lives in a DocumentFragment
105
+ root.querySelectorAll<HTMLTemplateElement>('template[data-soma-role]').forEach((tmpl) => {
106
+ if (tmpl.content) {
107
+ scanNode(tmpl.content);
108
+ }
109
+ });
110
+ };
111
+
112
+ scanNode(container);
113
+
114
+ const duplicates = new Map<string, number>();
115
+ for (const [somaId, count] of counts.entries()) {
116
+ if (count > 1) {
117
+ duplicates.set(somaId, count);
118
+ }
119
+ }
120
+
121
+ return { anchors, duplicates };
122
+ }
123
+
124
+ private validateShowMapping(
125
+ show: ShowMapping,
126
+ anchors: Set<string>,
127
+ resolver: SomaScopeResolver,
128
+ rootInstance: object,
129
+ report: SomaContractReport,
130
+ basePath: string,
131
+ ): void {
132
+ for (const [rawKey, value] of Object.entries(show)) {
133
+ report.bindingCount += 1;
134
+ const currentPath = `${basePath}.${rawKey}`;
135
+ const somaId = this.extractSomaId(rawKey);
136
+
137
+ if (!anchors.has(somaId)) {
138
+ this.addError(report, `${currentPath}: 缺少 data-soma-id="${somaId}"`);
139
+ }
140
+
141
+ if (typeof value === 'string') {
142
+ this.validateReadablePath(value, currentPath, resolver, rootInstance, report);
143
+ continue;
144
+ }
145
+
146
+ if (this.isNestedShowMapping(value)) {
147
+ this.validateReadablePath(
148
+ value.bind.obj,
149
+ `${currentPath}.bind.obj`,
150
+ resolver,
151
+ rootInstance,
152
+ report,
153
+ );
154
+ this.validateShowMapping(
155
+ value.show,
156
+ anchors,
157
+ resolver,
158
+ rootInstance,
159
+ report,
160
+ `${currentPath}.show`,
161
+ );
162
+ continue;
163
+ }
164
+
165
+ if (this.isExtendedShowValue(value)) {
166
+ if (value.text) {
167
+ this.validateReadablePath(
168
+ value.text,
169
+ `${currentPath}.text`,
170
+ resolver,
171
+ rootInstance,
172
+ report,
173
+ );
174
+ }
175
+ if (value.model) {
176
+ this.validateReadablePath(
177
+ value.model,
178
+ `${currentPath}.model`,
179
+ resolver,
180
+ rootInstance,
181
+ report,
182
+ );
183
+ }
184
+ if (value.when) {
185
+ this.validateReadablePath(
186
+ value.when,
187
+ `${currentPath}.when`,
188
+ resolver,
189
+ rootInstance,
190
+ report,
191
+ );
192
+ }
193
+ if (value.class) {
194
+ for (const [className, expr] of Object.entries(value.class)) {
195
+ this.validateReadablePath(
196
+ expr,
197
+ `${currentPath}.class.${className}`,
198
+ resolver,
199
+ rootInstance,
200
+ report,
201
+ );
202
+ }
203
+ }
204
+ if (value.show) {
205
+ this.validateShowMapping(
206
+ value.show,
207
+ anchors,
208
+ resolver,
209
+ rootInstance,
210
+ report,
211
+ `${currentPath}.show`,
212
+ );
213
+ }
214
+ }
215
+ }
216
+ }
217
+
218
+ private validateEvents(
219
+ events: ParsedEvent[],
220
+ anchors: Set<string>,
221
+ resolver: SomaScopeResolver,
222
+ rootInstance: object,
223
+ report: SomaContractReport,
224
+ ): void {
225
+ const eventKeys = new Set<string>();
226
+
227
+ for (const event of events) {
228
+ const eventKey = `${event.domEvent}:${event.somaId}`;
229
+ if (eventKeys.has(eventKey)) {
230
+ this.addError(report, `event.${eventKey}: 重复声明的事件绑定`);
231
+ } else {
232
+ eventKeys.add(eventKey);
233
+ }
234
+
235
+ if (!anchors.has(event.somaId)) {
236
+ this.addError(report, `event.${eventKey}: 缺少事件源 data-soma-id="${event.somaId}"`);
237
+ }
238
+
239
+ if (event.targetId && event.targetId !== 'self' && !anchors.has(event.targetId)) {
240
+ this.addError(
241
+ report,
242
+ `event.${eventKey}: 缺少交互目标 data-soma-id="${event.targetId}"`,
243
+ );
244
+ }
245
+
246
+ if (event.funcPath) {
247
+ this.validateFunctionPath(
248
+ event.funcPath,
249
+ `event.${eventKey}.funcPath`,
250
+ resolver,
251
+ rootInstance,
252
+ report,
253
+ );
254
+ }
255
+ }
256
+ }
257
+
258
+ private validateReadablePath(
259
+ rawPath: string,
260
+ location: string,
261
+ resolver: SomaScopeResolver,
262
+ rootInstance: object,
263
+ report: SomaContractReport,
264
+ ): void {
265
+ let path = rawPath.trim();
266
+ if (!path) {
267
+ this.addError(report, `${location}: 绑定路径不能为空`);
268
+ return;
269
+ }
270
+
271
+ if (path.startsWith('!')) {
272
+ path = path.slice(1);
273
+ }
274
+
275
+ const segments = path.split('.').filter(Boolean);
276
+ if (segments.length === 0) {
277
+ this.addError(report, `${location}: 绑定路径不能为空`);
278
+ return;
279
+ }
280
+
281
+ const rootToken = segments[0];
282
+
283
+ if (resolver.hasVar(rootToken)) {
284
+ const varPath = resolver.getVarPath(rootToken);
285
+ if (varPath === '') {
286
+ this.validateSegments(rootInstance, segments.slice(1), location, report);
287
+ }
288
+ return;
289
+ }
290
+
291
+ this.validateSegments(rootInstance, segments, location, report);
292
+ }
293
+
294
+ private validateFunctionPath(
295
+ funcPath: string,
296
+ location: string,
297
+ resolver: SomaScopeResolver,
298
+ rootInstance: object,
299
+ report: SomaContractReport,
300
+ ): void {
301
+ const segments = funcPath.split('.').filter(Boolean);
302
+ if (segments.length < 2) {
303
+ this.addError(report, `${location}: 函数路径至少需要 "对象.方法" 两段`);
304
+ return;
305
+ }
306
+
307
+ const rootToken = segments[0];
308
+ if (resolver.hasVar(rootToken)) {
309
+ const varPath = resolver.getVarPath(rootToken);
310
+ if (varPath === '') {
311
+ try {
312
+ resolver.resolveFunction(funcPath);
313
+ } catch (error) {
314
+ const message = error instanceof Error ? error.message : String(error);
315
+ this.addError(report, `${location}: ${message}`);
316
+ }
317
+ return;
318
+ }
319
+
320
+ const sample = this.resolveAliasSample(rootToken, resolver, rootInstance);
321
+ if (sample === undefined) {
322
+ this.addWarning(
323
+ report,
324
+ `${location}: 别名 "${rootToken}" 当前缺少可验证样本,延迟到运行时校验`,
325
+ );
326
+ return;
327
+ }
328
+
329
+ this.validateFunctionOnTarget(sample, segments.slice(1), location, report, funcPath);
330
+ return;
331
+ }
332
+
333
+ try {
334
+ resolver.resolveFunction(funcPath);
335
+ } catch (error) {
336
+ const message = error instanceof Error ? error.message : String(error);
337
+ this.addError(report, `${location}: ${message}`);
338
+ }
339
+ }
340
+
341
+ private validateSegments(
342
+ rootInstance: object,
343
+ segments: string[],
344
+ location: string,
345
+ report: SomaContractReport,
346
+ ): void {
347
+ if (segments.length === 0) {
348
+ return;
349
+ }
350
+
351
+ let current: any = rootInstance;
352
+ for (let index = 0; index < segments.length; index++) {
353
+ const segment = segments[index];
354
+
355
+ if (current == null) {
356
+ this.addWarning(
357
+ report,
358
+ `${location}: 在 "${segments.slice(0, index).join('.')}" 处遇到空值,延迟到运行时校验`,
359
+ );
360
+ return;
361
+ }
362
+
363
+ if (Array.isArray(current)) {
364
+ this.addWarning(
365
+ report,
366
+ `${location}: "${segments.slice(0, index).join('.')}" 是集合,元素字段延迟到运行时校验`,
367
+ );
368
+ return;
369
+ }
370
+
371
+ if (!(segment in Object(current))) {
372
+ const message = `${location}: 路径 "${segments.slice(0, index + 1).join('.')}" 不存在`;
373
+ if (index === 0) {
374
+ this.addError(report, message);
375
+ } else {
376
+ this.addWarning(report, message);
377
+ }
378
+ return;
379
+ }
380
+
381
+ current = current[segment];
382
+ }
383
+ }
384
+
385
+ private validateFunctionOnTarget(
386
+ target: any,
387
+ segments: string[],
388
+ location: string,
389
+ report: SomaContractReport,
390
+ funcPath: string,
391
+ ): void {
392
+ let current = target;
393
+
394
+ for (let index = 0; index < segments.length; index++) {
395
+ if (current == null) {
396
+ this.addWarning(report, `${location}: "${funcPath}" 在运行时可能为空对象`);
397
+ return;
398
+ }
399
+
400
+ if (Array.isArray(current)) {
401
+ if (current.length === 0) {
402
+ this.addWarning(report, `${location}: "${funcPath}" 对应集合为空,延迟到运行时校验`);
403
+ return;
404
+ }
405
+ current = current[0];
406
+ }
407
+
408
+ const segment = segments[index];
409
+ if (!(segment in Object(current))) {
410
+ this.addError(
411
+ report,
412
+ `${location}: 函数路径 "${funcPath}" 缺少属性 "${segment}"`,
413
+ );
414
+ return;
415
+ }
416
+
417
+ const next = current[segment];
418
+ if (index === segments.length - 1 && typeof next !== 'function') {
419
+ this.addError(report, `${location}: "${funcPath}" 不是可调用函数`);
420
+ return;
421
+ }
422
+
423
+ current = next;
424
+ }
425
+ }
426
+
427
+ private resolveAliasSample(
428
+ alias: string,
429
+ resolver: SomaScopeResolver,
430
+ rootInstance: object,
431
+ ): any {
432
+ const varPath = resolver.getVarPath(alias);
433
+ if (varPath === undefined) return undefined;
434
+ if (!varPath) return rootInstance;
435
+
436
+ const resolved = resolver.readFromRoot(varPath);
437
+ if (Array.isArray(resolved)) {
438
+ return resolved[0];
439
+ }
440
+ return resolved;
441
+ }
442
+
443
+ private extractSomaId(rawKey: string): string {
444
+ const [somaId] = rawKey.split('@');
445
+ return somaId;
446
+ }
447
+
448
+ private isNestedShowMapping(value: unknown): value is NestedShowMapping {
449
+ return typeof value === 'object' && value !== null && 'bind' in value && 'show' in value;
450
+ }
451
+
452
+ private isExtendedShowValue(value: unknown): value is ExtendedShowValue {
453
+ return typeof value === 'object' && value !== null;
454
+ }
455
+
456
+ private addError(report: SomaContractReport, message: string): void {
457
+ report.errors.push(message);
458
+ this.diagnostics?.recordValidation('error', message);
459
+ }
460
+
461
+ private addWarning(report: SomaContractReport, message: string): void {
462
+ report.warnings.push(message);
463
+ this.diagnostics?.recordValidation('warning', message);
464
+ }
465
+ }
package/dist/cli/soma.js CHANGED
@@ -35,7 +35,7 @@ if (!nextBin) {
35
35
  console.error('[soma] 找不到 next,请在 soma-core 包内安装依赖。');
36
36
  process.exit(1);
37
37
  }
38
- /** 在宿主根执行 CLI;子进程仅注入 SOMA_HOST_DIR */
38
+ /** 在业务应用根执行 CLI;子进程仅注入 SOMA_HOST_DIR */
39
39
  const hostDir = node_path_1.default.resolve(process.cwd());
40
40
  const nextArgs = [nextBin, command, ...args.slice(1)];
41
41
  const child = (0, node_child_process_1.spawnSync)(process.execPath, nextArgs, {
package/next.config.js CHANGED
@@ -4,7 +4,7 @@ const path = require('path');
4
4
  const rawHostDir = process.env.SOMA_HOST_DIR;
5
5
  if (!rawHostDir || !String(rawHostDir).trim()) {
6
6
  throw new Error(
7
- '[soma-core] 请设置 SOMA_HOST_DIR(宿主应用根)。通过 `npx soma` 或由 npm scripts 写入。',
7
+ '[soma-core] 请设置 SOMA_HOST_DIR(业务应用根目录)。通过 `npx soma` 或由 npm scripts 写入。',
8
8
  );
9
9
  }
10
10
  const hostDir = path.resolve(rawHostDir);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soma-core",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "SOMA — Semantic Oriented Modular Architecture. A declarative frontend framework runtime built on Next.js 14+ App Router.",
5
5
  "keywords": ["soma", "declarative-ui", "nextjs", "framework", "modular-architecture"],
6
6
  "license": "MIT",