@tschk/moonshine-cli 0.3.4 → 0.3.5
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.
- package/README.md +76 -12
- package/bin/moonshine.ts +6 -3
- package/package.json +13 -9
- package/src/adopt.ts +761 -57
- package/src/new.ts +3 -0
- package/src/tui.ts +61 -0
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ bun packages/cli/bin/moonshine.ts preview
|
|
|
11
11
|
|
|
12
12
|
Commands:
|
|
13
13
|
|
|
14
|
-
- `adopt [dir] [--dry-run] [--force]`
|
|
14
|
+
- `adopt [dir] [--dry-run] [--yes|-y] [--force]`
|
|
15
15
|
- `new <name> [--react|--solid|--crepus] [--adapter bun|node|cloudflare|vercel] [--vite]`
|
|
16
16
|
- `build [dir] [--adapter bun|node|cloudflare|vercel]`
|
|
17
17
|
- `inspect [path] [--json]`
|
|
@@ -21,22 +21,86 @@ Commands:
|
|
|
21
21
|
|
|
22
22
|
## `adopt`
|
|
23
23
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
both `bun run` and `Bun.build`. `moonshine.config.ts` records the route
|
|
28
|
-
directory and convention so `moonshine build` reads `app/` or `pages/` in place.
|
|
24
|
+
Run it with no arguments inside the app you want to move. It walks up from the
|
|
25
|
+
working directory to the nearest `package.json` that looks like a project, and
|
|
26
|
+
detects the framework rather than assuming one.
|
|
29
27
|
|
|
30
28
|
```bash
|
|
31
|
-
|
|
32
|
-
moonshine adopt #
|
|
29
|
+
cd ~/code/my-app/app/dashboard
|
|
30
|
+
moonshine adopt # finds ~/code/my-app, asks, then applies
|
|
31
|
+
moonshine adopt --dry-run # print the plan, write nothing, never prompt
|
|
32
|
+
moonshine adopt --yes # skip the prompt (CI, scripts)
|
|
33
33
|
bun install && moonshine build && moonshine preview
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
36
|
+
Two adoption paths, decided by what it finds:
|
|
37
|
+
|
|
38
|
+
| Detected | How it is adopted |
|
|
39
|
+
| ------------------------------------------- | -------------------------------------------------------------------------------- |
|
|
40
|
+
| Next App Router, Next Pages Router | `next/*` aliased to `@tschk/moonshine-next` through `compilerOptions.paths` |
|
|
41
|
+
| react-router / Remix, TanStack Router, Waku | host specifiers aliased to the matching `@tschk/moonshine-*` adapter |
|
|
42
|
+
| Svelte, Vue, Astro, Angular | templates compiled to View IR by crepuscularity and emitted as generated modules |
|
|
43
|
+
| Vite + React, plain React | config and dependencies only; nothing to alias |
|
|
44
|
+
|
|
45
|
+
No source file is ever edited. For the aliasing path, every specifier the
|
|
46
|
+
adapter implements is remapped through `compilerOptions.paths`, which Bun
|
|
47
|
+
honours in both `bun run` and `Bun.build`. For the template path, each file is
|
|
48
|
+
parsed by the crepuscularity frontend its filename selects into View IR, and a
|
|
49
|
+
module renders that IR through `@tschk/crepus-moonshine`:
|
|
50
|
+
`moonshine/routes/` for templates that map to a URL, `moonshine/components/` for
|
|
51
|
+
templates that do not. `moonshine.config.ts` records the route directory and
|
|
52
|
+
convention either way.
|
|
53
|
+
|
|
54
|
+
Which files each template frontend claims:
|
|
55
|
+
|
|
56
|
+
| Framework | Files | Routing |
|
|
57
|
+
| --------- | ------------------------------------------------ | -------------------------------------------------------------- |
|
|
58
|
+
| Svelte | `**/*.svelte` | `+page.svelte` under `routes/` |
|
|
59
|
+
| Vue | `**/*.vue` | files under `routes/` or `pages/` |
|
|
60
|
+
| Astro | `**/*.astro` | `src/pages/**` (`index.astro` → `/`, `about.astro` → `/about`) |
|
|
61
|
+
| Angular | `**/*.component.html`, `**/*.ng.html`, `**/*.ng` | none — Angular has no file-based routing |
|
|
62
|
+
|
|
63
|
+
Plain `.html` is deliberately not claimed: an `index.html` is left alone.
|
|
64
|
+
|
|
65
|
+
Only the markup is compiled. Svelte `<script>` blocks, Vue's Composition API,
|
|
66
|
+
Astro's `---` frontmatter and the Angular component class are **not** executed —
|
|
67
|
+
no runes, stores, lifecycle hooks, imports, data fetching, DI or pipes — and that
|
|
68
|
+
logic has to be ported to moonshine signals. Template constructs the parser does
|
|
69
|
+
not support are hard errors reported per file, not silent drops:
|
|
70
|
+
|
|
71
|
+
- **Astro** rejects any uppercase component tag (`<Layout>` — the frontend
|
|
72
|
+
resolves no modules), `<slot />`, `{...spread}`, `transition:*` and
|
|
73
|
+
`define:vars`. **This matters in practice**: a real Astro app whose pages use
|
|
74
|
+
components will see those pages fail while the component-free ones compile, so
|
|
75
|
+
expect a partial adoption, not a whole-app one.
|
|
76
|
+
- **Angular** rejects `<ng-template>`, `<ng-content>`, `*ngSwitch`,
|
|
77
|
+
`[ngStyle]`/`[style.x]`, `#templateRef`, `@switch`, `@defer` and `@empty`.
|
|
78
|
+
- **Angular routes nothing.** Every compiled template lands in
|
|
79
|
+
`moonshine/components/` and stays unmounted until you write a route module that
|
|
80
|
+
imports it. Filenames are not guessed into URLs.
|
|
81
|
+
|
|
82
|
+
Because the IR is captured at adopt time, re-run `moonshine adopt --force` after
|
|
83
|
+
editing a template.
|
|
84
|
+
|
|
85
|
+
The `.astro` and Angular frontends landed in crepuscularity after
|
|
86
|
+
`@tschk/crepuscularity-wasm@0.1.2`. `adopt` probes the installed parser build
|
|
87
|
+
before touching anything and refuses, non-zero and without writing, when the
|
|
88
|
+
frontend is missing — the dispatcher's fallback to generic markup is silent, and
|
|
89
|
+
adopting against it would produce quietly wrong pages.
|
|
90
|
+
|
|
91
|
+
### Confirmation
|
|
92
|
+
|
|
93
|
+
Before writing anything the command prints the exact plan — every file created
|
|
94
|
+
or modified, and every key and value it adds — under a full-width yellow warning
|
|
95
|
+
bar, then asks. Only `y` / `yes` proceeds. Without a TTY it prints the same plan
|
|
96
|
+
in plain text and exits non-zero rather than waiting on a prompt nobody can
|
|
97
|
+
answer; pass `--yes` in CI.
|
|
98
|
+
|
|
99
|
+
The command ends with a scorecard: how many imports it aliased or templates it
|
|
100
|
+
compiled, how many source files it rewrote (zero), and a precise list of what it
|
|
101
|
+
cannot carry over — middleware, the metadata API, ISR, `next.config` options,
|
|
102
|
+
server actions, async server components, image optimization, and component
|
|
103
|
+
script logic.
|
|
40
104
|
|
|
41
105
|
See [DESIGN.md](../../DESIGN.md), [docs/ROUTING.md](../../docs/ROUTING.md),
|
|
42
106
|
[docs/DEPLOYMENT.md](../../docs/DEPLOYMENT.md), and
|
package/bin/moonshine.ts
CHANGED
|
@@ -19,8 +19,9 @@ Usage:
|
|
|
19
19
|
--crepus add Crepus renderer
|
|
20
20
|
--adapter deployment target (default: bun)
|
|
21
21
|
--vite client-only Vite SPA
|
|
22
|
-
moonshine adopt [dir] Convert
|
|
22
|
+
moonshine adopt [dir] Convert the app you are standing in to moonshine
|
|
23
23
|
--dry-run print the plan, write nothing
|
|
24
|
+
--yes, -y skip the confirmation prompt
|
|
24
25
|
--force rewrite an existing moonshine.config.ts
|
|
25
26
|
moonshine compile [file] .crepus / View IR JSON → .tsx
|
|
26
27
|
moonshine build [dir] Build project into .moonshine/manifest.json
|
|
@@ -39,9 +40,11 @@ switch (cmd) {
|
|
|
39
40
|
case "new":
|
|
40
41
|
await newCommand(args);
|
|
41
42
|
break;
|
|
42
|
-
case "adopt":
|
|
43
|
-
await adoptCommand(args);
|
|
43
|
+
case "adopt": {
|
|
44
|
+
const result = await adoptCommand(args);
|
|
45
|
+
if (result.code !== 0) process.exit(result.code);
|
|
44
46
|
break;
|
|
47
|
+
}
|
|
45
48
|
case "compile":
|
|
46
49
|
await compileCommand(args);
|
|
47
50
|
break;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tschk/moonshine-cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.5",
|
|
4
4
|
"description": "Bun CLI for moonshine — new, dev, build, preview, inspect, compile",
|
|
5
5
|
"license": "ISC",
|
|
6
6
|
"type": "module",
|
|
@@ -19,13 +19,17 @@
|
|
|
19
19
|
"crepus"
|
|
20
20
|
],
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@tschk/crepus-moonshine": "^0.3.
|
|
23
|
-
"@tschk/
|
|
24
|
-
"@tschk/moonshine-
|
|
25
|
-
"@tschk/moonshine-
|
|
26
|
-
"@tschk/moonshine-
|
|
27
|
-
"@tschk/moonshine-
|
|
28
|
-
"@tschk/moonshine-
|
|
22
|
+
"@tschk/crepus-moonshine": "^0.3.5",
|
|
23
|
+
"@tschk/crepuscularity-wasm": "^0.1.3",
|
|
24
|
+
"@tschk/moonshine-compiler": "^0.3.5",
|
|
25
|
+
"@tschk/moonshine-deploy-bun": "^0.3.5",
|
|
26
|
+
"@tschk/moonshine-framework": "^0.3.5",
|
|
27
|
+
"@tschk/moonshine-next": "^0.3.5",
|
|
28
|
+
"@tschk/moonshine-react": "^0.3.5",
|
|
29
|
+
"@tschk/moonshine-react-router": "^0.3.5",
|
|
30
|
+
"@tschk/moonshine-server": "^0.3.5",
|
|
31
|
+
"@tschk/moonshine-tanstack": "^0.3.5",
|
|
32
|
+
"@tschk/moonshine-waku": "^0.3.5"
|
|
29
33
|
},
|
|
30
34
|
"scripts": {
|
|
31
35
|
"format": "bunx prettier --check .",
|
|
@@ -34,6 +38,6 @@
|
|
|
34
38
|
"test": "bun test"
|
|
35
39
|
},
|
|
36
40
|
"optionalDependencies": {
|
|
37
|
-
"@tschk/moonshine-solid": "^0.3.
|
|
41
|
+
"@tschk/moonshine-solid": "^0.3.5"
|
|
38
42
|
}
|
|
39
43
|
}
|
package/src/adopt.ts
CHANGED
|
@@ -1,10 +1,158 @@
|
|
|
1
|
-
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { dirname, join, relative, resolve } from "node:path";
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
nextAliases,
|
|
5
|
+
resolveAlias as resolveNextAlias,
|
|
6
|
+
} from "@tschk/moonshine-next/aliases";
|
|
7
|
+
import {
|
|
8
|
+
reactRouterAliases,
|
|
9
|
+
resolveAlias as resolveReactRouterAlias,
|
|
10
|
+
} from "@tschk/moonshine-react-router/aliases";
|
|
11
|
+
import {
|
|
12
|
+
tanstackAliases,
|
|
13
|
+
resolveAlias as resolveTanstackAlias,
|
|
14
|
+
} from "@tschk/moonshine-tanstack/aliases";
|
|
15
|
+
import {
|
|
16
|
+
wakuAliases,
|
|
17
|
+
resolveAlias as resolveWakuAlias,
|
|
18
|
+
} from "@tschk/moonshine-waku/aliases";
|
|
4
19
|
import type { RouteConvention } from "@tschk/moonshine-compiler";
|
|
5
20
|
import { detectMoonshineRoot, packagePath } from "./new.js";
|
|
21
|
+
import { terminalTui, truncate, warningBar, type Tui } from "./tui.js";
|
|
6
22
|
|
|
7
|
-
export type Framework =
|
|
23
|
+
export type Framework =
|
|
24
|
+
| "next-app"
|
|
25
|
+
| "next-pages"
|
|
26
|
+
| "react-router"
|
|
27
|
+
| "tanstack"
|
|
28
|
+
| "waku"
|
|
29
|
+
| "svelte"
|
|
30
|
+
| "vue"
|
|
31
|
+
| "astro"
|
|
32
|
+
| "angular"
|
|
33
|
+
| "vite-react"
|
|
34
|
+
| "react"
|
|
35
|
+
| "unknown";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Frameworks adopted by compiling their templates to View IR, not by aliasing
|
|
39
|
+
* imports, and the globs whose files crepuscularity's dispatcher claims.
|
|
40
|
+
*
|
|
41
|
+
* Angular is keyed on the Angular CLI's `*.component.html`, on `*.ng.html` and
|
|
42
|
+
* on a bare `.ng`. Plain `.html` is deliberately absent: the dispatcher does not
|
|
43
|
+
* claim it, so a project's `index.html` must not be swept in here either.
|
|
44
|
+
*/
|
|
45
|
+
const TEMPLATE_FRAMEWORKS: Readonly<Record<string, readonly string[]>> = {
|
|
46
|
+
svelte: ["**/*.svelte"],
|
|
47
|
+
vue: ["**/*.vue"],
|
|
48
|
+
astro: ["**/*.astro"],
|
|
49
|
+
angular: ["**/*.component.html", "**/*.ng.html", "**/*.ng"],
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
function templateGlobs(framework: Framework): readonly string[] | undefined {
|
|
53
|
+
return TEMPLATE_FRAMEWORKS[framework];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A sample only the real frontend compiles into control flow. The dispatcher
|
|
58
|
+
* falls back to generic markup for an extension it does not know, and that
|
|
59
|
+
* fallback is silent — it yields plausible-looking IR with the framework's own
|
|
60
|
+
* constructs quietly dropped. Probing for the structural node proves the
|
|
61
|
+
* installed parser build actually carries the frontend.
|
|
62
|
+
*/
|
|
63
|
+
const FRONTEND_PROBES: Readonly<
|
|
64
|
+
Record<string, { file: string; source: string }>
|
|
65
|
+
> = {
|
|
66
|
+
astro: { file: "probe.astro", source: "{ok && <p>y</p>}" },
|
|
67
|
+
angular: { file: "probe.ng.html", source: "@if (a) { <p>y</p> }" },
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** Version of the parser build actually loaded, for the refusal message. */
|
|
71
|
+
async function parserVersion(): Promise<string | undefined> {
|
|
72
|
+
try {
|
|
73
|
+
const entry = Bun.resolveSync(
|
|
74
|
+
"@tschk/crepuscularity-wasm",
|
|
75
|
+
import.meta.dir,
|
|
76
|
+
);
|
|
77
|
+
const pkg = readJson<{ version?: string }>(
|
|
78
|
+
join(dirname(entry), "package.json"),
|
|
79
|
+
);
|
|
80
|
+
return pkg?.version;
|
|
81
|
+
} catch {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function hasFrontend(framework: Framework): Promise<boolean> {
|
|
87
|
+
const probe = FRONTEND_PROBES[framework];
|
|
88
|
+
if (!probe) return true;
|
|
89
|
+
try {
|
|
90
|
+
const { parseTemplate } = await import("@tschk/crepuscularity-wasm");
|
|
91
|
+
const ir = parseTemplate(probe.source, probe.file);
|
|
92
|
+
return (ir.root ?? []).some((node) => node.kind === "if");
|
|
93
|
+
} catch {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** A host package moonshine reimplements, and how its specifiers map to files. */
|
|
99
|
+
type HostAdapter = {
|
|
100
|
+
/** Package the aliases resolve into. */
|
|
101
|
+
pkg: string;
|
|
102
|
+
/** Bare specifier → adapter subpath. */
|
|
103
|
+
aliases: Readonly<Record<string, string>>;
|
|
104
|
+
resolveAlias: (specifier: string) => string | undefined;
|
|
105
|
+
/** A specifier whose backing file sits directly in `src/`, used to locate it. */
|
|
106
|
+
reference: string;
|
|
107
|
+
/** Specifiers in the source that belong to this host, aliasable or not. */
|
|
108
|
+
imports: RegExp;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const ADAPTERS = {
|
|
112
|
+
next: {
|
|
113
|
+
pkg: "@tschk/moonshine-next",
|
|
114
|
+
aliases: nextAliases,
|
|
115
|
+
resolveAlias: resolveNextAlias,
|
|
116
|
+
reference: "next/link",
|
|
117
|
+
imports: /^next(?:\/.*)?$/,
|
|
118
|
+
},
|
|
119
|
+
"react-router": {
|
|
120
|
+
pkg: "@tschk/moonshine-react-router",
|
|
121
|
+
aliases: reactRouterAliases,
|
|
122
|
+
resolveAlias: resolveReactRouterAlias,
|
|
123
|
+
reference: "react-router",
|
|
124
|
+
imports: /^(?:react-router|react-router-dom|@remix-run\/[^/]+)$/,
|
|
125
|
+
},
|
|
126
|
+
tanstack: {
|
|
127
|
+
pkg: "@tschk/moonshine-tanstack",
|
|
128
|
+
aliases: tanstackAliases,
|
|
129
|
+
resolveAlias: resolveTanstackAlias,
|
|
130
|
+
reference: "@tanstack/react-router",
|
|
131
|
+
imports: /^@tanstack\/(?:react-router|router-core|react-start|start)$/,
|
|
132
|
+
},
|
|
133
|
+
waku: {
|
|
134
|
+
pkg: "@tschk/moonshine-waku",
|
|
135
|
+
aliases: wakuAliases,
|
|
136
|
+
resolveAlias: resolveWakuAlias,
|
|
137
|
+
reference: "waku/router",
|
|
138
|
+
imports: /^waku(?:\/.*)?$/,
|
|
139
|
+
},
|
|
140
|
+
} as const satisfies Record<string, HostAdapter>;
|
|
141
|
+
|
|
142
|
+
const FRAMEWORK_ADAPTER: Readonly<
|
|
143
|
+
Partial<Record<Framework, keyof typeof ADAPTERS>>
|
|
144
|
+
> = {
|
|
145
|
+
"next-app": "next",
|
|
146
|
+
"next-pages": "next",
|
|
147
|
+
"react-router": "react-router",
|
|
148
|
+
tanstack: "tanstack",
|
|
149
|
+
waku: "waku",
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
function adapterFor(framework: Framework): HostAdapter | undefined {
|
|
153
|
+
const id = FRAMEWORK_ADAPTER[framework];
|
|
154
|
+
return id ? ADAPTERS[id] : undefined;
|
|
155
|
+
}
|
|
8
156
|
|
|
9
157
|
export type NextImport = {
|
|
10
158
|
/** Project-relative file holding the import. */
|
|
@@ -14,6 +162,25 @@ export type NextImport = {
|
|
|
14
162
|
aliasable: boolean;
|
|
15
163
|
};
|
|
16
164
|
|
|
165
|
+
export type TemplateFile = {
|
|
166
|
+
/** Project-relative `.svelte` / `.vue` file. */
|
|
167
|
+
file: string;
|
|
168
|
+
/** URL path this template becomes, when it maps to one. */
|
|
169
|
+
route?: string;
|
|
170
|
+
/** Project-relative route module generated for it. */
|
|
171
|
+
generated?: string;
|
|
172
|
+
/** Whether the crepuscularity frontend compiled the template. */
|
|
173
|
+
ok: boolean;
|
|
174
|
+
/** View IR nodes produced. */
|
|
175
|
+
nodes?: number;
|
|
176
|
+
/** The compiled View IR, embedded in the generated route module. */
|
|
177
|
+
ir?: unknown;
|
|
178
|
+
/** IR schema version the parser emitted. */
|
|
179
|
+
irVersion?: number;
|
|
180
|
+
/** Parse error, verbatim. Unsupported constructs are errors, not silent drops. */
|
|
181
|
+
error?: string;
|
|
182
|
+
};
|
|
183
|
+
|
|
17
184
|
export type AdoptScan = {
|
|
18
185
|
projectDir: string;
|
|
19
186
|
framework: Framework;
|
|
@@ -21,6 +188,8 @@ export type AdoptScan = {
|
|
|
21
188
|
routesDir?: string;
|
|
22
189
|
convention?: RouteConvention;
|
|
23
190
|
routes: { path: string; file: string }[];
|
|
191
|
+
/** Templates compiled to View IR, for the Svelte and Vue paths. */
|
|
192
|
+
templates: TemplateFile[];
|
|
24
193
|
imports: NextImport[];
|
|
25
194
|
conventions: string[];
|
|
26
195
|
/** Blunt list of what adoption does not carry over. */
|
|
@@ -30,6 +199,10 @@ export type AdoptScan = {
|
|
|
30
199
|
export type AdoptChange = {
|
|
31
200
|
file: string;
|
|
32
201
|
summary: string;
|
|
202
|
+
/** What the write does to a file that may or may not exist yet. */
|
|
203
|
+
action: "create" | "modify" | "none";
|
|
204
|
+
/** Concrete keys and values the write adds, shown before confirmation. */
|
|
205
|
+
details: string[];
|
|
33
206
|
/** Already true before this run; used to keep repeat runs honest. */
|
|
34
207
|
alreadyApplied: boolean;
|
|
35
208
|
contents?: string;
|
|
@@ -51,7 +224,6 @@ const RUNTIME_DEPS = [
|
|
|
51
224
|
"@tschk/moonshine-compiler",
|
|
52
225
|
"@tschk/moonshine-server",
|
|
53
226
|
"@tschk/moonshine-react",
|
|
54
|
-
"@tschk/moonshine-next",
|
|
55
227
|
"@tschk/moonshine-deploy-bun",
|
|
56
228
|
] as const;
|
|
57
229
|
|
|
@@ -81,31 +253,143 @@ function sourceFiles(projectDir: string): string[] {
|
|
|
81
253
|
return found.sort();
|
|
82
254
|
}
|
|
83
255
|
|
|
84
|
-
/** Every
|
|
85
|
-
function
|
|
86
|
-
|
|
256
|
+
/** Every host specifier (`next/*`, `react-router`, …) a source file pulls in. */
|
|
257
|
+
function findHostImports(
|
|
258
|
+
projectDir: string,
|
|
259
|
+
files: string[],
|
|
260
|
+
adapter: HostAdapter | undefined,
|
|
261
|
+
): NextImport[] {
|
|
262
|
+
if (!adapter) return [];
|
|
263
|
+
const pattern = /["']([^"']+)["']/g;
|
|
87
264
|
const found: NextImport[] = [];
|
|
88
265
|
for (const file of files) {
|
|
89
266
|
const source = readFileSync(join(projectDir, file), "utf8");
|
|
90
267
|
for (const match of source.matchAll(pattern)) {
|
|
91
268
|
const specifier = match[1]!;
|
|
269
|
+
if (!adapter.imports.test(specifier)) continue;
|
|
92
270
|
// A bare string is only an import when a module keyword introduces it.
|
|
93
271
|
const before = source.slice(Math.max(0, match.index - 40), match.index);
|
|
94
272
|
if (!/(?:from|import|require)\s*\(?\s*$/.test(before)) continue;
|
|
95
273
|
found.push({
|
|
96
274
|
file,
|
|
97
275
|
specifier,
|
|
98
|
-
aliasable: specifier in
|
|
276
|
+
aliasable: specifier in adapter.aliases,
|
|
99
277
|
});
|
|
100
278
|
}
|
|
101
279
|
}
|
|
102
280
|
return found;
|
|
103
281
|
}
|
|
104
282
|
|
|
283
|
+
type PackageJson = {
|
|
284
|
+
name?: string;
|
|
285
|
+
workspaces?: unknown;
|
|
286
|
+
dependencies?: Record<string, string>;
|
|
287
|
+
devDependencies?: Record<string, string>;
|
|
288
|
+
scripts?: Record<string, string>;
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
const LOCKFILES = [
|
|
292
|
+
"bun.lock",
|
|
293
|
+
"bun.lockb",
|
|
294
|
+
"package-lock.json",
|
|
295
|
+
"pnpm-lock.yaml",
|
|
296
|
+
"yarn.lock",
|
|
297
|
+
];
|
|
298
|
+
|
|
299
|
+
function hasLockfile(dir: string): boolean {
|
|
300
|
+
return LOCKFILES.some((name) => existsSync(join(dir, name)));
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function allDeps(pkg: PackageJson | undefined): Record<string, string> {
|
|
304
|
+
return { ...pkg?.dependencies, ...pkg?.devDependencies };
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Where `moonshine adopt` writes the route modules it generates from templates. */
|
|
308
|
+
const GENERATED_ROUTES = "moonshine/routes";
|
|
309
|
+
|
|
310
|
+
/** Where compiled-but-unrouted templates land, importable but not mounted. */
|
|
311
|
+
const GENERATED_COMPONENTS = "moonshine/components";
|
|
312
|
+
|
|
313
|
+
function templateFiles(projectDir: string, globs: readonly string[]): string[] {
|
|
314
|
+
const found = new Set<string>();
|
|
315
|
+
for (const glob of globs) {
|
|
316
|
+
for (const entry of new Bun.Glob(glob).scanSync(projectDir)) {
|
|
317
|
+
const rel = toPosix(entry);
|
|
318
|
+
if (!ignored(rel)) found.add(rel);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return [...found].sort();
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Projects adopted through a crepuscularity template frontend: `.svelte`,
|
|
326
|
+
* `.vue`, `.astro` and Angular component templates all compile to the same View
|
|
327
|
+
* IR as `.crepus` and JSX, which crepus-moonshine renders as React elements.
|
|
328
|
+
*/
|
|
329
|
+
function detectTemplateFramework(
|
|
330
|
+
projectDir: string,
|
|
331
|
+
deps: Record<string, string>,
|
|
332
|
+
):
|
|
333
|
+
| { framework: Framework; routesDir: string; convention: RouteConvention }
|
|
334
|
+
| undefined {
|
|
335
|
+
const checks: {
|
|
336
|
+
framework: Framework;
|
|
337
|
+
deps: string[];
|
|
338
|
+
files: string[];
|
|
339
|
+
}[] = [
|
|
340
|
+
{
|
|
341
|
+
framework: "svelte",
|
|
342
|
+
deps: ["svelte", "@sveltejs/kit"],
|
|
343
|
+
files: ["svelte.config.js", "svelte.config.ts"],
|
|
344
|
+
},
|
|
345
|
+
{
|
|
346
|
+
framework: "vue",
|
|
347
|
+
deps: ["vue", "nuxt"],
|
|
348
|
+
files: ["vue.config.js", "nuxt.config.ts"],
|
|
349
|
+
},
|
|
350
|
+
{
|
|
351
|
+
framework: "astro",
|
|
352
|
+
deps: ["astro"],
|
|
353
|
+
files: ["astro.config.mjs", "astro.config.ts", "astro.config.js"],
|
|
354
|
+
},
|
|
355
|
+
{
|
|
356
|
+
framework: "angular",
|
|
357
|
+
deps: ["@angular/core"],
|
|
358
|
+
files: ["angular.json"],
|
|
359
|
+
},
|
|
360
|
+
];
|
|
361
|
+
|
|
362
|
+
for (const check of checks) {
|
|
363
|
+
const declared =
|
|
364
|
+
check.deps.some((dep) => deps[dep] !== undefined) ||
|
|
365
|
+
check.files.some((file) => existsSync(join(projectDir, file)));
|
|
366
|
+
const present =
|
|
367
|
+
templateFiles(projectDir, templateGlobs(check.framework)!).length > 0;
|
|
368
|
+
if (!declared && !present) continue;
|
|
369
|
+
return {
|
|
370
|
+
framework: check.framework,
|
|
371
|
+
routesDir: GENERATED_ROUTES,
|
|
372
|
+
convention: "moonshine",
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
return undefined;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** Route directory for the conventions moonshine reads directly. */
|
|
379
|
+
function findMoonshineRoutes(projectDir: string): string | undefined {
|
|
380
|
+
for (const dir of ["src/routes", "routes", "app/routes"]) {
|
|
381
|
+
if (existsSync(join(projectDir, dir))) return dir;
|
|
382
|
+
}
|
|
383
|
+
return undefined;
|
|
384
|
+
}
|
|
385
|
+
|
|
105
386
|
function detectFramework(
|
|
106
387
|
projectDir: string,
|
|
107
|
-
pkg:
|
|
388
|
+
pkg: PackageJson | undefined,
|
|
108
389
|
): { framework: Framework; routesDir?: string; convention?: RouteConvention } {
|
|
390
|
+
const deps = allDeps(pkg);
|
|
391
|
+
const template = detectTemplateFramework(projectDir, deps);
|
|
392
|
+
if (template) return template;
|
|
109
393
|
for (const dir of ["app", "src/app"]) {
|
|
110
394
|
if (
|
|
111
395
|
existsSync(join(projectDir, dir, "page.tsx")) ||
|
|
@@ -124,13 +408,207 @@ function detectFramework(
|
|
|
124
408
|
};
|
|
125
409
|
}
|
|
126
410
|
}
|
|
411
|
+
if (deps.next) return { framework: "next-app" };
|
|
412
|
+
|
|
413
|
+
const routesDir = findMoonshineRoutes(projectDir);
|
|
414
|
+
const routed = (framework: Framework) => ({
|
|
415
|
+
framework,
|
|
416
|
+
...(routesDir && { routesDir, convention: "moonshine" as RouteConvention }),
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
if (deps.waku || existsSync(join(projectDir, "waku.config.ts"))) {
|
|
420
|
+
return routed("waku");
|
|
421
|
+
}
|
|
422
|
+
if (deps["@tanstack/react-router"] || deps["@tanstack/react-start"]) {
|
|
423
|
+
return routed("tanstack");
|
|
424
|
+
}
|
|
425
|
+
if (
|
|
426
|
+
deps["react-router"] ||
|
|
427
|
+
deps["react-router-dom"] ||
|
|
428
|
+
deps["@remix-run/react"] ||
|
|
429
|
+
existsSync(join(projectDir, "react-router.config.ts")) ||
|
|
430
|
+
existsSync(join(projectDir, "remix.config.js"))
|
|
431
|
+
) {
|
|
432
|
+
return routed("react-router");
|
|
433
|
+
}
|
|
127
434
|
if (
|
|
128
435
|
existsSync(join(projectDir, "vite.config.ts")) ||
|
|
129
436
|
existsSync(join(projectDir, "vite.config.js"))
|
|
130
437
|
) {
|
|
131
|
-
return
|
|
438
|
+
return routed("vite-react");
|
|
439
|
+
}
|
|
440
|
+
if (deps.react) return routed("react");
|
|
441
|
+
return { framework: "unknown" };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Nearest ancestor of `from` that looks like the project being adopted.
|
|
446
|
+
*
|
|
447
|
+
* The nearest `package.json` wins when a framework is detectable there — that
|
|
448
|
+
* is the app the user is standing in, even inside a monorepo. Only when it says
|
|
449
|
+
* nothing does the walk continue to a workspace root (lockfile or `workspaces`).
|
|
450
|
+
*/
|
|
451
|
+
export function findProjectRoot(from: string): string | undefined {
|
|
452
|
+
let dir = resolve(from);
|
|
453
|
+
const candidates: string[] = [];
|
|
454
|
+
for (;;) {
|
|
455
|
+
if (existsSync(join(dir, "package.json"))) candidates.push(dir);
|
|
456
|
+
const parent = dirname(dir);
|
|
457
|
+
if (parent === dir) break;
|
|
458
|
+
dir = parent;
|
|
459
|
+
}
|
|
460
|
+
for (const candidate of candidates) {
|
|
461
|
+
const pkg = readJson<PackageJson>(join(candidate, "package.json"));
|
|
462
|
+
if (detectFramework(candidate, pkg).framework !== "unknown")
|
|
463
|
+
return candidate;
|
|
132
464
|
}
|
|
133
|
-
|
|
465
|
+
for (const candidate of candidates) {
|
|
466
|
+
const pkg = readJson<PackageJson>(join(candidate, "package.json"));
|
|
467
|
+
if (hasLockfile(candidate) || pkg?.workspaces !== undefined)
|
|
468
|
+
return candidate;
|
|
469
|
+
}
|
|
470
|
+
return candidates[0];
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function countNodes(nodes: readonly unknown[] = []): number {
|
|
474
|
+
let total = 0;
|
|
475
|
+
for (const node of nodes) {
|
|
476
|
+
total += 1;
|
|
477
|
+
const children = (node as { children?: unknown }).children;
|
|
478
|
+
if (Array.isArray(children)) total += countNodes(children);
|
|
479
|
+
}
|
|
480
|
+
return total;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** URL path a template file serves, or `undefined` when it is a plain component. */
|
|
484
|
+
function templateRoute(file: string, framework: Framework): string | undefined {
|
|
485
|
+
// Angular has no file-based routing convention: routes live in the router
|
|
486
|
+
// module's TypeScript, which is not compiled here. Inventing a URL from a
|
|
487
|
+
// component's filename would be a guess, so its components stay unmounted.
|
|
488
|
+
if (framework === "angular") return undefined;
|
|
489
|
+
const segments = file.split("/");
|
|
490
|
+
const base = segments.pop()!;
|
|
491
|
+
const stem = base.replace(/\.(svelte|vue|astro)$/, "");
|
|
492
|
+
const rootIndex = segments.findIndex((s) => s === "routes" || s === "pages");
|
|
493
|
+
|
|
494
|
+
if (stem.startsWith("+page")) {
|
|
495
|
+
if (rootIndex === -1) return "/";
|
|
496
|
+
const rest = segments
|
|
497
|
+
.slice(rootIndex + 1)
|
|
498
|
+
.filter((s) => !s.startsWith("("));
|
|
499
|
+
return `/${rest.join("/")}`.replace(/\/$/, "") || "/";
|
|
500
|
+
}
|
|
501
|
+
if (rootIndex !== -1) {
|
|
502
|
+
const rest = [...segments.slice(rootIndex + 1), stem].filter(
|
|
503
|
+
(s) => !s.startsWith("("),
|
|
504
|
+
);
|
|
505
|
+
if (rest.at(-1) === "index") rest.pop();
|
|
506
|
+
return `/${rest.join("/")}`.replace(/\/$/, "") || "/";
|
|
507
|
+
}
|
|
508
|
+
if (/^(app|App)$/.test(stem) && segments.length <= 1) return "/";
|
|
509
|
+
return undefined;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function generatedModule(route: string): string {
|
|
513
|
+
const rest = route.replace(/^\//, "");
|
|
514
|
+
return `${GENERATED_ROUTES}/${rest === "" ? "index" : rest}.tsx`;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* A template that compiles but maps to no URL still becomes a component module,
|
|
519
|
+
* so the compiled IR is importable. Angular has no file-based routing at all, so
|
|
520
|
+
* this is the whole of its output — mounting it stays the user's decision.
|
|
521
|
+
*/
|
|
522
|
+
function componentModule(file: string): string {
|
|
523
|
+
const slug = file
|
|
524
|
+
.replace(/\.(svelte|vue|astro|ng)$/, "")
|
|
525
|
+
.replace(/\.(component|ng)\.html$/, "")
|
|
526
|
+
.replace(/[^a-zA-Z0-9/-]/g, "-");
|
|
527
|
+
return `${GENERATED_COMPONENTS}/${slug}.tsx`;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Compile every template through the crepuscularity frontend its filename
|
|
532
|
+
* selects. A template that does not compile is recorded with the parser's own
|
|
533
|
+
* message: unsupported constructs are hard errors, so nothing is silently
|
|
534
|
+
* dropped from the page.
|
|
535
|
+
*/
|
|
536
|
+
async function compileTemplates(
|
|
537
|
+
projectDir: string,
|
|
538
|
+
framework: Framework,
|
|
539
|
+
globs: readonly string[],
|
|
540
|
+
): Promise<TemplateFile[]> {
|
|
541
|
+
const { parseTemplate } = await import("@tschk/crepuscularity-wasm");
|
|
542
|
+
const files = templateFiles(projectDir, globs);
|
|
543
|
+
|
|
544
|
+
const templates: TemplateFile[] = [];
|
|
545
|
+
const taken = new Set<string>();
|
|
546
|
+
for (const file of files) {
|
|
547
|
+
const route = templateRoute(file, framework);
|
|
548
|
+
const entry: TemplateFile = { file, ok: false };
|
|
549
|
+
if (route !== undefined && !taken.has(route)) {
|
|
550
|
+
taken.add(route);
|
|
551
|
+
entry.route = route;
|
|
552
|
+
}
|
|
553
|
+
try {
|
|
554
|
+
const ir = parseTemplate(
|
|
555
|
+
readFileSync(join(projectDir, file), "utf8"),
|
|
556
|
+
file.split("/").pop()!,
|
|
557
|
+
);
|
|
558
|
+
entry.ok = true;
|
|
559
|
+
entry.nodes = countNodes(ir.root ?? []);
|
|
560
|
+
entry.ir = ir;
|
|
561
|
+
entry.irVersion = ir.version;
|
|
562
|
+
entry.generated =
|
|
563
|
+
entry.route !== undefined
|
|
564
|
+
? generatedModule(entry.route)
|
|
565
|
+
: componentModule(file);
|
|
566
|
+
} catch (error) {
|
|
567
|
+
entry.error = error instanceof Error ? error.message : String(error);
|
|
568
|
+
delete entry.route;
|
|
569
|
+
}
|
|
570
|
+
templates.push(entry);
|
|
571
|
+
}
|
|
572
|
+
return templates;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** Modules generated from the templates: IR in, React elements out. */
|
|
576
|
+
function planTemplateRoutes(scan: AdoptScan): AdoptChange[] {
|
|
577
|
+
const changes: AdoptChange[] = [];
|
|
578
|
+
for (const template of scan.templates) {
|
|
579
|
+
if (!template.generated) continue;
|
|
580
|
+
const path = join(scan.projectDir, template.generated);
|
|
581
|
+
const name = template.route ? "Route" : "Component";
|
|
582
|
+
const contents = `// Generated by \`moonshine adopt\` from ${template.file}: crepuscularity parsed that template into View IR v${template.irVersion}. Re-run \`moonshine adopt --force\` after editing the template.
|
|
583
|
+
import { renderCrepusIr, type CrepusIr } from "@tschk/crepus-moonshine";
|
|
584
|
+
|
|
585
|
+
const ir = ${JSON.stringify(template.ir, null, 2)} as CrepusIr;
|
|
586
|
+
|
|
587
|
+
export default function ${name}() {
|
|
588
|
+
return renderCrepusIr(ir);
|
|
589
|
+
}
|
|
590
|
+
`;
|
|
591
|
+
const exists = existsSync(path);
|
|
592
|
+
const alreadyApplied = exists && readFileSync(path, "utf8") === contents;
|
|
593
|
+
const what = template.route
|
|
594
|
+
? `route ${template.route}`
|
|
595
|
+
: "unmounted component";
|
|
596
|
+
changes.push({
|
|
597
|
+
file: template.generated,
|
|
598
|
+
action: alreadyApplied ? "none" : exists ? "modify" : "create",
|
|
599
|
+
details: alreadyApplied
|
|
600
|
+
? []
|
|
601
|
+
: [
|
|
602
|
+
`${what} renders ${template.file} (${template.nodes ?? 0} View IR nodes)`,
|
|
603
|
+
],
|
|
604
|
+
summary: alreadyApplied
|
|
605
|
+
? "already generated"
|
|
606
|
+
: `${exists ? "regenerated" : "generated"} ${what} from ${template.file}`,
|
|
607
|
+
alreadyApplied,
|
|
608
|
+
...(alreadyApplied ? {} : { contents }),
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
return changes;
|
|
134
612
|
}
|
|
135
613
|
|
|
136
614
|
/** Next conventions present in the tree, named the way the user named them. */
|
|
@@ -277,17 +755,72 @@ const ALIAS_CAVEATS: Readonly<Record<string, string>> = {
|
|
|
277
755
|
"next/dynamic lazy-loads on the client only; `ssr: false` is the effective behaviour either way.",
|
|
278
756
|
};
|
|
279
757
|
|
|
758
|
+
/**
|
|
759
|
+
* The honest boundary of the template path: crepuscularity compiles the markup
|
|
760
|
+
* only. Nothing inside `<script>` runs, so component logic has to be ported.
|
|
761
|
+
*/
|
|
762
|
+
function templateManualWork(
|
|
763
|
+
framework: Framework,
|
|
764
|
+
templates: TemplateFile[],
|
|
765
|
+
): string[] {
|
|
766
|
+
if (!templateGlobs(framework) || templates.length === 0) return [];
|
|
767
|
+
const boundary: Readonly<Record<string, string>> = {
|
|
768
|
+
svelte:
|
|
769
|
+
"<script> blocks are not executed: runes, stores, reactive statements, lifecycle hooks and event handler bodies are compiled as template text, not run. Port that logic to moonshine signals.",
|
|
770
|
+
vue: "<script> blocks are not executed: the Composition API, reactive refs, computed properties and lifecycle hooks do not run. Port that logic to moonshine signals.",
|
|
771
|
+
astro:
|
|
772
|
+
"The `---` frontmatter is blanked, never executed: imports, top-level awaits, data fetching and `Astro.props` do not run. Only the markup below it is compiled.",
|
|
773
|
+
angular:
|
|
774
|
+
"The component class is not executed: constructors, decorators, DI, `@Input`/`@Output`, pipes and lifecycle hooks do not run. Only the template is compiled.",
|
|
775
|
+
};
|
|
776
|
+
const rejects: Readonly<Record<string, string>> = {
|
|
777
|
+
astro:
|
|
778
|
+
"Astro templates that use an imported component (`<Layout>`, any uppercase tag), `<slot />`, `{...spread}`, `transition:*` or `define:vars` are parse errors — the frontend compiles markup and resolves no modules. In a real Astro app most page files use components, so expect per-file failures rather than a whole-app adoption.",
|
|
779
|
+
angular:
|
|
780
|
+
"Angular templates that use `<ng-template>`, `<ng-content>`, `*ngSwitch`, `[ngStyle]`/`[style.x]`, `#templateRef`, `@switch`, `@defer` or `@empty` are parse errors.",
|
|
781
|
+
};
|
|
782
|
+
const notes: string[] = [boundary[framework]!];
|
|
783
|
+
if (rejects[framework]) notes.push(rejects[framework]!);
|
|
784
|
+
notes.push(
|
|
785
|
+
"Route modules embed the View IR produced at adopt time. Re-run `moonshine adopt --force` after editing a template.",
|
|
786
|
+
);
|
|
787
|
+
if (framework === "angular") {
|
|
788
|
+
notes.push(
|
|
789
|
+
"Angular has no file-based routing, so no component is mounted at a URL. The generated IR is compiled but unrouted until you write route modules that render it.",
|
|
790
|
+
);
|
|
791
|
+
}
|
|
792
|
+
for (const template of templates) {
|
|
793
|
+
if (!template.ok) {
|
|
794
|
+
notes.push(
|
|
795
|
+
`${template.file}: did not compile — ${template.error}. No route was generated for it; unsupported template constructs are parse errors, not silent drops.`,
|
|
796
|
+
);
|
|
797
|
+
} else if (!template.route) {
|
|
798
|
+
notes.push(
|
|
799
|
+
`${template.file}: compiled (${template.nodes} nodes) but maps to no URL, so it is not mounted. Its IR is in ${template.generated} — import that from a route module to render it.`,
|
|
800
|
+
);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
return notes;
|
|
804
|
+
}
|
|
805
|
+
|
|
280
806
|
export async function scanProject(projectDir: string): Promise<AdoptScan> {
|
|
281
807
|
const dir = resolve(projectDir);
|
|
282
|
-
const pkg = readJson<
|
|
283
|
-
join(dir, "package.json"),
|
|
284
|
-
);
|
|
808
|
+
const pkg = readJson<PackageJson>(join(dir, "package.json"));
|
|
285
809
|
const files = sourceFiles(dir);
|
|
286
810
|
const detected = detectFramework(dir, pkg);
|
|
287
|
-
const imports =
|
|
811
|
+
const imports = findHostImports(dir, files, adapterFor(detected.framework));
|
|
812
|
+
|
|
813
|
+
const globs = templateGlobs(detected.framework);
|
|
814
|
+
const templates = globs
|
|
815
|
+
? await compileTemplates(dir, detected.framework, globs)
|
|
816
|
+
: [];
|
|
288
817
|
|
|
289
818
|
const routes: { path: string; file: string }[] = [];
|
|
290
|
-
if (
|
|
819
|
+
if (
|
|
820
|
+
detected.routesDir &&
|
|
821
|
+
detected.convention &&
|
|
822
|
+
existsSync(join(dir, detected.routesDir))
|
|
823
|
+
) {
|
|
291
824
|
const { discoverRoutes } = await import("@tschk/moonshine-compiler");
|
|
292
825
|
const discovered = await discoverRoutes({
|
|
293
826
|
routesDir: join(dir, detected.routesDir),
|
|
@@ -307,9 +840,11 @@ export async function scanProject(projectDir: string): Promise<AdoptScan> {
|
|
|
307
840
|
...(detected.routesDir && { routesDir: detected.routesDir }),
|
|
308
841
|
...(detected.convention && { convention: detected.convention }),
|
|
309
842
|
routes,
|
|
843
|
+
templates,
|
|
310
844
|
imports,
|
|
311
845
|
conventions: findConventions(dir, files),
|
|
312
846
|
manual: [
|
|
847
|
+
...templateManualWork(detected.framework, templates),
|
|
313
848
|
...findManualWork(dir, files, detected),
|
|
314
849
|
...[...new Set(imports.map((i) => i.specifier))]
|
|
315
850
|
.sort()
|
|
@@ -326,16 +861,17 @@ export async function scanProject(projectDir: string): Promise<AdoptScan> {
|
|
|
326
861
|
* the global module cache — a copy that can predate the adapter's current
|
|
327
862
|
* surface, leaving specifiers pointing at files that do not exist.
|
|
328
863
|
*/
|
|
329
|
-
function adapterDir(projectDir: string): string {
|
|
864
|
+
function adapterDir(projectDir: string, pkg: string): string {
|
|
865
|
+
const parts = pkg.split("/");
|
|
330
866
|
let dir = projectDir;
|
|
331
867
|
for (;;) {
|
|
332
|
-
const candidate = join(dir, "node_modules",
|
|
868
|
+
const candidate = join(dir, "node_modules", ...parts);
|
|
333
869
|
if (existsSync(candidate)) return candidate;
|
|
334
870
|
const parent = dirname(dir);
|
|
335
871
|
if (parent === dir) break;
|
|
336
872
|
dir = parent;
|
|
337
873
|
}
|
|
338
|
-
return join(projectDir, "node_modules",
|
|
874
|
+
return join(projectDir, "node_modules", ...parts);
|
|
339
875
|
}
|
|
340
876
|
|
|
341
877
|
/**
|
|
@@ -343,12 +879,17 @@ function adapterDir(projectDir: string): string {
|
|
|
343
879
|
* at a real file. Bun applies tsconfig paths in both `bun run` and `Bun.build`,
|
|
344
880
|
* but only for relative targets — a bare package specifier is not remapped.
|
|
345
881
|
*/
|
|
346
|
-
export function aliasPaths(
|
|
347
|
-
|
|
348
|
-
|
|
882
|
+
export function aliasPaths(
|
|
883
|
+
projectDir: string,
|
|
884
|
+
framework: Framework = "next-app",
|
|
885
|
+
): Record<string, string[]> {
|
|
886
|
+
const adapter = adapterFor(framework);
|
|
887
|
+
if (!adapter) return {};
|
|
888
|
+
const pkgDir = adapterDir(projectDir, adapter.pkg);
|
|
889
|
+
const srcDir = dirname(adapter.resolveAlias(adapter.reference)!);
|
|
349
890
|
const paths: Record<string, string[]> = {};
|
|
350
|
-
for (const specifier of Object.keys(
|
|
351
|
-
const source = resolveAlias(specifier);
|
|
891
|
+
for (const specifier of Object.keys(adapter.aliases)) {
|
|
892
|
+
const source = adapter.resolveAlias(specifier);
|
|
352
893
|
if (!source) continue;
|
|
353
894
|
const file = join(pkgDir, "src", relative(srcDir, source));
|
|
354
895
|
const rel = toPosix(relative(projectDir, file));
|
|
@@ -363,7 +904,7 @@ function planTsconfig(scan: AdoptScan): AdoptChange {
|
|
|
363
904
|
readJson<{ compilerOptions?: Record<string, unknown> }>(path) ?? {};
|
|
364
905
|
const compilerOptions = { ...existing.compilerOptions };
|
|
365
906
|
const previous = (compilerOptions.paths ?? {}) as Record<string, string[]>;
|
|
366
|
-
const wanted = aliasPaths(scan.projectDir);
|
|
907
|
+
const wanted = aliasPaths(scan.projectDir, scan.framework);
|
|
367
908
|
const paths = { ...previous, ...wanted };
|
|
368
909
|
compilerOptions.baseUrl = compilerOptions.baseUrl ?? ".";
|
|
369
910
|
compilerOptions.jsx = compilerOptions.jsx ?? "react-jsx";
|
|
@@ -372,12 +913,30 @@ function planTsconfig(scan: AdoptScan): AdoptChange {
|
|
|
372
913
|
const alreadyApplied = Object.entries(wanted).every(
|
|
373
914
|
([key, value]) => previous[key]?.[0] === value[0],
|
|
374
915
|
);
|
|
916
|
+
const adapter = adapterFor(scan.framework);
|
|
917
|
+
const added = Object.entries(wanted).filter(
|
|
918
|
+
([key, value]) => previous[key]?.[0] !== value[0],
|
|
919
|
+
);
|
|
920
|
+
const details: string[] = [];
|
|
921
|
+
if (existing.compilerOptions?.baseUrl === undefined) {
|
|
922
|
+
details.push(`compilerOptions.baseUrl = "."`);
|
|
923
|
+
}
|
|
924
|
+
if (existing.compilerOptions?.jsx === undefined) {
|
|
925
|
+
details.push(`compilerOptions.jsx = "react-jsx"`);
|
|
926
|
+
}
|
|
927
|
+
for (const [key, value] of added) {
|
|
928
|
+
details.push(`compilerOptions.paths["${key}"] = "${value[0]}"`);
|
|
929
|
+
}
|
|
375
930
|
|
|
376
931
|
return {
|
|
377
932
|
file: "tsconfig.json",
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
933
|
+
action: existsSync(path) ? "modify" : "create",
|
|
934
|
+
details,
|
|
935
|
+
summary: !adapter
|
|
936
|
+
? "baseUrl and jsx set; this framework needs no import aliases"
|
|
937
|
+
: alreadyApplied
|
|
938
|
+
? `already aliases ${Object.keys(wanted).length} specifiers`
|
|
939
|
+
: `aliases ${Object.keys(wanted).length} specifiers to ${adapter.pkg}`,
|
|
381
940
|
alreadyApplied,
|
|
382
941
|
contents: JSON.stringify({ ...existing, compilerOptions }, null, 2) + "\n",
|
|
383
942
|
};
|
|
@@ -401,6 +960,12 @@ export default defineConfig(${JSON.stringify(entries, null, 2)});
|
|
|
401
960
|
const alreadyApplied = exists && (current === contents || !force);
|
|
402
961
|
return {
|
|
403
962
|
file: "moonshine.config.ts",
|
|
963
|
+
action: alreadyApplied ? "none" : exists ? "modify" : "create",
|
|
964
|
+
details: alreadyApplied
|
|
965
|
+
? []
|
|
966
|
+
: Object.entries(entries).map(
|
|
967
|
+
([key, value]) => `defineConfig.${key} = ${JSON.stringify(value)}`,
|
|
968
|
+
),
|
|
404
969
|
summary: alreadyApplied
|
|
405
970
|
? "already present, left untouched"
|
|
406
971
|
: `${exists ? "rewritten" : "created"} (routesDir ${scan.routesDir ?? "src/routes"}, convention ${scan.convention ?? "moonshine"})`,
|
|
@@ -421,7 +986,13 @@ function planPackageJson(scan: AdoptScan): AdoptChange {
|
|
|
421
986
|
|
|
422
987
|
const dependencies = { ...pkg.dependencies };
|
|
423
988
|
const added: string[] = [];
|
|
424
|
-
|
|
989
|
+
const adapter = adapterFor(scan.framework);
|
|
990
|
+
const template = templateGlobs(scan.framework) !== undefined;
|
|
991
|
+
for (const name of [
|
|
992
|
+
...RUNTIME_DEPS,
|
|
993
|
+
...(adapter ? [adapter.pkg] : []),
|
|
994
|
+
...(template ? ["@tschk/crepus-moonshine"] : []),
|
|
995
|
+
] as string[]) {
|
|
425
996
|
if (dependencies[name]) continue;
|
|
426
997
|
const spec = packagePath(name, root, version);
|
|
427
998
|
if (!spec) continue;
|
|
@@ -438,7 +1009,12 @@ function planPackageJson(scan: AdoptScan): AdoptChange {
|
|
|
438
1009
|
};
|
|
439
1010
|
for (const [key, value] of Object.entries(mapping)) {
|
|
440
1011
|
const current = scripts[key];
|
|
441
|
-
if (
|
|
1012
|
+
if (
|
|
1013
|
+
current !== undefined &&
|
|
1014
|
+
!/^(next|vite|remix|react-router|waku)(\s|$)/.test(current)
|
|
1015
|
+
) {
|
|
1016
|
+
continue;
|
|
1017
|
+
}
|
|
442
1018
|
if (current === value) continue;
|
|
443
1019
|
scripts[key] = value;
|
|
444
1020
|
repointed.push(key);
|
|
@@ -452,6 +1028,13 @@ function planPackageJson(scan: AdoptScan): AdoptChange {
|
|
|
452
1028
|
|
|
453
1029
|
return {
|
|
454
1030
|
file: "package.json",
|
|
1031
|
+
action: existsSync(path) ? "modify" : "create",
|
|
1032
|
+
details: [
|
|
1033
|
+
...added.map(
|
|
1034
|
+
(name) => `dependencies["${name}"] = "${dependencies[name]}"`,
|
|
1035
|
+
),
|
|
1036
|
+
...repointed.map((key) => `scripts["${key}"] = "${scripts[key]}"`),
|
|
1037
|
+
],
|
|
455
1038
|
summary: alreadyApplied ? "already adopted" : parts.join(", "),
|
|
456
1039
|
alreadyApplied,
|
|
457
1040
|
contents: JSON.stringify({ ...pkg, dependencies, scripts }, null, 2) + "\n",
|
|
@@ -476,6 +1059,7 @@ export async function planAdoption(
|
|
|
476
1059
|
planTsconfig(scan),
|
|
477
1060
|
planConfig(scan, options.force ?? false),
|
|
478
1061
|
planPackageJson(scan),
|
|
1062
|
+
...planTemplateRoutes(scan),
|
|
479
1063
|
],
|
|
480
1064
|
// Aliasing covers every specifier the adapter implements, so nothing in the
|
|
481
1065
|
// user's source is edited. Unaliasable specifiers are reported, not rewritten,
|
|
@@ -487,7 +1071,9 @@ export async function planAdoption(
|
|
|
487
1071
|
export function applyPlan(plan: AdoptPlan): void {
|
|
488
1072
|
for (const change of plan.changes) {
|
|
489
1073
|
if (change.contents === undefined) continue;
|
|
490
|
-
|
|
1074
|
+
const path = join(plan.scan.projectDir, change.file);
|
|
1075
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
1076
|
+
writeFileSync(path, change.contents);
|
|
491
1077
|
}
|
|
492
1078
|
}
|
|
493
1079
|
|
|
@@ -511,15 +1097,34 @@ export function formatReport(plan: AdoptPlan, dryRun: boolean): string {
|
|
|
511
1097
|
}
|
|
512
1098
|
if (scan.routes.length > 12) push(` … ${scan.routes.length - 12} more`);
|
|
513
1099
|
|
|
1100
|
+
if (scan.templates.length) {
|
|
1101
|
+
const ok = scan.templates.filter((t) => t.ok);
|
|
1102
|
+
push(
|
|
1103
|
+
` templates ${ok.length}/${scan.templates.length} compiled to View IR`,
|
|
1104
|
+
);
|
|
1105
|
+
for (const template of scan.templates) {
|
|
1106
|
+
const mark = template.ok
|
|
1107
|
+
? template.route
|
|
1108
|
+
? "route"
|
|
1109
|
+
: "no url"
|
|
1110
|
+
: "FAILED";
|
|
1111
|
+
push(
|
|
1112
|
+
` ${template.file.padEnd(34)} ${mark.padEnd(7)} ${template.ok ? `${template.nodes} nodes${template.route ? ` → ${template.route}` : ""}` : template.error}`,
|
|
1113
|
+
);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
|
|
514
1117
|
const bySpecifier = new Map<string, NextImport[]>();
|
|
515
1118
|
for (const imp of scan.imports) {
|
|
516
1119
|
const list = bySpecifier.get(imp.specifier) ?? [];
|
|
517
1120
|
list.push(imp);
|
|
518
1121
|
bySpecifier.set(imp.specifier, list);
|
|
519
1122
|
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
)
|
|
1123
|
+
if (adapterFor(scan.framework)) {
|
|
1124
|
+
push(
|
|
1125
|
+
` host imports ${scan.imports.length} across ${new Set(scan.imports.map((i) => i.file)).size} files`,
|
|
1126
|
+
);
|
|
1127
|
+
}
|
|
523
1128
|
for (const [specifier, list] of [...bySpecifier].sort()) {
|
|
524
1129
|
const mark = list[0]!.aliasable ? "alias" : "NO IMPL";
|
|
525
1130
|
push(
|
|
@@ -532,9 +1137,10 @@ export function formatReport(plan: AdoptPlan, dryRun: boolean): string {
|
|
|
532
1137
|
|
|
533
1138
|
push();
|
|
534
1139
|
push(dryRun ? "REWRITE (planned)" : "REWRITE");
|
|
1140
|
+
const column = Math.max(...plan.changes.map((c) => c.file.length), 18);
|
|
535
1141
|
for (const change of plan.changes) {
|
|
536
1142
|
const mark = change.alreadyApplied ? "no-op" : dryRun ? "would" : "wrote";
|
|
537
|
-
push(` ${mark.padEnd(6)} ${change.file.padEnd(
|
|
1143
|
+
push(` ${mark.padEnd(6)} ${change.file.padEnd(column)} ${change.summary}`);
|
|
538
1144
|
}
|
|
539
1145
|
|
|
540
1146
|
const aliased = scan.imports.filter((i) => i.aliasable);
|
|
@@ -542,9 +1148,17 @@ export function formatReport(plan: AdoptPlan, dryRun: boolean): string {
|
|
|
542
1148
|
|
|
543
1149
|
push();
|
|
544
1150
|
push("SCORECARD");
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
)
|
|
1151
|
+
if (adapterFor(scan.framework)) {
|
|
1152
|
+
push(
|
|
1153
|
+
` aliased ${pluralize(aliased.length, "import")} across ${pluralize(new Set(aliased.map((i) => i.file)).size, "file")} — 0 source files edited`,
|
|
1154
|
+
);
|
|
1155
|
+
}
|
|
1156
|
+
if (scan.templates.length) {
|
|
1157
|
+
const ok = scan.templates.filter((t) => t.ok);
|
|
1158
|
+
push(
|
|
1159
|
+
` compiled ${pluralize(ok.length, "template")}, ${pluralize(ok.filter((t) => t.route).length, "route")} mounted, ${scan.templates.length - ok.length} failed — 0 source files edited`,
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
548
1162
|
push(` rewritten ${pluralize(plan.rewritten.length, "source file")}`);
|
|
549
1163
|
for (const file of plan.rewritten) push(` ${file}`);
|
|
550
1164
|
|
|
@@ -569,39 +1183,129 @@ export function formatReport(plan: AdoptPlan, dryRun: boolean): string {
|
|
|
569
1183
|
return lines.join("\n");
|
|
570
1184
|
}
|
|
571
1185
|
|
|
572
|
-
|
|
1186
|
+
/**
|
|
1187
|
+
* Every file the run would touch, with the exact keys and values it adds, so
|
|
1188
|
+
* the answer to the prompt is informed rather than hopeful.
|
|
1189
|
+
*/
|
|
1190
|
+
export function formatPlan(
|
|
1191
|
+
plan: AdoptPlan,
|
|
1192
|
+
tui: Pick<Tui, "isTTY" | "columns">,
|
|
1193
|
+
): string {
|
|
1194
|
+
const width = tui.columns;
|
|
1195
|
+
const lines: string[] = [];
|
|
1196
|
+
lines.push(truncate("moonshine adopt will modify", width));
|
|
1197
|
+
lines.push(truncate(` ${plan.scan.projectDir}`, width));
|
|
1198
|
+
lines.push("");
|
|
1199
|
+
for (const change of plan.changes) {
|
|
1200
|
+
const verb =
|
|
1201
|
+
change.action === "none"
|
|
1202
|
+
? "unchanged"
|
|
1203
|
+
: change.action === "create"
|
|
1204
|
+
? "create"
|
|
1205
|
+
: "modify";
|
|
1206
|
+
lines.push(truncate(` ${verb.padEnd(9)} ${change.file}`, width));
|
|
1207
|
+
for (const detail of change.details) {
|
|
1208
|
+
lines.push(truncate(` + ${detail}`, width));
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
lines.push("");
|
|
1212
|
+
lines.push(
|
|
1213
|
+
warningBar(
|
|
1214
|
+
"DESTRUCTIVE: these files are rewritten in place. Back up or commit first.",
|
|
1215
|
+
tui,
|
|
1216
|
+
),
|
|
1217
|
+
);
|
|
1218
|
+
return lines.join("\n");
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
/**
|
|
1222
|
+
* Ask before writing. Without a TTY there is nobody to ask, so the run stops
|
|
1223
|
+
* and points at `--yes` instead of blocking forever on a prompt.
|
|
1224
|
+
*/
|
|
1225
|
+
export async function confirmPlan(
|
|
1226
|
+
plan: AdoptPlan,
|
|
1227
|
+
tui: Tui,
|
|
1228
|
+
): Promise<{ ok: boolean; message?: string }> {
|
|
1229
|
+
tui.write(`${formatPlan(plan, tui)}\n`);
|
|
1230
|
+
if (!tui.isTTY) {
|
|
1231
|
+
return {
|
|
1232
|
+
ok: false,
|
|
1233
|
+
message:
|
|
1234
|
+
"Not a terminal, so there is nothing to confirm with. Re-run with --yes to apply, or --dry-run to inspect.",
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
const answer = (await tui.prompt("Apply these changes? [y/N] ")).trim();
|
|
1238
|
+
return /^y(es)?$/i.test(answer)
|
|
1239
|
+
? { ok: true }
|
|
1240
|
+
: { ok: false, message: "Aborted. Nothing was written." };
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
export type AdoptResult = {
|
|
1244
|
+
code: number;
|
|
1245
|
+
plan?: AdoptPlan;
|
|
1246
|
+
/** True when the plan was written to disk. */
|
|
1247
|
+
applied: boolean;
|
|
1248
|
+
};
|
|
1249
|
+
|
|
1250
|
+
export async function adoptCommand(
|
|
1251
|
+
args: string[],
|
|
1252
|
+
tui: Tui = terminalTui(),
|
|
1253
|
+
): Promise<AdoptResult> {
|
|
573
1254
|
let projectDir = "";
|
|
574
1255
|
let dryRun = false;
|
|
575
1256
|
let force = false;
|
|
576
|
-
|
|
577
|
-
|
|
1257
|
+
let yes = false;
|
|
1258
|
+
const fail = (message: string): AdoptResult => {
|
|
1259
|
+
console.error(message);
|
|
1260
|
+
return { code: 1, applied: false };
|
|
1261
|
+
};
|
|
1262
|
+
|
|
1263
|
+
for (const arg of args) {
|
|
578
1264
|
if (arg === "--dry-run") dryRun = true;
|
|
579
1265
|
else if (arg === "--force") force = true;
|
|
580
|
-
else if (arg
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
projectDir = arg;
|
|
585
|
-
} else {
|
|
586
|
-
console.error(`Unknown flag: ${arg}`);
|
|
587
|
-
process.exit(1);
|
|
588
|
-
}
|
|
1266
|
+
else if (arg === "--yes" || arg === "-y") yes = true;
|
|
1267
|
+
else if (arg.startsWith("-")) return fail(`Unknown flag: ${arg}`);
|
|
1268
|
+
else if (!projectDir) projectDir = arg;
|
|
1269
|
+
else return fail(`Unknown flag: ${arg}`);
|
|
589
1270
|
}
|
|
590
1271
|
|
|
591
|
-
const
|
|
1272
|
+
const start = resolve(projectDir || process.cwd());
|
|
1273
|
+
const dir = projectDir ? start : (findProjectRoot(start) ?? start);
|
|
592
1274
|
if (!existsSync(join(dir, "package.json"))) {
|
|
593
|
-
|
|
594
|
-
|
|
1275
|
+
return fail(
|
|
1276
|
+
`No package.json in ${dir} — nothing to adopt. Looked for a package.json in ${start} and every directory above it.`,
|
|
1277
|
+
);
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
const pkg = readJson<PackageJson>(join(dir, "package.json"));
|
|
1281
|
+
const detected = detectFramework(dir, pkg).framework;
|
|
1282
|
+
if (!(await hasFrontend(detected))) {
|
|
1283
|
+
const installed = await parserVersion();
|
|
1284
|
+
return fail(
|
|
1285
|
+
`${dir} is a ${detected} project, but the installed @tschk/crepuscularity-wasm${installed ? ` (${installed})` : ""} has no ${detected} template frontend.\n` +
|
|
1286
|
+
`Its dispatcher falls back to generic markup for an extension it does not know, which drops ${detected === "astro" ? "`{cond && <m/>}` / `{list.map(…)}` lowering" : "`@if` / `@for` blocks and the structural directives"} silently — so adopting against this build would produce quietly wrong pages.\n` +
|
|
1287
|
+
`Upgrade @tschk/crepuscularity-wasm to a build that carries parser/${detected}/. Nothing was written.`,
|
|
1288
|
+
);
|
|
595
1289
|
}
|
|
596
1290
|
|
|
597
1291
|
const plan = await planAdoption(dir, { force });
|
|
598
1292
|
if (plan.scan.framework === "unknown") {
|
|
599
|
-
|
|
600
|
-
`Could not identify a
|
|
1293
|
+
return fail(
|
|
1294
|
+
`Could not identify a JavaScript app in ${dir}.\n` +
|
|
1295
|
+
`Looked for: .svelte, .vue, .astro or Angular (*.component.html, *.ng.html, *.ng) templates, app/ or src/app/ (Next App Router), pages/ or src/pages/ (Next Pages Router), a next/waku/@tanstack/react-router/react-router dependency, a vite config, or a react dependency.\n` +
|
|
1296
|
+
`Nothing was written.`,
|
|
601
1297
|
);
|
|
602
|
-
process.exit(1);
|
|
603
1298
|
}
|
|
1299
|
+
|
|
1300
|
+
if (!dryRun && !yes) {
|
|
1301
|
+
const confirmed = await confirmPlan(plan, tui);
|
|
1302
|
+
if (!confirmed.ok) {
|
|
1303
|
+
tui.write(`${confirmed.message}\n`);
|
|
1304
|
+
return { code: 1, plan, applied: false };
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
|
|
604
1308
|
if (!dryRun) applyPlan(plan);
|
|
605
1309
|
console.log(formatReport(plan, dryRun));
|
|
606
|
-
return plan;
|
|
1310
|
+
return { code: 0, plan, applied: !dryRun };
|
|
607
1311
|
}
|
package/src/new.ts
CHANGED
|
@@ -33,6 +33,9 @@ export function packagePath(
|
|
|
33
33
|
const map: Record<string, string> = {
|
|
34
34
|
"@tschk/moonshine": "packages/core",
|
|
35
35
|
"@tschk/moonshine-next": "packages/adapter-next",
|
|
36
|
+
"@tschk/moonshine-react-router": "packages/adapter-react-router",
|
|
37
|
+
"@tschk/moonshine-tanstack": "packages/adapter-tanstack",
|
|
38
|
+
"@tschk/moonshine-waku": "packages/adapter-waku",
|
|
36
39
|
"@tschk/moonshine-framework": "packages/framework",
|
|
37
40
|
"@tschk/moonshine-compiler": "packages/compiler",
|
|
38
41
|
"@tschk/moonshine-server": "packages/server",
|
package/src/tui.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal helpers for destructive confirmations.
|
|
3
|
+
*
|
|
4
|
+
* Everything degrades: without a TTY there is no ANSI, and there is no prompt
|
|
5
|
+
* either — a pipe cannot answer a question, and a hung CI job is worse than a
|
|
6
|
+
* failed one.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export type Tui = {
|
|
10
|
+
/** Whether stdout is a terminal. Drives colour and whether prompting is possible. */
|
|
11
|
+
isTTY: boolean;
|
|
12
|
+
/** Usable width, clamped so narrow terminals still align. */
|
|
13
|
+
columns: number;
|
|
14
|
+
write(text: string): void;
|
|
15
|
+
/** Read one line of input. Only called when `isTTY`. */
|
|
16
|
+
prompt(question: string): Promise<string>;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const MIN_COLUMNS = 20;
|
|
20
|
+
const MAX_COLUMNS = 100;
|
|
21
|
+
|
|
22
|
+
export function clampColumns(raw: number | undefined): number {
|
|
23
|
+
if (!raw || !Number.isFinite(raw)) return 80;
|
|
24
|
+
return Math.max(MIN_COLUMNS, Math.min(MAX_COLUMNS, Math.floor(raw)));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function terminalTui(): Tui {
|
|
28
|
+
const isTTY = process.stdout.isTTY === true;
|
|
29
|
+
return {
|
|
30
|
+
isTTY,
|
|
31
|
+
columns: clampColumns(process.stdout.columns),
|
|
32
|
+
write(text) {
|
|
33
|
+
process.stdout.write(text);
|
|
34
|
+
},
|
|
35
|
+
async prompt(question) {
|
|
36
|
+
process.stdout.write(question);
|
|
37
|
+
for await (const line of console) return line;
|
|
38
|
+
return "";
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Cut `text` to `width` columns, marking the cut so nothing looks complete when it is not. */
|
|
44
|
+
export function truncate(text: string, width: number): string {
|
|
45
|
+
if (text.length <= width) return text;
|
|
46
|
+
if (width <= 1) return text.slice(0, Math.max(0, width));
|
|
47
|
+
return `${text.slice(0, width - 1)}…`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A full-width black-on-yellow bar. One line exactly, never wrapping: the text
|
|
52
|
+
* is truncated to the terminal width before the padding is added, so the bar
|
|
53
|
+
* cannot spill onto a second row and tear.
|
|
54
|
+
*/
|
|
55
|
+
export function warningBar(text: string, tui: Pick<Tui, "isTTY" | "columns">) {
|
|
56
|
+
const width = tui.columns;
|
|
57
|
+
const body = ` ${truncate(text, Math.max(0, width - 2))} `.padEnd(width, " ");
|
|
58
|
+
return tui.isTTY
|
|
59
|
+
? `\x1b[30;43m${body}\x1b[0m`
|
|
60
|
+
: `!! ${truncate(text, width - 3)}`;
|
|
61
|
+
}
|