@tschk/moonshine-cli 0.4.1 → 0.4.49

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.
@@ -1,6 +1,8 @@
1
1
  /** Non-React templates, compiled through the parser into route modules. */
2
+ import { existsSync } from "node:fs";
2
3
  import { readFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
+ import { dirname, join, relative, sep } from "node:path";
5
+ import { emitCrepusSource, requireCrepusCompiler } from "../compile.js";
4
6
  import type { Framework } from "./frameworks.js";
5
7
  import type { AdoptChange, AdoptScan, TemplateFile } from "./types.js";
6
8
  import {
@@ -33,7 +35,14 @@ export function templateRoute(
33
35
  const stem = base.replace(/\.(svelte|vue|astro)$/, "");
34
36
  const rootIndex = segments.findIndex((s) => s === "routes" || s === "pages");
35
37
 
36
- if (stem.startsWith("+page")) {
38
+ if (
39
+ framework === "svelte" &&
40
+ rootIndex !== -1 &&
41
+ !/^\+page(?:@.*)?$/.test(stem)
42
+ ) {
43
+ return undefined;
44
+ }
45
+ if (/^\+page(?:@.*)?$/.test(stem)) {
37
46
  if (rootIndex === -1) return "/";
38
47
  const rest = segments
39
48
  .slice(rootIndex + 1)
@@ -53,7 +62,12 @@ export function templateRoute(
53
62
 
54
63
  export function generatedModule(route: string): string {
55
64
  const rest = route.replace(/^\//, "");
56
- return `${GENERATED_ROUTES}/${rest === "" ? "index" : rest}.tsx`;
65
+ const name = rest.split("/").at(-1) ?? "";
66
+ const reserved =
67
+ name === "index" ||
68
+ name.startsWith("+") ||
69
+ /\.(data|server|client)$/.test(name);
70
+ return `${GENERATED_ROUTES}/${rest === "" ? "index" : reserved ? `${rest}/index` : rest}.ts`;
57
71
  }
58
72
 
59
73
  /**
@@ -62,26 +76,24 @@ export function generatedModule(route: string): string {
62
76
  * this is the whole of its output — mounting it stays the user's decision.
63
77
  */
64
78
  export function componentModule(file: string): string {
65
- const slug = file
66
- .replace(/\.(svelte|vue|astro|ng)$/, "")
67
- .replace(/\.(component|ng)\.html$/, "")
68
- .replace(/[^a-zA-Z0-9/-]/g, "-");
69
- return `${GENERATED_COMPONENTS}/${slug}.tsx`;
79
+ return `${GENERATED_COMPONENTS}/${file}.ssr.ts`;
70
80
  }
71
81
 
72
82
  /**
73
83
  * Compile every template through the crepuscularity frontend its filename
74
84
  * selects. A template that does not compile is recorded with the parser's own
75
- * message: unsupported constructs are hard errors, so nothing is silently
76
- * dropped from the page.
85
+ * message. Native emission rejects unsupported IR; accepted markup still needs
86
+ * a fidelity review, especially forms and accessibility.
77
87
  */
78
88
  export async function compileTemplates(
79
89
  projectDir: string,
80
90
  framework: Framework,
81
91
  globs: readonly string[],
92
+ compiler?: string,
82
93
  ): Promise<TemplateFile[]> {
83
- const { parseTemplate } = await import("@tschk/crepuscularity-wasm");
84
94
  const files = templateFiles(projectDir, globs);
95
+ if (files.length === 0) return [];
96
+ const executable = requireCrepusCompiler(compiler);
85
97
 
86
98
  const taken = new Set<string>();
87
99
 
@@ -95,86 +107,152 @@ export async function compileTemplates(
95
107
  return { file, entry };
96
108
  });
97
109
 
98
- const templates = await Promise.all(
99
- jobs.map(async ({ file, entry }) => {
100
- try {
101
- const content = await readFile(join(projectDir, file), "utf8");
102
- const ir = parseTemplate(content, file.split("/").pop()!);
103
- entry.ok = true;
110
+ // Reuse the prior adopter's .tsx path without leaving duplicate route IDs.
111
+ for (const { entry } of jobs) {
112
+ if (entry.route === undefined) continue;
113
+ const current = generatedModule(entry.route);
114
+ const legacy = current.slice(0, -3) + ".tsx";
115
+ const hasCurrent = existsSync(join(projectDir, current));
116
+ const hasLegacy = existsSync(join(projectDir, legacy));
117
+ if (hasCurrent && hasLegacy)
118
+ throw new Error(
119
+ `Conflicting generated route files: ${current} and ${legacy}; resolve the duplicate before adopting`,
120
+ );
121
+ entry.generated = hasLegacy ? legacy : current;
122
+ }
123
+ const planned = new Set<string>();
124
+ for (const { entry } of jobs) {
125
+ const outputs = [
126
+ componentModule(entry.file),
127
+ ...(entry.route !== undefined ? [entry.generated!] : []),
128
+ ];
129
+ for (const output of outputs) {
130
+ if (planned.has(output))
131
+ throw new Error(`Conflicting planned output path: ${output}`);
132
+ planned.add(output);
133
+ }
134
+ }
135
+ for (const { entry } of jobs) {
136
+ if (entry.route === undefined) continue;
137
+ const rest = entry.route.replace(/^\//, "");
138
+ const flat = `${GENERATED_ROUTES}/${rest === "" ? "index" : rest}.ts`;
139
+ const current = generatedModule(entry.route);
140
+ if (flat === current) continue;
141
+ for (const previous of [flat, flat.slice(0, -3) + ".tsx"]) {
142
+ if (existsSync(join(projectDir, previous)) && !planned.has(previous)) {
143
+ throw new Error(
144
+ `Unsafe legacy generated route ${previous}; retire it manually before adopting ${entry.route} at ${current}`,
145
+ );
146
+ }
147
+ }
148
+ }
149
+ const templates: TemplateFile[] = [];
150
+ for (const { file, entry } of jobs) {
151
+ try {
152
+ const { source, ir, graph } = await emitCrepusSource(
153
+ join(projectDir, file),
154
+ "moonshine-ssr",
155
+ executable,
156
+ );
157
+ if (graph)
158
+ throw new Error(
159
+ "Module graph adoption is not supported; use moonshine compile for authored modules",
160
+ );
161
+ entry.ok = true;
162
+ entry.source = source;
163
+ entry.component = componentModule(file);
164
+ if (ir) {
104
165
  entry.nodes = countNodes(ir.root ?? []);
105
- entry.ir = ir;
106
166
  entry.irVersion = ir.version;
107
- entry.generated =
108
- entry.route !== undefined
109
- ? generatedModule(entry.route)
110
- : componentModule(file);
111
- } catch (error) {
112
- entry.error = error instanceof Error ? error.message : String(error);
113
- delete entry.route;
114
167
  }
115
- return entry;
116
- }),
117
- );
168
+ if (entry.route === undefined) entry.generated = entry.component;
169
+ } catch (error) {
170
+ if (
171
+ entry.route !== undefined &&
172
+ entry.generated &&
173
+ existsSync(join(projectDir, entry.generated))
174
+ ) {
175
+ throw new Error(
176
+ `Cannot replace existing generated route ${entry.generated}: ${error instanceof Error ? error.message : String(error)}; resolve the failed template before adopting`,
177
+ { cause: error },
178
+ );
179
+ }
180
+ entry.ok = false;
181
+ delete entry.generated;
182
+ entry.error = error instanceof Error ? error.message : String(error);
183
+ delete entry.route;
184
+ }
185
+ templates.push(entry);
186
+ }
118
187
 
119
188
  return templates;
120
189
  }
121
190
 
122
- /** Modules generated from the templates: IR in, React elements out. */
191
+ /** Native compiler bytes stay unchanged; route wrappers expose only explicit request data. */
123
192
  export async function planTemplateRoutes(
124
193
  scan: AdoptScan,
125
194
  ): Promise<AdoptChange[]> {
126
- const changes: AdoptChange[] = [];
127
- const promises = scan.templates.map(async (template) => {
128
- if (!template.generated) return;
129
- const path = join(scan.projectDir, template.generated);
130
- const name = template.route ? "Route" : "Component";
131
- 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.
132
- import { renderCrepusIr, type CrepusIr } from "@tschk/crepus-moonshine";
195
+ const files: Array<{ file: string; contents: string; summary: string }> = [];
196
+ for (const template of scan.templates) {
197
+ if (
198
+ !template.generated ||
199
+ !template.component ||
200
+ template.source === undefined
201
+ )
202
+ continue;
203
+ files.push({
204
+ file: template.component,
205
+ contents: template.source,
206
+ summary: `native SSR component from ${template.file}`,
207
+ });
208
+ if (template.route !== undefined) {
209
+ // Route wrappers may be nested; derive their relative component path.
210
+ const relativePath = relative(
211
+ dirname(template.generated),
212
+ template.component,
213
+ )
214
+ .split(sep)
215
+ .join("/");
216
+ files.push({
217
+ file: template.generated,
218
+ summary: `SSR route ${template.route} from ${template.file}`,
219
+ contents: `// Generated by moonshine adopt. Port template state/handlers explicitly; scripts are not executed.
220
+ import Component from ${JSON.stringify(relativePath.startsWith(".") ? relativePath : "./" + relativePath)};
133
221
 
134
- const ir = ${JSON.stringify(template.ir, null, 2)} as CrepusIr;
135
-
136
- export default function ${name}() {
137
- return renderCrepusIr(ir);
222
+ export default function Route({ params, data }: { params: Record<string, string>; data: unknown }) {
223
+ return Component({ scope: { params, data } });
138
224
  }
139
- `;
140
-
141
- let existingContent: string | null = null;
142
- let exists = false;
143
- try {
144
- existingContent = await readFile(path, "utf8");
145
- exists = true;
146
- } catch (err: any) {
147
- if (err.code !== "ENOENT") {
148
- throw err;
149
- }
150
- }
151
-
152
- const alreadyApplied = exists && existingContent === contents;
153
- const what = template.route
154
- ? `route ${template.route}`
155
- : "unmounted component";
156
- return {
157
- file: template.generated,
158
- action: alreadyApplied ? "none" : exists ? "modify" : "create",
159
- details: alreadyApplied
160
- ? []
161
- : [
162
- `${what} renders ${template.file} (${template.nodes ?? 0} View IR nodes)`,
163
- ],
164
- summary: alreadyApplied
165
- ? "already generated"
166
- : `${exists ? "regenerated" : "generated"} ${what} from ${template.file}`,
167
- alreadyApplied,
168
- ...(alreadyApplied ? {} : { contents }),
169
- } as AdoptChange;
170
- });
171
-
172
- const results = await Promise.all(promises);
173
- for (const change of results) {
174
- if (change) {
175
- changes.push(change);
225
+ `,
226
+ });
176
227
  }
177
228
  }
178
-
179
- return changes;
229
+ const outputs = new Set<string>();
230
+ for (const { file } of files) {
231
+ if (outputs.has(file))
232
+ throw new Error(`Conflicting planned output path: ${file}`);
233
+ outputs.add(file);
234
+ }
235
+ return Promise.all(
236
+ files.map(async ({ file, contents, summary }) => {
237
+ let existing: string | undefined;
238
+ try {
239
+ existing = await readFile(join(scan.projectDir, file), "utf8");
240
+ } catch (error) {
241
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
242
+ }
243
+ const alreadyApplied = existing === contents;
244
+ return {
245
+ file,
246
+ action: alreadyApplied
247
+ ? "none"
248
+ : existing === undefined
249
+ ? "create"
250
+ : "modify",
251
+ summary: alreadyApplied ? "already generated" : summary,
252
+ details: alreadyApplied ? [] : [summary],
253
+ alreadyApplied,
254
+ ...(alreadyApplied ? {} : { contents }),
255
+ } as AdoptChange;
256
+ }),
257
+ );
180
258
  }
@@ -13,7 +13,7 @@ export type NextImport = {
13
13
  };
14
14
 
15
15
  export type TemplateFile = {
16
- /** Project-relative `.svelte` / `.vue` file. */
16
+ /** Project-relative frontend template file. */
17
17
  file: string;
18
18
  /** URL path this template becomes, when it maps to one. */
19
19
  route?: string;
@@ -23,8 +23,11 @@ export type TemplateFile = {
23
23
  ok: boolean;
24
24
  /** View IR nodes produced. */
25
25
  nodes?: number;
26
- /** The compiled View IR, embedded in the generated route module. */
26
+ /** Legacy parsed View IR; native adoption stores emitted source instead. */
27
27
  ir?: unknown;
28
+ /** Unchanged native SSR compiler output. */
29
+ source?: string;
30
+ component?: string;
28
31
  /** IR schema version the parser emitted. */
29
32
  irVersion?: number;
30
33
  /** Parse error, verbatim. Unsupported constructs are errors, not silent drops. */
@@ -38,7 +41,7 @@ export type AdoptScan = {
38
41
  routesDir?: string;
39
42
  convention?: RouteConvention;
40
43
  routes: { path: string; file: string }[];
41
- /** Templates compiled to View IR, for the Svelte and Vue paths. */
44
+ /** Templates emitted as native SSR components for non-React frontends. */
42
45
  templates: TemplateFile[];
43
46
  imports: NextImport[];
44
47
  conventions: string[];
package/src/adopt.ts CHANGED
@@ -19,13 +19,7 @@
19
19
  */
20
20
  import { existsSync } from "node:fs";
21
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";
22
+ import { findProjectRoot } from "./adopt/scan.js";
29
23
  import { planAdoption, applyPlan } from "./adopt/plan.js";
30
24
  import { formatReport, confirmPlan } from "./adopt/report.js";
31
25
  import { terminalTui, type Tui } from "./tui.js";
@@ -60,12 +54,20 @@ export async function adoptCommand(
60
54
  let dryRun = false;
61
55
  let force = false;
62
56
  let yes = false;
57
+ let compiler: string | undefined;
63
58
  const fail = (message: string): AdoptResult => {
64
59
  console.error(message);
65
60
  return { code: 1, applied: false };
66
61
  };
67
62
 
68
- for (const arg of args) {
63
+ for (let i = 0; i < args.length; i++) {
64
+ const arg = args[i]!;
65
+ if (arg === "--compiler") {
66
+ compiler = args[++i];
67
+ if (!compiler || compiler.startsWith("--"))
68
+ return fail("--compiler requires a path");
69
+ continue;
70
+ }
69
71
  if (arg === "--dry-run") dryRun = true;
70
72
  else if (arg === "--force") force = true;
71
73
  else if (arg === "--yes" || arg === "-y") yes = true;
@@ -82,18 +84,14 @@ export async function adoptCommand(
82
84
  );
83
85
  }
84
86
 
85
- const pkg = readJson<PackageJson>(join(dir, "package.json"));
86
- const detected = detectFramework(dir, pkg).framework;
87
- if (!(await hasFrontend(detected))) {
88
- const installed = await parserVersion();
87
+ let plan: AdoptPlan;
88
+ try {
89
+ plan = await planAdoption(dir, { force, compiler });
90
+ } catch (error) {
89
91
  return fail(
90
- `${dir} is a ${detected} project, but the installed @tschk/crepuscularity-wasm${installed ? ` (${installed})` : ""} has no ${detected} template frontend.\n` +
91
- `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` +
92
- `Upgrade @tschk/crepuscularity-wasm to a build that carries parser/${detected}/. Nothing was written.`,
92
+ `${error instanceof Error ? error.message : String(error)}. Nothing was written.`,
93
93
  );
94
94
  }
95
-
96
- const plan = await planAdoption(dir, { force });
97
95
  if (plan.scan.framework === "unknown") {
98
96
  return fail(
99
97
  `Could not identify a JavaScript app in ${dir}.\n` +
package/src/build.ts CHANGED
@@ -21,7 +21,7 @@ function defaultRuntime(adapter: AdapterName): string {
21
21
 
22
22
  export async function buildCommand(args: string[]): Promise<MoonshineManifest> {
23
23
  let projectDir = "";
24
- let adapter: AdapterName = "bun";
24
+ let adapter: AdapterName | undefined;
25
25
  for (let i = 0; i < args.length; i++) {
26
26
  const arg = args[i]!;
27
27
  if (arg === "--adapter") {
@@ -45,12 +45,52 @@ export async function buildCommand(args: string[]): Promise<MoonshineManifest> {
45
45
  const resolvedDir = resolve(projectDir || process.cwd());
46
46
  const configPath = findConfig(resolvedDir);
47
47
  const config = configPath ? await loadConfig(configPath) : {};
48
- const runtime = (config.runtime ?? defaultRuntime(adapter)) as
48
+ adapter ??= config.adapter ?? "bun";
49
+ if (!["bun", "node", "cloudflare", "vercel"].includes(adapter)) {
50
+ throw new Error(`Invalid configured adapter: ${adapter}`);
51
+ }
52
+ const nativeRuntime = adapter === "vercel" ? "node" : adapter;
53
+ const runtime = (config.runtime ??
54
+ (config.renderer === "native"
55
+ ? nativeRuntime
56
+ : defaultRuntime(adapter))) as
49
57
  "bun" | "node" | "cloudflare" | "vercel-edge";
50
58
 
59
+ const unsupportedServerTarget =
60
+ !["bun", "node"].includes(adapter) ||
61
+ runtime !== adapter ||
62
+ config.routes?.some((route) => route.runtime && route.runtime !== adapter);
63
+ const unsupportedNativeTarget =
64
+ runtime !== nativeRuntime ||
65
+ config.routes?.some(
66
+ (route) => route.runtime && route.runtime !== nativeRuntime,
67
+ );
68
+ if (config.renderer === "native" && unsupportedNativeTarget) {
69
+ throw new Error(
70
+ "Native renderer requires matching Bun, Node or Cloudflare runtimes; Vercel native functions require Node",
71
+ );
72
+ }
73
+
74
+ if (config.requestContext && unsupportedServerTarget) {
75
+ throw new Error(
76
+ "Request context supports only matching Bun or Node deployment adapters/runtimes",
77
+ );
78
+ }
79
+
80
+ if (config.dataRequests && unsupportedServerTarget) {
81
+ throw new Error(
82
+ "Route data requests support only matching Bun or Node deployment adapters/runtimes",
83
+ );
84
+ }
85
+
51
86
  const manifest = await buildProject({
52
87
  projectDir: resolvedDir,
53
88
  runtime,
89
+ renderer: config.renderer,
90
+ requestContext: config.requestContext,
91
+ dataRequests: config.dataRequests,
92
+ mode: config.mode,
93
+ programmatic: config.routes,
54
94
  ...(config.routesDir && {
55
95
  routesDir: resolve(resolvedDir, config.routesDir),
56
96
  }),
@@ -58,7 +98,14 @@ export async function buildCommand(args: string[]): Promise<MoonshineManifest> {
58
98
  });
59
99
 
60
100
  const outDir = resolve(resolvedDir, ".moonshine");
61
- const adapterModule = await import(`@tschk/moonshine-deploy-${adapter}`);
101
+ const adapterSpecifier = `@tschk/moonshine-deploy-${adapter}`;
102
+ let adapterPath: string;
103
+ try {
104
+ adapterPath = Bun.resolveSync(adapterSpecifier, resolvedDir);
105
+ } catch {
106
+ adapterPath = Bun.resolveSync(adapterSpecifier, import.meta.dir);
107
+ }
108
+ const adapterModule = await import(adapterPath);
62
109
  const adapterFn = adapterModule[`${adapter}Adapter`];
63
110
  if (typeof adapterFn?.build !== "function") {
64
111
  throw new Error(`Adapter "${adapter}" does not export a build function`);
@@ -0,0 +1,6 @@
1
+ export {
2
+ readCrepusGraph,
3
+ validateNativeRuntimeImport,
4
+ type CrepusGraph,
5
+ type CrepusGraphTarget,
6
+ } from "@tschk/moonshine-compiler/source";
@@ -0,0 +1 @@
1
+ export { publishCrepusGraph } from "@tschk/moonshine-compiler/source";
package/src/compile.ts CHANGED
@@ -1,23 +1,13 @@
1
1
  import { access, readFile, writeFile } from "node:fs/promises";
2
2
  import { basename, dirname, extname, join, resolve } from "node:path";
3
-
4
- async function exists(path: string): Promise<boolean> {
5
- try {
6
- await access(path);
7
- return true;
8
- } catch {
9
- return false;
10
- }
11
- }
12
-
13
- async function which(bin: string): Promise<string | null> {
14
- const path = process.env.PATH ?? "";
15
- for (const dir of path.split(":")) {
16
- const candidate = join(dir, bin);
17
- if (await exists(candidate)) return candidate;
18
- }
19
- return null;
20
- }
3
+ import {
4
+ emitCrepusSource,
5
+ publishCrepusGraph,
6
+ } from "@tschk/moonshine-compiler/source";
7
+ export {
8
+ emitCrepusSource,
9
+ requireCrepusCompiler,
10
+ } from "@tschk/moonshine-compiler/source";
21
11
 
22
12
  async function emitTsxFromIr(ir: unknown, outPath: string): Promise<void> {
23
13
  const json = JSON.stringify(ir, null, 2);
@@ -37,56 +27,74 @@ createApp({ root: App }).mount("#app");
37
27
  }
38
28
 
39
29
  export async function compileCommand(args: string[]): Promise<void> {
40
- const input = args[0];
41
- if (!input) {
42
- console.error("Usage: moonshine compile <file.crepus|file.json>");
43
- process.exit(1);
30
+ let input: string | undefined;
31
+ let compiler: string | undefined;
32
+ let site: string | undefined;
33
+ let target: "moonshine-dom" | "moonshine-ssr" | "react" = "moonshine-dom";
34
+ let selected = false;
35
+ for (let i = 0; i < args.length; i++) {
36
+ const arg = args[i]!;
37
+ if (arg === "--ssr" || arg === "--react") {
38
+ if (selected) throw new Error("Choose only one of --ssr or --react");
39
+ selected = true;
40
+ target = arg === "--ssr" ? "moonshine-ssr" : "react";
41
+ } else if (arg === "--compiler" || arg === "--site") {
42
+ const value = args[++i];
43
+ if (!value || value.startsWith("--"))
44
+ throw new Error(`${arg} requires a path`);
45
+ if (arg === "--compiler") compiler = value;
46
+ else site = value;
47
+ } else if (arg.startsWith("-")) throw new Error(`Unknown flag: ${arg}`);
48
+ else if (input) throw new Error(`Unexpected argument: ${arg}`);
49
+ else input = arg;
44
50
  }
45
-
46
- const abs = resolve(process.cwd(), input);
47
- if (!(await exists(abs))) {
48
- console.error(`File not found: ${abs}`);
49
- process.exit(1);
51
+ if (!input)
52
+ throw new Error(
53
+ "Usage: moonshine compile <source> [--ssr|--react] [--compiler <path>] [--site <root>]",
54
+ );
55
+ const abs = resolve(input);
56
+ try {
57
+ await access(abs);
58
+ } catch {
59
+ throw new Error(`File not found: ${abs}`);
50
60
  }
51
-
52
- const ext = extname(abs).toLowerCase();
53
- const outPath = join(dirname(abs), `${basename(abs, ext)}.tsx`);
54
-
61
+ const extension = extname(abs);
62
+ const ext = extension.toLowerCase();
63
+ const suffix =
64
+ target === "react"
65
+ ? ext === ".json"
66
+ ? ".tsx"
67
+ : ".react.tsx"
68
+ : target === "moonshine-ssr"
69
+ ? ".ssr.ts"
70
+ : ".dom.ts";
71
+ const outPath = join(dirname(abs), `${basename(abs, extension)}${suffix}`);
55
72
  if (ext === ".json") {
56
- const ir = JSON.parse(await readFile(abs, "utf8"));
57
- await emitTsxFromIr(ir, outPath);
73
+ if (target !== "react")
74
+ throw new Error(
75
+ "Native JSON IR emission is unavailable; compile frontend source or use --react for legacy JSON IR output",
76
+ );
77
+ await emitTsxFromIr(JSON.parse(await readFile(abs, "utf8")), outPath);
58
78
  return;
59
79
  }
60
-
61
- if (ext === ".crepus") {
62
- const crepus = await which("crepus");
63
- if (crepus) {
64
- const proc = Bun.spawn(
65
- [crepus, "web", "build", "--emit", "moonshine", abs],
66
- {
67
- cwd: dirname(abs),
68
- stdout: "inherit",
69
- stderr: "inherit",
70
- },
71
- );
72
- const code = await proc.exited;
73
- if (code !== 0) process.exit(code);
74
- console.log(`crepus emit finished for ${abs}`);
75
- return;
76
- }
77
-
78
- console.error(
79
- `No \`crepus\` on PATH and input is .crepus (not JSON IR).
80
-
81
- Install crepus (≥ 0.11) and retry, or pass View IR JSON:
82
-
83
- moonshine compile view.json
84
-
85
- Hint: crepus web build --emit moonshine ${input}`,
86
- );
87
- process.exit(1);
80
+ // Crepus web/build.rs is_framework_template defines this frontend contract.
81
+ if (
82
+ ![
83
+ ".crepus",
84
+ ".jsx",
85
+ ".tsx",
86
+ ".csx",
87
+ ".svelte",
88
+ ".vue",
89
+ ".astro",
90
+ ".ng",
91
+ ".html",
92
+ ].includes(ext)
93
+ ) {
94
+ throw new Error(`Unsupported source extension: ${ext}`);
88
95
  }
89
-
90
- console.error(`Unsupported extension: ${ext} (expected .crepus or .json)`);
91
- process.exit(1);
96
+ const { source, graph } = await emitCrepusSource(abs, target, compiler, site);
97
+ if (graph) await publishCrepusGraph(outPath, graph);
98
+ else await writeFile(outPath, source);
99
+ console.log(`Wrote ${outPath}`);
92
100
  }
package/src/config.ts CHANGED
@@ -5,10 +5,11 @@ import { defineConfig as baseDefineConfig } from "@tschk/moonshine-framework";
5
5
  import type { RouteConvention } from "@tschk/moonshine-compiler";
6
6
  import type {
7
7
  MoonshineConfig,
8
+ RendererName,
8
9
  RouteDefinition,
9
10
  } from "@tschk/moonshine-framework";
10
11
 
11
- export type RendererName = "react" | "solid" | "crepus";
12
+ export type { RendererName } from "@tschk/moonshine-framework";
12
13
 
13
14
  export type MoonshineCliConfig = MoonshineConfig & {
14
15
  adapter?: "bun" | "node" | "cloudflare" | "vercel";
package/src/dev.ts CHANGED
@@ -36,6 +36,8 @@ export async function devCommand(args: string[]): Promise<void> {
36
36
  let preview: PreviewHandle | undefined;
37
37
  let watcher: ReturnType<typeof watch> | undefined;
38
38
  let rebuildTimer: ReturnType<typeof setTimeout> | undefined;
39
+ let buildChain: Promise<void> = Promise.resolve();
40
+ let rebuildQueued = false;
39
41
 
40
42
  async function runBuildAndPreview(): Promise<void> {
41
43
  if (preview) {
@@ -51,6 +53,15 @@ export async function devCommand(args: string[]): Promise<void> {
51
53
  }
52
54
  }
53
55
 
56
+ function scheduleRebuild(): void {
57
+ if (rebuildQueued) return;
58
+ rebuildQueued = true;
59
+ buildChain = buildChain.then(async () => {
60
+ rebuildQueued = false;
61
+ await runBuildAndPreview();
62
+ });
63
+ }
64
+
54
65
  await runBuildAndPreview();
55
66
 
56
67
  if (watcher) {
@@ -60,7 +71,7 @@ export async function devCommand(args: string[]): Promise<void> {
60
71
  watcher = watch(srcDir, { recursive: true }, () => {
61
72
  if (rebuildTimer) clearTimeout(rebuildTimer);
62
73
  rebuildTimer = setTimeout(() => {
63
- void runBuildAndPreview();
74
+ scheduleRebuild();
64
75
  }, 100);
65
76
  });
66
77