soma-core 1.0.0 → 1.0.2

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 (228) hide show
  1. package/app/SomaPageClient.tsx +336 -0
  2. package/app/api/[...path]/route.ts +77 -0
  3. package/app/api/page/route.ts +18 -16
  4. package/app/api/soma-manifest/route.ts +39 -0
  5. package/app/components/SomaHydrationShell.tsx +23 -0
  6. package/app/layout.tsx +2 -2
  7. package/app/loading.tsx +5 -0
  8. package/app/page.tsx +19 -128
  9. package/bin/soma-lsp.cjs +195 -0
  10. package/bin/soma-sync.cjs +3 -0
  11. package/bin/soma.cjs +13 -1
  12. package/core/api/IService.ts +29 -0
  13. package/core/api/load-host-service.ts +72 -0
  14. package/core/api/service-path.ts +39 -0
  15. package/core/base/SomaEntity.ts +3 -10
  16. package/core/base/SomaLocaleOnlyPageRoot.ts +3 -4
  17. package/core/base/SomaPageRootBase.ts +20 -3
  18. package/core/base/decorators/Event.ts +23 -0
  19. package/core/base/decorators/Locale.ts +35 -0
  20. package/core/base/decorators/Page.ts +16 -0
  21. package/core/base/decorators/Show.ts +20 -0
  22. package/core/base/decorators/ShowList.ts +34 -0
  23. package/core/base/decorators/index.ts +5 -0
  24. package/core/base/index.ts +2 -0
  25. package/core/base/runAsync.ts +32 -0
  26. package/core/compiler/full-manifest-builder.ts +33 -7
  27. package/core/compiler/host-config-sync.cjs +38 -0
  28. package/core/compiler/manifest-compiler.ts +3 -2
  29. package/core/compiler/page-base-resolver.ts +23 -0
  30. package/core/compiler/precompiled-manifest-loader.ts +34 -0
  31. package/core/compiler/rollup-plugin-soma.ts +45 -0
  32. package/core/compiler/rspack-plugin-soma.js +33 -0
  33. package/core/compiler/soma-manifest-webpack-plugin.js +72 -0
  34. package/core/compiler/soma-precompile.js +3513 -0
  35. package/core/compiler/soma-precompile.ts +52 -6
  36. package/core/compiler/soma-rspack-yaml-loader.js +22 -0
  37. package/core/compiler/soma-webpack-loader.js +7 -1
  38. package/core/compiler/vite-plugin-soma.ts +11 -1
  39. package/core/container/IContainerAdapter.ts +36 -0
  40. package/core/container/MiniProgramContainerAdapter.ts +190 -0
  41. package/core/container/ReactNativeContainerAdapter.ts +189 -0
  42. package/core/container/SomaContainerAdapter.ts +17 -6
  43. package/core/diagnostics/SomaDiagnostics.ts +1 -1
  44. package/core/diagnostics/SomaTelemetry.ts +100 -0
  45. package/core/diagnostics/telemetry-context.ts +15 -0
  46. package/core/engine/asset-resolver.ts +39 -4
  47. package/core/engine/dom-renderer.ts +9 -11
  48. package/core/engine/event-engine.ts +110 -41
  49. package/core/engine/on-change-engine.ts +71 -0
  50. package/core/engine/property-watcher.ts +117 -0
  51. package/core/engine/reactive-proxy.ts +11 -5
  52. package/core/engine/render-engine.ts +97 -11
  53. package/core/engine/runtime-builder.ts +88 -11
  54. package/core/engine/scope-resolver.ts +65 -9
  55. package/core/engine/soma-bootstrap.ts +448 -244
  56. package/core/engine/style-binder.ts +423 -0
  57. package/core/engine/theme-variables.ts +37 -0
  58. package/core/engine/timer-engine.ts +92 -0
  59. package/core/engine/trigger-engine.ts +55 -0
  60. package/core/host/resolve-host-bootstrap.ts +28 -0
  61. package/core/host/soma-bootstrap-host.stub.ts +4 -0
  62. package/core/index.ts +40 -6
  63. package/core/infra/auth/TokenAuthService.ts +17 -3
  64. package/core/infra/http/IHttpClient.ts +11 -1
  65. package/core/infra/http/SomaHttpService.ts +89 -31
  66. package/core/infra/i18n/DefaultI18n.ts +6 -18
  67. package/core/infra/i18n/II18n.ts +2 -3
  68. package/core/infra/notify/DomNotifyService.ts +98 -0
  69. package/core/infra/notify/INotifyTheme.ts +22 -0
  70. package/core/infra/realtime/IRealtimeService.ts +23 -0
  71. package/core/infra/realtime/IRealtimeTransport.ts +9 -0
  72. package/core/infra/realtime/SomaRealtimeService.ts +95 -0
  73. package/core/infra/realtime/SseRealtimeTransport.ts +36 -0
  74. package/core/infra/realtime/WebSocketRealtimeTransport.ts +102 -0
  75. package/core/infra/router/router-path.ts +28 -0
  76. package/core/infra/storage/SessionStorageService.ts +59 -0
  77. package/core/lsp/cross-file-diagnostics.cjs +160 -0
  78. package/core/lsp/event-yaml-completion.cjs +106 -0
  79. package/core/lsp/extra-completion.cjs +64 -0
  80. package/core/lsp/lsp-navigation.cjs +191 -0
  81. package/core/lsp/ui-yaml-completion.cjs +170 -0
  82. package/core/manifest/manifest-contract.ts +12 -0
  83. package/core/middleware/createPermissionMiddleware.ts +37 -0
  84. package/core/parser/annotation-extractor.ts +113 -0
  85. package/core/parser/pipeline-parser.ts +344 -276
  86. package/core/parser/style-config-parser.ts +340 -0
  87. package/core/parser/timer-parser.ts +70 -0
  88. package/core/parser/trigger-parser.ts +90 -0
  89. package/core/parser/ui-config-parser.ts +73 -1
  90. package/core/quality/SomaQualityRegistry.ts +68 -0
  91. package/core/runtime/SomaRuntimeServices.ts +100 -0
  92. package/core/runtime/SomaSnapshotStore.ts +5 -3
  93. package/core/types/domain.types.ts +5 -2
  94. package/core/types/event.types.ts +82 -57
  95. package/core/types/manifest.types.ts +2 -0
  96. package/core/types/style-config.types.ts +76 -0
  97. package/core/types/timer.types.ts +23 -0
  98. package/core/types/trigger.types.ts +14 -0
  99. package/core/types/ui-config.types.ts +9 -0
  100. package/core/types/watcher.types.ts +29 -0
  101. package/core/validation/contract-validator.ts +465 -465
  102. package/dist/cli/soma.js +23 -23
  103. package/dist/core/index.cjs +8968 -0
  104. package/dist/diagnostics/telemetry.cjs +105 -0
  105. package/dist/preview-export.cjs +3401 -0
  106. package/dist/tsconfig.types.tsbuildinfo +1 -0
  107. package/dist/types/api/IService.d.ts +28 -0
  108. package/dist/types/api/load-host-service.d.ts +5 -0
  109. package/dist/types/api/service-path.d.ts +13 -0
  110. package/dist/types/base/SomaApi.d.ts +5 -0
  111. package/dist/types/base/SomaDict.d.ts +89 -0
  112. package/dist/types/base/SomaEntity.d.ts +15 -0
  113. package/dist/types/base/SomaHttpClient.d.ts +66 -0
  114. package/dist/types/base/SomaLocaleOnlyPageRoot.d.ts +3 -0
  115. package/dist/types/base/SomaPageRootBase.d.ts +49 -0
  116. package/dist/types/base/SomaValidator.d.ts +55 -0
  117. package/dist/types/base/decorators/Event.d.ts +10 -0
  118. package/dist/types/base/decorators/Locale.d.ts +9 -0
  119. package/dist/types/base/decorators/Page.d.ts +4 -0
  120. package/dist/types/base/decorators/Show.d.ts +7 -0
  121. package/dist/types/base/decorators/ShowList.d.ts +12 -0
  122. package/dist/types/base/decorators/index.d.ts +5 -0
  123. package/dist/types/base/index.d.ts +9 -0
  124. package/dist/types/base/runAsync.d.ts +12 -0
  125. package/dist/types/compiler/full-manifest-builder.d.ts +35 -0
  126. package/dist/types/compiler/manifest-compiler.d.ts +29 -0
  127. package/dist/types/compiler/page-base-resolver.d.ts +6 -0
  128. package/dist/types/compiler/precompiled-manifest-loader.d.ts +5 -0
  129. package/dist/types/compiler/rollup-plugin-soma.d.ts +14 -0
  130. package/dist/types/compiler/route-builder.d.ts +12 -0
  131. package/dist/types/compiler/soma-precompile.d.ts +40 -0
  132. package/dist/types/compiler/vite-plugin-soma.d.ts +34 -0
  133. package/dist/types/container/IContainerAdapter.d.ts +30 -0
  134. package/dist/types/container/MiniProgramContainerAdapter.d.ts +52 -0
  135. package/dist/types/container/ReactNativeContainerAdapter.d.ts +47 -0
  136. package/dist/types/container/SomaContainerAdapter.d.ts +30 -0
  137. package/dist/types/diagnostics/SomaDiagnostics.d.ts +64 -0
  138. package/dist/types/diagnostics/SomaTelemetry.d.ts +32 -0
  139. package/dist/types/diagnostics/telemetry-context.d.ts +4 -0
  140. package/dist/types/engine/asset-resolver.d.ts +17 -0
  141. package/dist/types/engine/dom-renderer.d.ts +35 -0
  142. package/dist/types/engine/event-engine.d.ts +64 -0
  143. package/dist/types/engine/lis.d.ts +10 -0
  144. package/dist/types/engine/on-change-engine.d.ts +16 -0
  145. package/dist/types/engine/property-watcher.d.ts +18 -0
  146. package/dist/types/engine/reactive-proxy.d.ts +58 -0
  147. package/dist/types/engine/render-engine.d.ts +73 -0
  148. package/dist/types/engine/runtime-builder.d.ts +58 -0
  149. package/dist/types/engine/scope-resolver.d.ts +90 -0
  150. package/dist/types/engine/soma-bootstrap.d.ts +112 -0
  151. package/dist/types/engine/style-binder.d.ts +81 -0
  152. package/dist/types/engine/theme-variables.d.ts +3 -0
  153. package/dist/types/engine/timer-engine.d.ts +19 -0
  154. package/dist/types/engine/trigger-engine.d.ts +16 -0
  155. package/dist/types/host/resolve-host-bootstrap.d.ts +11 -0
  156. package/dist/types/host/soma-bootstrap-host.stub.d.ts +3 -0
  157. package/dist/types/index.d.ts +35 -0
  158. package/dist/types/infra/auth/IAuthService.d.ts +12 -0
  159. package/dist/types/infra/auth/TokenAuthService.d.ts +26 -0
  160. package/dist/types/infra/cache/ICache.d.ts +12 -0
  161. package/dist/types/infra/cache/MemoryCache.d.ts +14 -0
  162. package/dist/types/infra/cache/ServerFileCache.d.ts +37 -0
  163. package/dist/types/infra/config/IConfig.d.ts +9 -0
  164. package/dist/types/infra/config/SomaConfig.d.ts +21 -0
  165. package/dist/types/infra/event-bus/IEventBus.d.ts +8 -0
  166. package/dist/types/infra/event-bus/SomaEventBus.d.ts +9 -0
  167. package/dist/types/infra/http/IHttpClient.d.ts +28 -0
  168. package/dist/types/infra/http/SomaHttpService.d.ts +27 -0
  169. package/dist/types/infra/i18n/DefaultI18n.d.ts +7 -0
  170. package/dist/types/infra/i18n/II18n.d.ts +6 -0
  171. package/dist/types/infra/logger/ConsoleLogger.d.ts +14 -0
  172. package/dist/types/infra/logger/ILogger.d.ts +17 -0
  173. package/dist/types/infra/notify/DefaultNotifyService.d.ts +16 -0
  174. package/dist/types/infra/notify/DomNotifyService.d.ts +16 -0
  175. package/dist/types/infra/notify/INotifyService.d.ts +12 -0
  176. package/dist/types/infra/notify/INotifyTheme.d.ts +12 -0
  177. package/dist/types/infra/permission/IPermission.d.ts +10 -0
  178. package/dist/types/infra/permission/SomaPermission.d.ts +19 -0
  179. package/dist/types/infra/realtime/IRealtimeService.d.ts +13 -0
  180. package/dist/types/infra/realtime/IRealtimeTransport.d.ts +8 -0
  181. package/dist/types/infra/realtime/SomaRealtimeService.d.ts +20 -0
  182. package/dist/types/infra/realtime/SseRealtimeTransport.d.ts +11 -0
  183. package/dist/types/infra/realtime/WebSocketRealtimeTransport.d.ts +30 -0
  184. package/dist/types/infra/router/IRouter.d.ts +16 -0
  185. package/dist/types/infra/router/SomaRouter.d.ts +18 -0
  186. package/dist/types/infra/router/router-path.d.ts +6 -0
  187. package/dist/types/infra/storage/IStorageService.d.ts +7 -0
  188. package/dist/types/infra/storage/MemoryStorageService.d.ts +15 -0
  189. package/dist/types/infra/storage/SessionStorageService.d.ts +14 -0
  190. package/dist/types/infra/timer/ITimer.d.ts +13 -0
  191. package/dist/types/infra/timer/SomaTimer.d.ts +21 -0
  192. package/dist/types/manifest/manifest-contract.d.ts +4 -0
  193. package/dist/types/middleware/SomaMiddlewareChain.d.ts +6 -0
  194. package/dist/types/middleware/createPermissionMiddleware.d.ts +14 -0
  195. package/dist/types/parser/annotation-extractor.d.ts +12 -0
  196. package/dist/types/parser/pipeline-parser.d.ts +62 -0
  197. package/dist/types/parser/style-config-parser.d.ts +20 -0
  198. package/dist/types/parser/timer-parser.d.ts +6 -0
  199. package/dist/types/parser/trigger-parser.d.ts +13 -0
  200. package/dist/types/parser/ui-config-parser.d.ts +34 -0
  201. package/dist/types/parser/yaml-loader.d.ts +21 -0
  202. package/dist/types/quality/SomaQualityRegistry.d.ts +31 -0
  203. package/dist/types/runtime/SomaRuntimeServices.d.ts +35 -0
  204. package/dist/types/runtime/SomaSnapshotStore.d.ts +13 -0
  205. package/dist/types/scheduler/SomaScheduler.d.ts +25 -0
  206. package/dist/types/types/domain.types.d.ts +82 -0
  207. package/dist/types/types/engine.types.d.ts +22 -0
  208. package/dist/types/types/event.types.d.ts +61 -0
  209. package/dist/types/types/keyboard.types.d.ts +4 -0
  210. package/dist/types/types/manifest.types.d.ts +29 -0
  211. package/dist/types/types/scheduler.types.d.ts +8 -0
  212. package/dist/types/types/style-config.types.d.ts +62 -0
  213. package/dist/types/types/timer.types.d.ts +19 -0
  214. package/dist/types/types/trigger.types.d.ts +12 -0
  215. package/dist/types/types/ui-config.types.d.ts +85 -0
  216. package/dist/types/types/watcher.types.d.ts +24 -0
  217. package/dist/types/validation/contract-validator.d.ts +40 -0
  218. package/editor/vscode/extension.js +39 -0
  219. package/editor/vscode/language-configuration.json +17 -0
  220. package/editor/vscode/package.json +98 -0
  221. package/editor/vscode/syntaxes/soma-event-yaml.tmLanguage.json +30 -0
  222. package/editor/vscode/syntaxes/soma-ui-yaml.tmLanguage.json +42 -0
  223. package/global.d.ts +19 -0
  224. package/next.config.js +9 -4
  225. package/package.json +53 -16
  226. package/tailwind.config.ts +26 -7
  227. package/tsconfig.json +6 -2
  228. package/core/router/RouteHandler.ts +0 -93
@@ -0,0 +1,336 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useEffect, useRef, useState } from 'react';
4
+ import { usePathname, useRouter, useSearchParams } from 'next/navigation';
5
+ import { SomaHydrationShell } from './components/SomaHydrationShell';
6
+ import type { SomaBootstrap as SomaBootstrapType, SomaPageAssets } from '../core/engine/soma-bootstrap';
7
+
8
+ const isDev = process.env.NODE_ENV !== 'production';
9
+
10
+ export default function SomaEntry() {
11
+ const pathname = usePathname();
12
+ const searchParams = useSearchParams();
13
+ const router = useRouter();
14
+ const navigate = useCallback((url: string) => {
15
+ router.push(url);
16
+ }, [router]);
17
+ const routerPath = searchParams.toString()
18
+ ? `${pathname}?${searchParams.toString()}`
19
+ : pathname;
20
+ return (
21
+ <SomaPageRenderer
22
+ pagePath={pathname}
23
+ routerPath={routerPath}
24
+ onNavigate={navigate}
25
+ />
26
+ );
27
+ }
28
+
29
+ function urlPathToPageBase(urlPath: string): string {
30
+ const clean = urlPath.replace(/^\//, '').replace(/\.html$/i, '');
31
+ return clean || 'index';
32
+ }
33
+
34
+ async function loadDomainClass(base: string): Promise<new () => any> {
35
+ try {
36
+ const mod = await import(
37
+ /* webpackInclude: /\/domain\/ui\/.*Class\.ts$/ */
38
+ `@soma-host/domain/ui/${base}Class`
39
+ );
40
+ if (typeof mod.default === 'function') return mod.default;
41
+ const ctor = Object.values(mod).find((v) => typeof v === 'function');
42
+ if (ctor) return ctor as new () => any;
43
+ throw new Error(`domain class missing: ${base}Class`);
44
+ } catch {
45
+ const { SomaLocaleOnlyPageRoot } = await import('../core/base/SomaLocaleOnlyPageRoot');
46
+ return SomaLocaleOnlyPageRoot;
47
+ }
48
+ }
49
+
50
+ type PagePayload = {
51
+ base: string;
52
+ html: string;
53
+ ui: string;
54
+ event: string;
55
+ styleYaml?: string;
56
+ includes?: Record<string, string>;
57
+ localeYaml: string;
58
+ appConfigYaml: string;
59
+ };
60
+
61
+ type PrecompiledAssets = Pick<
62
+ SomaPageAssets,
63
+ 'uiConfig' | 'eventConfig' | 'triggerConfig' | 'timerConfig' | 'styleConfig' | 'locale' | 'appConfig'
64
+ >;
65
+
66
+ function normalizeEventBundle(raw: unknown): {
67
+ events: PrecompiledAssets['eventConfig'];
68
+ triggers: NonNullable<PrecompiledAssets['triggerConfig']>;
69
+ timers: NonNullable<PrecompiledAssets['timerConfig']>;
70
+ } {
71
+ if (Array.isArray(raw)) {
72
+ return { events: raw, triggers: [], timers: [] };
73
+ }
74
+ if (raw && typeof raw === 'object' && 'events' in raw) {
75
+ const bundle = raw as { events?: unknown; triggers?: unknown; timers?: unknown };
76
+ return {
77
+ events: (bundle.events ?? []) as NonNullable<PrecompiledAssets['eventConfig']>,
78
+ triggers: (bundle.triggers ?? []) as NonNullable<PrecompiledAssets['triggerConfig']>,
79
+ timers: (bundle.timers ?? []) as NonNullable<PrecompiledAssets['timerConfig']>,
80
+ };
81
+ }
82
+ return { events: [], triggers: [], timers: [] };
83
+ }
84
+
85
+ const pageAssetCache = new Map<string, PagePayload>();
86
+
87
+ async function loadPrecompiledFromManifest(base: string, path: string): Promise<PrecompiledAssets | null> {
88
+ try {
89
+ const res = await fetch(`/api/soma-manifest?path=${encodeURIComponent(path)}`);
90
+ if (!res.ok) return null;
91
+ const data = await res.json();
92
+ return {
93
+ uiConfig: data.uiConfig,
94
+ eventConfig: data.eventConfig,
95
+ triggerConfig: data.triggers ?? [],
96
+ timerConfig: data.timers ?? [],
97
+ styleConfig: data.styleConfig,
98
+ locale: data.locale ?? {},
99
+ appConfig: data.appConfig ?? null,
100
+ };
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
105
+
106
+ async function loadPrecompiledAssets(base: string, urlPath = `/${base}`): Promise<PrecompiledAssets | null> {
107
+ try {
108
+ const [uiMod, eventMod, styleMod, localeMod, configMod] = await Promise.all([
109
+ import(
110
+ /* webpackInclude: /\/ui\/.*_ui\.yaml$/ */
111
+ `@soma-host/ui/${base}_ui.yaml`
112
+ ).catch(() => null),
113
+ import(
114
+ /* webpackInclude: /\/event\/.*_event\.yaml$/ */
115
+ `@soma-host/event/${base}_event.yaml`
116
+ ).catch(() => null),
117
+ import(
118
+ /* webpackInclude: /\/ui\/.*_style\.yaml$/ */
119
+ `@soma-host/ui/${base}_style.yaml`
120
+ ).catch(() => null),
121
+ import(
122
+ /* webpackInclude: /\/config\/locale\.yaml$/ */
123
+ '@soma-host/config/locale.yaml'
124
+ ).catch(() => null),
125
+ import(
126
+ /* webpackInclude: /\/config\/app\.config\.yaml$/ */
127
+ '@soma-host/config/app.config.yaml'
128
+ ).catch(() => null),
129
+ ]);
130
+
131
+ if (!uiMod?.default || !eventMod?.default) {
132
+ return null;
133
+ }
134
+
135
+ const eventBundle = normalizeEventBundle(eventMod.default);
136
+
137
+ return {
138
+ uiConfig: uiMod.default,
139
+ eventConfig: eventBundle.events,
140
+ triggerConfig: eventBundle.triggers,
141
+ timerConfig: eventBundle.timers,
142
+ styleConfig: styleMod?.default ?? undefined,
143
+ locale: (localeMod?.default ?? {}) as Record<string, unknown>,
144
+ appConfig: configMod?.default ?? null,
145
+ };
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+
151
+ function SomaPageRenderer({
152
+ pagePath,
153
+ routerPath,
154
+ onNavigate,
155
+ }: {
156
+ pagePath: string;
157
+ routerPath: string;
158
+ onNavigate: (url: string) => void;
159
+ }) {
160
+ const containerRef = useRef<HTMLDivElement>(null);
161
+ const bootstrapRef = useRef<SomaBootstrapType | null>(null);
162
+ const routerBridgeRef = useRef<(() => void) | null>(null);
163
+ const [error, setError] = useState<string | null>(null);
164
+ const [mounting, setMounting] = useState(true);
165
+
166
+ useEffect(() => {
167
+ if (!containerRef.current) return;
168
+
169
+ let cancelled = false;
170
+
171
+ const mountInto = async (
172
+ DomainClass: new () => any,
173
+ SomaBootstrapCtor: new (...args: any[]) => SomaBootstrapType,
174
+ assets: Omit<SomaPageAssets, 'html' | 'includes' | 'DomainClass'>,
175
+ html: string,
176
+ includes?: Record<string, string>,
177
+ ) => {
178
+ await bootstrapRef.current?.unmount();
179
+
180
+ const getServices = () =>
181
+ bootstrapRef.current?.getDomainInstance()?._services as import('../core/runtime/SomaRuntimeServices').SomaRuntimeServices | undefined;
182
+
183
+ const { resolveHostBootstrapOptions } = await import('../core/host/resolve-host-bootstrap');
184
+ const hostBootstrapOptions = await resolveHostBootstrapOptions(getServices);
185
+
186
+ const bs = new SomaBootstrapCtor(hostBootstrapOptions);
187
+ bootstrapRef.current = bs;
188
+
189
+ await bs.mount(containerRef.current!, {
190
+ html,
191
+ includes,
192
+ DomainClass,
193
+ ...assets,
194
+ });
195
+
196
+ routerBridgeRef.current?.();
197
+ const domain = bs.getDomainInstance() as {
198
+ _services?: {
199
+ router: {
200
+ getCurrentPath: () => string;
201
+ onNavigate: (cb: (p: string) => void) => () => void;
202
+ };
203
+ };
204
+ } | null;
205
+ if (domain?._services?.router) {
206
+ const somaRouter = domain._services.router;
207
+ routerBridgeRef.current = somaRouter.onNavigate((nextPath) => {
208
+ if (nextPath !== routerPath) {
209
+ onNavigate(nextPath);
210
+ }
211
+ });
212
+ // onMount 里触发的 navigate 发生在桥接注册之前,此处补同步到 Next 路由
213
+ const pending = somaRouter.getCurrentPath();
214
+ if (pending !== routerPath) {
215
+ onNavigate(pending);
216
+ }
217
+ }
218
+
219
+ if (isDev && typeof window !== 'undefined') {
220
+ window.__SOMA__ = {
221
+ getDiagnosticsSnapshot: () => bs.getDiagnosticsSnapshot(),
222
+ getTelemetrySnapshot: () => bs.getTelemetrySnapshot(),
223
+ getAvailableThemes: () => bs.getAvailableThemes(),
224
+ getDomainInstance: () => bs.getDomainInstance(),
225
+ captureSnapshot: () => bs.captureSnapshot(),
226
+ restoreSnapshot: (id: number) => bs.restoreSnapshot(id),
227
+ switchTheme: (name: string | null) => bs.switchTheme(name),
228
+ };
229
+ }
230
+ };
231
+
232
+ const run = async () => {
233
+ try {
234
+ setError(null);
235
+ setMounting(true);
236
+
237
+ const { SomaBootstrap } = await import('../core/engine/soma-bootstrap');
238
+
239
+ const res = await fetch(`/api/page?path=${encodeURIComponent(pagePath)}`);
240
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
241
+ const data = await res.json();
242
+ if (cancelled) return;
243
+
244
+ const base = (data.base as string) || urlPathToPageBase(pagePath);
245
+ const DomainClass = await loadDomainClass(base);
246
+ const routeAssets = { routerPath };
247
+
248
+ if (!isDev) {
249
+ const fromManifest = await loadPrecompiledFromManifest(base, pagePath);
250
+ const precompiled = fromManifest ?? await loadPrecompiledAssets(base, pagePath);
251
+ if (precompiled) {
252
+ await mountInto(
253
+ DomainClass,
254
+ SomaBootstrap,
255
+ { ...precompiled, ...routeAssets },
256
+ data.html,
257
+ data.includes,
258
+ );
259
+ return;
260
+ }
261
+
262
+ const cached = pageAssetCache.get(routerPath);
263
+ if (cached) {
264
+ const CachedClass = await loadDomainClass(cached.base);
265
+ await mountInto(CachedClass, SomaBootstrap, {
266
+ uiYaml: cached.ui,
267
+ eventYaml: cached.event,
268
+ styleYaml: cached.styleYaml,
269
+ localeYaml: cached.localeYaml ?? '',
270
+ appConfigYaml: cached.appConfigYaml ?? '',
271
+ ...routeAssets,
272
+ }, cached.html, cached.includes);
273
+ return;
274
+ }
275
+ }
276
+
277
+ const payload: PagePayload = {
278
+ base,
279
+ html: data.html,
280
+ ui: data.ui,
281
+ event: data.event,
282
+ styleYaml: data.styleYaml ?? '',
283
+ includes: data.includes,
284
+ localeYaml: data.localeYaml ?? '',
285
+ appConfigYaml: data.appConfigYaml ?? '',
286
+ };
287
+
288
+ if (!isDev) {
289
+ pageAssetCache.set(routerPath, payload);
290
+ }
291
+
292
+ await mountInto(DomainClass, SomaBootstrap, {
293
+ uiYaml: payload.ui,
294
+ eventYaml: payload.event,
295
+ styleYaml: payload.styleYaml,
296
+ localeYaml: payload.localeYaml ?? '',
297
+ appConfigYaml: payload.appConfigYaml ?? '',
298
+ ...routeAssets,
299
+ }, payload.html, payload.includes);
300
+ } catch (err: any) {
301
+ if (!cancelled) setError(err?.message ?? String(err));
302
+ } finally {
303
+ if (!cancelled) setMounting(false);
304
+ }
305
+ };
306
+
307
+ void run();
308
+
309
+ return () => {
310
+ cancelled = true;
311
+ routerBridgeRef.current?.();
312
+ routerBridgeRef.current = null;
313
+ if (typeof window !== 'undefined') {
314
+ delete window.__SOMA__;
315
+ }
316
+ void bootstrapRef.current?.unmount();
317
+ bootstrapRef.current = null;
318
+ };
319
+ }, [pagePath, routerPath, onNavigate]);
320
+
321
+ if (error) {
322
+ return (
323
+ <div className="p-8 text-red-600">
324
+ <p className="font-bold">Page failed to load</p>
325
+ <p className="text-sm mt-1">{error}</p>
326
+ </div>
327
+ );
328
+ }
329
+
330
+ return (
331
+ <>
332
+ {mounting && !error ? <SomaHydrationShell /> : null}
333
+ <div ref={containerRef} className={mounting && !error ? 'hidden' : undefined} />
334
+ </>
335
+ );
336
+ }
@@ -0,0 +1,77 @@
1
+ import { NextRequest } from 'next/server';
2
+ import type { IService } from '@/core/api/IService';
3
+ import { loadHostService } from '@/core/api/load-host-service';
4
+
5
+ // ─── HTTP 方法分发工厂 ─────────────────────────────────────
6
+
7
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
8
+
9
+ function createHandler(method: HttpMethod) {
10
+ const methodKey = method.toLowerCase() as keyof IService;
11
+
12
+ return async function handler(
13
+ req: NextRequest,
14
+ { params }: { params: { path: string[] } },
15
+ ): Promise<Response> {
16
+ const segments = params.path || [];
17
+
18
+ if (segments.length === 0) {
19
+ return Response.json(
20
+ { error: 'Missing API path. Expected: /api/{module}/{action}' },
21
+ { status: 400 },
22
+ );
23
+ }
24
+
25
+ const service = loadHostService(segments);
26
+
27
+ if (!service) {
28
+ return Response.json(
29
+ { error: `API not found: /api/${segments.join('/')}` },
30
+ { status: 404 },
31
+ );
32
+ }
33
+
34
+ const handlerFn = service[methodKey];
35
+ if (typeof handlerFn !== 'function') {
36
+ return Response.json(
37
+ {
38
+ error: `Method ${method} not allowed: /api/${segments.join('/')}`,
39
+ },
40
+ {
41
+ status: 405,
42
+ headers: { Allow: getAllowHeader(service) },
43
+ },
44
+ );
45
+ }
46
+
47
+ try {
48
+ return await handlerFn.call(service, req);
49
+ } catch (e: unknown) {
50
+ const message = e instanceof Error ? e.message : String(e);
51
+ console.error(`[soma-api] ${method} /api/${segments.join('/')}:`, message);
52
+ return Response.json(
53
+ { error: message || 'Internal server error' },
54
+ { status: 500 },
55
+ );
56
+ }
57
+ };
58
+ }
59
+
60
+ /** 生成 Allow 响应头 */
61
+ function getAllowHeader(service: IService): string {
62
+ const methods: string[] = [];
63
+ if (typeof service.get === 'function') methods.push('GET');
64
+ if (typeof service.post === 'function') methods.push('POST');
65
+ if (typeof service.put === 'function') methods.push('PUT');
66
+ if (typeof service.patch === 'function') methods.push('PATCH');
67
+ if (typeof service.delete === 'function') methods.push('DELETE');
68
+ return methods.join(', ');
69
+ }
70
+
71
+ // ─── 导出所有 HTTP 方法处理器 ───────────────────────────────
72
+
73
+ export const GET = createHandler('GET');
74
+ export const POST = createHandler('POST');
75
+ export const PUT = createHandler('PUT');
76
+ export const PATCH = createHandler('PATCH');
77
+ export const DELETE = createHandler('DELETE');
@@ -1,8 +1,9 @@
1
- // soma-core/app/api/page/route.ts — URL 直接映射 html/ui/event 文件
2
- // 规则:/ → index.html,其他 /xxx → xxx.html,/xxx/yyy → xxx/yyy.html
1
+ // URL → html/ui/event files: / → index.html, /a/b → a/b.html; */index.html also maps to short path /a
3
2
 
4
- import { join, normalize, resolve } from 'path';
3
+ import { existsSync } from 'fs';
4
+ import { join, resolve } from 'path';
5
5
  import { NextRequest } from 'next/server';
6
+ import { isSafePageBase, urlPathToCandidates } from '../../../core/compiler/page-base-resolver';
6
7
  import { ServerFileCache } from '../../../core/infra/cache/ServerFileCache';
7
8
 
8
9
  const cache = ServerFileCache.getInstance();
@@ -19,14 +20,13 @@ function ensureWatch(root: string) {
19
20
  cache.watchAndInvalidate(root);
20
21
  }
21
22
 
22
- function urlToBase(urlPath: string): string {
23
- const clean = urlPath.replace(/^\//, '').replace(/\.html$/, '');
24
- return clean || 'index';
25
- }
26
-
27
- function isPathSafe(base: string): boolean {
28
- const normalized = normalize(base);
29
- return !normalized.startsWith('..') && !normalized.includes('\0') && !/^[a-zA-Z]:/.test(normalized);
23
+ function resolvePageBase(hostDir: string, urlPath: string): string | null {
24
+ for (const candidate of urlPathToCandidates(urlPath)) {
25
+ if (!isSafePageBase(candidate)) continue;
26
+ const htmlPath = join(hostDir, 'html', `${candidate}.html`);
27
+ if (existsSync(htmlPath)) return candidate;
28
+ }
29
+ return null;
30
30
  }
31
31
 
32
32
  function collectIncludes(hostDir: string): Record<string, string> {
@@ -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 is not set. Run: npx soma dev from your app root.' },
50
50
  { status: 503 },
51
51
  );
52
52
  }
@@ -54,10 +54,10 @@ export async function GET(req: NextRequest) {
54
54
  ensureWatch(hostDir);
55
55
 
56
56
  const urlPath = req.nextUrl.searchParams.get('path') || '/';
57
- const base = urlToBase(urlPath);
57
+ const base = resolvePageBase(hostDir, urlPath);
58
58
 
59
- if (!isPathSafe(base)) {
60
- return Response.json({ error: 'Invalid path' }, { status: 400 });
59
+ if (!base) {
60
+ return Response.json({ error: `Page not found: ${urlPath}` }, { status: 404 });
61
61
  }
62
62
 
63
63
  const htmlPath = join(hostDir, 'html', `${base}.html`);
@@ -70,10 +70,11 @@ export async function GET(req: NextRequest) {
70
70
  try {
71
71
  const html = cache.readFile(htmlPath);
72
72
 
73
- let ui: string, event: string, localeYaml: string, appConfigYaml: string;
73
+ let ui: string, event: string, style: string, localeYaml: string, appConfigYaml: string;
74
74
  try {
75
75
  ui = cache.tryReadFile(join(hostDir, 'ui', `${base}_ui.yaml`));
76
76
  event = cache.tryReadFile(join(hostDir, 'event', `${base}_event.yaml`));
77
+ style = cache.tryReadFile(join(hostDir, 'ui', `${base}_style.yaml`));
77
78
  localeYaml = cache.tryReadFile(join(hostDir, 'config', 'locale.yaml'));
78
79
  appConfigYaml = cache.tryReadFile(join(hostDir, 'config', 'app.config.yaml'));
79
80
  } catch (e: any) {
@@ -87,6 +88,7 @@ export async function GET(req: NextRequest) {
87
88
  html,
88
89
  ui,
89
90
  event,
91
+ styleYaml: style,
90
92
  localeYaml,
91
93
  appConfigYaml,
92
94
  includes,
@@ -0,0 +1,39 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { loadPrecompiledManifest, findPrecompiledPage } from '@/core/compiler/precompiled-manifest-loader';
4
+
5
+ /** GET /api/soma-manifest?path=/items — returns precompiled page config */
6
+ export async function GET(request: Request): Promise<Response> {
7
+ const hostDir = process.env.SOMA_HOST_DIR;
8
+ if (!hostDir) {
9
+ return Response.json({ error: 'SOMA_HOST_DIR not set' }, { status: 500 });
10
+ }
11
+
12
+ const url = new URL(request.url);
13
+ const pagePath = url.searchParams.get('path') ?? '/';
14
+
15
+ const manifest = loadPrecompiledManifest(hostDir);
16
+ if (!manifest) {
17
+ return Response.json({ error: 'manifest not found' }, { status: 404 });
18
+ }
19
+
20
+ const page = findPrecompiledPage(manifest, pagePath);
21
+ if (!page) {
22
+ return Response.json({ error: `page not in manifest: ${pagePath}` }, { status: 404 });
23
+ }
24
+
25
+ return Response.json({
26
+ path: page.path,
27
+ uiConfig: page.uiConfig,
28
+ eventConfig: page.eventConfig,
29
+ triggers: page.triggers,
30
+ timers: page.timers ?? [],
31
+ styleConfig: page.styleConfig,
32
+ locale: manifest.locale,
33
+ appConfig: manifest.appConfig,
34
+ manifestVersion: '1.0.0',
35
+ generatedAt: fs.existsSync(path.join(hostDir, '.soma', 'manifest.json'))
36
+ ? fs.statSync(path.join(hostDir, '.soma', 'manifest.json')).mtime.toISOString()
37
+ : null,
38
+ });
39
+ }
@@ -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
+ }
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
+ }