soma-core 1.0.0

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 (78) hide show
  1. package/app/api/page/route.ts +97 -0
  2. package/app/globals.css +3 -0
  3. package/app/layout.tsx +18 -0
  4. package/app/page.tsx +129 -0
  5. package/bin/soma.cjs +2 -0
  6. package/core/base/SomaApi.ts +14 -0
  7. package/core/base/SomaDict.ts +168 -0
  8. package/core/base/SomaEntity.ts +41 -0
  9. package/core/base/SomaHttpClient.ts +126 -0
  10. package/core/base/SomaLocaleOnlyPageRoot.ts +4 -0
  11. package/core/base/SomaPageRootBase.ts +54 -0
  12. package/core/base/SomaValidator.ts +147 -0
  13. package/core/base/index.ts +7 -0
  14. package/core/compiler/full-manifest-builder.ts +43 -0
  15. package/core/compiler/manifest-compiler.ts +237 -0
  16. package/core/compiler/route-builder.ts +31 -0
  17. package/core/compiler/soma-precompile.ts +48 -0
  18. package/core/compiler/soma-webpack-loader.js +35 -0
  19. package/core/compiler/vite-plugin-soma.ts +73 -0
  20. package/core/container/SomaContainerAdapter.ts +169 -0
  21. package/core/diagnostics/SomaDiagnostics.ts +186 -0
  22. package/core/engine/asset-resolver.ts +67 -0
  23. package/core/engine/dom-renderer.ts +366 -0
  24. package/core/engine/event-engine.ts +287 -0
  25. package/core/engine/lis.ts +60 -0
  26. package/core/engine/reactive-proxy.ts +225 -0
  27. package/core/engine/render-engine.ts +264 -0
  28. package/core/engine/runtime-builder.ts +100 -0
  29. package/core/engine/scope-resolver.ts +252 -0
  30. package/core/engine/soma-bootstrap.ts +244 -0
  31. package/core/index.ts +6 -0
  32. package/core/infra/auth/IAuthService.ts +13 -0
  33. package/core/infra/auth/TokenAuthService.ts +98 -0
  34. package/core/infra/cache/ICache.ts +13 -0
  35. package/core/infra/cache/MemoryCache.ts +95 -0
  36. package/core/infra/cache/ServerFileCache.ts +123 -0
  37. package/core/infra/config/IConfig.ts +9 -0
  38. package/core/infra/config/SomaConfig.ts +85 -0
  39. package/core/infra/event-bus/IEventBus.ts +9 -0
  40. package/core/infra/event-bus/SomaEventBus.ts +53 -0
  41. package/core/infra/http/IHttpClient.ts +21 -0
  42. package/core/infra/http/SomaHttpService.ts +141 -0
  43. package/core/infra/i18n/DefaultI18n.ts +41 -0
  44. package/core/infra/i18n/II18n.ts +7 -0
  45. package/core/infra/logger/ConsoleLogger.ts +81 -0
  46. package/core/infra/logger/ILogger.ts +19 -0
  47. package/core/infra/notify/DefaultNotifyService.ts +31 -0
  48. package/core/infra/notify/INotifyService.ts +14 -0
  49. package/core/infra/permission/IPermission.ts +10 -0
  50. package/core/infra/permission/SomaPermission.ts +48 -0
  51. package/core/infra/router/IRouter.ts +19 -0
  52. package/core/infra/router/SomaRouter.ts +66 -0
  53. package/core/infra/storage/IStorageService.ts +7 -0
  54. package/core/infra/storage/MemoryStorageService.ts +53 -0
  55. package/core/infra/timer/ITimer.ts +9 -0
  56. package/core/infra/timer/SomaTimer.ts +118 -0
  57. package/core/middleware/SomaMiddlewareChain.ts +29 -0
  58. package/core/parser/pipeline-parser.ts +276 -0
  59. package/core/parser/ui-config-parser.ts +336 -0
  60. package/core/parser/yaml-loader.ts +36 -0
  61. package/core/router/RouteHandler.ts +93 -0
  62. package/core/runtime/SomaSnapshotStore.ts +98 -0
  63. package/core/scheduler/SomaScheduler.ts +190 -0
  64. package/core/types/domain.types.ts +88 -0
  65. package/core/types/engine.types.ts +35 -0
  66. package/core/types/event.types.ts +57 -0
  67. package/core/types/keyboard.types.ts +18 -0
  68. package/core/types/manifest.types.ts +30 -0
  69. package/core/types/scheduler.types.ts +10 -0
  70. package/core/types/ui-config.types.ts +89 -0
  71. package/core/validation/contract-validator.ts +465 -0
  72. package/dist/cli/soma.js +49 -0
  73. package/global.d.ts +14 -0
  74. package/next.config.js +61 -0
  75. package/package.json +77 -0
  76. package/postcss.config.js +6 -0
  77. package/tailwind.config.ts +21 -0
  78. package/tsconfig.json +35 -0
@@ -0,0 +1,169 @@
1
+ export interface SomaAnchorStats {
2
+ anchors: Set<string>;
3
+ duplicates: Map<string, number>;
4
+ }
5
+
6
+ export class SomaContainerAdapter {
7
+ mount(
8
+ container: HTMLElement,
9
+ html: string,
10
+ includes?: Record<string, string>,
11
+ ): void {
12
+ container.innerHTML = html;
13
+ if (includes) {
14
+ this.resolveIncludes(container, includes);
15
+ }
16
+ }
17
+
18
+ collectAnchors(container: HTMLElement): SomaAnchorStats {
19
+ const anchors = new Set<string>();
20
+ const counts = new Map<string, number>();
21
+
22
+ container.querySelectorAll<HTMLElement>('[data-soma-id]').forEach((element) => {
23
+ const somaId = element.getAttribute('data-soma-id');
24
+ if (!somaId) return;
25
+ anchors.add(somaId);
26
+ counts.set(somaId, (counts.get(somaId) ?? 0) + 1);
27
+ });
28
+
29
+ const duplicates = new Map<string, number>();
30
+ for (const [somaId, count] of counts.entries()) {
31
+ if (count > 1) {
32
+ duplicates.set(somaId, count);
33
+ }
34
+ }
35
+
36
+ return { anchors, duplicates };
37
+ }
38
+
39
+ findAnchor(root: ParentNode, somaId: string): HTMLElement | null {
40
+ return root.querySelector<HTMLElement>(`[data-soma-id="${somaId}"]`);
41
+ }
42
+
43
+ findClosestAnchor(target: EventTarget | null): HTMLElement | null {
44
+ if (!(target instanceof HTMLElement)) {
45
+ return null;
46
+ }
47
+ return target.closest<HTMLElement>('[data-soma-id]');
48
+ }
49
+
50
+ getAnchorId(element: HTMLElement): string | null {
51
+ return element.getAttribute('data-soma-id');
52
+ }
53
+
54
+ readRole(element: HTMLElement): string | null {
55
+ return (
56
+ element.getAttribute('data-soma-role') ??
57
+ element.querySelector('template')?.getAttribute('data-soma-role') ??
58
+ null
59
+ );
60
+ }
61
+
62
+ getTemplate(element: HTMLElement): HTMLTemplateElement | null {
63
+ return element.querySelector('template');
64
+ }
65
+
66
+ cloneTemplate(element: HTMLElement): DocumentFragment | null {
67
+ const template = this.getTemplate(element);
68
+ if (!template) {
69
+ return null;
70
+ }
71
+
72
+ return template.content.cloneNode(true) as DocumentFragment;
73
+ }
74
+
75
+ clearRenderedChildren(element: HTMLElement): void {
76
+ for (const child of Array.from(element.children)) {
77
+ if (child.tagName === 'TEMPLATE') {
78
+ continue;
79
+ }
80
+ child.remove();
81
+ }
82
+ }
83
+
84
+ appendFragment(element: HTMLElement, fragment: DocumentFragment): void {
85
+ element.appendChild(fragment);
86
+ }
87
+
88
+ setText(element: HTMLElement, value: string): void {
89
+ element.textContent = value;
90
+ }
91
+
92
+ setAttribute(element: HTMLElement, attrName: string, value: string): void {
93
+ element.setAttribute(attrName, value);
94
+ }
95
+
96
+ setHtml(element: HTMLElement, value: string): void {
97
+ const purify = (globalThis as { DOMPurify?: { sanitize: (html: string) => string } }).DOMPurify;
98
+ if (purify) {
99
+ element.innerHTML = purify.sanitize(value);
100
+ return;
101
+ }
102
+
103
+ const tmp = document.createElement('div');
104
+ tmp.textContent = value;
105
+ element.innerHTML = tmp.innerHTML;
106
+ }
107
+
108
+ setVisibility(element: HTMLElement, visible: boolean): void {
109
+ element.style.display = visible ? '' : 'none';
110
+ element.classList.toggle('soma-visible', visible);
111
+ element.classList.toggle('soma-hidden', !visible);
112
+ }
113
+
114
+ isVisible(element: HTMLElement): boolean {
115
+ return element.style.display !== 'none';
116
+ }
117
+
118
+ toggleClasses(element: HTMLElement, classes: string[], enabled: boolean): void {
119
+ if (classes.length === 0) return;
120
+ if (enabled) {
121
+ element.classList.add(...classes);
122
+ return;
123
+ }
124
+ element.classList.remove(...classes);
125
+ }
126
+
127
+ setValue(element: HTMLElement, value: string): void {
128
+ (element as HTMLInputElement).value = value;
129
+ }
130
+
131
+ getValue(element: HTMLElement): string {
132
+ return (element as HTMLInputElement).value ?? '';
133
+ }
134
+
135
+ listen(
136
+ element: HTMLElement,
137
+ eventType: string,
138
+ listener: (event: Event) => void,
139
+ signal: AbortSignal,
140
+ ): void {
141
+ element.addEventListener(eventType, listener, { signal });
142
+ }
143
+
144
+ confirm(message: string): boolean {
145
+ return window.confirm(message);
146
+ }
147
+
148
+ navigate(url: string): void {
149
+ window.location.href = url;
150
+ }
151
+
152
+ now(): number {
153
+ return globalThis.performance?.now?.() ?? Date.now();
154
+ }
155
+
156
+ private resolveIncludes(container: HTMLElement, includes: Record<string, string>): void {
157
+ const elements = container.querySelectorAll<HTMLElement>('[data-soma-include]');
158
+ for (const element of elements) {
159
+ const includePath = element.getAttribute('data-soma-include');
160
+ if (!includePath || !includes[includePath]) {
161
+ continue;
162
+ }
163
+
164
+ element.innerHTML = includes[includePath];
165
+ element.removeAttribute('data-soma-include');
166
+ this.resolveIncludes(element, includes);
167
+ }
168
+ }
169
+ }
@@ -0,0 +1,186 @@
1
+ // ─── 环形缓冲区:O(1) 写入,替代 push + shift 的 O(n) ─────
2
+
3
+ class RingBuffer<T> {
4
+ private buffer: (T | undefined)[];
5
+ private head = 0;
6
+ private count = 0;
7
+
8
+ constructor(private readonly capacity: number) {
9
+ this.buffer = new Array(capacity);
10
+ }
11
+
12
+ push(item: T): void {
13
+ const index = (this.head + this.count) % this.capacity;
14
+ if (this.count < this.capacity) {
15
+ this.count++;
16
+ } else {
17
+ // 满了,覆盖最旧的条目,head 前移
18
+ this.head = (this.head + 1) % this.capacity;
19
+ }
20
+ this.buffer[index] = item;
21
+ }
22
+
23
+ toArray(): T[] {
24
+ const result: T[] = [];
25
+ for (let i = 0; i < this.count; i++) {
26
+ result.push(this.buffer[(this.head + i) % this.capacity] as T);
27
+ }
28
+ return result;
29
+ }
30
+
31
+ get length(): number {
32
+ return this.count;
33
+ }
34
+ }
35
+
36
+ // ─── 高精度时间戳工具 ─────────────────────────────────
37
+
38
+ function highResTimestamp(): number {
39
+ return globalThis.performance?.now?.() ?? Date.now();
40
+ }
41
+
42
+ // ─── 类型定义 ─────────────────────────────────────────
43
+
44
+ export interface SomaMutationRecord {
45
+ path: string;
46
+ valuePreview: string;
47
+ timestamp: number;
48
+ }
49
+
50
+ export interface SomaRenderRecord {
51
+ phase: 'full-render' | 'patch';
52
+ path?: string;
53
+ bindingCount: number;
54
+ affectedCount: number;
55
+ durationMs: number;
56
+ timestamp: number;
57
+ }
58
+
59
+ export interface SomaEventRecord {
60
+ somaId: string;
61
+ domEvent: string;
62
+ eventType: string;
63
+ funcPath?: string | null;
64
+ status: 'success' | 'blocked' | 'error';
65
+ durationMs: number;
66
+ message?: string;
67
+ timestamp: number;
68
+ }
69
+
70
+ export interface SomaValidationRecord {
71
+ level: 'warning' | 'error';
72
+ message: string;
73
+ timestamp: number;
74
+ }
75
+
76
+ export interface SomaSchedulerRecord {
77
+ priority: 'immediate' | 'visible' | 'background';
78
+ label?: string;
79
+ durationMs: number;
80
+ status?: 'success' | 'error';
81
+ timestamp: number;
82
+ }
83
+
84
+ export interface SomaDiagnosticsSnapshot {
85
+ mutations: SomaMutationRecord[];
86
+ renders: SomaRenderRecord[];
87
+ events: SomaEventRecord[];
88
+ validations: SomaValidationRecord[];
89
+ scheduler: SomaSchedulerRecord[];
90
+ counters: {
91
+ mutations: number;
92
+ renders: number;
93
+ events: number;
94
+ validations: number;
95
+ scheduler: number;
96
+ };
97
+ }
98
+
99
+ // ─── 诊断系统 ─────────────────────────────────────────
100
+
101
+ export class SomaDiagnostics {
102
+ private mutations: RingBuffer<SomaMutationRecord>;
103
+ private renders: RingBuffer<SomaRenderRecord>;
104
+ private events: RingBuffer<SomaEventRecord>;
105
+ private validations: RingBuffer<SomaValidationRecord>;
106
+ private scheduler: RingBuffer<SomaSchedulerRecord>;
107
+
108
+ constructor(maxEntries: number = 200) {
109
+ this.mutations = new RingBuffer(maxEntries);
110
+ this.renders = new RingBuffer(maxEntries);
111
+ this.events = new RingBuffer(maxEntries);
112
+ this.validations = new RingBuffer(maxEntries);
113
+ this.scheduler = new RingBuffer(maxEntries);
114
+ }
115
+
116
+ recordMutation(path: string, value: any): void {
117
+ this.mutations.push({
118
+ path,
119
+ valuePreview: this.preview(value),
120
+ timestamp: highResTimestamp(),
121
+ });
122
+ }
123
+
124
+ recordRender(record: Omit<SomaRenderRecord, 'timestamp'>): void {
125
+ this.renders.push({
126
+ ...record,
127
+ timestamp: highResTimestamp(),
128
+ });
129
+ }
130
+
131
+ recordEvent(record: Omit<SomaEventRecord, 'timestamp'>): void {
132
+ this.events.push({
133
+ ...record,
134
+ timestamp: highResTimestamp(),
135
+ });
136
+ }
137
+
138
+ recordValidation(level: SomaValidationRecord['level'], message: string): void {
139
+ this.validations.push({
140
+ level,
141
+ message,
142
+ timestamp: highResTimestamp(),
143
+ });
144
+ }
145
+
146
+ recordScheduler(record: Omit<SomaSchedulerRecord, 'timestamp'>): void {
147
+ this.scheduler.push({
148
+ ...record,
149
+ timestamp: highResTimestamp(),
150
+ });
151
+ }
152
+
153
+ snapshot(): SomaDiagnosticsSnapshot {
154
+ return {
155
+ mutations: this.mutations.toArray(),
156
+ renders: this.renders.toArray(),
157
+ events: this.events.toArray(),
158
+ validations: this.validations.toArray(),
159
+ scheduler: this.scheduler.toArray(),
160
+ counters: {
161
+ mutations: this.mutations.length,
162
+ renders: this.renders.length,
163
+ events: this.events.length,
164
+ validations: this.validations.length,
165
+ scheduler: this.scheduler.length,
166
+ },
167
+ };
168
+ }
169
+
170
+ private preview(value: any): string {
171
+ if (value === null) return 'null';
172
+ if (value === undefined) return 'undefined';
173
+ if (typeof value === 'string') return value;
174
+ if (typeof value === 'number' || typeof value === 'boolean') {
175
+ return String(value);
176
+ }
177
+ if (Array.isArray(value)) {
178
+ return `[Array(${value.length})]`;
179
+ }
180
+ try {
181
+ return JSON.stringify(value);
182
+ } catch {
183
+ return Object.prototype.toString.call(value);
184
+ }
185
+ }
186
+ }
@@ -0,0 +1,67 @@
1
+ // core/engine/asset-resolver.ts
2
+ // 职责:YAML 解析 + 预编译模式切换 + 解析缓存
3
+
4
+ import yaml from 'js-yaml';
5
+ import type { ICache } from '../infra/cache/ICache';
6
+ import { MemoryCache } from '../infra/cache/MemoryCache';
7
+ import { parseEventConfig } from '../parser/pipeline-parser';
8
+ import { parseUiConfig } from '../parser/ui-config-parser';
9
+ import type { SomaPageAssets, ParsedRuntimeAssets } from './soma-bootstrap';
10
+
11
+ /**
12
+ * 资产解析器:将 SomaPageAssets 解析为引擎可消费的 ParsedRuntimeAssets。
13
+ *
14
+ * 支持两种模式:
15
+ * - 预编译模式:assets 中已有 uiConfig/eventConfig,直接使用,零开销
16
+ * - 字符串模式:assets 中是 yaml 字符串,运行时解析,带 LRU 缓存
17
+ */
18
+ export class SomaAssetResolver {
19
+ private cache: ICache<ParsedRuntimeAssets>;
20
+
21
+ constructor(cache?: ICache<ParsedRuntimeAssets>) {
22
+ this.cache = cache ?? new MemoryCache({ maxSize: 50 });
23
+ }
24
+
25
+ resolve(assets: SomaPageAssets): ParsedRuntimeAssets {
26
+ // 预编译模式:直接使用已编译的对象,零解析开销
27
+ if (assets.uiConfig && assets.eventConfig) {
28
+ return {
29
+ uiConfig: assets.uiConfig,
30
+ eventConfig: assets.eventConfig,
31
+ locale: assets.locale ?? this.parseLocale(assets.localeYaml),
32
+ appConfig: assets.appConfig ?? this.parseAppConfig(assets.appConfigYaml),
33
+ };
34
+ }
35
+
36
+ // 字符串模式:运行时解析,带缓存
37
+ const uiYaml = assets.uiYaml!;
38
+ const eventYaml = assets.eventYaml!;
39
+ const localeYaml = assets.localeYaml ?? '';
40
+
41
+ const cacheKey = `${uiYaml}\0${eventYaml}\0${localeYaml}\0${assets.appConfigYaml ?? ''}`;
42
+ const cached = this.cache.get(cacheKey);
43
+ if (cached) {
44
+ return cached;
45
+ }
46
+
47
+ const result: ParsedRuntimeAssets = {
48
+ uiConfig: parseUiConfig(yaml.load(uiYaml)),
49
+ eventConfig: parseEventConfig(yaml.load(eventYaml) as any),
50
+ locale: localeYaml ? (yaml.load(localeYaml) as Record<string, unknown>) || {} : {},
51
+ appConfig: this.parseAppConfig(assets.appConfigYaml),
52
+ };
53
+
54
+ this.cache.set(cacheKey, result);
55
+ return result;
56
+ }
57
+
58
+ private parseLocale(localeYaml?: string): Record<string, unknown> {
59
+ if (!localeYaml) return {};
60
+ return (yaml.load(localeYaml) as Record<string, unknown>) || {};
61
+ }
62
+
63
+ private parseAppConfig(appConfigYaml?: string): unknown {
64
+ if (!appConfigYaml) return null;
65
+ return yaml.load(appConfigYaml);
66
+ }
67
+ }