@tschk/moonshine-cli 0.3.7 → 0.4.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.
package/src/adopt.ts CHANGED
@@ -1,1244 +1,49 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { dirname, join, relative, resolve } from "node:path";
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";
19
- import type { RouteConvention } from "@tschk/moonshine-compiler";
20
- import { detectMoonshineRoot, packagePath } from "./new.js";
21
- import { terminalTui, truncate, warningBar, type Tui } from "./tui.js";
22
-
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
1
  /**
38
- * Frameworks adopted by compiling their templates to View IR, not by aliasing
39
- * imports, and the globs whose files crepuscularity's dispatcher claims.
2
+ * `moonshine adopt` — the command itself.
40
3
  *
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
- }
156
-
157
- export type NextImport = {
158
- /** Project-relative file holding the import. */
159
- file: string;
160
- specifier: string;
161
- /** Whether `@tschk/moonshine-next` implements this specifier. */
162
- aliasable: boolean;
163
- };
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
-
184
- export type AdoptScan = {
185
- projectDir: string;
186
- framework: Framework;
187
- /** Project-relative route directory, when one was found. */
188
- routesDir?: string;
189
- convention?: RouteConvention;
190
- routes: { path: string; file: string }[];
191
- /** Templates compiled to View IR, for the Svelte and Vue paths. */
192
- templates: TemplateFile[];
193
- imports: NextImport[];
194
- conventions: string[];
195
- /** Blunt list of what adoption does not carry over. */
196
- manual: string[];
197
- };
198
-
199
- export type AdoptChange = {
200
- file: string;
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[];
206
- /** Already true before this run; used to keep repeat runs honest. */
207
- alreadyApplied: boolean;
208
- contents?: string;
209
- };
210
-
211
- export type AdoptPlan = {
212
- scan: AdoptScan;
213
- changes: AdoptChange[];
214
- /** Source files whose imports had to be edited because no alias covered them. */
215
- rewritten: string[];
216
- };
217
-
218
- const SOURCE_GLOB = "**/*.{ts,tsx,js,jsx,mjs}";
219
- const IGNORED = ["node_modules/", ".next/", ".moonshine/", "dist/", "build/"];
220
-
221
- const RUNTIME_DEPS = [
222
- "@tschk/moonshine",
223
- "@tschk/moonshine-framework",
224
- "@tschk/moonshine-compiler",
225
- "@tschk/moonshine-server",
226
- "@tschk/moonshine-react",
227
- "@tschk/moonshine-deploy-bun",
228
- ] as const;
229
-
230
- function toPosix(p: string): string {
231
- return p.replaceAll("\\", "/");
232
- }
233
-
234
- function ignored(rel: string): boolean {
235
- return IGNORED.some((dir) => rel === dir || rel.includes(dir));
236
- }
237
-
238
- function readJson<T>(path: string): T | undefined {
239
- if (!existsSync(path)) return undefined;
240
- try {
241
- return JSON.parse(readFileSync(path, "utf8")) as T;
242
- } catch {
243
- return undefined;
244
- }
245
- }
246
-
247
- function sourceFiles(projectDir: string): string[] {
248
- const found: string[] = [];
249
- for (const entry of new Bun.Glob(SOURCE_GLOB).scanSync(projectDir)) {
250
- const rel = toPosix(entry);
251
- if (!ignored(rel)) found.push(rel);
252
- }
253
- return found.sort();
254
- }
255
-
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;
264
- const found: NextImport[] = [];
265
- for (const file of files) {
266
- const source = readFileSync(join(projectDir, file), "utf8");
267
- for (const match of source.matchAll(pattern)) {
268
- const specifier = match[1]!;
269
- if (!adapter.imports.test(specifier)) continue;
270
- // A bare string is only an import when a module keyword introduces it.
271
- const before = source.slice(Math.max(0, match.index - 40), match.index);
272
- if (!/(?:from|import|require)\s*\(?\s*$/.test(before)) continue;
273
- found.push({
274
- file,
275
- specifier,
276
- aliasable: specifier in adapter.aliases,
277
- });
278
- }
279
- }
280
- return found;
281
- }
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
-
386
- function detectFramework(
387
- projectDir: string,
388
- pkg: PackageJson | undefined,
389
- ): { framework: Framework; routesDir?: string; convention?: RouteConvention } {
390
- const deps = allDeps(pkg);
391
- const template = detectTemplateFramework(projectDir, deps);
392
- if (template) return template;
393
- for (const dir of ["app", "src/app"]) {
394
- if (
395
- existsSync(join(projectDir, dir, "page.tsx")) ||
396
- existsSync(join(projectDir, dir, "page.jsx")) ||
397
- existsSync(join(projectDir, dir, "layout.tsx"))
398
- ) {
399
- return { framework: "next-app", routesDir: dir, convention: "next-app" };
400
- }
401
- }
402
- for (const dir of ["pages", "src/pages"]) {
403
- if (existsSync(join(projectDir, dir))) {
404
- return {
405
- framework: "next-pages",
406
- routesDir: dir,
407
- convention: "next-pages",
408
- };
409
- }
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
- }
434
- if (
435
- existsSync(join(projectDir, "vite.config.ts")) ||
436
- existsSync(join(projectDir, "vite.config.js"))
437
- ) {
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.
4
+ * The work is split by what it is about, because this file grew to 1300 lines
5
+ * and stopped being navigable:
446
6
  *
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;
464
- }
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;
612
- }
613
-
614
- /** Next conventions present in the tree, named the way the user named them. */
615
- function findConventions(projectDir: string, files: string[]): string[] {
616
- const seen: string[] = [];
617
- for (const candidate of [
618
- "next.config.js",
619
- "next.config.mjs",
620
- "next.config.ts",
621
- "middleware.ts",
622
- "middleware.js",
623
- "src/middleware.ts",
624
- "instrumentation.ts",
625
- ]) {
626
- if (existsSync(join(projectDir, candidate))) seen.push(candidate);
627
- }
628
- for (const file of files) {
629
- const base = file.split("/").pop()!;
630
- const stem = base.replace(/\.[jt]sx?$/, "");
631
- if (
632
- [
633
- "layout",
634
- "route",
635
- "loading",
636
- "template",
637
- "not-found",
638
- "error",
639
- "default",
640
- ].includes(stem)
641
- ) {
642
- seen.push(file);
643
- }
644
- }
645
- return seen;
646
- }
647
-
648
- /** Source-level Next features with no moonshine equivalent yet. */
649
- function findManualWork(
650
- projectDir: string,
651
- files: string[],
652
- scan: Pick<AdoptScan, "framework" | "routesDir">,
653
- ): string[] {
654
- const manual: string[] = [];
655
- const note = (text: string) => {
656
- if (!manual.includes(text)) manual.push(text);
657
- };
658
-
659
- for (const candidate of [
660
- "middleware.ts",
661
- "middleware.js",
662
- "src/middleware.ts",
663
- ]) {
664
- if (existsSync(join(projectDir, candidate))) {
665
- note(
666
- `${candidate}: Next middleware does not run. Moonshine has no edge middleware phase — port it to a route loader or a Bun server wrapper.`,
667
- );
668
- }
669
- }
670
- for (const candidate of [
671
- "next.config.js",
672
- "next.config.mjs",
673
- "next.config.ts",
674
- ]) {
675
- if (existsSync(join(projectDir, candidate))) {
676
- note(
677
- `${candidate}: not read. redirects/rewrites/headers/images/webpack options are all ignored.`,
678
- );
679
- }
680
- }
681
-
682
- for (const file of files) {
683
- const source = readFileSync(join(projectDir, file), "utf8");
684
- const stem = file
685
- .split("/")
686
- .pop()!
687
- .replace(/\.[jt]sx?$/, "");
688
-
689
- if (
690
- /export\s+(?:const|async\s+function|function)\s+generateMetadata/.test(
691
- source,
692
- )
693
- ) {
694
- note(
695
- `${file}: generateMetadata() is not called. Moonshine emits its own <head>; move tags into a layout.`,
696
- );
697
- } else if (/export\s+const\s+metadata\b/.test(source)) {
698
- note(
699
- `${file}: the metadata export is not read. Moonshine emits its own <head>; move tags into a layout.`,
700
- );
701
- }
702
- if (/export\s+const\s+revalidate\b/.test(source)) {
703
- note(`${file}: ISR (export const revalidate) is not implemented.`);
704
- }
705
- if (/^\s*["']use server["']/m.test(source)) {
706
- note(`${file}: server actions ("use server") are not supported.`);
707
- }
708
- if (/export\s+default\s+async\s+function/.test(source) && stem === "page") {
709
- note(
710
- `${file}: async server component. Moonshine renders with react-dom/server, which cannot await a component — move the fetch into a loader.`,
711
- );
712
- }
713
- if (stem === "layout" && /<html\b/.test(source)) {
714
- note(
715
- `${file}: returns <html>/<body>, but moonshine already emits the document shell. Return a fragment instead.`,
716
- );
717
- }
718
- if (["loading", "template", "not-found", "default"].includes(stem)) {
719
- note(`${file}: ${stem}.tsx has no moonshine equivalent and is ignored.`);
720
- }
721
- if (/getServerSideProps|getStaticProps|getStaticPaths/.test(source)) {
722
- note(
723
- `${file}: getServerSideProps/getStaticProps are not called. Rename to a moonshine loader.`,
724
- );
725
- }
726
- }
727
-
728
- if (scan.routesDir) {
729
- for (const file of files) {
730
- if (!file.startsWith(`${scan.routesDir}/`)) continue;
731
- const segments = file.split("/");
732
- if (segments.some((s) => s.startsWith("@"))) {
733
- note(`${file}: parallel routes (@slot) are dropped.`);
734
- }
735
- if (segments.some((s) => /^\(\.+\)/.test(s))) {
736
- note(`${file}: intercepting routes are dropped.`);
737
- }
738
- }
739
- }
740
-
741
- return manual;
742
- }
743
-
744
- /** Behavioural gaps in the reimplementations the app actually imports. */
745
- const ALIAS_CAVEATS: Readonly<Record<string, string>> = {
746
- "next/image":
747
- "next/image renders a plain <img>: no resizing, no AVIF/WebP negotiation, no blur placeholder.",
748
- "next/link":
749
- "next/link navigates through the moonshine router; prefetch is a browser <link rel=prefetch> hint, not an RSC payload warm-up.",
750
- "next/headers":
751
- "next/headers reads the moonshine request context; cookie mutations do not propagate to the response.",
752
- "next/font/google":
753
- "next/font/google emits a Google Fonts <link> instead of self-hosting; call fontLinks() in your layout head or the family never loads.",
754
- "next/dynamic":
755
- "next/dynamic lazy-loads on the client only; `ssr: false` is the effective behaviour either way.",
756
- };
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
-
806
- export async function scanProject(projectDir: string): Promise<AdoptScan> {
807
- const dir = resolve(projectDir);
808
- const pkg = readJson<PackageJson>(join(dir, "package.json"));
809
- const files = sourceFiles(dir);
810
- const detected = detectFramework(dir, pkg);
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
- : [];
817
-
818
- const routes: { path: string; file: string }[] = [];
819
- if (
820
- detected.routesDir &&
821
- detected.convention &&
822
- existsSync(join(dir, detected.routesDir))
823
- ) {
824
- const { discoverRoutes } = await import("@tschk/moonshine-compiler");
825
- const discovered = await discoverRoutes({
826
- routesDir: join(dir, detected.routesDir),
827
- convention: detected.convention,
828
- });
829
- for (const route of discovered) {
830
- routes.push({
831
- path: route.path,
832
- file: toPosix(relative(dir, route.file)),
833
- });
834
- }
835
- }
836
-
837
- return {
838
- projectDir: dir,
839
- framework: detected.framework,
840
- ...(detected.routesDir && { routesDir: detected.routesDir }),
841
- ...(detected.convention && { convention: detected.convention }),
842
- routes,
843
- templates,
844
- imports,
845
- conventions: findConventions(dir, files),
846
- manual: [
847
- ...templateManualWork(detected.framework, templates),
848
- ...findManualWork(dir, files, detected),
849
- ...[...new Set(imports.map((i) => i.specifier))]
850
- .sort()
851
- .map((s) => ALIAS_CAVEATS[s])
852
- .filter((note): note is string => note !== undefined),
853
- ],
854
- };
855
- }
856
-
857
- /**
858
- * Where the project will find `@tschk/moonshine-next` on disk. Only installed
859
- * `node_modules` trees count: adopt normally runs before `bun install`, and
860
- * `Bun.resolveSync` would then answer with whatever version happens to sit in
861
- * the global module cache — a copy that can predate the adapter's current
862
- * surface, leaving specifiers pointing at files that do not exist.
863
- */
864
- function adapterDir(projectDir: string, pkg: string): string {
865
- const parts = pkg.split("/");
866
- let dir = projectDir;
867
- for (;;) {
868
- const candidate = join(dir, "node_modules", ...parts);
869
- if (existsSync(candidate)) return candidate;
870
- const parent = dirname(dir);
871
- if (parent === dir) break;
872
- dir = parent;
873
- }
874
- return join(projectDir, "node_modules", ...parts);
875
- }
876
-
877
- /**
878
- * `compilerOptions.paths` entries pointing every aliasable `next/*` specifier
879
- * at a real file. Bun applies tsconfig paths in both `bun run` and `Bun.build`,
880
- * but only for relative targets — a bare package specifier is not remapped.
881
- */
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)!);
890
- const paths: Record<string, string[]> = {};
891
- for (const specifier of Object.keys(adapter.aliases)) {
892
- const source = adapter.resolveAlias(specifier);
893
- if (!source) continue;
894
- const file = join(pkgDir, "src", relative(srcDir, source));
895
- const rel = toPosix(relative(projectDir, file));
896
- paths[specifier] = [rel.startsWith(".") ? rel : `./${rel}`];
897
- }
898
- return paths;
899
- }
900
-
901
- function planTsconfig(scan: AdoptScan): AdoptChange {
902
- const path = join(scan.projectDir, "tsconfig.json");
903
- const existing =
904
- readJson<{ compilerOptions?: Record<string, unknown> }>(path) ?? {};
905
- const compilerOptions = { ...existing.compilerOptions };
906
- const previous = (compilerOptions.paths ?? {}) as Record<string, string[]>;
907
- const wanted = aliasPaths(scan.projectDir, scan.framework);
908
- const paths = { ...previous, ...wanted };
909
- compilerOptions.baseUrl = compilerOptions.baseUrl ?? ".";
910
- compilerOptions.jsx = compilerOptions.jsx ?? "react-jsx";
911
- compilerOptions.paths = paths;
912
-
913
- const alreadyApplied = Object.entries(wanted).every(
914
- ([key, value]) => previous[key]?.[0] === value[0],
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
- }
930
-
931
- return {
932
- file: "tsconfig.json",
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}`,
940
- alreadyApplied,
941
- contents: JSON.stringify({ ...existing, compilerOptions }, null, 2) + "\n",
942
- };
943
- }
944
-
945
- function planConfig(scan: AdoptScan, force: boolean): AdoptChange {
946
- const path = join(scan.projectDir, "moonshine.config.ts");
947
- const exists = existsSync(path);
948
- const entries: Record<string, unknown> = {
949
- runtime: "bun",
950
- adapter: "bun",
951
- renderer: "react",
952
- ...(scan.routesDir && { routesDir: scan.routesDir }),
953
- ...(scan.convention && { convention: scan.convention }),
954
- };
955
- const contents = `import { defineConfig } from "@tschk/moonshine-framework";
956
-
957
- export default defineConfig(${JSON.stringify(entries, null, 2)});
958
- `;
959
- const current = exists ? readFileSync(path, "utf8") : "";
960
- const alreadyApplied = exists && (current === contents || !force);
961
- return {
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
- ),
969
- summary: alreadyApplied
970
- ? "already present, left untouched"
971
- : `${exists ? "rewritten" : "created"} (routesDir ${scan.routesDir ?? "src/routes"}, convention ${scan.convention ?? "moonshine"})`,
972
- alreadyApplied,
973
- ...(alreadyApplied ? {} : { contents }),
974
- };
975
- }
976
-
977
- function planPackageJson(scan: AdoptScan): AdoptChange {
978
- const path = join(scan.projectDir, "package.json");
979
- const pkg =
980
- readJson<{
981
- dependencies?: Record<string, string>;
982
- scripts?: Record<string, string>;
983
- }>(path) ?? {};
984
- const root = detectMoonshineRoot();
985
- const version = `^${cliVersion()}`;
986
-
987
- const dependencies = { ...pkg.dependencies };
988
- const added: string[] = [];
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[]) {
996
- if (dependencies[name]) continue;
997
- const spec = packagePath(name, root, version);
998
- if (!spec) continue;
999
- dependencies[name] = spec;
1000
- added.push(name);
1001
- }
1002
-
1003
- const scripts = { ...pkg.scripts };
1004
- const repointed: string[] = [];
1005
- const mapping: Record<string, string> = {
1006
- dev: "moonshine dev",
1007
- build: "moonshine build",
1008
- start: "moonshine preview",
1009
- };
1010
- for (const [key, value] of Object.entries(mapping)) {
1011
- const current = scripts[key];
1012
- if (
1013
- current !== undefined &&
1014
- !/^(next|vite|remix|react-router|waku)(\s|$)/.test(current)
1015
- ) {
1016
- continue;
1017
- }
1018
- if (current === value) continue;
1019
- scripts[key] = value;
1020
- repointed.push(key);
1021
- }
1022
-
1023
- const alreadyApplied = added.length === 0 && repointed.length === 0;
1024
- const parts: string[] = [];
1025
- if (added.length) parts.push(`+${added.length} dependencies`);
1026
- if (repointed.length)
1027
- parts.push(`scripts ${repointed.join(", ")} → moonshine`);
1028
-
1029
- return {
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
- ],
1038
- summary: alreadyApplied ? "already adopted" : parts.join(", "),
1039
- alreadyApplied,
1040
- contents: JSON.stringify({ ...pkg, dependencies, scripts }, null, 2) + "\n",
1041
- };
1042
- }
1043
-
1044
- function cliVersion(): string {
1045
- const pkg = readJson<{ version?: string }>(
1046
- join(import.meta.dir, "..", "package.json"),
1047
- );
1048
- return pkg?.version ?? "0.3.2";
1049
- }
1050
-
1051
- export async function planAdoption(
1052
- projectDir: string,
1053
- options: { force?: boolean } = {},
1054
- ): Promise<AdoptPlan> {
1055
- const scan = await scanProject(projectDir);
1056
- return {
1057
- scan,
1058
- changes: [
1059
- planTsconfig(scan),
1060
- planConfig(scan, options.force ?? false),
1061
- planPackageJson(scan),
1062
- ...planTemplateRoutes(scan),
1063
- ],
1064
- // Aliasing covers every specifier the adapter implements, so nothing in the
1065
- // user's source is edited. Unaliasable specifiers are reported, not rewritten,
1066
- // because there is no moonshine implementation to rewrite them to.
1067
- rewritten: [],
1068
- };
1069
- }
1070
-
1071
- export function applyPlan(plan: AdoptPlan): void {
1072
- for (const change of plan.changes) {
1073
- if (change.contents === undefined) continue;
1074
- const path = join(plan.scan.projectDir, change.file);
1075
- mkdirSync(dirname(path), { recursive: true });
1076
- writeFileSync(path, change.contents);
1077
- }
1078
- }
1079
-
1080
- function pluralize(n: number, word: string): string {
1081
- return `${n} ${word}${n === 1 ? "" : "s"}`;
1082
- }
1083
-
1084
- export function formatReport(plan: AdoptPlan, dryRun: boolean): string {
1085
- const { scan } = plan;
1086
- const lines: string[] = [];
1087
- const push = (text = "") => lines.push(text);
1088
-
1089
- push(`moonshine adopt — ${scan.projectDir}${dryRun ? " (dry run)" : ""}`);
1090
- push();
1091
- push("SCAN");
1092
- push(` framework ${scan.framework}`);
1093
- push(` routes dir ${scan.routesDir ?? "(none found)"}`);
1094
- push(` routes ${scan.routes.length}`);
1095
- for (const route of scan.routes.slice(0, 12)) {
1096
- push(` ${route.path.padEnd(24)} ${route.file}`);
1097
- }
1098
- if (scan.routes.length > 12) push(` … ${scan.routes.length - 12} more`);
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
-
1117
- const bySpecifier = new Map<string, NextImport[]>();
1118
- for (const imp of scan.imports) {
1119
- const list = bySpecifier.get(imp.specifier) ?? [];
1120
- list.push(imp);
1121
- bySpecifier.set(imp.specifier, list);
1122
- }
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
- }
1128
- for (const [specifier, list] of [...bySpecifier].sort()) {
1129
- const mark = list[0]!.aliasable ? "alias" : "NO IMPL";
1130
- push(
1131
- ` ${specifier.padEnd(24)} ${mark.padEnd(8)} ${list.map((l) => l.file).join(", ")}`,
1132
- );
1133
- }
1134
- if (scan.conventions.length) {
1135
- push(` conventions ${scan.conventions.join(", ")}`);
1136
- }
1137
-
1138
- push();
1139
- push(dryRun ? "REWRITE (planned)" : "REWRITE");
1140
- const column = Math.max(...plan.changes.map((c) => c.file.length), 18);
1141
- for (const change of plan.changes) {
1142
- const mark = change.alreadyApplied ? "no-op" : dryRun ? "would" : "wrote";
1143
- push(` ${mark.padEnd(6)} ${change.file.padEnd(column)} ${change.summary}`);
1144
- }
1145
-
1146
- const aliased = scan.imports.filter((i) => i.aliasable);
1147
- const unaliasable = scan.imports.filter((i) => !i.aliasable);
1148
-
1149
- push();
1150
- push("SCORECARD");
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
- }
1162
- push(` rewritten ${pluralize(plan.rewritten.length, "source file")}`);
1163
- for (const file of plan.rewritten) push(` ${file}`);
1164
-
1165
- const blockers = [
1166
- ...unaliasable.map(
1167
- (i) =>
1168
- `${i.file}: imports ${i.specifier}, which @tschk/moonshine-next does not implement. This import will not resolve.`,
1169
- ),
1170
- ...scan.manual,
1171
- ];
1172
- push(` cannot automate ${blockers.length}`);
1173
- for (const item of blockers) push(` - ${item}`);
1174
-
1175
- push();
1176
- if (dryRun) {
1177
- push("Nothing was written. Drop --dry-run to apply.");
1178
- } else {
1179
- push("Next:");
1180
- push(" bun install");
1181
- push(" bunx moonshine build && bunx moonshine preview");
1182
- }
1183
- return lines.join("\n");
1184
- }
1185
-
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.
7
+ * frameworks which hosts moonshine knows, and how their specifiers map
8
+ * types the shapes a scan and a plan travel in
9
+ * scan what is on disk: sources, imports, framework detection
10
+ * conventions host conventions present in the tree, named as the user named them
11
+ * templates non-React templates compiled through the parser into route modules
12
+ * gaps what does not carry over, per host and per template
13
+ * project one scan of a project directory, composed from the above
14
+ * plan the changes adoption would make
15
+ * report how a plan is shown, and confirmed
16
+ *
17
+ * The public surface is re-exported here so `bin/moonshine.ts` and the tests
18
+ * keep one import site for the command and its plan/report primitives.
1224
19
  */
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
- }
20
+ import { existsSync } from "node:fs";
21
+ import { join, resolve } from "node:path";
22
+ import { hasFrontend, parserVersion } from "./adopt/frameworks.js";
23
+ import {
24
+ detectFramework,
25
+ findProjectRoot,
26
+ readJson,
27
+ type PackageJson,
28
+ } from "./adopt/scan.js";
29
+ import { planAdoption, applyPlan } from "./adopt/plan.js";
30
+ import { formatReport, confirmPlan } from "./adopt/report.js";
31
+ import { terminalTui, type Tui } from "./tui.js";
32
+ import type { AdoptPlan } from "./adopt/types.js";
33
+
34
+ export type {
35
+ Framework,
36
+ NextImport,
37
+ TemplateFile,
38
+ AdoptScan,
39
+ AdoptChange,
40
+ AdoptPlan,
41
+ } from "./adopt/types.js";
42
+ export { hasFrontend } from "./adopt/frameworks.js";
43
+ export { findProjectRoot } from "./adopt/scan.js";
44
+ export { scanProject } from "./adopt/project.js";
45
+ export { aliasPaths, planAdoption, applyPlan } from "./adopt/plan.js";
46
+ export { formatReport, formatPlan, confirmPlan } from "./adopt/report.js";
1242
47
 
1243
48
  export type AdoptResult = {
1244
49
  code: number;