@20baht/cli 0.0.0-stage → 0.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 (140) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +214 -2
  3. package/dist/application/create.js +72 -0
  4. package/dist/application/generate.js +239 -0
  5. package/dist/application/ports.js +1 -0
  6. package/dist/args.js +49 -0
  7. package/dist/cli.js +207 -0
  8. package/dist/domain/blueprint.js +6 -0
  9. package/dist/domain/create-plan.js +59 -0
  10. package/dist/domain/deploy-plan.js +82 -0
  11. package/dist/domain/form-dsl.js +120 -0
  12. package/dist/domain/generate-plan.js +60 -0
  13. package/dist/domain/naming.js +18 -0
  14. package/dist/domain/remote-plan.js +153 -0
  15. package/dist/domain/template-path.js +19 -0
  16. package/dist/infrastructure/fs-reader.js +19 -0
  17. package/dist/infrastructure/fs-writer.js +27 -0
  18. package/dist/infrastructure/shell-runner.js +32 -0
  19. package/dist/infrastructure/spawn-plan.js +35 -0
  20. package/dist/infrastructure/template-renderer.js +16 -0
  21. package/dist/infrastructure/template-source.js +28 -0
  22. package/package.json +53 -4
  23. package/templates/angular/README.md.hbs +46 -0
  24. package/templates/angular/_dependency-cruiser.mjs +51 -0
  25. package/templates/angular/apps/server/package.json +30 -0
  26. package/templates/angular/apps/server/src/app.ts +14 -0
  27. package/templates/angular/apps/server/src/index.ts +8 -0
  28. package/templates/angular/apps/server/test/app.test.ts +12 -0
  29. package/templates/angular/apps/server/tsconfig.json +7 -0
  30. package/templates/angular/apps/server/tsconfig.types.json +12 -0
  31. package/templates/angular/apps/shell/_editorconfig +17 -0
  32. package/templates/angular/apps/shell/angular.json +115 -0
  33. package/templates/angular/apps/shell/federation.config.mjs +44 -0
  34. package/templates/angular/apps/shell/package.json +43 -0
  35. package/templates/angular/apps/shell/public/federation.manifest.json +1 -0
  36. package/templates/angular/apps/shell/src/app/app.config.ts +20 -0
  37. package/templates/angular/apps/shell/src/app/app.css +4 -0
  38. package/templates/angular/apps/shell/src/app/app.html.hbs +16 -0
  39. package/templates/angular/apps/shell/src/app/app.routes.ts.hbs +39 -0
  40. package/templates/angular/apps/shell/src/app/app.ts +57 -0
  41. package/templates/angular/apps/shell/src/app/core/federation/load-remote.ts +31 -0
  42. package/templates/angular/apps/shell/src/app/core/federation/manifest.spec.ts +46 -0
  43. package/templates/angular/apps/shell/src/app/core/federation/manifest.ts +37 -0
  44. package/templates/angular/apps/shell/src/app/core/federation/remote-loader.ts +20 -0
  45. package/templates/angular/apps/shell/src/app/core/federation/timeout.ts +17 -0
  46. package/templates/angular/apps/shell/src/app/modules/home/home.component.ts.hbs +46 -0
  47. package/templates/angular/apps/shell/src/app/modules/unavailable/unavailable.component.ts +39 -0
  48. package/templates/angular/apps/shell/src/bootstrap.ts +25 -0
  49. package/templates/angular/apps/shell/src/environments/environment.development.ts +10 -0
  50. package/templates/angular/apps/shell/src/environments/environment.ts +10 -0
  51. package/templates/angular/apps/shell/src/index.html.hbs +12 -0
  52. package/templates/angular/apps/shell/src/main.ts +43 -0
  53. package/templates/angular/apps/shell/src/styles.css +19 -0
  54. package/templates/angular/apps/shell/tsconfig.app.json +10 -0
  55. package/templates/angular/apps/shell/tsconfig.federation.json +4 -0
  56. package/templates/angular/apps/shell/tsconfig.json.hbs +39 -0
  57. package/templates/angular/apps/shell/tsconfig.spec.json +9 -0
  58. package/templates/angular/bahtui.json +6 -0
  59. package/templates/angular/eslint.config.ts.hbs +28 -0
  60. package/templates/angular/knip.ts +30 -0
  61. package/templates/angular/package.json.hbs +52 -0
  62. package/templates/angular/packages/kit/package.json.hbs +27 -0
  63. package/templates/angular/packages/kit/src/api.ts +21 -0
  64. package/templates/angular/packages/kit/src/errors.ts +28 -0
  65. package/templates/angular/packages/kit/src/index.ts +2 -0
  66. package/templates/angular/packages/kit/test/errors.test.ts +28 -0
  67. package/templates/angular/packages/kit/tsconfig.json +9 -0
  68. package/templates/create/README.md.hbs +32 -0
  69. package/templates/create/_github/workflows/ci.yml +56 -0
  70. package/templates/create/_gitignore +6 -0
  71. package/templates/create/_husky/pre-commit +3 -0
  72. package/templates/create/_prettierignore +3 -0
  73. package/templates/create/_prettierrc.json +4 -0
  74. package/templates/create/apps/api/package.json.hbs +21 -0
  75. package/templates/create/apps/api/src/index.test.ts.hbs +10 -0
  76. package/templates/create/apps/api/src/index.ts.hbs +14 -0
  77. package/templates/create/apps/api/tsconfig.json +7 -0
  78. package/templates/create/apps/web/index.html.hbs +20 -0
  79. package/templates/create/apps/web/package.json.hbs +24 -0
  80. package/templates/create/apps/web/src/App.tsx.hbs +31 -0
  81. package/templates/create/apps/web/src/app.css +27 -0
  82. package/templates/create/apps/web/src/health.test.ts.hbs +28 -0
  83. package/templates/create/apps/web/src/health.ts.hbs +14 -0
  84. package/templates/create/apps/web/src/main.tsx.hbs +20 -0
  85. package/templates/create/apps/web/src/vite-env.d.ts.hbs +1 -0
  86. package/templates/create/apps/web/tsconfig.json +8 -0
  87. package/templates/create/apps/web/vite.config.ts.hbs +6 -0
  88. package/templates/create/bahtui.json.hbs +7 -0
  89. package/templates/create/eslint.config.js +30 -0
  90. package/templates/create/knip.json +9 -0
  91. package/templates/create/libs/shared/eden/index.ts.hbs +9 -0
  92. package/templates/create/libs/shared/eden/package.json.hbs +15 -0
  93. package/templates/create/libs/shared/eden/tsconfig.json +4 -0
  94. package/templates/create/package.json.hbs +47 -0
  95. package/templates/create/tsconfig.base.json +17 -0
  96. package/templates/deploy/deploy/__project__.service.hbs +23 -0
  97. package/templates/deploy/deploy/env.example.hbs +4 -0
  98. package/templates/deploy/deploy/install.sh.hbs +58 -0
  99. package/templates/deploy/deploy/nginx.conf.hbs +67 -0
  100. package/templates/deploy/scripts/deploy.ts.hbs +33 -0
  101. package/templates/deploy/scripts/preview.ts.hbs +57 -0
  102. package/templates/deploy/scripts/release.ts.hbs +48 -0
  103. package/templates/new/CLAUDE.md +3 -0
  104. package/templates/new/README.md.hbs +38 -0
  105. package/templates/new/_dependency-cruiser.mjs +9 -0
  106. package/templates/new/_github/actions/setup/action.yml +15 -0
  107. package/templates/new/_github/workflows/ci.yml +122 -0
  108. package/templates/new/_gitignore +12 -0
  109. package/templates/new/_gitleaks.toml +6 -0
  110. package/templates/new/_husky/commit-msg +1 -0
  111. package/templates/new/_husky/pre-commit +8 -0
  112. package/templates/new/_husky/pre-push +1 -0
  113. package/templates/new/_jscpd.json +20 -0
  114. package/templates/new/_mcp.json +9 -0
  115. package/templates/new/_prettierignore +5 -0
  116. package/templates/new/apps/_gitkeep +0 -0
  117. package/templates/new/commitlint.config.js +1 -0
  118. package/templates/new/eslint.config.ts.hbs +7 -0
  119. package/templates/new/knip.ts +7 -0
  120. package/templates/new/lint-staged.config.js +1 -0
  121. package/templates/new/package.json.hbs +51 -0
  122. package/templates/new/packages/_gitkeep +0 -0
  123. package/templates/new/renovate.json +23 -0
  124. package/templates/new/scripts/dev.ts +54 -0
  125. package/templates/new/scripts/each.ts +29 -0
  126. package/templates/new/scripts/workspaces.ts +24 -0
  127. package/templates/new/tsconfig.base.json +3 -0
  128. package/templates/new/tsconfig.json +7 -0
  129. package/templates/remote/_editorconfig +17 -0
  130. package/templates/remote/angular.json.hbs +95 -0
  131. package/templates/remote/federation.config.mjs.hbs +48 -0
  132. package/templates/remote/package.json.hbs +38 -0
  133. package/templates/remote/src/app/__name__.routes.ts.hbs +12 -0
  134. package/templates/remote/src/app/modules/__name__/__name__.component.ts.hbs +37 -0
  135. package/templates/remote/src/app/services/__name__.service.ts.hbs +14 -0
  136. package/templates/remote/src/index.html.hbs +11 -0
  137. package/templates/remote/src/main.ts.hbs +3 -0
  138. package/templates/remote/tsconfig.app.json +10 -0
  139. package/templates/remote/tsconfig.federation.json +4 -0
  140. package/templates/remote/tsconfig.json.hbs +36 -0
@@ -0,0 +1,115 @@
1
+ {
2
+ "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3
+ "version": 1,
4
+ "cli": {
5
+ "packageManager": "bun"
6
+ },
7
+ "newProjectRoot": "projects",
8
+ "projects": {
9
+ "shell": {
10
+ "projectType": "application",
11
+ "schematics": {},
12
+ "root": "",
13
+ "sourceRoot": "src",
14
+ "prefix": "app",
15
+ "architect": {
16
+ "build": {
17
+ "builder": "@angular-architects/native-federation:build",
18
+ "options": {
19
+ "cacheExternalArtifacts": true,
20
+ "tsConfig": "tsconfig.federation.json"
21
+ },
22
+ "configurations": {
23
+ "production": {
24
+ "target": "shell:esbuild:production"
25
+ },
26
+ "development": {
27
+ "target": "shell:esbuild:development",
28
+ "dev": true
29
+ }
30
+ },
31
+ "defaultConfiguration": "production"
32
+ },
33
+ "serve": {
34
+ "builder": "@angular-architects/native-federation:build",
35
+ "options": {
36
+ "target": "shell:serve-original:development",
37
+ "tsConfig": "tsconfig.federation.json",
38
+ "rebuildDelay": 500,
39
+ "cacheExternalArtifacts": true,
40
+ "dev": true,
41
+ "devServer": true,
42
+ "port": 0
43
+ }
44
+ },
45
+ "test": {
46
+ "builder": "@angular/build:unit-test",
47
+ "options": {
48
+ "buildTarget": "shell:esbuild:development",
49
+ "coverageReporters": ["text", "lcov"],
50
+ "coverageExclude": ["src/main.ts", "src/bootstrap.ts", "src/environments/**"]
51
+ }
52
+ },
53
+ "esbuild": {
54
+ "builder": "@angular/build:application",
55
+ "options": {
56
+ "browser": "src/main.ts",
57
+ "tsConfig": "tsconfig.app.json",
58
+ "assets": [
59
+ {
60
+ "glob": "**/*",
61
+ "input": "public"
62
+ }
63
+ ],
64
+ "styles": ["node_modules/@20baht/ui/dist/tokens.css", "src/styles.css"],
65
+ "polyfills": ["es-module-shims"]
66
+ },
67
+ "configurations": {
68
+ "production": {
69
+ "budgets": [
70
+ {
71
+ "type": "initial",
72
+ "maximumWarning": "500kB",
73
+ "maximumError": "1MB"
74
+ },
75
+ {
76
+ "type": "anyComponentStyle",
77
+ "maximumWarning": "4kB",
78
+ "maximumError": "8kB"
79
+ }
80
+ ],
81
+ "outputHashing": "all"
82
+ },
83
+ "development": {
84
+ "optimization": false,
85
+ "extractLicenses": false,
86
+ "sourceMap": true,
87
+ "fileReplacements": [
88
+ {
89
+ "replace": "src/environments/environment.ts",
90
+ "with": "src/environments/environment.development.ts"
91
+ }
92
+ ]
93
+ }
94
+ },
95
+ "defaultConfiguration": "production"
96
+ },
97
+ "serve-original": {
98
+ "builder": "@angular/build:dev-server",
99
+ "configurations": {
100
+ "production": {
101
+ "buildTarget": "shell:esbuild:production"
102
+ },
103
+ "development": {
104
+ "buildTarget": "shell:esbuild:development"
105
+ }
106
+ },
107
+ "defaultConfiguration": "development",
108
+ "options": {
109
+ "port": 4210
110
+ }
111
+ }
112
+ }
113
+ }
114
+ }
115
+ }
@@ -0,0 +1,44 @@
1
+ import { withNativeFederation, fromPackageJson } from '@angular-architects/native-federation/config'
2
+
3
+ export default withNativeFederation({
4
+ name: 'shell',
5
+
6
+ shared: fromPackageJson({
7
+ singleton: true,
8
+ strictVersion: true,
9
+ requiredVersion: 'auto',
10
+ build: 'package',
11
+ })
12
+ // includeSecondaries is an opt-out of ignoreUnusedDeps, so all of
13
+ // @angular/core is shared to prevent mismatches.
14
+ .patch(['@angular/core'], { includeSecondaries: { keepAll: true } })
15
+ // Same for @20baht/ui: the remotes import @20baht/ui/overlay, the
16
+ // host only @20baht/ui. Unshared, each side bundles its own copy of the
17
+ // elements and the second customElements.define('baht-button') throws.
18
+ .patch(['@20baht/ui'], { includeSecondaries: { keepAll: true } }),
19
+
20
+ skip: [
21
+ 'rxjs/ajax',
22
+ 'rxjs/fetch',
23
+ 'rxjs/testing',
24
+ 'rxjs/webSocket',
25
+ // Server / React entry points of @20baht/ui (pulled in by keepAll above).
26
+ '@20baht/ui/ssr',
27
+ '@20baht/ui/hydrate',
28
+ '@20baht/ui/react',
29
+ // marked's command-line entry imports Node built-ins.
30
+ /^marked\/bin/,
31
+ ],
32
+
33
+ // The kit (a tsconfig path into packages/kit) is compiled into each app, not shared.
34
+ sharedMappings: [],
35
+
36
+ features: {
37
+ // Off: the unused-dependency scan (sheriff) refuses sources outside the app folder, and
38
+ // the kit lives in packages/kit. Every package.json dependency is shared instead, so each
39
+ // app lists @20baht/ui's optional peers (marked, dompurify, flatpickr) itself.
40
+ ignoreUnusedDeps: false,
41
+ // Groups chunks in remoteEntry.json for a smaller metadata file.
42
+ denseChunking: true,
43
+ },
44
+ })
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "shell",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "scripts": {
6
+ "ng": "ng",
7
+ "dev": "ng serve",
8
+ "build": "ng build",
9
+ "test": "ng test",
10
+ "test:coverage": "ng test --watch=false --coverage",
11
+ "typecheck": "tsc -b --noEmit",
12
+ "pretypecheck": "bun run --filter server build:types",
13
+ "prebuild": "bun run --filter server build:types"
14
+ },
15
+ "dependencies": {
16
+ "@angular-architects/native-federation": "^22.2.1",
17
+ "@angular/common": "^22.2.0",
18
+ "@angular/compiler": "^22.2.0",
19
+ "@angular/core": "^22.2.0",
20
+ "@angular/platform-browser": "^22.2.0",
21
+ "@angular/router": "^22.2.0",
22
+ "@20baht/engine": "0.1.0",
23
+ "@20baht/ui": "0.1.0",
24
+ "@20baht/angular": "0.1.0",
25
+ "dompurify": "3.4.17",
26
+ "es-module-shims": "^2.8.0",
27
+ "flatpickr": "4.6.13",
28
+ "marked": "18.1.3",
29
+ "@20baht/ngx-eden": "^0.1.0",
30
+ "rxjs": "~7.8.0",
31
+ "tslib": "^2.3.0"
32
+ },
33
+ "devDependencies": {
34
+ "@angular/build": "^22.2.0",
35
+ "@angular/cli": "^22.2.0",
36
+ "@angular/compiler-cli": "^22.2.0",
37
+ "@softarc/native-federation-orchestrator": "^4.6.0",
38
+ "@vitest/coverage-v8": "^4.0.8",
39
+ "jsdom": "^30.0.0",
40
+ "typescript": "~6.0.2",
41
+ "vitest": "^4.0.8"
42
+ }
43
+ }
@@ -0,0 +1,20 @@
1
+ import type { ApplicationConfig } from '@angular/core'
2
+ import { provideBrowserGlobalErrorListeners } from '@angular/core'
3
+ import { provideHttpClient } from '@angular/common/http'
4
+ import { provideRouter, withComponentInputBinding } from '@angular/router'
5
+ import { routesFor } from './app.routes'
6
+ import type { Manifest } from './core/federation/manifest'
7
+
8
+ /**
9
+ * The host owns the root: router and `HttpClient`. The remotes' services are
10
+ * `providedIn: 'root'`, so they use this `HttpClient` too.
11
+ */
12
+ export function appConfig(manifest: Manifest): ApplicationConfig {
13
+ return {
14
+ providers: [
15
+ provideBrowserGlobalErrorListeners(),
16
+ provideRouter(routesFor(manifest), withComponentInputBinding()),
17
+ provideHttpClient(),
18
+ ],
19
+ }
20
+ }
@@ -0,0 +1,4 @@
1
+ .shell-main {
2
+ display: block;
3
+ min-width: 0;
4
+ }
@@ -0,0 +1,16 @@
1
+ <baht-app-shell
2
+ brand="{{name}}"
3
+ brand-href="/"
4
+ label="{{name}}"
5
+ [items]="items"
6
+ [value]="current()"
7
+ (baht-nav)="navigate($event)"
8
+ >
9
+ <div data-slot="actions">
10
+ <baht-theme-toggle default="system"></baht-theme-toggle>
11
+ </div>
12
+ <main class="shell-main">
13
+ <router-outlet />
14
+ </main>
15
+ </baht-app-shell>
16
+ <baht-toast></baht-toast>
@@ -0,0 +1,39 @@
1
+ import type { Routes } from '@angular/router'
2
+ import { loadRemoteRoutes } from './core/federation/load-remote'
3
+ import type { Manifest } from './core/federation/manifest'
4
+
5
+ const unavailable = () =>
6
+ import('./modules/unavailable/unavailable.component').then((m) => m.UnavailableComponent)
7
+
8
+ /**
9
+ * The home page, one URL prefix per remote in the manifest, and a not-found page. A remote that
10
+ * cannot be loaded shows a fallback page under its prefix; the rest of the app keeps working.
11
+ */
12
+ export const routesFor = (manifest: Manifest): Routes => [
13
+ {
14
+ path: '',
15
+ pathMatch: 'full',
16
+ title: '{{name}}',
17
+ loadComponent: () => import('./modules/home/home.component').then((m) => m.HomeComponent),
18
+ },
19
+ ...Object.entries(manifest).map(([name, remote]) => ({
20
+ path: remote.base,
21
+ title: `${remote.title} · {{name}}`,
22
+ loadChildren: loadRemoteRoutes(name, () => [
23
+ {
24
+ path: '**',
25
+ data: {
26
+ heading: `${remote.title} is unavailable`,
27
+ message: 'This part of the app could not be loaded. The rest still works.',
28
+ },
29
+ loadComponent: unavailable,
30
+ },
31
+ ]),
32
+ })),
33
+ {
34
+ path: '**',
35
+ title: 'Not found · {{name}}',
36
+ data: { heading: 'Page not found', message: 'Nothing lives at this address.' },
37
+ loadComponent: unavailable,
38
+ },
39
+ ]
@@ -0,0 +1,57 @@
1
+ import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core'
2
+ import { toSignal } from '@angular/core/rxjs-interop'
3
+ import { NavigationEnd, Router, RouterOutlet } from '@angular/router'
4
+ import type { ShellNavItem } from '@20baht/ui'
5
+ import { BAHT_UI } from '@20baht/angular'
6
+ import { filter, map } from 'rxjs'
7
+ import { MANIFEST } from './core/federation/remote-loader'
8
+
9
+ /** The frame every page sits in: brand, a navigator built from the federation manifest, the page. */
10
+ @Component({
11
+ changeDetection: ChangeDetectionStrategy.OnPush,
12
+ imports: [RouterOutlet, BAHT_UI],
13
+ selector: 'app-root',
14
+ templateUrl: './app.html',
15
+ styleUrl: './app.css',
16
+ })
17
+ export class App {
18
+ private readonly router = inject(Router)
19
+ private readonly manifest = inject(MANIFEST)
20
+
21
+ private readonly url = toSignal(
22
+ this.router.events.pipe(
23
+ filter((event) => event instanceof NavigationEnd),
24
+ map((event) => event.urlAfterRedirects),
25
+ ),
26
+ { initialValue: this.router.url },
27
+ )
28
+
29
+ protected readonly items: ShellNavItem[] = [
30
+ { key: '', label: 'Home', href: '/' },
31
+ ...Object.values(this.manifest).flatMap((remote) =>
32
+ remote.nav.map((nav) => ({
33
+ key: nav.path,
34
+ label: nav.label,
35
+ href: `/${nav.path}`,
36
+ group: remote.title,
37
+ })),
38
+ ),
39
+ ]
40
+
41
+ /** The navigator entry whose path the URL sits under; the longest one wins. */
42
+ protected readonly current = computed(() => {
43
+ const path = (this.url().split(/[?#]/)[0] ?? '').replace(/^\//, '')
44
+ const keys = this.items
45
+ .map((item) => item.key)
46
+ .filter((key) => key !== '' && (path === key || path.startsWith(`${key}/`)))
47
+ return keys.sort((a, b) => b.length - a.length)[0] ?? ''
48
+ })
49
+
50
+ /** Route in place instead of letting the link reload the page. */
51
+ protected navigate(event: Event): void {
52
+ const { href } = (event as CustomEvent<{ href: string | undefined }>).detail
53
+ if (href === undefined) return
54
+ event.preventDefault()
55
+ void this.router.navigateByUrl(href)
56
+ }
57
+ }
@@ -0,0 +1,31 @@
1
+ import { inject } from '@angular/core'
2
+ import type { Routes } from '@angular/router'
3
+ import { REMOTE_LOADER } from './remote-loader'
4
+ import { withTimeout } from './timeout'
5
+
6
+ /** What every remote exposes as `./Routes`. */
7
+ type RoutesModule = { routes: Routes }
8
+
9
+ /** How long a first visit waits for a remote before showing the fallback page. */
10
+ const LOAD_TIMEOUT_MS = 10_000
11
+
12
+ /**
13
+ * `loadChildren` for a remote's URL prefix: its `./Routes`, or `fallback()` when federation is
14
+ * off or the remote cannot be loaded. One remote being down never takes the others with it.
15
+ */
16
+ export const loadRemoteRoutes =
17
+ (name: string, fallback: () => Routes): (() => Promise<Routes>) =>
18
+ async () => {
19
+ const loadRemoteModule = inject(REMOTE_LOADER)
20
+ if (loadRemoteModule === null) return fallback()
21
+ try {
22
+ const module = await withTimeout(
23
+ loadRemoteModule<RoutesModule>(name, './Routes'),
24
+ LOAD_TIMEOUT_MS,
25
+ )
26
+ return module.routes
27
+ } catch (err) {
28
+ console.error(`${name} ./Routes failed to load`, err)
29
+ return fallback()
30
+ }
31
+ }
@@ -0,0 +1,46 @@
1
+ import { parseManifest } from './manifest'
2
+ import { withTimeout } from './timeout'
3
+
4
+ const entry = {
5
+ entry: 'http://localhost:4201/remoteEntry.json',
6
+ title: 'Hello',
7
+ base: 'hello',
8
+ nav: [{ label: 'Hello', path: 'hello' }],
9
+ }
10
+
11
+ describe('parseManifest', () => {
12
+ it('accepts well-formed entries', () => {
13
+ expect(parseManifest({ 'hello-web': entry })).toEqual({ 'hello-web': entry })
14
+ expect(parseManifest({})).toEqual({})
15
+ })
16
+
17
+ it('rejects the whole file when one entry is wrong', () => {
18
+ expect(parseManifest(null)).toBeNull()
19
+ expect(parseManifest([entry])).toBeNull()
20
+ expect(parseManifest({ ok: entry, bad: { ...entry, entry: 1 } })).toBeNull()
21
+ expect(parseManifest({ bad: { ...entry, base: '../etc' } })).toBeNull()
22
+ expect(parseManifest({ bad: { ...entry, nav: [{ label: 'x' }] } })).toBeNull()
23
+ })
24
+ })
25
+
26
+ describe('withTimeout', () => {
27
+ it('passes a settled promise through', async () => {
28
+ await expect(withTimeout(Promise.resolve('ok'), 50)).resolves.toBe('ok')
29
+ await expect(withTimeout(Promise.reject(new Error('no')), 50)).rejects.toThrow('no')
30
+ await expect(
31
+ withTimeout(
32
+ new Promise((_resolve, reject) => {
33
+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- the case under test: a non-Error rejection is wrapped
34
+ reject('text')
35
+ }),
36
+ 50,
37
+ ),
38
+ ).rejects.toThrow('text')
39
+ })
40
+
41
+ it('rejects when the promise is too slow', async () => {
42
+ await expect(withTimeout(new Promise(() => undefined), 5)).rejects.toThrow(
43
+ 'timed out after 5 ms',
44
+ )
45
+ })
46
+ })
@@ -0,0 +1,37 @@
1
+ /** One page a remote adds to the navigator. */
2
+ type RemoteNav = { label: string; path: string }
3
+
4
+ /** A microfrontend: where its code is, the URL prefix it owns and what it puts in the navigator. */
5
+ type RemoteEntry = {
6
+ /** URL of its `remoteEntry.json`. */
7
+ entry: string
8
+ /** Group heading in the navigator. */
9
+ title: string
10
+ /** First URL segment; everything under it is routed by the remote's `./Routes`. */
11
+ base: string
12
+ nav: RemoteNav[]
13
+ }
14
+
15
+ export type Manifest = Record<string, RemoteEntry>
16
+
17
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
18
+ typeof value === 'object' && value !== null && !Array.isArray(value)
19
+
20
+ const isNav = (value: unknown): value is RemoteNav =>
21
+ isRecord(value) && typeof value['label'] === 'string' && typeof value['path'] === 'string'
22
+
23
+ const isEntry = (value: unknown): value is RemoteEntry =>
24
+ isRecord(value) &&
25
+ typeof value['entry'] === 'string' &&
26
+ typeof value['title'] === 'string' &&
27
+ typeof value['base'] === 'string' &&
28
+ /^[a-z0-9-]+$/.test(value['base']) &&
29
+ Array.isArray(value['nav']) &&
30
+ value['nav'].every(isNav)
31
+
32
+ /** The manifest when every entry has the right shape, else null: a broken file must not half-load. */
33
+ export const parseManifest = (json: unknown): Manifest | null => {
34
+ if (!isRecord(json)) return null
35
+ const entries = Object.entries(json)
36
+ return entries.every(([, value]) => isEntry(value)) ? (json as Manifest) : null
37
+ }
@@ -0,0 +1,20 @@
1
+ import { InjectionToken } from '@angular/core'
2
+ import type { NativeFederationResult } from '@angular-architects/native-federation'
3
+ import type { Manifest } from './manifest'
4
+
5
+ export type RemoteLoader = NativeFederationResult['loadRemoteModule']
6
+
7
+ /**
8
+ * The `loadRemoteModule` that `initFederation` resolved with in `main.ts`. Null when federation
9
+ * failed to start (or in unit tests); every remote route then shows the fallback page.
10
+ */
11
+ export const REMOTE_LOADER = new InjectionToken<RemoteLoader | null>('REMOTE_LOADER', {
12
+ providedIn: 'root',
13
+ factory: () => null,
14
+ })
15
+
16
+ /** The remotes this host knows, as read at boot. */
17
+ export const MANIFEST = new InjectionToken<Manifest>('MANIFEST', {
18
+ providedIn: 'root',
19
+ factory: () => ({}),
20
+ })
@@ -0,0 +1,17 @@
1
+ /** `promise`, or a rejection once `ms` pass without it settling. */
2
+ export const withTimeout = <T>(promise: Promise<T>, ms: number): Promise<T> =>
3
+ new Promise<T>((resolve, reject) => {
4
+ const timer = setTimeout(() => {
5
+ reject(new Error(`timed out after ${String(ms)} ms`))
6
+ }, ms)
7
+ promise.then(
8
+ (value) => {
9
+ clearTimeout(timer)
10
+ resolve(value)
11
+ },
12
+ (error: unknown) => {
13
+ clearTimeout(timer)
14
+ reject(error instanceof Error ? error : new Error(String(error)))
15
+ },
16
+ )
17
+ })
@@ -0,0 +1,46 @@
1
+ import { ChangeDetectionStrategy, Component, inject } from '@angular/core'
2
+ import { Router } from '@angular/router'
3
+ import { BAHT_UI } from '@20baht/angular'
4
+ import { MANIFEST } from '../../core/federation/remote-loader'
5
+
6
+ /** The landing page: one card per remote in the federation manifest. */
7
+ @Component({
8
+ changeDetection: ChangeDetectionStrategy.OnPush,
9
+ imports: [BAHT_UI],
10
+ selector: 'shell-home',
11
+ styles: `
12
+ .remotes {
13
+ display: grid;
14
+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
15
+ gap: var(--baht-space-4);
16
+ }
17
+ `,
18
+ template: `
19
+ <div class="app-page">
20
+ <baht-page-header
21
+ heading="{{name}}"
22
+ description="A Native Federation host. Each card is a remote, loaded at runtime."
23
+ ></baht-page-header>
24
+ <div class="remotes">
25
+ @for (remote of remotes; track remote.base) {
26
+ <baht-card [heading]="remote.title">
27
+ <baht-button variant="secondary" (click)="go(remote.base)">Open</baht-button>
28
+ </baht-card>
29
+ } @empty {
30
+ <baht-empty-state
31
+ message="No remotes yet"
32
+ hint="Add one with bahtui g remote, then restart bun run dev."
33
+ ></baht-empty-state>
34
+ }
35
+ </div>
36
+ </div>
37
+ `,
38
+ })
39
+ export class HomeComponent {
40
+ private readonly router = inject(Router)
41
+ protected readonly remotes = Object.values(inject(MANIFEST))
42
+
43
+ protected go(base: string): void {
44
+ void this.router.navigateByUrl(`/${base}`)
45
+ }
46
+ }
@@ -0,0 +1,39 @@
1
+ import { ChangeDetectionStrategy, Component, input } from '@angular/core'
2
+ import { BAHT_UI } from '@20baht/angular'
3
+
4
+ /**
5
+ * Shown when a remote's routes cannot be loaded over Native Federation, and for unknown URLs.
6
+ * The route's `data` sets the copy; all this page can offer is another try.
7
+ */
8
+ @Component({
9
+ changeDetection: ChangeDetectionStrategy.OnPush,
10
+ imports: [BAHT_UI],
11
+ selector: 'shell-unavailable',
12
+ styles: `
13
+ :host {
14
+ display: grid;
15
+ place-content: center;
16
+ min-height: 60dvh;
17
+ padding: var(--baht-space-4);
18
+ }
19
+ baht-error-state {
20
+ max-width: 440px;
21
+ }
22
+ `,
23
+ template: `
24
+ <baht-error-state
25
+ [attr.heading]="heading()"
26
+ [attr.message]="message()"
27
+ retry-label="Try again"
28
+ (bahtRetry)="retry()"
29
+ ></baht-error-state>
30
+ `,
31
+ })
32
+ export class UnavailableComponent {
33
+ readonly heading = input('Something is unavailable')
34
+ readonly message = input('This page could not be loaded. Try again in a moment.')
35
+
36
+ protected retry(): void {
37
+ window.location.reload()
38
+ }
39
+ }
@@ -0,0 +1,25 @@
1
+ import type { ApplicationRef } from '@angular/core'
2
+ import { bootstrapApplication } from '@angular/platform-browser'
3
+ import { appConfig } from './app/app.config'
4
+ import { App } from './app/app'
5
+ import type { Manifest } from './app/core/federation/manifest'
6
+ import { MANIFEST, REMOTE_LOADER, type RemoteLoader } from './app/core/federation/remote-loader'
7
+
8
+ export async function bootstrap(
9
+ loadRemoteModule: RemoteLoader | null,
10
+ manifest: Manifest,
11
+ ): Promise<ApplicationRef> {
12
+ // Registers the <baht-*> custom elements in its own chunk; they upgrade in place once it
13
+ // lands. Shared with the remotes, so each tag is defined once.
14
+ void import('@20baht/ui')
15
+
16
+ const config = appConfig(manifest)
17
+ return bootstrapApplication(App, {
18
+ ...config,
19
+ providers: [
20
+ ...config.providers,
21
+ { provide: REMOTE_LOADER, useValue: loadRemoteModule },
22
+ { provide: MANIFEST, useValue: manifest },
23
+ ],
24
+ })
25
+ }
@@ -0,0 +1,10 @@
1
+ import type { Manifest } from '../app/core/federation/manifest'
2
+
3
+ /** The remotes on their dev servers (`bun run dev`). `bahtui g remote` adds an entry. */
4
+ const remotes: Manifest = {
5
+ // bahtui:remotes
6
+ }
7
+
8
+ export const federation: string | Manifest = remotes
9
+
10
+ export const federationFallback: Manifest = remotes
@@ -0,0 +1,10 @@
1
+ import type { Manifest } from '../app/core/federation/manifest'
2
+
3
+ /**
4
+ * Where the remotes load from: `public/federation.manifest.json`, read at runtime, so a remote can
5
+ * be added or repointed on the web server with no host build.
6
+ */
7
+ export const federation: string | Manifest = '/federation.manifest.json'
8
+
9
+ /** What the host boots with when that file cannot be fetched: no remotes, the home page only. */
10
+ export const federationFallback: Manifest = {}
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <title>{{name}}</title>
6
+ <base href="/" />
7
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
8
+ </head>
9
+ <body>
10
+ <app-root></app-root>
11
+ </body>
12
+ </html>