soma-core 1.0.1 → 1.0.3

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 (234) hide show
  1. package/app/SomaPageClient.tsx +364 -0
  2. package/app/api/[...path]/route.ts +9 -85
  3. package/app/api/page/route.ts +57 -35
  4. package/app/api/soma-manifest/route.ts +39 -0
  5. package/app/components/SomaHydrationShell.tsx +23 -0
  6. package/app/favicon.ico/route.ts +13 -0
  7. package/app/layout.tsx +2 -2
  8. package/app/loading.tsx +5 -0
  9. package/app/page.tsx +19 -128
  10. package/bin/soma-lsp.cjs +195 -0
  11. package/bin/soma-sync.cjs +3 -0
  12. package/bin/soma.cjs +13 -1
  13. package/core/api/IService.ts +6 -10
  14. package/core/api/load-host-service.ts +75 -0
  15. package/core/api/service-path.ts +39 -0
  16. package/core/base/SomaEntity.ts +3 -10
  17. package/core/base/SomaLocaleOnlyPageRoot.ts +3 -4
  18. package/core/base/SomaPageRootBase.ts +20 -3
  19. package/core/base/decorators/Event.ts +23 -0
  20. package/core/base/decorators/Locale.ts +35 -0
  21. package/core/base/decorators/Page.ts +16 -0
  22. package/core/base/decorators/Show.ts +20 -0
  23. package/core/base/decorators/ShowList.ts +34 -0
  24. package/core/base/decorators/index.ts +5 -0
  25. package/core/base/index.ts +2 -0
  26. package/core/base/runAsync.ts +32 -0
  27. package/core/compiler/full-manifest-builder.ts +33 -7
  28. package/core/compiler/host-config-sync.cjs +38 -0
  29. package/core/compiler/manifest-compiler.ts +3 -2
  30. package/core/compiler/page-base-resolver.ts +26 -0
  31. package/core/compiler/precompiled-manifest-loader.ts +34 -0
  32. package/core/compiler/rollup-plugin-soma.ts +45 -0
  33. package/core/compiler/rspack-plugin-soma.js +33 -0
  34. package/core/compiler/soma-manifest-webpack-plugin.js +188 -0
  35. package/core/compiler/soma-precompile.js +3513 -0
  36. package/core/compiler/soma-precompile.ts +52 -6
  37. package/core/compiler/soma-rspack-yaml-loader.js +22 -0
  38. package/core/compiler/soma-webpack-loader.js +7 -1
  39. package/core/compiler/vite-plugin-soma.ts +11 -1
  40. package/core/container/IContainerAdapter.ts +36 -0
  41. package/core/container/MiniProgramContainerAdapter.ts +190 -0
  42. package/core/container/ReactNativeContainerAdapter.ts +189 -0
  43. package/core/container/SomaContainerAdapter.ts +17 -6
  44. package/core/diagnostics/SomaDiagnostics.ts +1 -1
  45. package/core/diagnostics/SomaTelemetry.ts +100 -0
  46. package/core/diagnostics/telemetry-context.ts +15 -0
  47. package/core/engine/asset-resolver.ts +39 -4
  48. package/core/engine/dom-renderer.ts +169 -35
  49. package/core/engine/event-engine.ts +110 -41
  50. package/core/engine/on-change-engine.ts +71 -0
  51. package/core/engine/property-watcher.ts +117 -0
  52. package/core/engine/reactive-proxy.ts +11 -5
  53. package/core/engine/render-engine.ts +97 -11
  54. package/core/engine/runtime-builder.ts +88 -11
  55. package/core/engine/scope-resolver.ts +65 -9
  56. package/core/engine/soma-bootstrap.ts +448 -244
  57. package/core/engine/style-binder.ts +423 -0
  58. package/core/engine/theme-variables.ts +37 -0
  59. package/core/engine/timer-engine.ts +92 -0
  60. package/core/engine/trigger-engine.ts +55 -0
  61. package/core/host/app-config.stub.ts +2 -0
  62. package/core/host/locale.stub.ts +2 -0
  63. package/core/host/resolve-host-bootstrap.ts +28 -0
  64. package/core/host/soma-bootstrap-host.stub.ts +4 -0
  65. package/core/host/source-packages.ts +112 -0
  66. package/core/index.ts +33 -2
  67. package/core/infra/auth/TokenAuthService.ts +17 -3
  68. package/core/infra/http/IHttpClient.ts +11 -1
  69. package/core/infra/http/SomaHttpService.ts +89 -31
  70. package/core/infra/i18n/DefaultI18n.ts +6 -18
  71. package/core/infra/i18n/II18n.ts +2 -3
  72. package/core/infra/notify/DomNotifyService.ts +98 -0
  73. package/core/infra/notify/INotifyTheme.ts +22 -0
  74. package/core/infra/realtime/IRealtimeService.ts +23 -0
  75. package/core/infra/realtime/IRealtimeTransport.ts +9 -0
  76. package/core/infra/realtime/SomaRealtimeService.ts +95 -0
  77. package/core/infra/realtime/SseRealtimeTransport.ts +36 -0
  78. package/core/infra/realtime/WebSocketRealtimeTransport.ts +102 -0
  79. package/core/infra/router/router-path.ts +28 -0
  80. package/core/infra/storage/SessionStorageService.ts +59 -0
  81. package/core/lsp/cross-file-diagnostics.cjs +160 -0
  82. package/core/lsp/event-yaml-completion.cjs +106 -0
  83. package/core/lsp/extra-completion.cjs +64 -0
  84. package/core/lsp/lsp-navigation.cjs +191 -0
  85. package/core/lsp/ui-yaml-completion.cjs +170 -0
  86. package/core/manifest/manifest-contract.ts +12 -0
  87. package/core/middleware/createPermissionMiddleware.ts +37 -0
  88. package/core/parser/annotation-extractor.ts +113 -0
  89. package/core/parser/pipeline-parser.ts +344 -276
  90. package/core/parser/style-config-parser.ts +340 -0
  91. package/core/parser/timer-parser.ts +70 -0
  92. package/core/parser/trigger-parser.ts +90 -0
  93. package/core/parser/ui-config-parser.ts +73 -1
  94. package/core/quality/SomaQualityRegistry.ts +68 -0
  95. package/core/runtime/SomaRuntimeServices.ts +100 -0
  96. package/core/runtime/SomaSnapshotStore.ts +5 -3
  97. package/core/types/domain.types.ts +5 -2
  98. package/core/types/event.types.ts +82 -57
  99. package/core/types/manifest.types.ts +2 -0
  100. package/core/types/style-config.types.ts +76 -0
  101. package/core/types/timer.types.ts +23 -0
  102. package/core/types/trigger.types.ts +14 -0
  103. package/core/types/ui-config.types.ts +9 -0
  104. package/core/types/watcher.types.ts +29 -0
  105. package/dist/cli/soma.js +23 -23
  106. package/dist/core/index.cjs +9065 -0
  107. package/dist/diagnostics/telemetry.cjs +105 -0
  108. package/dist/preview-export.cjs +3401 -0
  109. package/dist/tsconfig.types.tsbuildinfo +1 -0
  110. package/dist/types/api/IService.d.ts +28 -0
  111. package/dist/types/api/load-host-service.d.ts +5 -0
  112. package/dist/types/api/service-path.d.ts +13 -0
  113. package/dist/types/base/SomaApi.d.ts +5 -0
  114. package/dist/types/base/SomaDict.d.ts +89 -0
  115. package/dist/types/base/SomaEntity.d.ts +15 -0
  116. package/dist/types/base/SomaHttpClient.d.ts +66 -0
  117. package/dist/types/base/SomaLocaleOnlyPageRoot.d.ts +3 -0
  118. package/dist/types/base/SomaPageRootBase.d.ts +49 -0
  119. package/dist/types/base/SomaValidator.d.ts +55 -0
  120. package/dist/types/base/decorators/Event.d.ts +10 -0
  121. package/dist/types/base/decorators/Locale.d.ts +9 -0
  122. package/dist/types/base/decorators/Page.d.ts +4 -0
  123. package/dist/types/base/decorators/Show.d.ts +7 -0
  124. package/dist/types/base/decorators/ShowList.d.ts +12 -0
  125. package/dist/types/base/decorators/index.d.ts +5 -0
  126. package/dist/types/base/index.d.ts +9 -0
  127. package/dist/types/base/runAsync.d.ts +12 -0
  128. package/dist/types/compiler/full-manifest-builder.d.ts +35 -0
  129. package/dist/types/compiler/manifest-compiler.d.ts +29 -0
  130. package/dist/types/compiler/page-base-resolver.d.ts +6 -0
  131. package/dist/types/compiler/precompiled-manifest-loader.d.ts +5 -0
  132. package/dist/types/compiler/rollup-plugin-soma.d.ts +14 -0
  133. package/dist/types/compiler/route-builder.d.ts +12 -0
  134. package/dist/types/compiler/soma-precompile.d.ts +40 -0
  135. package/dist/types/compiler/vite-plugin-soma.d.ts +34 -0
  136. package/dist/types/container/IContainerAdapter.d.ts +30 -0
  137. package/dist/types/container/MiniProgramContainerAdapter.d.ts +52 -0
  138. package/dist/types/container/ReactNativeContainerAdapter.d.ts +47 -0
  139. package/dist/types/container/SomaContainerAdapter.d.ts +30 -0
  140. package/dist/types/diagnostics/SomaDiagnostics.d.ts +64 -0
  141. package/dist/types/diagnostics/SomaTelemetry.d.ts +32 -0
  142. package/dist/types/diagnostics/telemetry-context.d.ts +4 -0
  143. package/dist/types/engine/asset-resolver.d.ts +17 -0
  144. package/dist/types/engine/dom-renderer.d.ts +41 -0
  145. package/dist/types/engine/event-engine.d.ts +64 -0
  146. package/dist/types/engine/lis.d.ts +10 -0
  147. package/dist/types/engine/on-change-engine.d.ts +16 -0
  148. package/dist/types/engine/property-watcher.d.ts +18 -0
  149. package/dist/types/engine/reactive-proxy.d.ts +58 -0
  150. package/dist/types/engine/render-engine.d.ts +73 -0
  151. package/dist/types/engine/runtime-builder.d.ts +58 -0
  152. package/dist/types/engine/scope-resolver.d.ts +90 -0
  153. package/dist/types/engine/soma-bootstrap.d.ts +112 -0
  154. package/dist/types/engine/style-binder.d.ts +81 -0
  155. package/dist/types/engine/theme-variables.d.ts +3 -0
  156. package/dist/types/engine/timer-engine.d.ts +19 -0
  157. package/dist/types/engine/trigger-engine.d.ts +16 -0
  158. package/dist/types/host/app-config.stub.d.ts +3 -0
  159. package/dist/types/host/locale.stub.d.ts +3 -0
  160. package/dist/types/host/resolve-host-bootstrap.d.ts +11 -0
  161. package/dist/types/host/soma-bootstrap-host.stub.d.ts +3 -0
  162. package/dist/types/host/source-packages.d.ts +8 -0
  163. package/dist/types/index.d.ts +35 -0
  164. package/dist/types/infra/auth/IAuthService.d.ts +12 -0
  165. package/dist/types/infra/auth/TokenAuthService.d.ts +26 -0
  166. package/dist/types/infra/cache/ICache.d.ts +12 -0
  167. package/dist/types/infra/cache/MemoryCache.d.ts +14 -0
  168. package/dist/types/infra/cache/ServerFileCache.d.ts +37 -0
  169. package/dist/types/infra/config/IConfig.d.ts +9 -0
  170. package/dist/types/infra/config/SomaConfig.d.ts +21 -0
  171. package/dist/types/infra/event-bus/IEventBus.d.ts +8 -0
  172. package/dist/types/infra/event-bus/SomaEventBus.d.ts +9 -0
  173. package/dist/types/infra/http/IHttpClient.d.ts +28 -0
  174. package/dist/types/infra/http/SomaHttpService.d.ts +27 -0
  175. package/dist/types/infra/i18n/DefaultI18n.d.ts +7 -0
  176. package/dist/types/infra/i18n/II18n.d.ts +6 -0
  177. package/dist/types/infra/logger/ConsoleLogger.d.ts +14 -0
  178. package/dist/types/infra/logger/ILogger.d.ts +17 -0
  179. package/dist/types/infra/notify/DefaultNotifyService.d.ts +16 -0
  180. package/dist/types/infra/notify/DomNotifyService.d.ts +16 -0
  181. package/dist/types/infra/notify/INotifyService.d.ts +12 -0
  182. package/dist/types/infra/notify/INotifyTheme.d.ts +12 -0
  183. package/dist/types/infra/permission/IPermission.d.ts +10 -0
  184. package/dist/types/infra/permission/SomaPermission.d.ts +19 -0
  185. package/dist/types/infra/realtime/IRealtimeService.d.ts +13 -0
  186. package/dist/types/infra/realtime/IRealtimeTransport.d.ts +8 -0
  187. package/dist/types/infra/realtime/SomaRealtimeService.d.ts +20 -0
  188. package/dist/types/infra/realtime/SseRealtimeTransport.d.ts +11 -0
  189. package/dist/types/infra/realtime/WebSocketRealtimeTransport.d.ts +30 -0
  190. package/dist/types/infra/router/IRouter.d.ts +16 -0
  191. package/dist/types/infra/router/SomaRouter.d.ts +18 -0
  192. package/dist/types/infra/router/router-path.d.ts +6 -0
  193. package/dist/types/infra/storage/IStorageService.d.ts +7 -0
  194. package/dist/types/infra/storage/MemoryStorageService.d.ts +15 -0
  195. package/dist/types/infra/storage/SessionStorageService.d.ts +14 -0
  196. package/dist/types/infra/timer/ITimer.d.ts +13 -0
  197. package/dist/types/infra/timer/SomaTimer.d.ts +21 -0
  198. package/dist/types/manifest/manifest-contract.d.ts +4 -0
  199. package/dist/types/middleware/SomaMiddlewareChain.d.ts +6 -0
  200. package/dist/types/middleware/createPermissionMiddleware.d.ts +14 -0
  201. package/dist/types/parser/annotation-extractor.d.ts +12 -0
  202. package/dist/types/parser/pipeline-parser.d.ts +62 -0
  203. package/dist/types/parser/style-config-parser.d.ts +20 -0
  204. package/dist/types/parser/timer-parser.d.ts +6 -0
  205. package/dist/types/parser/trigger-parser.d.ts +13 -0
  206. package/dist/types/parser/ui-config-parser.d.ts +34 -0
  207. package/dist/types/parser/yaml-loader.d.ts +21 -0
  208. package/dist/types/quality/SomaQualityRegistry.d.ts +31 -0
  209. package/dist/types/runtime/SomaRuntimeServices.d.ts +35 -0
  210. package/dist/types/runtime/SomaSnapshotStore.d.ts +13 -0
  211. package/dist/types/scheduler/SomaScheduler.d.ts +25 -0
  212. package/dist/types/types/domain.types.d.ts +82 -0
  213. package/dist/types/types/engine.types.d.ts +22 -0
  214. package/dist/types/types/event.types.d.ts +61 -0
  215. package/dist/types/types/keyboard.types.d.ts +4 -0
  216. package/dist/types/types/manifest.types.d.ts +29 -0
  217. package/dist/types/types/scheduler.types.d.ts +8 -0
  218. package/dist/types/types/style-config.types.d.ts +62 -0
  219. package/dist/types/types/timer.types.d.ts +19 -0
  220. package/dist/types/types/trigger.types.d.ts +12 -0
  221. package/dist/types/types/ui-config.types.d.ts +85 -0
  222. package/dist/types/types/watcher.types.d.ts +24 -0
  223. package/dist/types/validation/contract-validator.d.ts +40 -0
  224. package/editor/vscode/extension.js +39 -0
  225. package/editor/vscode/language-configuration.json +17 -0
  226. package/editor/vscode/package.json +98 -0
  227. package/editor/vscode/syntaxes/soma-event-yaml.tmLanguage.json +30 -0
  228. package/editor/vscode/syntaxes/soma-ui-yaml.tmLanguage.json +42 -0
  229. package/global.d.ts +22 -3
  230. package/next.config.js +73 -4
  231. package/package.json +58 -17
  232. package/tailwind.config.ts +36 -13
  233. package/tsconfig.json +6 -2
  234. package/core/router/RouteHandler.ts +0 -93
@@ -0,0 +1,23 @@
1
+ /**
2
+ * SSR 首屏占位 — SOMA 运行时仅在客户端 mount(8.4)
3
+ * 避免 hydration mismatch,同时提供可访问的加载态
4
+ */
5
+ export function SomaHydrationShell() {
6
+ return (
7
+ <div
8
+ className="flex min-h-screen items-center justify-center bg-gray-50"
9
+ role="status"
10
+ aria-live="polite"
11
+ aria-busy="true"
12
+ data-soma-hydration="pending"
13
+ >
14
+ <div className="text-center">
15
+ <div
16
+ className="mx-auto mb-3 h-8 w-8 animate-spin rounded-full border-2 border-blue-600 border-t-transparent"
17
+ aria-hidden
18
+ />
19
+ <p className="text-sm text-gray-600">Loading SOMA page…</p>
20
+ </div>
21
+ </div>
22
+ );
23
+ }
@@ -0,0 +1,13 @@
1
+ const faviconSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
2
+ <rect width="64" height="64" rx="14" fill="#1677ff"/>
3
+ <path d="M18 22h8l6 18 6-18h8L35 48h-6L18 22z" fill="#ffffff"/>
4
+ </svg>`;
5
+
6
+ export function GET(): Response {
7
+ return new Response(faviconSvg, {
8
+ headers: {
9
+ 'content-type': 'image/svg+xml; charset=utf-8',
10
+ 'cache-control': 'public, max-age=86400',
11
+ },
12
+ });
13
+ }
package/app/layout.tsx CHANGED
@@ -1,8 +1,8 @@
1
1
  import './globals.css';
2
2
 
3
3
  export const metadata = {
4
- title: process.env.SOMA_APP_TITLE || 'SOMA App',
5
- description: process.env.SOMA_APP_DESC || 'SOMA Framework',
4
+ title: 'SOMA',
5
+ description: 'SOMA declarative UI runtime',
6
6
  };
7
7
 
8
8
  export default function RootLayout({
@@ -0,0 +1,5 @@
1
+ import { SomaHydrationShell } from './components/SomaHydrationShell';
2
+
3
+ export default function Loading() {
4
+ return <SomaHydrationShell />;
5
+ }
package/app/page.tsx CHANGED
@@ -1,129 +1,20 @@
1
- 'use client';
2
-
3
- import { useEffect, useRef, useState } from 'react';
4
- import { usePathname } from 'next/navigation';
5
- import type { SomaBootstrap as SomaBootstrapType } from '../core/engine/soma-bootstrap';
6
-
7
- const isDev = process.env.NODE_ENV !== 'production';
8
-
9
- export default function SomaEntry() {
10
- const pathname = usePathname();
11
- return <SomaPageRenderer path={pathname} />;
12
- }
13
-
14
- function urlToBase(urlPath: string): string {
15
- const clean = urlPath.replace(/^\//, '').replace(/\.html$/, '');
16
- return clean || 'index';
17
- }
18
-
19
- type PagePayload = {
20
- html: string;
21
- ui: string;
22
- event: string;
23
- includes?: Record<string, string>;
24
- localeYaml: string;
25
- appConfigYaml: string;
26
- };
27
-
28
- const pageAssetCache = new Map<string, PagePayload>();
29
-
30
- function SomaPageRenderer({ path }: { path: string }) {
31
- const containerRef = useRef<HTMLDivElement>(null);
32
- const bootstrapRef = useRef<SomaBootstrapType | null>(null);
33
- const [error, setError] = useState<string | null>(null);
34
-
35
- useEffect(() => {
36
- if (!containerRef.current) return;
37
-
38
- const base = urlToBase(path);
39
- let cancelled = false;
40
-
41
- const run = async () => {
42
- try {
43
- setError(null);
44
-
45
- let DomainClass: new () => any;
46
- try {
47
- const mod = await import(
48
- /* webpackInclude: /\.ts$/ */
49
- `@soma-host/domain/ui/${base}Class`
50
- );
51
- DomainClass = mod.default ?? mod[Object.keys(mod)[0]];
52
- } catch {
53
- const { SomaLocaleOnlyPageRoot } = await import('../core/base/SomaLocaleOnlyPageRoot');
54
- DomainClass = SomaLocaleOnlyPageRoot;
55
- }
56
-
57
- const { SomaBootstrap } = await import('../core/engine/soma-bootstrap');
58
-
59
- // dev 模式不使用客户端 payload 缓存(服务端文件变更需实时反映)
60
- if (!isDev) {
61
- const cached = pageAssetCache.get(path);
62
- if (cached) {
63
- await mountInto(DomainClass, SomaBootstrap, cached);
64
- return;
65
- }
66
- }
67
-
68
- const res = await fetch(
69
- `/api/page?path=${encodeURIComponent(path)}`,
70
- );
71
- if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
72
-
73
- const data = await res.json();
74
- if (cancelled) return;
75
-
76
- const payload: PagePayload = {
77
- html: data.html,
78
- ui: data.ui,
79
- event: data.event,
80
- includes: data.includes,
81
- localeYaml: data.localeYaml ?? '',
82
- appConfigYaml: data.appConfigYaml ?? '',
83
- };
84
-
85
- if (!isDev) {
86
- pageAssetCache.set(path, payload);
87
- }
88
- await mountInto(DomainClass, SomaBootstrap, payload);
89
- } catch (err: any) {
90
- if (!cancelled) setError(err?.message ?? String(err));
91
- }
92
- };
93
-
94
- const mountInto = async (DomainClass: new () => any, SomaBootstrap: any, payload: PagePayload) => {
95
- await bootstrapRef.current?.unmount();
96
- const bs = new SomaBootstrap();
97
- bootstrapRef.current = bs;
98
-
99
- await bs.mount(containerRef.current!, {
100
- html: payload.html,
101
- includes: payload.includes,
102
- DomainClass,
103
- uiYaml: payload.ui,
104
- eventYaml: payload.event,
105
- localeYaml: payload.localeYaml ?? '',
106
- appConfigYaml: payload.appConfigYaml ?? '',
107
- });
108
- };
109
-
110
- void run();
111
-
112
- return () => {
113
- cancelled = true;
114
- void bootstrapRef.current?.unmount();
115
- bootstrapRef.current = null;
116
- };
117
- }, [path]);
118
-
119
- if (error) {
120
- return (
121
- <div className="p-8 text-red-600">
122
- <p className="font-bold">页面加载失败</p>
123
- <p className="text-sm mt-1">{error}</p>
124
- </div>
125
- );
126
- }
127
-
128
- return <div ref={containerRef} />;
1
+ import dynamic from 'next/dynamic';
2
+ import { Suspense } from 'react';
3
+ import { SomaHydrationShell } from './components/SomaHydrationShell';
4
+
5
+ /**
6
+ * SSR 边界(8.4):服务端仅渲染占位壳,SOMA 运行时在客户端 mount。
7
+ * 避免 window/document 在 SSR 阶段被访问,消除 hydration mismatch。
8
+ */
9
+ const SomaPageClient = dynamic(() => import('./SomaPageClient'), {
10
+ ssr: false,
11
+ loading: () => <SomaHydrationShell />,
12
+ });
13
+
14
+ export default function SomaEntryPage() {
15
+ return (
16
+ <Suspense fallback={<SomaHydrationShell />}>
17
+ <SomaPageClient />
18
+ </Suspense>
19
+ );
129
20
  }
@@ -0,0 +1,195 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * SOMA Language Server — 跨文件锚点诊断(html ↔ ui ↔ event)
4
+ */
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const { lintAnchorConsistency } = require('../core/lsp/cross-file-diagnostics.cjs');
8
+ const { getUiYamlCompletions } = require('../core/lsp/ui-yaml-completion.cjs');
9
+ const { getEventYamlCompletions } = require('../core/lsp/event-yaml-completion.cjs');
10
+ const { getHover, getDefinition } = require('../core/lsp/lsp-navigation.cjs');
11
+ const { getLocaleYamlCompletions, getHtmlAnchorCompletions } = require('../core/lsp/extra-completion.cjs');
12
+
13
+ let hostDir = process.env.SOMA_HOST_DIR || null;
14
+ /** @type {Map<string, string>} */
15
+ const openDocs = new Map();
16
+
17
+ function readDocText(uri) {
18
+ if (openDocs.has(uri)) return openDocs.get(uri);
19
+ try {
20
+ const filePath = decodeURIComponent(uri.replace(/^file:\/\//, ''));
21
+ return fs.readFileSync(filePath, 'utf8');
22
+ } catch {
23
+ return '';
24
+ }
25
+ }
26
+
27
+ function uriToHostDir(uri) {
28
+ if (!uri) return hostDir;
29
+ try {
30
+ const filePath = decodeURIComponent(uri.replace(/^file:\/\//, ''));
31
+ let dir = path.dirname(filePath);
32
+ for (let i = 0; i < 6; i++) {
33
+ if (fs.existsSync(path.join(dir, 'html')) && fs.existsSync(path.join(dir, 'ui'))) {
34
+ return dir;
35
+ }
36
+ const parent = path.dirname(dir);
37
+ if (parent === dir) break;
38
+ dir = parent;
39
+ }
40
+ } catch {
41
+ /* ignore */
42
+ }
43
+ return hostDir;
44
+ }
45
+
46
+ function send(msg) {
47
+ const body = JSON.stringify(msg);
48
+ process.stdout.write(`Content-Length: ${Buffer.byteLength(body, 'utf8')}\r\n\r\n${body}`);
49
+ }
50
+
51
+ function respond(id, result) {
52
+ send({ jsonrpc: '2.0', id, result: result ?? null });
53
+ }
54
+
55
+ function notify(method, params) {
56
+ send({ jsonrpc: '2.0', method, params });
57
+ }
58
+
59
+ function publishAllDiagnostics(resolvedHost) {
60
+ if (!resolvedHost) return;
61
+ const crossFile = lintAnchorConsistency(resolvedHost);
62
+ const byUri = new Map();
63
+ for (const d of crossFile) {
64
+ const list = byUri.get(d.uri) ?? [];
65
+ list.push(d);
66
+ byUri.set(d.uri, list);
67
+ }
68
+ for (const [uri, diagnostics] of byUri) {
69
+ notify('textDocument/publishDiagnostics', { uri, diagnostics });
70
+ }
71
+ }
72
+
73
+ function handleMessage(msg) {
74
+ const { id, method, params } = msg;
75
+
76
+ switch (method) {
77
+ case 'initialize':
78
+ hostDir = uriToHostDir(params.rootUri ?? params.rootPath) ?? hostDir;
79
+ respond(id, {
80
+ capabilities: {
81
+ textDocumentSync: 1,
82
+ completionProvider: {
83
+ triggerCharacters: ['.', ':', ' ', '|', '"'],
84
+ resolveProvider: false,
85
+ },
86
+ hoverProvider: true,
87
+ definitionProvider: true,
88
+ },
89
+ serverInfo: { name: 'soma-lsp', version: '1.2.0' },
90
+ });
91
+ publishAllDiagnostics(hostDir);
92
+ break;
93
+
94
+ case 'initialized':
95
+ break;
96
+
97
+ case 'textDocument/didOpen':
98
+ if (params.textDocument?.uri) {
99
+ openDocs.set(params.textDocument.uri, params.textDocument.text ?? readDocText(params.textDocument.uri));
100
+ }
101
+ publishAllDiagnostics(uriToHostDir(params.textDocument?.uri) ?? hostDir);
102
+ break;
103
+
104
+ case 'textDocument/didChange':
105
+ if (params.textDocument?.uri && params.contentChanges?.length) {
106
+ const latest = params.contentChanges[params.contentChanges.length - 1].text;
107
+ if (typeof latest === 'string') openDocs.set(params.textDocument.uri, latest);
108
+ }
109
+ break;
110
+
111
+ case 'textDocument/didClose':
112
+ if (params.textDocument?.uri) openDocs.delete(params.textDocument.uri);
113
+ break;
114
+
115
+ case 'textDocument/didSave':
116
+ publishAllDiagnostics(uriToHostDir(params.textDocument?.uri) ?? hostDir);
117
+ break;
118
+
119
+ case 'textDocument/completion': {
120
+ const resolved = uriToHostDir(params.textDocument?.uri) ?? hostDir;
121
+ const uri = params.textDocument?.uri ?? '';
122
+ const text = readDocText(uri);
123
+ const pos = params.position ?? { line: 0, character: 0 };
124
+ const fileName = decodeURIComponent(uri.split('/').pop() ?? '');
125
+ let items = [];
126
+ if (resolved) {
127
+ if (fileName.endsWith('_ui.yaml')) {
128
+ items = getUiYamlCompletions(resolved, uri, text, pos);
129
+ } else if (fileName.endsWith('_event.yaml')) {
130
+ items = getEventYamlCompletions(resolved, uri, text, pos);
131
+ } else if (fileName === 'locale.yaml') {
132
+ items = getLocaleYamlCompletions(resolved, uri, text, pos);
133
+ } else if (fileName.endsWith('.html')) {
134
+ items = getHtmlAnchorCompletions(resolved, uri, text, pos);
135
+ }
136
+ }
137
+ respond(id, { isIncomplete: false, items });
138
+ break;
139
+ }
140
+
141
+ case 'textDocument/hover': {
142
+ const resolved = uriToHostDir(params.textDocument?.uri) ?? hostDir;
143
+ const uri = params.textDocument?.uri ?? '';
144
+ const text = readDocText(uri);
145
+ const result = resolved ? getHover(resolved, uri, text, params.position ?? { line: 0, character: 0 }) : null;
146
+ respond(id, result);
147
+ break;
148
+ }
149
+
150
+ case 'textDocument/definition': {
151
+ const resolved = uriToHostDir(params.textDocument?.uri) ?? hostDir;
152
+ const uri = params.textDocument?.uri ?? '';
153
+ const text = readDocText(uri);
154
+ const result = resolved ? getDefinition(resolved, uri, text, params.position ?? { line: 0, character: 0 }) : null;
155
+ respond(id, result ? [result] : []);
156
+ break;
157
+ }
158
+
159
+ case 'shutdown':
160
+ respond(id, null);
161
+ break;
162
+
163
+ case 'exit':
164
+ process.exit(0);
165
+ break;
166
+
167
+ default:
168
+ if (id !== undefined) respond(id, null);
169
+ }
170
+ }
171
+
172
+ let buffer = Buffer.alloc(0);
173
+
174
+ process.stdin.on('data', (chunk) => {
175
+ buffer = Buffer.concat([buffer, chunk]);
176
+ while (true) {
177
+ const headerEnd = buffer.indexOf('\r\n\r\n');
178
+ if (headerEnd === -1) break;
179
+ const header = buffer.slice(0, headerEnd).toString('utf8');
180
+ const match = header.match(/Content-Length: (\d+)/i);
181
+ if (!match) break;
182
+ const length = parseInt(match[1], 10);
183
+ const bodyStart = headerEnd + 4;
184
+ if (buffer.length < bodyStart + length) break;
185
+ const body = buffer.slice(bodyStart, bodyStart + length).toString('utf8');
186
+ buffer = buffer.slice(bodyStart + length);
187
+ try {
188
+ handleMessage(JSON.parse(body));
189
+ } catch {
190
+ /* ignore malformed */
191
+ }
192
+ }
193
+ });
194
+
195
+ process.stderr.write('[soma-lsp] ready on stdio\n');
@@ -0,0 +1,3 @@
1
+ const { syncHostConfig } = require('../core/compiler/host-config-sync.cjs');
2
+
3
+ module.exports = { syncHostConfig };
package/bin/soma.cjs CHANGED
@@ -1,2 +1,14 @@
1
1
  #!/usr/bin/env node
2
- require('../dist/cli/soma.js');
2
+ /**
3
+ * SOMA CLI 薄入口 — 优先委托 dist/cli/soma.js,回退到内联实现
4
+ */
5
+ const path = require('node:path');
6
+ const fs = require('node:fs');
7
+
8
+ const distCli = path.resolve(__dirname, '..', 'dist', 'cli', 'soma.js');
9
+
10
+ if (fs.existsSync(distCli)) {
11
+ require(distCli);
12
+ } else {
13
+ require('./soma-inline.cjs');
14
+ }
@@ -1,7 +1,7 @@
1
1
  import { NextRequest } from 'next/server';
2
2
 
3
3
  /**
4
- * SOMA 后端服务接口 —— app-demo/api/service/ 下的服务类必须实现此接口。
4
+ * SOMA 后端服务接口 —— 宿主项目 `api/service/` 下的服务类可实现此接口。
5
5
  *
6
6
  * 实现约定:
7
7
  * - 每个文件 default export 一个实现 IService 的类
@@ -10,16 +10,12 @@ import { NextRequest } from 'next/server';
10
10
  *
11
11
  * @example
12
12
  * ```ts
13
- * // app-demo/api/service/Login.ts
14
- * import type { IService } from 'soma-core/core/api/IService';
13
+ * // {host}/api/service/Health.ts
14
+ * import type { IService } from '@core/api/IService';
15
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 });
16
+ * export default class HealthService implements IService {
17
+ * async get(): Promise<Response> {
18
+ * return Response.json({ ok: true });
23
19
  * }
24
20
  * }
25
21
  * ```
@@ -0,0 +1,75 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import createJiti from 'jiti';
4
+ import type { IService } from './IService';
5
+ import { resolveServiceFilePath } from './service-path';
6
+ import { getSomaAssetSources } from '../host/source-packages';
7
+
8
+ function isService(obj: unknown): obj is IService {
9
+ if (!obj || typeof obj !== 'object') return false;
10
+ const methods = ['get', 'post', 'put', 'patch', 'delete'] as const;
11
+ return methods.some((m) => typeof (obj as IService)[m] === 'function');
12
+ }
13
+
14
+ function getCoreDir(): string {
15
+ // soma-core 根目录(route 运行于 next dev/build,cwd 即 soma-core)
16
+ return path.resolve(process.cwd(), 'core');
17
+ }
18
+
19
+ let jitiLoader: ReturnType<typeof createJiti> | null = null;
20
+ let jitiHostDir: string | null = null;
21
+ const instanceCache = new Map<string, IService>();
22
+
23
+ function getJiti(hostDir: string): ReturnType<typeof createJiti> {
24
+ if (!jitiLoader || jitiHostDir !== hostDir) {
25
+ jitiLoader = createJiti(import.meta.url, {
26
+ interopDefault: true,
27
+ alias: {
28
+ '@core': getCoreDir(),
29
+ '@soma-host': hostDir,
30
+ },
31
+ });
32
+ jitiHostDir = hostDir;
33
+ }
34
+ return jitiLoader;
35
+ }
36
+
37
+ /**
38
+ * 按约定从宿主 api/service/ 加载 IService 实例(运行时读盘,无需手写 registry)。
39
+ */
40
+ export function loadHostService(segments: string[]): IService | null {
41
+ const hostDir = process.env.SOMA_HOST_DIR;
42
+ if (!hostDir) return null;
43
+
44
+ const filePath = getSomaAssetSources(hostDir)
45
+ .map((source) => resolveServiceFilePath(source.codeRoot, segments))
46
+ .find((candidate): candidate is string => Boolean(candidate && fs.existsSync(candidate)));
47
+ if (!filePath) return null;
48
+
49
+ const isDev = process.env.NODE_ENV !== 'production';
50
+ if (!isDev && instanceCache.has(filePath)) {
51
+ return instanceCache.get(filePath)!;
52
+ }
53
+
54
+ try {
55
+ const mod = getJiti(hostDir)(filePath) as { default?: new () => IService };
56
+ const ServiceClass = mod?.default;
57
+ if (!ServiceClass || typeof ServiceClass !== 'function') {
58
+ console.warn(`[soma-api] ${filePath} missing default export`);
59
+ return null;
60
+ }
61
+
62
+ const instance = new ServiceClass();
63
+ if (!isService(instance)) {
64
+ console.warn(`[soma-api] ${filePath} does not implement IService`);
65
+ return null;
66
+ }
67
+
68
+ if (!isDev) instanceCache.set(filePath, instance);
69
+ return instance;
70
+ } catch (e: unknown) {
71
+ const message = e instanceof Error ? e.message : String(e);
72
+ console.error(`[soma-api] failed to load ${filePath}:`, message);
73
+ return null;
74
+ }
75
+ }
@@ -0,0 +1,39 @@
1
+ import { join, normalize, resolve } from 'node:path';
2
+
3
+ /**
4
+ * 将 kebab-case / snake_case 转为 PascalCase
5
+ * @example "user-profile" → "UserProfile", "oauth_token" → "OauthToken"
6
+ */
7
+ export function toPascalCase(str: string): string {
8
+ return str
9
+ .split(/[-_]/)
10
+ .map((s) => s.charAt(0).toUpperCase() + s.slice(1))
11
+ .join('');
12
+ }
13
+
14
+ /**
15
+ * 从 /api/{...path} 片段解析宿主服务文件绝对路径。
16
+ *
17
+ * 规则(与文档 12.4 一致):
18
+ * - ["login"] → {host}/api/service/Login.ts
19
+ * - ["user", "profile"] → {host}/api/service/user/Profile.ts
20
+ */
21
+ export function resolveServiceFilePath(hostDir: string, segments: string[]): string | null {
22
+ if (segments.length === 0) return null;
23
+
24
+ for (const segment of segments) {
25
+ if (!segment || segment.startsWith('_')) return null;
26
+ const normalized = normalize(segment);
27
+ if (normalized.startsWith('..') || normalized.includes('\0')) return null;
28
+ }
29
+
30
+ const fileName = `${toPascalCase(segments[segments.length - 1])}.ts`;
31
+ const dirs = segments.slice(0, -1);
32
+ const filePath = join(hostDir, 'api', 'service', ...dirs, fileName);
33
+
34
+ const resolved = resolve(filePath);
35
+ const serviceRoot = resolve(hostDir, 'api', 'service');
36
+ if (!resolved.startsWith(serviceRoot)) return null;
37
+
38
+ return resolved;
39
+ }
@@ -2,6 +2,8 @@
2
2
  * SomaEntity - 业务实体基类
3
3
  * 封装通用的异步操作状态管理和序列化能力
4
4
  */
5
+ import { runAsync as runAsyncUtil } from './runAsync';
6
+
5
7
  export abstract class SomaEntity<T extends Record<string, any> = Record<string, any>> {
6
8
  /** 实体级 loading 状态(Proxy 响应式) */
7
9
  loading: boolean = false;
@@ -13,16 +15,7 @@ export abstract class SomaEntity<T extends Record<string, any> = Record<string,
13
15
  * 封装异步操作:自动管理 loading/error 状态
14
16
  */
15
17
  protected async runAsync<R>(fn: () => Promise<R>): Promise<R | null> {
16
- this.loading = true;
17
- this.error = null;
18
- try {
19
- return await fn();
20
- } catch (e) {
21
- this.error = e instanceof Error ? e.message : String(e);
22
- return null;
23
- } finally {
24
- this.loading = false;
25
- }
18
+ return runAsyncUtil(this, fn);
26
19
  }
27
20
 
28
21
  /**
@@ -1,4 +1,3 @@
1
- import { SomaPageRootBase } from './SomaPageRootBase';
2
-
3
- /** 无独立 Domain 实现时的占位页(仅 locale/appConfig 文案) */
4
- export class SomaLocaleOnlyPageRoot extends SomaPageRootBase {}
1
+ import { SomaPageRootBase } from './SomaPageRootBase';
2
+
3
+ export class SomaLocaleOnlyPageRoot extends SomaPageRootBase {}
@@ -2,6 +2,9 @@
2
2
  // 不依赖任何 DOM API,可在 Node.js 环境下独立运行
3
3
 
4
4
  import type { SomaPageRoot, SomaAppConfig } from '../types/domain.types';
5
+ import type { SomaRuntimeServices } from '../runtime/SomaRuntimeServices';
6
+ import { readQueryParam } from '../infra/router/router-path';
7
+ import { runAsync as runAsyncUtil } from './runAsync';
5
8
 
6
9
  /**
7
10
  * SomaPageRootBase — 页面聚合根基类
@@ -22,9 +25,8 @@ export abstract class SomaPageRootBase implements SomaPageRoot {
22
25
  pageError: string | null = null;
23
26
 
24
27
  /**
25
- * 由引擎注入的 locale 配置
26
- * 包含页面上的固定文案(按钮文字、标题、提示语等)
27
- * Class 不负责加载此数据,由编排层(SomaBootstrap)统一加载并注入
28
+ * Content strings from locale.yaml injected by bootstrap.
29
+ * Not a multi-locale switcher — replace locale.yaml to change copy.
28
30
  */
29
31
  _locale: Record<string, string> = {};
30
32
 
@@ -34,6 +36,21 @@ export abstract class SomaPageRootBase implements SomaPageRoot {
34
36
  */
35
37
  _config: SomaAppConfig = {} as SomaAppConfig;
36
38
 
39
+ /** 由引擎注入的运行时基础设施(router / http / notify 等) */
40
+ _services?: SomaRuntimeServices;
41
+
42
+ /**
43
+ * 封装页面级异步操作:自动管理 pageLoading / pageError
44
+ */
45
+ protected async runAsync<R>(fn: () => Promise<R>): Promise<R | null> {
46
+ return runAsyncUtil(this, fn);
47
+ }
48
+
49
+ /** 读取 URL query(优先内存路由,回退地址栏) */
50
+ protected readQueryParam(key: string): string {
51
+ return readQueryParam(key, this._services?.router.getCurrentPath());
52
+ }
53
+
37
54
  /**
38
55
  * 页面初始化生命周期钩子
39
56
  * 引擎在渲染完成后调用
@@ -0,0 +1,23 @@
1
+ export interface EventEntry {
2
+ methodName: string;
3
+ pipeline: string;
4
+ }
5
+
6
+ const EVENT_REGISTRY = new WeakMap<Function, EventEntry[]>();
7
+
8
+ /**
9
+ * @Event(pipelineString) — 标记交互方法
10
+ * 格式: "anchorId.domEvent: ACTION_TYPE | [funcPath] | [target]"
11
+ */
12
+ export function Event(pipelineString: string): MethodDecorator {
13
+ return (target: object, propertyKey: string | symbol) => {
14
+ const ctor = (target as { constructor: Function }).constructor;
15
+ const existing = EVENT_REGISTRY.get(ctor) ?? [];
16
+ existing.push({ methodName: String(propertyKey), pipeline: pipelineString });
17
+ EVENT_REGISTRY.set(ctor, existing);
18
+ };
19
+ }
20
+
21
+ export function getEventMetadata(ctor: Function): EventEntry[] {
22
+ return EVENT_REGISTRY.get(ctor) ?? [];
23
+ }