@20baht/cli 0.0.0-stage → 0.1.1

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,153 @@
1
+ import { isTemplate, outputPath } from './template-path.js';
2
+ const REMOTE_MARKER = '// bahtui:remotes';
3
+ /** The host serves on 4200; remotes take the ports after it. */
4
+ const FIRST_REMOTE_PORT = 4201;
5
+ /** Template paths spell the remote's name `__name__`. */
6
+ const NAME_TOKEN = '__name__';
7
+ const REMOTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
8
+ export function validateRemoteName(name) {
9
+ if (!REMOTE_NAME.test(name)) {
10
+ return [
11
+ `"${name}" is not a valid remote name — lowercase letters, digits and single dashes, starting with a letter.`,
12
+ ];
13
+ }
14
+ if (name.endsWith('-web')) {
15
+ return [`"${name}": leave "-web" off, the app folder adds it (apps/${name}).`];
16
+ }
17
+ return [];
18
+ }
19
+ export function remoteFor(name, port) {
20
+ const words = name.split('-');
21
+ const cap = (w) => w.charAt(0).toUpperCase() + w.slice(1);
22
+ return {
23
+ name,
24
+ app: `${name}-web`,
25
+ title: words.map(cap).join(' '),
26
+ pascal: words.map(cap).join(''),
27
+ port,
28
+ };
29
+ }
30
+ /** Where the remote wiring lives, relative to the workspace root, for a host app folder. */
31
+ export function wiringPaths(host) {
32
+ return {
33
+ eslint: 'eslint.config.ts',
34
+ knip: 'knip.ts',
35
+ depcruise: '.dependency-cruiser.mjs',
36
+ devManifest: `${host}/src/environments/environment.development.ts`,
37
+ manifest: `${host}/public/federation.manifest.json`,
38
+ };
39
+ }
40
+ export class RemoteWiringError extends Error {
41
+ }
42
+ /** The port after the highest one the dev manifest already uses. */
43
+ export function nextRemotePort(devManifest) {
44
+ const ports = [...devManifest.matchAll(/localhost:(\d+)\//g)].map((m) => Number(m[1]));
45
+ return ports.length === 0 ? FIRST_REMOTE_PORT : Math.max(...ports) + 1;
46
+ }
47
+ /** Renders `templates/remote` for one remote, under `apps/<name>-web/`. */
48
+ export function planRemoteFiles(remote, project, templates, render) {
49
+ const data = { ...remote, project };
50
+ return templates.map((t) => ({
51
+ path: `apps/${remote.app}/${outputPath(t.relPath, { [NAME_TOKEN]: remote.name })}`,
52
+ contents: isTemplate(t.relPath) ? render(t.raw, data) : t.raw,
53
+ }));
54
+ }
55
+ function insertAtMarker(text, file, lines) {
56
+ const at = text.split('\n').findIndex((l) => l.trim() === REMOTE_MARKER);
57
+ if (at === -1) {
58
+ throw new RemoteWiringError(`${file} has no "${REMOTE_MARKER}" line to add the remote above. Add it back, or add this by hand:\n${lines.join('\n')}`);
59
+ }
60
+ const all = text.split('\n');
61
+ const indent = /^\s*/.exec(all[at] ?? '')?.[0] ?? '';
62
+ all.splice(at, 0, ...lines.map((l) => (l === '' ? l : indent + l)));
63
+ return all.join('\n');
64
+ }
65
+ function addToManifest(text, file, remote) {
66
+ let json;
67
+ try {
68
+ json = JSON.parse(text);
69
+ }
70
+ catch {
71
+ throw new RemoteWiringError(`${file} is not valid JSON.`);
72
+ }
73
+ if (typeof json !== 'object' || json === null || Array.isArray(json)) {
74
+ throw new RemoteWiringError(`${file} must hold a JSON object of remotes.`);
75
+ }
76
+ const entry = {
77
+ entry: `/remotes/${remote.app}/remoteEntry.json`,
78
+ title: remote.title,
79
+ base: remote.name,
80
+ nav: [{ label: remote.title, path: remote.name }],
81
+ };
82
+ return JSON.stringify({ ...json, [remote.app]: entry }, null, 2) + '\n';
83
+ }
84
+ /**
85
+ * Adds a remote to the host workspace: the eslint and knip workspaces, the dependency-cruiser
86
+ * app list, and both federation manifests (dev ports, deployed paths).
87
+ */
88
+ export function wireRemote(current, host, remote) {
89
+ const paths = wiringPaths(host);
90
+ if (current.knip.includes(`'apps/${remote.app}'`)) {
91
+ throw new RemoteWiringError(`${paths.knip} already lists apps/${remote.app}.`);
92
+ }
93
+ return [
94
+ {
95
+ path: paths.eslint,
96
+ contents: insertAtMarker(current.eslint, paths.eslint, [`'apps/${remote.app}/src/**',`]),
97
+ },
98
+ {
99
+ path: paths.knip,
100
+ contents: insertAtMarker(current.knip, paths.knip, [
101
+ `'apps/${remote.app}': remote('${remote.name}'),`,
102
+ ]),
103
+ },
104
+ {
105
+ path: paths.depcruise,
106
+ contents: insertAtMarker(current.depcruise, paths.depcruise, [`'${remote.app}',`]),
107
+ },
108
+ {
109
+ path: paths.devManifest,
110
+ contents: insertAtMarker(current.devManifest, paths.devManifest, [
111
+ `'${remote.app}': {`,
112
+ ` entry: 'http://localhost:${remote.port}/remoteEntry.json',`,
113
+ ` title: '${remote.title}',`,
114
+ ` base: '${remote.name}',`,
115
+ ` nav: [{ label: '${remote.title}', path: '${remote.name}' }],`,
116
+ `},`,
117
+ ]),
118
+ },
119
+ { path: paths.manifest, contents: addToManifest(current.manifest, paths.manifest, remote) },
120
+ ];
121
+ }
122
+ /** Replaces or adds files by path, keeping codepoint order. */
123
+ function mergeFiles(base, changes) {
124
+ const byPath = new Map(base.map((f) => [f.path, f]));
125
+ for (const f of changes)
126
+ byPath.set(f.path, f);
127
+ return [...byPath.values()].sort((a, b) => (a.path < b.path ? -1 : 1));
128
+ }
129
+ /** The Angular scaffold's first remote, wired into the files `planCreate` produced. */
130
+ export function withFirstRemote(blueprint, project, host, remoteTemplates, render, name = 'hello') {
131
+ const paths = wiringPaths(host);
132
+ const read = (path) => {
133
+ const file = blueprint.files.find((f) => f.path === path);
134
+ if (!file)
135
+ throw new RemoteWiringError(`template set lacks ${path}`);
136
+ return file.contents;
137
+ };
138
+ const current = {
139
+ eslint: read(paths.eslint),
140
+ knip: read(paths.knip),
141
+ depcruise: read(paths.depcruise),
142
+ devManifest: read(paths.devManifest),
143
+ manifest: read(paths.manifest),
144
+ };
145
+ const remote = remoteFor(name, nextRemotePort(current.devManifest));
146
+ return {
147
+ ...blueprint,
148
+ files: mergeFiles(blueprint.files, [
149
+ ...planRemoteFiles(remote, project, remoteTemplates, render),
150
+ ...wireRemote(current, host, remote),
151
+ ]),
152
+ };
153
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Where a template file lands: `.hbs` stripped, path tokens substituted, then a leading `_` in
3
+ * any segment turned into a dot (templates keep dotfiles as `_name`). Tokens go first because
4
+ * `__name__` starts with `_` as well. One function for every planner: `g remote` once skipped
5
+ * the dot step and wrote a dead `_editorconfig`.
6
+ */
7
+ export function outputPath(relPath, tokens = {}) {
8
+ let rel = relPath.endsWith('.hbs') ? relPath.slice(0, -'.hbs'.length) : relPath;
9
+ for (const [token, value] of Object.entries(tokens))
10
+ rel = rel.replaceAll(token, value);
11
+ return rel
12
+ .split('/')
13
+ .map((part) => (part.startsWith('_') ? `.${part.slice(1)}` : part))
14
+ .join('/');
15
+ }
16
+ /** A `.hbs` file is rendered; anything else is copied as it is. */
17
+ export function isTemplate(relPath) {
18
+ return relPath.endsWith('.hbs');
19
+ }
@@ -0,0 +1,19 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ export class DiskFileReader {
3
+ exists(path) {
4
+ return existsSync(path);
5
+ }
6
+ read(path) {
7
+ try {
8
+ return readFileSync(path, 'utf8');
9
+ }
10
+ catch (err) {
11
+ // null strictly means "not there" — callers use it to decide the file is
12
+ // absent (e.g. "run bahtui init first"). A permission or IO error must
13
+ // surface, not masquerade as a missing file.
14
+ if (err.code === 'ENOENT')
15
+ return null;
16
+ throw err;
17
+ }
18
+ }
19
+ }
@@ -0,0 +1,27 @@
1
+ import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from 'node:fs';
2
+ import { dirname, resolve, sep } from 'node:path';
3
+ export class DiskFileWriter {
4
+ ensureUsableDir(dir, force) {
5
+ if (!existsSync(dir))
6
+ return;
7
+ if (!statSync(dir).isDirectory()) {
8
+ throw new Error(`${dir} exists and is not a directory.`);
9
+ }
10
+ if (readdirSync(dir).length === 0)
11
+ return;
12
+ if (force)
13
+ return;
14
+ throw new Error(`${dir} already exists and is not empty (use --force to write anyway).`);
15
+ }
16
+ writeFiles(blueprint) {
17
+ const root = resolve(blueprint.root);
18
+ for (const file of blueprint.files) {
19
+ const abs = resolve(root, file.path);
20
+ if (abs !== root && !abs.startsWith(root + sep)) {
21
+ throw new Error(`Refusing to write "${file.path}" — it resolves outside the target directory ${root}.`);
22
+ }
23
+ mkdirSync(dirname(abs), { recursive: true });
24
+ writeFileSync(abs, file.contents);
25
+ }
26
+ }
27
+ }
@@ -0,0 +1,32 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { describeSpawnError, planSpawn } from './spawn-plan.js';
3
+ /** First hit of `where` (Windows); only called there. */
4
+ function whereFirst(cmd) {
5
+ const found = spawnSync('where', [cmd], { encoding: 'utf8' });
6
+ if (found.status !== 0)
7
+ return null;
8
+ return (found.stdout
9
+ .split(/\r?\n/)
10
+ .find((line) => line.trim() !== '')
11
+ ?.trim() ?? null);
12
+ }
13
+ export class ShellRunner {
14
+ run(cmd, args, cwd) {
15
+ const plan = planSpawn(cmd, args, {
16
+ platform: process.platform,
17
+ execPath: process.execPath,
18
+ underBun: Boolean(process.versions.bun),
19
+ which: whereFirst,
20
+ });
21
+ const result = spawnSync(plan.file, plan.args, {
22
+ cwd,
23
+ stdio: 'inherit',
24
+ windowsVerbatimArguments: plan.verbatim,
25
+ });
26
+ if (result.error)
27
+ throw new Error(describeSpawnError(cmd, result.error));
28
+ if (result.status !== 0) {
29
+ throw new Error(`${cmd} ${args.join(' ')} exited with code ${result.status}`);
30
+ }
31
+ }
32
+ }
@@ -0,0 +1,35 @@
1
+ // Characters cmd.exe would interpret; the CLI only passes plain words (install, run, -b, main).
2
+ const SAFE_ARG = /^[A-Za-z0-9._:/=@+,-]+$/;
3
+ const UNSAFE_PATH = /["%^&|<>()!]/;
4
+ /** Windows cannot spawn a `.cmd` shim directly, and `shell: true` would parse user-derived text. */
5
+ export function planSpawn(cmd, args, env) {
6
+ if (cmd === 'bun' && env.underBun)
7
+ return { file: env.execPath, args };
8
+ if (env.platform !== 'win32')
9
+ return { file: cmd, args };
10
+ const resolved = env.which(cmd);
11
+ if (!resolved)
12
+ throw new Error(`could not run ${cmd}: not found on PATH — install it first.`);
13
+ if (!/\.(cmd|bat)$/i.test(resolved))
14
+ return { file: resolved, args };
15
+ if (UNSAFE_PATH.test(resolved)) {
16
+ throw new Error(`could not run ${cmd}: refusing to run through cmd.exe from ${resolved}`);
17
+ }
18
+ const bad = args.find((a) => !SAFE_ARG.test(a));
19
+ if (bad !== undefined) {
20
+ throw new Error(`could not run ${cmd}: refusing argument ${JSON.stringify(bad)} for a .cmd shim`);
21
+ }
22
+ // `/s` strips the first and last quote of the line, so the whole command is quoted once more.
23
+ return {
24
+ file: 'cmd.exe',
25
+ args: ['/d', '/s', '/c', `"${[`"${resolved}"`, ...args].join(' ')}"`],
26
+ verbatim: true,
27
+ };
28
+ }
29
+ export function describeSpawnError(cmd, error) {
30
+ const code = error.code;
31
+ if (code === 'ENOENT') {
32
+ return `could not run ${cmd}: not found on PATH — install it first (${error.message})`;
33
+ }
34
+ return `could not run ${cmd}: ${error.message}${code ? ` (${code})` : ''}`;
35
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The create template set's only expression form is `{{key}}` substitution —
3
+ * a full template engine (handlebars, ~1.5 MB installed) buys nothing here.
4
+ * Unknown variables throw, matching the old handlebars strict-mode behavior.
5
+ * No escaping: these are code/config files, not HTML — quotes must survive.
6
+ */
7
+ export class TemplateRenderer {
8
+ render(raw, data) {
9
+ return raw.replaceAll(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => {
10
+ if (!Object.hasOwn(data, key)) {
11
+ throw new Error(`unknown template variable "${key}"`);
12
+ }
13
+ return String(data[key]);
14
+ });
15
+ }
16
+ }
@@ -0,0 +1,28 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join, relative, sep } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ /** templates/ sits at the package root, next to dist/ — hence ../../ from here. */
5
+ const TEMPLATES_ROOT = fileURLToPath(new URL('../../templates', import.meta.url));
6
+ export class DiskTemplateSource {
7
+ constructor(root = TEMPLATES_ROOT) {
8
+ this.root = root;
9
+ }
10
+ load(set) {
11
+ const setRoot = join(this.root, set);
12
+ if (!existsSync(setRoot)) {
13
+ throw new Error(`template set '${set}' missing — reinstall @20baht/cli`);
14
+ }
15
+ const entries = readdirSync(setRoot, { recursive: true, withFileTypes: true });
16
+ const files = [];
17
+ for (const entry of entries) {
18
+ if (!entry.isFile())
19
+ continue;
20
+ const abs = join(entry.parentPath, entry.name);
21
+ files.push({
22
+ relPath: relative(setRoot, abs).split(sep).join('/'),
23
+ raw: readFileSync(abs, 'utf8'),
24
+ });
25
+ }
26
+ return files;
27
+ }
28
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@20baht/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "description": "Scaffold bun workspaces (bahtui new) and DDD monorepos (React + Elysia + Eden, bahtui create) plus bahtui generators.",
6
+ "license": "MIT",
7
+ "author": "Nattapong Promthong",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/bank20baht/20baht.git",
11
+ "directory": "packages/tooling/cli"
12
+ },
13
+ "homepage": "https://github.com/bank20baht/20baht/tree/main/packages/tooling/cli#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/bank20baht/20baht/issues"
16
+ },
17
+ "keywords": [
18
+ "cli",
19
+ "scaffold",
20
+ "generator",
21
+ "ddd",
22
+ "bun",
23
+ "elysia",
24
+ "eden",
25
+ "react"
26
+ ],
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "engines": {
31
+ "node": ">=20.12"
32
+ },
33
+ "bin": {
34
+ "bahtui": "./dist/cli.js"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "templates"
39
+ ],
40
+ "scripts": {
41
+ "build": "rm -rf dist && tsc -p tsconfig.json",
42
+ "test": "vitest run",
43
+ "test:watch": "vitest",
44
+ "test:coverage": "vitest run --coverage",
45
+ "accept:angular": "bun scripts/accept-angular.ts"
46
+ },
47
+ "dependencies": {
48
+ "@20baht/validator": ">=0.1.0 <0.2.0"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "^22",
52
+ "typescript": "^5.8.3",
53
+ "vitest": "^3.2.4"
54
+ }
55
+ }
@@ -0,0 +1,46 @@
1
+ # {{name}}
2
+
3
+ Angular microfrontends on Native Federation, scaffolded by
4
+ [`@20baht/cli`](https://github.com/bank20baht/20baht) (`bahtui create --angular`).
5
+
6
+ ```
7
+ apps/shell the host (:4200): navigator from the federation manifest, a fallback page per remote
8
+ apps/hello-web a remote (:4201): one page calling one API route, exposed as ./Routes
9
+ apps/server Elysia API (:3001) under /api; exports `type App` as built declarations
10
+ packages/kit what the web apps share (typed ngx-eden client, error text), as @{{name}}/kit
11
+ ```
12
+
13
+ ## Quickstart
14
+
15
+ ```sh
16
+ bun install
17
+ bun run dev # every apps/* dev script in parallel
18
+ bun run check # lint, format, typecheck, madge, boundaries, knip, dup, build, test
19
+ ```
20
+
21
+ ## Add a remote
22
+
23
+ ```sh
24
+ bahtui g remote orders # apps/orders-web on the next port, mounted at /orders
25
+ bun install
26
+ ```
27
+
28
+ It also adds the remote to `eslint.config.ts`, `knip.ts`, `.dependency-cruiser.mjs`, the dev
29
+ manifest (`apps/shell/src/environments/environment.development.ts`) and the deployed one
30
+ (`apps/shell/public/federation.manifest.json`). Each of those holds a `// bahtui:remotes` line (the
31
+ JSON manifest is parsed instead); keep it, the generator inserts above it.
32
+
33
+ ## Things that are this way on purpose
34
+
35
+ - `features.ignoreUnusedDeps` is off in every `federation.config.mjs`: its scan refuses sources
36
+ outside the app folder, and the kit lives in `packages/kit`. So every `package.json` dependency is
37
+ shared, and each app lists @20baht/ui's optional peers (`marked`, `dompurify`, `flatpickr`);
38
+ `/^marked\/bin/` stays in `skip`.
39
+ - `fileReplacements` sit on `esbuild:development` in `angular.json`, not on `build`.
40
+ - The web apps see the server only as types, from `apps/server/dist/types` (`build:types` runs
41
+ before every web build and typecheck). Keep the server's imports extensionless: Angular's
42
+ compiler rejects `./x.ts` specifiers in sources it follows.
43
+ - A remote that is down when the host boots stays unavailable until a reload, so every remote's
44
+ URL prefix falls back to a page that says so, and the rest keeps working.
45
+ - In production the host reads `/federation.manifest.json` at runtime: serve each remote's build
46
+ under `/remotes/<app>/` and `/api` from the server on the same origin.
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Architecture boundaries, checked with `bun run deps`. `generic` gives no-circular and
3
+ * production-not-tests. The rules below keep the microfrontends apart: the host and the remotes
4
+ * meet only at runtime through the federation manifest, and share code only through packages/kit.
5
+ * Every rule is `error`: a violation is a decision, not a warning.
6
+ */
7
+ import { makeConfig } from '@20baht/strict/depcruise'
8
+
9
+ const HOST = 'shell'
10
+
11
+ /** `bahtui g remote` adds a line. */
12
+ const REMOTES = [
13
+ // bahtui:remotes
14
+ ]
15
+
16
+ const WEB_APPS = [HOST, ...REMOTES]
17
+
18
+ const base = makeConfig({ generic: true })
19
+
20
+ const apart = WEB_APPS.map((app) => ({
21
+ name: `${app}-imports-no-other-app`,
22
+ severity: 'error',
23
+ comment:
24
+ 'Web apps never import each other: a static import would bundle one app into another build.',
25
+ from: { path: `^apps/${app}/src/` },
26
+ to: { path: `^apps/(?!${app}/)(${WEB_APPS.join('|')})/` },
27
+ }))
28
+
29
+ const layers = WEB_APPS.map((app) => ({
30
+ name: `${app}-lower-layers-know-no-page`,
31
+ severity: 'error',
32
+ comment: 'core/, services/ and shared/ know no page; pages are reached through the router.',
33
+ from: { path: `^apps/${app}/src/app/(core|services|shared)/` },
34
+ to: { path: `^apps/${app}/src/app/modules/` },
35
+ }))
36
+
37
+ export default {
38
+ ...base,
39
+ forbidden: [
40
+ ...base.forbidden,
41
+ ...apart,
42
+ ...layers,
43
+ {
44
+ name: 'packages-know-no-app',
45
+ severity: 'error',
46
+ comment: 'packages/ are below the apps; the server reaches them only as built types.',
47
+ from: { path: '^packages/' },
48
+ to: { path: '^apps/', pathNot: '^apps/server/dist/types/' },
49
+ },
50
+ ],
51
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "server",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/types/index.d.ts",
9
+ "default": "./src/index.ts"
10
+ }
11
+ },
12
+ "types": "dist/types/index.d.ts",
13
+ "scripts": {
14
+ "dev": "bun run --watch src/index.ts",
15
+ "start": "bun run src/index.ts",
16
+ "build": "bun build src/index.ts --target bun --outdir dist",
17
+ "build:types": "tsc -p tsconfig.types.json",
18
+ "typecheck": "tsc --noEmit",
19
+ "test": "bun test",
20
+ "test:coverage": "bun test --coverage"
21
+ },
22
+ "dependencies": {
23
+ "@elysiajs/cors": "^1.4.3",
24
+ "elysia": "^1.4.31"
25
+ },
26
+ "devDependencies": {
27
+ "@types/bun": "^1.3.0",
28
+ "typescript": "^5.9.3"
29
+ }
30
+ }
@@ -0,0 +1,14 @@
1
+ import { cors } from '@elysiajs/cors'
2
+ import { Elysia } from 'elysia'
3
+
4
+ /** In dev the host and the remotes run on their own localhost ports; deployed, all share one origin. */
5
+ const DEV_ORIGIN = /^http:\/\/localhost:\d+$/
6
+
7
+ /**
8
+ * The API under `/api`. Keep imports extensionless (`./x`, never `./x.ts`): the web apps compile
9
+ * this file's declarations, and Angular's compiler rejects `.ts` specifiers.
10
+ */
11
+ export const buildApp = () =>
12
+ new Elysia({ prefix: '/api' })
13
+ .use(cors({ origin: DEV_ORIGIN, credentials: true }))
14
+ .get('/hello', () => ({ message: 'Hello from the server' }))
@@ -0,0 +1,8 @@
1
+ import { buildApp } from './app'
2
+
3
+ const app = buildApp().listen(Number(process.env['PORT'] ?? 3001))
4
+
5
+ console.log(`server on http://localhost:${String(app.server?.port)}`)
6
+
7
+ /** What the web apps type their client with (through `dist/types`, `bun run build:types`). */
8
+ export type App = typeof app
@@ -0,0 +1,12 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+
3
+ import { buildApp } from '../src/app'
4
+
5
+ describe('api', () => {
6
+ test('says hello', async () => {
7
+ const response = await buildApp().handle(new Request('http://localhost/api/hello'))
8
+
9
+ expect(response.status).toBe(200)
10
+ expect(await response.json()).toEqual({ message: 'Hello from the server' })
11
+ })
12
+ })
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "types": ["bun"]
5
+ },
6
+ "include": ["src", "test"]
7
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "noEmit": false,
5
+ "declaration": true,
6
+ "emitDeclarationOnly": true,
7
+ "declarationMap": false,
8
+ "outDir": "dist/types",
9
+ "rootDir": "src"
10
+ },
11
+ "include": ["src"]
12
+ }
@@ -0,0 +1,17 @@
1
+ # Editor configuration, see https://editorconfig.org
2
+ root = true
3
+
4
+ [*]
5
+ charset = utf-8
6
+ indent_style = space
7
+ indent_size = 2
8
+ insert_final_newline = true
9
+ trim_trailing_whitespace = true
10
+
11
+ [*.ts]
12
+ quote_type = single
13
+ ij_typescript_use_double_quotes = false
14
+
15
+ [*.md]
16
+ max_line_length = off
17
+ trim_trailing_whitespace = false