soma-core 1.0.2 → 1.1.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 (93) hide show
  1. package/app/SomaPageClient.tsx +11 -20
  2. package/app/[...path]/page.tsx +21 -0
  3. package/app/api/[...path]/route.ts +86 -77
  4. package/app/components/SomaHostPage.tsx +133 -0
  5. package/app/components/SomaHydrationShell.tsx +1 -1
  6. package/app/favicon.ico/route.ts +13 -0
  7. package/app/layout.tsx +10 -6
  8. package/app/page.tsx +7 -18
  9. package/app/soma/[...path]/route.ts +9 -0
  10. package/app/{api/soma-manifest → soma/manifest}/route.ts +3 -3
  11. package/app/soma/page/route.ts +29 -0
  12. package/app/soma/page-object/route.ts +158 -0
  13. package/app/soma/route.ts +9 -0
  14. package/bin/soma-mock.mjs +38 -0
  15. package/bin/soma.cjs +1 -1
  16. package/core/api/load-host-service.ts +5 -2
  17. package/core/base/SomaHttpClient.ts +5 -3
  18. package/core/compiler/full-manifest-builder.ts +84 -69
  19. package/core/compiler/host-config-sync.cjs +32 -6
  20. package/core/compiler/page-base-resolver.ts +3 -0
  21. package/core/compiler/soma-manifest-webpack-plugin.js +160 -10
  22. package/core/engine/dom-renderer.ts +160 -24
  23. package/core/engine/soma-headless-page.ts +86 -0
  24. package/core/host/app-config-composer.ts +90 -0
  25. package/core/host/app-config.stub.ts +2 -0
  26. package/core/host/host-config-paths.cjs +100 -0
  27. package/core/host/host-config-paths.ts +132 -0
  28. package/core/host/invoke-host-request-hook.ts +37 -0
  29. package/core/host/load-host-domain-class.ts +87 -0
  30. package/core/host/locale.stub.ts +2 -0
  31. package/core/host/page-response-mode.cjs +96 -0
  32. package/core/host/page-response-request.ts +35 -0
  33. package/core/host/request-origin.ts +18 -0
  34. package/core/host/resolve-host-request-hook.ts +29 -0
  35. package/core/host/server-page-assets.ts +193 -0
  36. package/core/host/soma-domain-loaders.stub.ts +6 -0
  37. package/core/host/soma-domain-loaders.ts +69 -0
  38. package/core/host/soma-request-hook-host.stub.ts +4 -0
  39. package/core/host/source-packages.ts +153 -0
  40. package/core/index.ts +22 -0
  41. package/core/infra/http/SomaHttpService.ts +23 -14
  42. package/core/infra/http/soma-server-request-context.ts +126 -0
  43. package/core/mock/node/catch-all.mjs +35 -0
  44. package/core/mock/node/cli.d.mts +58 -0
  45. package/core/mock/node/cli.mjs +243 -0
  46. package/core/mock/node/context.mjs +167 -0
  47. package/core/mock/node/environment-policy.mjs +52 -0
  48. package/core/mock/node/plugin-loader.mjs +212 -0
  49. package/core/mock/node/preload.mjs +91 -0
  50. package/core/mock/node/process-lifecycle.mjs +236 -0
  51. package/core/mock/node/public.d.mts +110 -0
  52. package/core/mock/node/public.mjs +4 -0
  53. package/core/mock/node/registry.mjs +336 -0
  54. package/core/mock/node/schema-generator.mjs +1310 -0
  55. package/core/mock/testing/host-harness.d.mts +66 -0
  56. package/core/mock/testing/host-harness.mjs +276 -0
  57. package/core/mock/testing/host-runtime.mjs +48 -0
  58. package/core/runtime/SomaRuntimeServices.ts +5 -1
  59. package/core/runtime/serialize-page-state.ts +152 -0
  60. package/dist/cli/soma.js +375 -4
  61. package/dist/core/index.cjs +2957 -2387
  62. package/dist/tsconfig.types.tsbuildinfo +1 -1
  63. package/dist/types/base/SomaHttpClient.d.ts +2 -0
  64. package/dist/types/compiler/full-manifest-builder.d.ts +2 -0
  65. package/dist/types/engine/dom-renderer.d.ts +6 -0
  66. package/dist/types/engine/soma-headless-page.d.ts +10 -0
  67. package/dist/types/host/app-config-composer.d.ts +6 -0
  68. package/dist/types/host/app-config.stub.d.ts +3 -0
  69. package/dist/types/host/host-config-paths.d.ts +23 -0
  70. package/dist/types/host/invoke-host-request-hook.d.ts +8 -0
  71. package/dist/types/host/load-host-domain-class.d.ts +12 -0
  72. package/dist/types/host/locale.stub.d.ts +3 -0
  73. package/dist/types/host/page-response-request.d.ts +9 -0
  74. package/dist/types/host/request-origin.d.ts +1 -0
  75. package/dist/types/host/resolve-host-request-hook.d.ts +16 -0
  76. package/dist/types/host/server-page-assets.d.ts +29 -0
  77. package/dist/types/host/soma-domain-loaders.d.ts +19 -0
  78. package/dist/types/host/soma-domain-loaders.stub.d.ts +4 -0
  79. package/dist/types/host/soma-request-hook-host.stub.d.ts +2 -0
  80. package/dist/types/host/source-packages.d.ts +12 -0
  81. package/dist/types/index.d.ts +3 -0
  82. package/dist/types/infra/http/SomaHttpService.d.ts +2 -0
  83. package/dist/types/infra/http/soma-server-request-context.d.ts +5 -0
  84. package/dist/types/runtime/serialize-page-state.d.ts +10 -0
  85. package/docs//351/241/265/351/235/242JSON/346/250/241/345/274/217/346/216/245/345/205/245/346/214/207/345/215/227.md +141 -0
  86. package/global.d.ts +74 -33
  87. package/middleware.ts +33 -0
  88. package/next.config.js +166 -16
  89. package/package.json +47 -13
  90. package/tailwind.config.ts +21 -17
  91. package/tsconfig.json +1 -5
  92. package/app/api/page/route.ts +0 -99
  93. package/app/loading.tsx +0 -5
@@ -3,6 +3,12 @@
3
3
  */
4
4
  const fs = require('node:fs');
5
5
  const path = require('node:path');
6
+ const createJiti = require('jiti');
7
+ const {
8
+ getSomaHostConfigRoot,
9
+ resolveAppConfigPath,
10
+ resolveHostAppConfigPath,
11
+ } = require('../host/host-config-paths.cjs');
6
12
 
7
13
  function collectHtmlFiles(dir, prefix = '', acc = []) {
8
14
  if (!fs.existsSync(dir)) return acc;
@@ -15,10 +21,146 @@ function collectHtmlFiles(dir, prefix = '', acc = []) {
15
21
  return acc;
16
22
  }
17
23
 
24
+ function readJson(filePath) {
25
+ try {
26
+ if (!fs.existsSync(filePath)) return null;
27
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ function packagePathInNodeModules(hostDir, packageName) {
34
+ return path.join(hostDir, 'node_modules', ...packageName.split('/'));
35
+ }
36
+
37
+ function resolvePackageRoot(hostDir, packageName, version) {
38
+ const nodeModulesPath = packagePathInNodeModules(hostDir, packageName);
39
+ if (fs.existsSync(nodeModulesPath)) {
40
+ return nodeModulesPath;
41
+ }
42
+
43
+ if (typeof version === 'string' && version.startsWith('file:')) {
44
+ const fileRoot = path.resolve(hostDir, version.slice('file:'.length));
45
+ if (fs.existsSync(fileRoot)) {
46
+ return fileRoot;
47
+ }
48
+ }
49
+
50
+ return null;
51
+ }
52
+
53
+ function readExplicitSourcePackages() {
54
+ return String(process.env.SOMA_SOURCE_PACKAGES ?? '')
55
+ .split(',')
56
+ .map((item) => item.trim())
57
+ .filter(Boolean);
58
+ }
59
+
60
+ function readHostDependencies(hostDir) {
61
+ const packageJson = readJson(path.join(hostDir, 'package.json'));
62
+ return {
63
+ ...(packageJson?.dependencies ?? {}),
64
+ ...(packageJson?.devDependencies ?? {}),
65
+ };
66
+ }
67
+
68
+ function resolveSafeChildRoot(parent, relativePath) {
69
+ const trimmed = typeof relativePath === 'string' ? relativePath.trim() : '';
70
+ if (!trimmed) return parent;
71
+
72
+ const resolved = path.resolve(parent, trimmed);
73
+ if ((resolved === parent || resolved.startsWith(`${parent}${path.sep}`)) && fs.existsSync(resolved)) {
74
+ return resolved;
75
+ }
76
+ return parent;
77
+ }
78
+
79
+ function getSomaHostSourceRoot(hostDir) {
80
+ const normalizedHostDir = path.resolve(hostDir);
81
+ const packageJson = readJson(path.join(normalizedHostDir, 'package.json'));
82
+ return resolveSafeChildRoot(normalizedHostDir, packageJson?.soma?.hostRoot);
83
+ }
84
+
85
+ function isSomaSourcePackage(packageRoot, explicit) {
86
+ if (explicit) return true;
87
+ const packageJson = readJson(path.join(packageRoot, 'package.json'));
88
+ return packageJson?.soma?.source === true || fs.existsSync(path.join(packageRoot, 'shell', 'html'));
89
+ }
90
+
91
+ function toPackageSource(packageName, packageRoot) {
92
+ const packageJson = readJson(path.join(packageRoot, 'package.json'));
93
+ const codeRoot = resolveSafeChildRoot(packageRoot, packageJson?.soma?.hostRoot);
94
+ const configRoot = resolveSafeChildRoot(packageRoot, packageJson?.soma?.configRoot);
95
+ const shellRoot = path.join(codeRoot, 'shell');
96
+ return {
97
+ type: 'package',
98
+ name: packageName,
99
+ packageName,
100
+ assetRoot: fs.existsSync(path.join(shellRoot, 'html')) ? shellRoot : codeRoot,
101
+ codeRoot,
102
+ configRoot,
103
+ };
104
+ }
105
+
106
+ function getSomaAssetSources(hostDir) {
107
+ const normalizedHostDir = path.resolve(hostDir);
108
+ const hostSourceRoot = getSomaHostSourceRoot(normalizedHostDir);
109
+ const dependencies = readHostDependencies(normalizedHostDir);
110
+ const explicitPackages = new Set(readExplicitSourcePackages());
111
+ const packageNames = new Set([
112
+ ...Object.keys(dependencies),
113
+ ...explicitPackages,
114
+ ]);
115
+
116
+ const sources = [
117
+ {
118
+ type: 'host',
119
+ name: 'host',
120
+ assetRoot: hostSourceRoot,
121
+ codeRoot: hostSourceRoot,
122
+ configRoot: getSomaHostConfigRoot(normalizedHostDir),
123
+ },
124
+ ];
125
+
126
+ for (const packageName of packageNames) {
127
+ const packageRoot = resolvePackageRoot(normalizedHostDir, packageName, dependencies[packageName]);
128
+ if (!packageRoot || !isSomaSourcePackage(packageRoot, explicitPackages.has(packageName))) {
129
+ continue;
130
+ }
131
+ sources.push(toPackageSource(packageName, packageRoot));
132
+ }
133
+
134
+ return sources;
135
+ }
136
+
137
+ function collectPageEntries(sources) {
138
+ const byHtmlFile = new Map();
139
+ const orderedSources = [
140
+ ...sources.filter((source) => source.type === 'package'),
141
+ ...sources.filter((source) => source.type === 'host'),
142
+ ];
143
+
144
+ for (const source of orderedSources) {
145
+ const htmlRoot = path.join(source.assetRoot, 'html');
146
+ for (const htmlFile of collectHtmlFiles(htmlRoot).sort()) {
147
+ byHtmlFile.set(htmlFile, { source, htmlFile });
148
+ }
149
+ }
150
+
151
+ return [...byHtmlFile.values()].sort((a, b) => a.htmlFile.localeCompare(b.htmlFile));
152
+ }
153
+
18
154
  class SomaManifestWebpackPlugin {
19
155
  constructor(options = {}) {
20
156
  this.hostDir = options.hostDir;
21
157
  this.outputDir = options.outputDir ?? '.soma';
158
+ this.jiti = createJiti(__filename, {
159
+ interopDefault: true,
160
+ alias: {
161
+ '@core': path.resolve(__dirname, '..'),
162
+ },
163
+ });
22
164
  }
23
165
 
24
166
  apply(compiler) {
@@ -30,25 +172,33 @@ class SomaManifestWebpackPlugin {
30
172
  }
31
173
 
32
174
  try {
33
- const { precompileAll } = require('./full-manifest-builder');
34
- const htmlFiles = collectHtmlFiles(path.join(hostDir, 'html'));
175
+ const { precompileAll } = this.jiti('./full-manifest-builder.ts');
176
+ const sources = getSomaAssetSources(hostDir);
177
+ const pageEntries = collectPageEntries(sources);
178
+ const htmlFiles = pageEntries.map((entry) => entry.htmlFile);
35
179
  const readYaml = (filePath) =>
36
180
  fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';
181
+ const hostConfigRoot = sources.find((source) => source.type === 'host')?.configRoot ?? hostDir;
182
+ const hostAppConfigPath = resolveHostAppConfigPath(hostDir);
37
183
 
38
- const pages = htmlFiles
39
- .filter((f) => !f.startsWith('shared/') && !f.startsWith('system/'))
40
- .map((htmlFile) => {
184
+ const pages = pageEntries
185
+ .filter(({ htmlFile }) => !htmlFile.startsWith('shared/') && !htmlFile.startsWith('system/'))
186
+ .map(({ source, htmlFile }) => {
41
187
  const base = htmlFile.replace(/\.html$/, '');
188
+ const sourceAppConfigPath = resolveAppConfigPath(source.configRoot);
42
189
  return {
43
190
  path: `/${base}`,
44
- uiYaml: readYaml(path.join(hostDir, 'ui', `${base}_ui.yaml`)),
45
- eventYaml: readYaml(path.join(hostDir, 'event', `${base}_event.yaml`)),
46
- styleYaml: readYaml(path.join(hostDir, 'ui', `${base}_style.yaml`)) || undefined,
191
+ uiYaml: readYaml(path.join(source.assetRoot, 'ui', `${base}_ui.yaml`)),
192
+ eventYaml: readYaml(path.join(source.assetRoot, 'event', `${base}_event.yaml`)),
193
+ styleYaml: readYaml(path.join(source.assetRoot, 'ui', `${base}_style.yaml`)) || undefined,
194
+ appConfigYaml: sourceAppConfigPath
195
+ ? readYaml(sourceAppConfigPath)
196
+ : (hostAppConfigPath ? readYaml(hostAppConfigPath) : ''),
47
197
  };
48
198
  });
49
199
 
50
- const localeYaml = readYaml(path.join(hostDir, 'config/locale.yaml'));
51
- const appConfigYaml = readYaml(path.join(hostDir, 'config/app.config.yaml'));
200
+ const localeYaml = readYaml(path.join(hostConfigRoot, 'locale.yaml'));
201
+ const appConfigYaml = hostAppConfigPath ? readYaml(hostAppConfigPath) : '';
52
202
  const manifest = precompileAll({ htmlFiles, localeYaml, appConfigYaml, pages });
53
203
 
54
204
  const outDir = path.join(hostDir, this.outputDir);
@@ -1,7 +1,12 @@
1
1
  import type { IContainerAdapter } from '../container/IContainerAdapter';
2
2
  import type { SomaCompiledBinding } from '../types/manifest.types';
3
3
  import type { BindingEntry } from '../types/engine.types';
4
- import type { ShowMapping } from '../types/ui-config.types';
4
+ import type {
5
+ ExtendedShowValue,
6
+ NestedShowMapping,
7
+ ShowMapping,
8
+ ShowValue,
9
+ } from '../types/ui-config.types';
5
10
  import type { SomaScopeResolver } from './scope-resolver';
6
11
  import { longestIncreasingSubsequence } from './lis';
7
12
 
@@ -314,18 +319,24 @@ export class SomaDomRenderer {
314
319
  this.adapter.appendFragment(entry.element, fragment);
315
320
  }
316
321
 
317
- private applyShowConfig(
318
- root: HTMLElement,
319
- data: any,
320
- showConfig: ShowMapping,
321
- ): void {
322
- for (const [rawKey, config] of Object.entries(showConfig)) {
323
- if (typeof config !== 'string') {
324
- continue;
325
- }
326
-
327
- const [somaId, attrName] = rawKey.split('@');
328
- const element = root.querySelector<HTMLElement>(`[data-soma-id="${somaId}"]`);
322
+ private applyShowConfig(
323
+ root: HTMLElement,
324
+ data: any,
325
+ showConfig: ShowMapping,
326
+ ): void {
327
+ for (const [rawKey, config] of Object.entries(showConfig)) {
328
+ if (this.isNestedShowMapping(config)) {
329
+ this.applyNestedShowConfig(root, data, rawKey, config);
330
+ continue;
331
+ }
332
+
333
+ if (this.isExtendedShowValue(config)) {
334
+ this.applyExtendedShowConfig(root, data, rawKey, config);
335
+ continue;
336
+ }
337
+
338
+ const [somaId, attrName] = rawKey.split('@');
339
+ const element = root.querySelector<HTMLElement>(`[data-soma-id="${somaId}"]`);
329
340
  if (!element) {
330
341
  continue;
331
342
  }
@@ -343,13 +354,122 @@ export class SomaDomRenderer {
343
354
  continue;
344
355
  }
345
356
 
346
- this.adapter?.setText(element, value != null ? String(value) : '--');
347
- }
348
- }
349
-
350
- private resolveShowValue(valuePath: string, itemData: any): any {
351
- const segments = valuePath.split('.');
352
- const firstSeg = segments[0];
357
+ this.adapter?.setText(element, value != null ? String(value) : '--');
358
+ }
359
+ }
360
+
361
+ private applyNestedShowConfig(
362
+ root: HTMLElement,
363
+ data: any,
364
+ rawKey: string,
365
+ config: NestedShowMapping,
366
+ ): void {
367
+ if (!this.adapter) {
368
+ return;
369
+ }
370
+
371
+ const [somaId] = rawKey.split('@');
372
+ const element = root.querySelector<HTMLElement>(`[data-soma-id="${somaId}"]`);
373
+ if (!element) {
374
+ return;
375
+ }
376
+
377
+ const nestedData = this.resolveShowValue(config.bind.obj, data);
378
+ const role = this.adapter.readRole(element);
379
+ const templateCache = this.adapter.cloneTemplate(element);
380
+ if (!templateCache) {
381
+ return;
382
+ }
383
+
384
+ this.adapter.clearRenderedChildren(element);
385
+
386
+ if (Array.isArray(nestedData) || role === 'item') {
387
+ const items = Array.isArray(nestedData) ? nestedData : [];
388
+ for (const itemData of items) {
389
+ this.appendNestedTemplateItem(element, templateCache, itemData, config.show);
390
+ }
391
+ return;
392
+ }
393
+
394
+ if (nestedData && typeof nestedData === 'object') {
395
+ this.appendNestedTemplateItem(element, templateCache, nestedData, config.show);
396
+ }
397
+ }
398
+
399
+ private appendNestedTemplateItem(
400
+ container: HTMLElement,
401
+ templateCache: DocumentFragment,
402
+ itemData: any,
403
+ showConfig: ShowMapping,
404
+ ): void {
405
+ if (!this.adapter) {
406
+ return;
407
+ }
408
+
409
+ const fragment = templateCache.cloneNode(true) as DocumentFragment;
410
+ const wrapper = fragment.firstElementChild as HTMLElement | null;
411
+ if (!wrapper) {
412
+ return;
413
+ }
414
+
415
+ if (itemData && typeof itemData === 'object') {
416
+ const key = 'id' in itemData ? itemData.id : ('key' in itemData ? itemData.key : undefined);
417
+ if (key != null) {
418
+ wrapper.setAttribute('data-soma-key', String(key));
419
+ }
420
+ }
421
+
422
+ this.scopeTracker?.set(wrapper, itemData);
423
+ this.applyShowConfig(wrapper, itemData, showConfig);
424
+ this.adapter.appendFragment(container, fragment);
425
+ }
426
+
427
+ private applyExtendedShowConfig(
428
+ root: HTMLElement,
429
+ data: any,
430
+ rawKey: string,
431
+ config: ExtendedShowValue,
432
+ ): void {
433
+ const [somaId, attrName] = rawKey.split('@');
434
+ const element = root.querySelector<HTMLElement>(`[data-soma-id="${somaId}"]`);
435
+
436
+ if (element) {
437
+ if (config.text) {
438
+ const value = this.resolveShowValue(config.text, data);
439
+ if (attrName === 'html') {
440
+ this.adapter?.setHtml(element, String(value ?? ''));
441
+ } else if (attrName) {
442
+ if (value != null) {
443
+ this.adapter?.setAttribute(element, attrName, String(value));
444
+ }
445
+ } else {
446
+ this.adapter?.setText(element, value != null ? String(value) : '--');
447
+ }
448
+ }
449
+
450
+ if (config.when) {
451
+ const { path, negate } = this.parseConditionalPath(config.when);
452
+ const value = this.resolveShowValue(path, data);
453
+ this.adapter?.setVisibility(element, negate ? !value : !!value);
454
+ }
455
+
456
+ if (config.class) {
457
+ for (const [classes, path] of Object.entries(config.class)) {
458
+ const enabled = !!this.resolveShowValue(path, data);
459
+ this.adapter?.toggleClasses(element, classes.split(' ').filter(Boolean), enabled);
460
+ }
461
+ }
462
+ }
463
+
464
+ if (config.show) {
465
+ const showRoot = element ?? root;
466
+ this.applyShowConfig(showRoot, data, config.show);
467
+ }
468
+ }
469
+
470
+ private resolveShowValue(valuePath: string, itemData: any): any {
471
+ const segments = valuePath.split('.');
472
+ const firstSeg = segments[0];
353
473
 
354
474
  if (this.resolver && this.resolver.hasVar(firstSeg)) {
355
475
  const varPath = this.resolver.getVarPath(firstSeg);
@@ -358,7 +478,23 @@ export class SomaDomRenderer {
358
478
  }
359
479
  return segments.slice(1).reduce((obj: any, key: string) => obj?.[key], itemData);
360
480
  }
361
-
362
- return segments.reduce((obj: any, key: string) => obj?.[key], itemData);
363
- }
364
- }
481
+
482
+ return segments.reduce((obj: any, key: string) => obj?.[key], itemData);
483
+ }
484
+
485
+ private parseConditionalPath(valuePath: string): { path: string; negate: boolean } {
486
+ const negate = valuePath.startsWith('!');
487
+ return {
488
+ path: negate ? valuePath.slice(1) : valuePath,
489
+ negate,
490
+ };
491
+ }
492
+
493
+ private isNestedShowMapping(value: ShowValue): value is NestedShowMapping {
494
+ return typeof value === 'object' && value !== null && 'bind' in value && 'show' in value;
495
+ }
496
+
497
+ private isExtendedShowValue(value: ShowValue): value is ExtendedShowValue {
498
+ return typeof value === 'object' && value !== null;
499
+ }
500
+ }
@@ -0,0 +1,86 @@
1
+ import { applyLocaleMetadata } from '../base/decorators/Locale';
2
+ import { createDefaultRuntimeServices } from '../runtime/SomaRuntimeServices';
3
+ import {
4
+ serializeSomaPageState,
5
+ type SomaJsonValue,
6
+ } from '../runtime/serialize-page-state';
7
+ import type { SomaPageRoot } from '../types/domain.types';
8
+ import { SomaAssetResolver } from './asset-resolver';
9
+ import { SomaScopeResolver } from './scope-resolver';
10
+
11
+ export interface SomaHeadlessPageAssets {
12
+ DomainClass: new () => SomaPageRoot;
13
+ uiYaml?: string;
14
+ localeYaml?: string;
15
+ appConfigYaml?: string;
16
+ routerPath: string;
17
+ }
18
+
19
+ const assetResolver = new SomaAssetResolver();
20
+
21
+ function createDomainInstance(
22
+ assets: SomaHeadlessPageAssets,
23
+ ): SomaPageRoot {
24
+ const parsed = assetResolver.resolve({
25
+ html: '',
26
+ uiYaml: assets.uiYaml ?? '',
27
+ eventYaml: '',
28
+ localeYaml: assets.localeYaml ?? '',
29
+ appConfigYaml: assets.appConfigYaml ?? '',
30
+ DomainClass: assets.DomainClass,
31
+ routerPath: assets.routerPath,
32
+ });
33
+
34
+ const domain = new assets.DomainClass();
35
+ domain._locale = parsed.locale;
36
+ if (parsed.appConfig) {
37
+ domain._config = parsed.appConfig;
38
+ }
39
+ applyLocaleMetadata(domain);
40
+ domain._services = createDefaultRuntimeServices({
41
+ appConfig: parsed.appConfig,
42
+ locale: parsed.locale,
43
+ initialPath: assets.routerPath,
44
+ });
45
+
46
+ const scope = new SomaScopeResolver();
47
+ scope.build(parsed.uiConfig, domain);
48
+ for (const [path, value] of Object.entries(parsed.uiConfig.initProps ?? {})) {
49
+ scope.writeToRoot(path, value);
50
+ }
51
+ return domain;
52
+ }
53
+
54
+ export async function runSomaHeadlessPage(
55
+ assets: SomaHeadlessPageAssets,
56
+ ): Promise<SomaJsonValue> {
57
+ const domain = createDomainInstance(assets);
58
+ let result: SomaJsonValue | undefined;
59
+ let primaryError: unknown;
60
+
61
+ try {
62
+ if (typeof domain.onMount === 'function') {
63
+ await domain.onMount();
64
+ }
65
+ result = serializeSomaPageState(domain);
66
+ } catch (error) {
67
+ primaryError = error;
68
+ }
69
+
70
+ try {
71
+ if (typeof domain.onUnmount === 'function') {
72
+ await domain.onUnmount();
73
+ }
74
+ } catch (error) {
75
+ if (primaryError === undefined) {
76
+ primaryError = error;
77
+ }
78
+ } finally {
79
+ domain._services?.http.abortAll();
80
+ }
81
+
82
+ if (primaryError !== undefined) {
83
+ throw primaryError;
84
+ }
85
+ return result as SomaJsonValue;
86
+ }
@@ -0,0 +1,90 @@
1
+ import fs from 'node:fs';
2
+ import yaml from 'js-yaml';
3
+ import { resolveHostAppConfigPath } from './host-config-paths';
4
+
5
+ type AppConfigRecord = Record<string, unknown>;
6
+
7
+ const UNSAFE_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
8
+
9
+ function isRecord(value: unknown): value is AppConfigRecord {
10
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
11
+ }
12
+
13
+ function cloneValue(value: unknown): unknown {
14
+ if (Array.isArray(value)) {
15
+ return value.map((item) => cloneValue(item));
16
+ }
17
+ if (!isRecord(value)) {
18
+ return value;
19
+ }
20
+ const result: AppConfigRecord = {};
21
+ for (const [key, child] of Object.entries(value)) {
22
+ if (!UNSAFE_KEYS.has(key)) {
23
+ result[key] = cloneValue(child);
24
+ }
25
+ }
26
+ return result;
27
+ }
28
+
29
+ function mergeRecords(defaults: AppConfigRecord, host: AppConfigRecord): AppConfigRecord {
30
+ const result = cloneValue(defaults) as AppConfigRecord;
31
+ for (const [key, hostValue] of Object.entries(host)) {
32
+ if (UNSAFE_KEYS.has(key)) {
33
+ continue;
34
+ }
35
+ const defaultValue = result[key];
36
+ result[key] = isRecord(defaultValue) && isRecord(hostValue)
37
+ ? mergeRecords(defaultValue, hostValue)
38
+ : cloneValue(hostValue);
39
+ }
40
+ return result;
41
+ }
42
+
43
+ export function parseAppConfigYaml(source: string): unknown {
44
+ return source.trim() ? yaml.load(source) ?? {} : {};
45
+ }
46
+
47
+ /** Source packages provide defaults; the Host remains the final App-config owner. */
48
+ export function mergeSourcePackageAppConfig(
49
+ sourcePackageConfig: unknown,
50
+ hostConfig: unknown,
51
+ ): unknown {
52
+ if (isRecord(sourcePackageConfig) && isRecord(hostConfig)) {
53
+ return mergeRecords(sourcePackageConfig, hostConfig);
54
+ }
55
+ if (hostConfig !== undefined && hostConfig !== null) {
56
+ return cloneValue(hostConfig);
57
+ }
58
+ return cloneValue(sourcePackageConfig ?? {});
59
+ }
60
+
61
+ export function composeAppConfigYaml(
62
+ sourcePackageConfigYaml: string,
63
+ hostConfigYaml: string,
64
+ ): string {
65
+ const merged = mergeSourcePackageAppConfig(
66
+ parseAppConfigYaml(sourcePackageConfigYaml),
67
+ parseAppConfigYaml(hostConfigYaml),
68
+ );
69
+ return yaml.dump(merged, { noRefs: true, lineWidth: -1 });
70
+ }
71
+
72
+ /** Browser metadata uses the Host App's displayName, never a source-package brand. */
73
+ export function readHostAppDisplayName(hostDir = process.env.SOMA_HOST_DIR): string {
74
+ if (!hostDir) {
75
+ return '';
76
+ }
77
+ const configPath = resolveHostAppConfigPath(hostDir);
78
+ if (!configPath) {
79
+ return '';
80
+ }
81
+ try {
82
+ const config = parseAppConfigYaml(fs.readFileSync(configPath, 'utf8'));
83
+ if (!isRecord(config) || typeof config.displayName !== 'string') {
84
+ return '';
85
+ }
86
+ return config.displayName.trim();
87
+ } catch {
88
+ return '';
89
+ }
90
+ }
@@ -0,0 +1,2 @@
1
+ /** Runtime fallback when host app does not provide config/app.config.yaml. */
2
+ export default {};
@@ -0,0 +1,100 @@
1
+ /** CJS mirror of host-config-paths.ts for next.config.js / webpack plugin. */
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+
5
+ function readJson(filePath) {
6
+ try {
7
+ if (!fs.existsSync(filePath)) return null;
8
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+
14
+ function resolveSafeChildRoot(parent, relativePath, options = {}) {
15
+ const trimmed = typeof relativePath === 'string' ? relativePath.trim() : '';
16
+ if (!trimmed) return parent;
17
+
18
+ const resolved = path.resolve(parent, trimmed);
19
+ const normalizedParent = path.resolve(parent);
20
+ if (resolved === normalizedParent || resolved.startsWith(`${normalizedParent}${path.sep}`)) {
21
+ if (options.requireExists && !fs.existsSync(resolved)) {
22
+ return normalizedParent;
23
+ }
24
+ return resolved;
25
+ }
26
+ return options.fallback ?? normalizedParent;
27
+ }
28
+
29
+ function normalizeSomaEnv(raw) {
30
+ const value = String(raw ?? '').trim().toLowerCase();
31
+ if (!value) return 'test';
32
+ if (
33
+ ['test', 'testing', 'dev', 'development', 'local', 'qa', 'staging', 'pre', 'prepub', 'uat']
34
+ .includes(value)
35
+ ) {
36
+ return 'test';
37
+ }
38
+ return 'prod';
39
+ }
40
+
41
+ /** Priority: SOMA_ENV → APP_ENV → NODE_ENV (framework-neutral only). */
42
+ function readSomaEnv(env = process.env) {
43
+ return normalizeSomaEnv(env.SOMA_ENV ?? env.APP_ENV ?? env.NODE_ENV);
44
+ }
45
+
46
+ function resolveHostConfigRoot(hostDir) {
47
+ const normalizedHostDir = path.resolve(hostDir);
48
+ const packageJson = readJson(path.join(normalizedHostDir, 'package.json'));
49
+ const configured = packageJson?.soma?.configRoot?.trim();
50
+ if (configured) {
51
+ return resolveSafeChildRoot(normalizedHostDir, configured, {
52
+ fallback: path.join(normalizedHostDir, 'config'),
53
+ });
54
+ }
55
+
56
+ const hostSourceRoot = resolveSafeChildRoot(normalizedHostDir, packageJson?.soma?.hostRoot, {
57
+ requireExists: true,
58
+ });
59
+ const candidates = [
60
+ path.join(normalizedHostDir, 'config'),
61
+ path.join(hostSourceRoot, 'config'),
62
+ ];
63
+ for (const candidate of candidates) {
64
+ if (fs.existsSync(candidate)) {
65
+ return candidate;
66
+ }
67
+ }
68
+ return path.join(hostSourceRoot, 'config');
69
+ }
70
+
71
+ function getSomaHostConfigRoot(hostDir) {
72
+ return resolveHostConfigRoot(hostDir);
73
+ }
74
+
75
+ function resolveAppConfigPath(configRoot, envName) {
76
+ const env = envName ?? readSomaEnv();
77
+ const candidates = [
78
+ path.join(configRoot, `app.config.${env}.yaml`),
79
+ path.join(configRoot, 'app.config.yaml'),
80
+ ];
81
+ for (const candidate of candidates) {
82
+ if (fs.existsSync(candidate)) {
83
+ return candidate;
84
+ }
85
+ }
86
+ return null;
87
+ }
88
+
89
+ function resolveHostAppConfigPath(hostDir, envName) {
90
+ return resolveAppConfigPath(resolveHostConfigRoot(hostDir), envName);
91
+ }
92
+
93
+ module.exports = {
94
+ normalizeSomaEnv,
95
+ readSomaEnv,
96
+ resolveHostConfigRoot,
97
+ getSomaHostConfigRoot,
98
+ resolveAppConfigPath,
99
+ resolveHostAppConfigPath,
100
+ };