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,191 @@
1
+ /**
2
+ * LSP Hover / Go-to-Definition — html ↔ ui ↔ event ↔ domain
3
+ */
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { scanDomainProperties } = require('./ui-yaml-completion.cjs');
7
+
8
+ function filePathFromUri(uri) {
9
+ return decodeURIComponent(uri.replace(/^file:\/\//, ''));
10
+ }
11
+
12
+ function pageBaseFromPath(filePath, hostDir) {
13
+ if (hostDir) {
14
+ const hostRoot = path.resolve(hostDir);
15
+ const resolved = path.resolve(filePath);
16
+ if (resolved.startsWith(hostRoot)) {
17
+ const rel = path.relative(hostRoot, resolved);
18
+ let mm = rel.match(/^ui[/\\](.+)_ui\.yaml$/);
19
+ if (mm) return mm[1].replace(/\\/g, '/');
20
+ mm = rel.match(/^event[/\\](.+)_event\.yaml$/);
21
+ if (mm) return mm[1].replace(/\\/g, '/');
22
+ mm = rel.match(/^html[/\\](.+)\.html$/);
23
+ if (mm) return mm[1].replace(/\\/g, '/');
24
+ }
25
+ }
26
+ const name = path.basename(filePath);
27
+ let m = name.match(/^(.+)_ui\.yaml$/);
28
+ if (m) return m[1];
29
+ m = name.match(/^(.+)_event\.yaml$/);
30
+ if (m) return m[1];
31
+ m = name.match(/^(.+)\.html$/);
32
+ if (m) return m[1].replace(/\\/g, '/');
33
+ return null;
34
+ }
35
+
36
+ function lineAtIndex(text, index) {
37
+ return text.slice(0, index).split('\n').length - 1;
38
+ }
39
+
40
+ function charAtIndex(text, index) {
41
+ const lineStart = text.lastIndexOf('\n', index - 1) + 1;
42
+ return index - lineStart;
43
+ }
44
+
45
+ function findAnchorInHtml(html, somaId) {
46
+ const re = new RegExp(`data-soma-id=["']${somaId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']`, 'g');
47
+ const m = re.exec(html);
48
+ if (!m) return null;
49
+ const line = lineAtIndex(html, m.index);
50
+ const character = charAtIndex(html, m.index);
51
+ return { line, character, length: m[0].length };
52
+ }
53
+
54
+ function findKeyInYaml(yaml, key) {
55
+ const re = new RegExp(`^\\s{0,4}${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*:`, 'm');
56
+ const m = re.exec(yaml);
57
+ if (!m) return null;
58
+ const line = lineAtIndex(yaml, m.index);
59
+ return { line, character: m.index - yaml.lastIndexOf('\n', m.index - 1) - 1, length: key.length };
60
+ }
61
+
62
+ function findEventAnchorInYaml(yaml, anchorId) {
63
+ const re = new RegExp(`^\\s*${anchorId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.`, 'm');
64
+ const m = re.exec(yaml);
65
+ if (!m) return null;
66
+ return { line: lineAtIndex(yaml, m.index), character: 0, length: anchorId.length };
67
+ }
68
+
69
+ function getHover(hostDir, uri, text, position) {
70
+ const filePath = filePathFromUri(uri);
71
+ const fileName = path.basename(filePath);
72
+ const line = (text.split('\n')[position.line] ?? '').trim();
73
+
74
+ const pathMatch = line.match(/page\.([\w.]+)/);
75
+ if (pathMatch && fileName.endsWith('_ui.yaml')) {
76
+ return {
77
+ contents: {
78
+ kind: 'markdown',
79
+ value: `**绑定路径** \`page.${pathMatch[1]}\`\n\n类型:domain 属性路径`,
80
+ },
81
+ };
82
+ }
83
+
84
+ const showKey = line.match(/^([\w@.-]+)\s*:/);
85
+ if (showKey && fileName.endsWith('_ui.yaml')) {
86
+ const pageBase = pageBaseFromPath(filePath, hostDir);
87
+ const htmlPath = path.join(hostDir, 'html', `${pageBase}.html`);
88
+ const html = fs.existsSync(htmlPath) ? fs.readFileSync(htmlPath, 'utf8') : '';
89
+ const inHtml = html.includes(`data-soma-id="${showKey[1]}"`);
90
+ return {
91
+ contents: {
92
+ kind: 'markdown',
93
+ value: `**锚点** \`${showKey[1]}\`\n\nHTML: ${inHtml ? '✓ 已声明' : '✗ 未找到'}`,
94
+ },
95
+ };
96
+ }
97
+
98
+ const eventAnchor = line.match(/^([\w@.-]+)\.([\w.]+)\s*:/);
99
+ if (eventAnchor && fileName.endsWith('_event.yaml')) {
100
+ return {
101
+ contents: {
102
+ kind: 'markdown',
103
+ value: `**事件** \`${eventAnchor[1]}.${eventAnchor[2]}\`\n\n类型:Pipeline 事件锚点`,
104
+ },
105
+ };
106
+ }
107
+
108
+ const htmlAnchor = line.match(/data-soma-id=["']([^"']+)["']/);
109
+ if (htmlAnchor && fileName.endsWith('.html')) {
110
+ const pageBase = pageBaseFromPath(filePath, hostDir);
111
+ const props = scanDomainProperties(hostDir, pageBase?.split('/').pop() ?? pageBase);
112
+ return {
113
+ contents: {
114
+ kind: 'markdown',
115
+ value: `**锚点 ID** \`${htmlAnchor[1]}\`\n\nDomain 属性示例:\`${props.slice(0, 5).join('`, `')}\``,
116
+ },
117
+ };
118
+ }
119
+
120
+ return null;
121
+ }
122
+
123
+ function getDefinition(hostDir, uri, text, position) {
124
+ const filePath = filePathFromUri(uri);
125
+ const fileName = path.basename(filePath);
126
+ const currentLine = text.split('\n')[position.line] ?? '';
127
+ const pageBase = pageBaseFromPath(filePath, hostDir);
128
+ if (!pageBase) return null;
129
+
130
+ const htmlPath = path.join(hostDir, 'html', `${pageBase}.html`);
131
+ const uiPath = path.join(hostDir, 'ui', `${pageBase}_ui.yaml`);
132
+ const eventPath = path.join(hostDir, 'event', `${pageBase}_event.yaml`);
133
+
134
+ if (fileName.endsWith('_ui.yaml')) {
135
+ const keyMatch = currentLine.match(/^\s*([\w@.-]+)\s*:/);
136
+ if (keyMatch && fs.existsSync(htmlPath)) {
137
+ const html = fs.readFileSync(htmlPath, 'utf8');
138
+ const loc = findAnchorInHtml(html, keyMatch[1]);
139
+ if (!loc) return null;
140
+ return {
141
+ uri: `file://${htmlPath}`,
142
+ range: {
143
+ start: { line: loc.line, character: loc.character },
144
+ end: { line: loc.line, character: loc.character + loc.length },
145
+ },
146
+ };
147
+ }
148
+ }
149
+
150
+ if (fileName.endsWith('_event.yaml')) {
151
+ const anchor = currentLine.match(/^\s*([\w@.-]+)\./);
152
+ if (anchor && fs.existsSync(htmlPath)) {
153
+ const html = fs.readFileSync(htmlPath, 'utf8');
154
+ const loc = findAnchorInHtml(html, anchor[1]);
155
+ if (!loc) return null;
156
+ return {
157
+ uri: `file://${htmlPath}`,
158
+ range: {
159
+ start: { line: loc.line, character: loc.character },
160
+ end: { line: loc.line, character: loc.character + loc.length },
161
+ },
162
+ };
163
+ }
164
+ }
165
+
166
+ if (fileName.endsWith('.html')) {
167
+ const m = currentLine.match(/data-soma-id=["']([^"']+)["']/);
168
+ if (m && fs.existsSync(uiPath)) {
169
+ const uiYaml = fs.readFileSync(uiPath, 'utf8');
170
+ const loc = findKeyInYaml(uiYaml, m[1]);
171
+ if (!loc) return null;
172
+ return {
173
+ uri: `file://${uiPath}`,
174
+ range: {
175
+ start: { line: loc.line, character: loc.character },
176
+ end: { line: loc.line, character: loc.character + loc.length },
177
+ },
178
+ };
179
+ }
180
+ }
181
+
182
+ return null;
183
+ }
184
+
185
+ module.exports = {
186
+ getHover,
187
+ getDefinition,
188
+ findAnchorInHtml,
189
+ findKeyInYaml,
190
+ findEventAnchorInYaml,
191
+ };
@@ -0,0 +1,170 @@
1
+ /**
2
+ * _ui.yaml 智能补全:html 锚点、domain 属性路径、YAML 关键字
3
+ */
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+
7
+ const UI_ROOT_KEYS = ['bind', 'show', 'model', 'when'];
8
+ const BIND_SUB_KEYS = ['obj', 'var'];
9
+ const SHOW_ATTR_SUFFIXES = ['@src', '@href', '@alt', '@title', '@value'];
10
+
11
+ function extractSomaIdsFromHtml(html) {
12
+ const ids = new Set();
13
+ for (const m of html.matchAll(/data-soma-id=["']([^"']+)["']/g)) {
14
+ ids.add(m[1]);
15
+ }
16
+ return [...ids].sort();
17
+ }
18
+
19
+ function collectHtmlPages(htmlDir) {
20
+ const pages = [];
21
+ if (!fs.existsSync(htmlDir)) return pages;
22
+ function walk(dir, prefix = '') {
23
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
24
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
25
+ const full = path.join(dir, entry.name);
26
+ if (entry.isDirectory()) walk(full, rel);
27
+ else if (entry.name.endsWith('.html')) pages.push(rel.replace(/\.html$/, ''));
28
+ }
29
+ }
30
+ walk(htmlDir);
31
+ return pages;
32
+ }
33
+
34
+ function scanDomainProperties(hostDir, pageBase) {
35
+ const props = new Set(['_locale', '_config', '_services']);
36
+ const classPath = path.join(hostDir, 'domain', 'ui', `${pageBase}Class.ts`);
37
+ if (!fs.existsSync(classPath)) return [...props].sort();
38
+
39
+ const src = fs.readFileSync(classPath, 'utf8');
40
+ for (const m of src.matchAll(/^\s+(\w+)\s*[=:]/gm)) props.add(m[1]);
41
+ for (const m of src.matchAll(/^\s+async\s+(\w+)\s*\(/gm)) props.add(m[1]);
42
+ for (const m of src.matchAll(/^\s+(\w+)\s*\([^)]*\)\s*[:{]/gm)) props.add(m[1]);
43
+ return [...props].sort();
44
+ }
45
+
46
+ function pageBaseFromUri(uri, hostDir) {
47
+ if (!uri) return null;
48
+ const filePath = decodeURIComponent(uri.replace(/^file:\/\//, ''));
49
+ const name = path.basename(filePath);
50
+ const m = name.match(/^(.+)_ui\.yaml$/);
51
+ if (m) return m[1];
52
+ if (hostDir && filePath.startsWith(hostDir)) {
53
+ const rel = path.relative(hostDir, filePath);
54
+ const mm = rel.match(/ui[/\\](.+)_ui\.yaml$/);
55
+ if (mm) return mm[1].replace(/\\/g, '/');
56
+ }
57
+ return null;
58
+ }
59
+
60
+ function linePrefix(text, position) {
61
+ const lines = text.split('\n');
62
+ const line = lines[position.line] ?? '';
63
+ return line.slice(0, position.character);
64
+ }
65
+
66
+ function getIndent(line) {
67
+ const m = line.match(/^(\s*)/);
68
+ return m ? m[1].length : 0;
69
+ }
70
+
71
+ function getYamlBlockContext(text, position) {
72
+ const lines = text.split('\n').slice(0, position.line + 1);
73
+ let ctx = 'root';
74
+ for (const line of lines) {
75
+ const t = line.trim();
76
+ if (/^bind:\s*$/.test(t)) ctx = 'bind';
77
+ else if (/^show:\s*$/.test(t)) ctx = 'show';
78
+ }
79
+ return ctx;
80
+ }
81
+
82
+ function completionItem(label, detail, kind = 10) {
83
+ return { label, kind, detail, insertText: label };
84
+ }
85
+
86
+ /**
87
+ * @returns {Array<{label:string,kind:number,detail?:string,insertText?:string}>}
88
+ */
89
+ function getUiYamlCompletions(hostDir, uri, text, position) {
90
+ const pageBase = pageBaseFromUri(uri, hostDir);
91
+ if (!pageBase) return [];
92
+
93
+ const prefix = linePrefix(text, position);
94
+ const trimmed = prefix.trimStart();
95
+ const indent = getIndent(prefix);
96
+ const items = [];
97
+
98
+ const htmlPath = path.join(hostDir, 'html', `${pageBase}.html`);
99
+ const somaIds = fs.existsSync(htmlPath) ? extractSomaIdsFromHtml(fs.readFileSync(htmlPath, 'utf8')) : [];
100
+ const domainProps = scanDomainProperties(hostDir, pageBase);
101
+
102
+ const blockCtx = getYamlBlockContext(text, position);
103
+
104
+ if (indent === 0 && trimmed.length === 0) {
105
+ for (const k of UI_ROOT_KEYS) items.push(completionItem(k, 'ui.yaml 根键'));
106
+ return items;
107
+ }
108
+
109
+ if (/^bind:\s*$/.test(trimmed) || (blockCtx === 'bind' && indent === 2 && trimmed === '')) {
110
+ for (const k of BIND_SUB_KEYS) items.push(completionItem(`${k}: `, 'bind 子键', 14));
111
+ return items;
112
+ }
113
+
114
+ const bindObj = prefix.match(/obj:\s*(\w*)$/);
115
+ if (bindObj) {
116
+ const guess = pageBase.charAt(0).toUpperCase() + pageBase.slice(1) + 'Class';
117
+ items.push(completionItem(guess, 'Domain 类名', 7));
118
+ return items;
119
+ }
120
+
121
+ const bindVar = prefix.match(/var:\s*(\w*)$/);
122
+ if (bindVar) {
123
+ for (const v of ['page', 'item', 'c', 'p', 'row']) {
124
+ items.push(completionItem(v, '循环变量', 6));
125
+ }
126
+ return items;
127
+ }
128
+
129
+ const showKey = prefix.match(/^(\s*)(\w*)$/);
130
+ if (showKey && indent >= 2) {
131
+ const partial = showKey[2];
132
+ for (const id of somaIds) {
133
+ if (!partial || id.startsWith(partial)) {
134
+ items.push(completionItem(`${id}: `, 'html data-soma-id', 5));
135
+ for (const sfx of SHOW_ATTR_SUFFIXES) {
136
+ items.push(completionItem(`${id}${sfx}: `, '属性绑定', 5));
137
+ }
138
+ }
139
+ }
140
+ if (trimmed.endsWith('when:') || prefix.match(/when:\s*$/)) {
141
+ for (const p of domainProps) {
142
+ items.push(completionItem(`page.${p}`, '条件表达式', 6));
143
+ }
144
+ }
145
+ return items;
146
+ }
147
+
148
+ const valuePath = prefix.match(/:\s*(page\.)?(\w*)$/);
149
+ if (valuePath) {
150
+ const partial = valuePath[2] ?? '';
151
+ for (const p of domainProps) {
152
+ if (!partial || p.startsWith(partial)) {
153
+ items.push(completionItem(`page.${p}`, `domain.${p}`, 6));
154
+ items.push(completionItem(`page._locale.${p}`, 'locale 文案', 6));
155
+ }
156
+ }
157
+ return items;
158
+ }
159
+
160
+ const modelLine = prefix.match(/^(\s*)(\w*)$/);
161
+ if (modelLine && indent >= 4) {
162
+ for (const p of domainProps) {
163
+ items.push(completionItem(`page.${p}`, 'model 绑定', 6));
164
+ }
165
+ }
166
+
167
+ return items;
168
+ }
169
+
170
+ module.exports = { getUiYamlCompletions, extractSomaIdsFromHtml, scanDomainProperties };
@@ -0,0 +1,12 @@
1
+ /** SOMA runtime manifest version contract */
2
+ export const SOMA_MANIFEST_VERSION = '1.0.0' as const;
3
+
4
+ export type SomaManifestVersion = typeof SOMA_MANIFEST_VERSION;
5
+
6
+ export function assertManifestVersion(version: string): void {
7
+ if (version !== SOMA_MANIFEST_VERSION) {
8
+ throw new Error(
9
+ `[SOMA] Incompatible manifest version: expected ${SOMA_MANIFEST_VERSION}, got ${version}`,
10
+ );
11
+ }
12
+ }
@@ -0,0 +1,37 @@
1
+ import type { SomaEventMiddlewareContext } from '../engine/event-engine';
2
+ import type { SomaRuntimeServices } from '../runtime/SomaRuntimeServices';
3
+
4
+ /**
5
+ * Opt-in event middleware: blocks handler execution when the event declares
6
+ * `permission:code` in _event.yaml and `_services.permission.check(code)` is false.
7
+ *
8
+ * Wire via `SomaBootstrapOptions.eventMiddleware` — framework does not mount this by default.
9
+ *
10
+ * @example
11
+ * const chain = new SomaMiddlewareChain<SomaEventMiddlewareContext>();
12
+ * chain.use(createPermissionMiddleware(() => bootstrap.getDomainInstance()?._services));
13
+ * new SomaBootstrap({ eventMiddleware: chain });
14
+ */
15
+ export function createPermissionMiddleware(
16
+ getServices: () => SomaRuntimeServices | undefined,
17
+ ) {
18
+ return async (
19
+ context: SomaEventMiddlewareContext,
20
+ next: () => Promise<void>,
21
+ ): Promise<void> => {
22
+ const services = getServices();
23
+ const permissionCode = context.config.permission;
24
+
25
+ if (permissionCode && services) {
26
+ const allowed = services.permission.check(permissionCode);
27
+ if (!allowed) {
28
+ context.status = 'blocked';
29
+ context.message = `Permission denied: ${permissionCode}`;
30
+ services.notify.toast({ level: 'error', message: context.message });
31
+ return;
32
+ }
33
+ }
34
+
35
+ await next();
36
+ };
37
+ }
@@ -0,0 +1,113 @@
1
+ import {
2
+ getPageId,
3
+ getShowMetadata,
4
+ getShowListMetadata,
5
+ getEventMetadata,
6
+ } from '../base/decorators';
7
+ import type { UiConfig, ShowMapping, ShowValue } from '../types/ui-config.types';
8
+ import type { ParsedEvent } from '../types/event.types';
9
+ import { parsePipeline } from './pipeline-parser';
10
+
11
+ export interface AnnotationExtractOptions {
12
+ /** 顶级 bind.var,默认 page */
13
+ pageVar?: string;
14
+ }
15
+
16
+ export interface AnnotationExtractResult {
17
+ uiConfig: UiConfig;
18
+ eventConfig: ParsedEvent[];
19
+ }
20
+
21
+ /** 从 Domain Class 装饰器元数据生成等价于 YAML 的配置 */
22
+ export function extractConfigFromDomainClass(
23
+ DomainClass: new (...args: unknown[]) => object,
24
+ options: AnnotationExtractOptions = {},
25
+ ): AnnotationExtractResult {
26
+ const pageVar = options.pageVar ?? 'page';
27
+ const pageId = getPageId(DomainClass) ?? DomainClass.name;
28
+
29
+ const show: ShowMapping = {};
30
+
31
+ for (const { propertyKey, somaId } of getShowMetadata(DomainClass)) {
32
+ show[somaId] = `${pageVar}.${propertyKey}`;
33
+ }
34
+
35
+ for (const entry of getShowListMetadata(DomainClass)) {
36
+ const itemVar = entry.itemVar ?? defaultItemVar(entry.propertyKey);
37
+ show[entry.somaId] = {
38
+ bind: {
39
+ obj: `${pageVar}.${entry.propertyKey}`,
40
+ var: itemVar,
41
+ },
42
+ show: buildEntityShowMapping(entry.entityClass, itemVar),
43
+ };
44
+ }
45
+
46
+ const uiConfig: UiConfig = {
47
+ bind: { obj: pageId, var: pageVar },
48
+ show,
49
+ };
50
+
51
+ const eventConfig: ParsedEvent[] = [
52
+ ...extractEvents(DomainClass, pageVar),
53
+ ...getShowListMetadata(DomainClass).flatMap((entry) => {
54
+ const itemVar = entry.itemVar ?? defaultItemVar(entry.propertyKey);
55
+ return extractEvents(entry.entityClass, itemVar);
56
+ }),
57
+ ];
58
+
59
+ return { uiConfig, eventConfig };
60
+ }
61
+
62
+ function buildEntityShowMapping(
63
+ entityClass: new (...args: unknown[]) => object,
64
+ itemVar: string,
65
+ ): ShowMapping {
66
+ const nested: ShowMapping = {};
67
+ for (const { propertyKey, somaId } of getShowMetadata(entityClass)) {
68
+ nested[somaId] = `${itemVar}.${propertyKey}`;
69
+ }
70
+ return nested;
71
+ }
72
+
73
+ function extractEvents(
74
+ ctor: new (...args: unknown[]) => object,
75
+ scopeVar: string,
76
+ ): ParsedEvent[] {
77
+ return getEventMetadata(ctor).map(({ methodName, pipeline }) =>
78
+ parseAnnotatedPipeline(methodName, scopeVar, pipeline),
79
+ );
80
+ }
81
+
82
+ function parseAnnotatedPipeline(
83
+ methodName: string,
84
+ scopeVar: string,
85
+ raw: string,
86
+ ): ParsedEvent {
87
+ const colonIdx = raw.indexOf(':');
88
+ if (colonIdx === -1) {
89
+ throw new Error(`[SOMA Annotation] 无效的 @Event 格式,缺少冒号: "${raw}"`);
90
+ }
91
+
92
+ const selector = raw.slice(0, colonIdx).trim();
93
+ const expression = raw.slice(colonIdx + 1).trim();
94
+ const defaultFunc = `${scopeVar}.${methodName}`;
95
+
96
+ const parts = expression.split('|').map((s) => s.trim());
97
+ const type = parts[0];
98
+
99
+ if (type === 'NAV_ACTION' && parts.length === 2) {
100
+ return parsePipeline(selector, `${type} | ${defaultFunc} | ${parts[1]}`);
101
+ }
102
+
103
+ if (type === 'UI_REFRESH' && parts.length === 1) {
104
+ return parsePipeline(selector, `${type} | ${defaultFunc}`);
105
+ }
106
+
107
+ return parsePipeline(selector, expression);
108
+ }
109
+
110
+ function defaultItemVar(propertyKey: string): string {
111
+ if (propertyKey.length === 0) return 'item';
112
+ return propertyKey.endsWith('s') ? propertyKey.charAt(0) : propertyKey;
113
+ }