@kiln-js/cli 0.1.4 → 0.1.6
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 +47 -0
- package/dist/doctor.d.ts +1 -0
- package/dist/errors.d.ts +1 -0
- package/dist/hints.d.ts +9 -0
- package/dist/index.js +1060 -421
- package/dist/preflight.d.ts +1 -0
- package/dist/runtime.d.ts +9 -0
- package/dist/test.d.ts +2 -0
- package/dist/typecheck.d.ts +1 -0
- package/dist/versions.d.ts +8 -0
- package/package.json +27 -27
- package/dist/config.d.ts +0 -3
package/dist/index.js
CHANGED
|
@@ -1,21 +1,17 @@
|
|
|
1
|
-
#!/usr/bin/env
|
|
2
|
-
// @bun
|
|
1
|
+
#!/usr/bin/env node
|
|
3
2
|
|
|
4
|
-
// src/index.ts
|
|
3
|
+
// packages/cli/src/index.ts
|
|
5
4
|
import { cac } from "cac";
|
|
6
5
|
|
|
7
|
-
// src/dev.ts
|
|
8
|
-
import
|
|
6
|
+
// packages/cli/src/dev.ts
|
|
7
|
+
import fs5 from "node:fs";
|
|
8
|
+
import path7 from "node:path";
|
|
9
|
+
import http from "node:http";
|
|
9
10
|
import { createServer as createViteServer } from "vite";
|
|
10
|
-
|
|
11
|
-
// src/config.ts
|
|
12
|
-
import fs from "fs";
|
|
13
|
-
import path2 from "path";
|
|
14
|
-
import { pathToFileURL } from "url";
|
|
15
11
|
import { kiln } from "@kiln-js/vite-plugin";
|
|
16
12
|
|
|
17
|
-
// src/paths.ts
|
|
18
|
-
import path from "path";
|
|
13
|
+
// packages/cli/src/paths.ts
|
|
14
|
+
import path from "node:path";
|
|
19
15
|
var root = process.cwd();
|
|
20
16
|
var paths = {
|
|
21
17
|
root,
|
|
@@ -26,7 +22,69 @@ var paths = {
|
|
|
26
22
|
serverOut: path.resolve(root, "dist/server")
|
|
27
23
|
};
|
|
28
24
|
|
|
29
|
-
// src/
|
|
25
|
+
// packages/cli/src/entries.ts
|
|
26
|
+
import fs from "node:fs";
|
|
27
|
+
import path2 from "node:path";
|
|
28
|
+
var EXTENSIONS = ["tsx", "ts", "jsx", "js"];
|
|
29
|
+
var ENV_TYPES = `// Generated by Kiln. Do not edit.
|
|
30
|
+
export {};
|
|
31
|
+
|
|
32
|
+
declare global {
|
|
33
|
+
namespace JSX {
|
|
34
|
+
interface IntrinsicElements {
|
|
35
|
+
"kiln:title": { children?: string | number | (string | number)[] };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
`;
|
|
40
|
+
var DEFAULT_CLIENT = `import { createClient } from "@kiln-js/client";
|
|
41
|
+
|
|
42
|
+
createClient().then((client) => client.start());
|
|
43
|
+
`;
|
|
44
|
+
var DEFAULT_SERVER = `import { createAppHandler, type KilnAssets } from "@kiln-js/server";
|
|
45
|
+
|
|
46
|
+
export function createHandler(assets: KilnAssets) {
|
|
47
|
+
return createAppHandler({ assets });
|
|
48
|
+
}
|
|
49
|
+
`;
|
|
50
|
+
function ensureKilnDir() {
|
|
51
|
+
fs.mkdirSync(paths.kilnDir, { recursive: true });
|
|
52
|
+
}
|
|
53
|
+
function findUserEntry(name) {
|
|
54
|
+
for (const ext of EXTENSIONS) {
|
|
55
|
+
const file2 = path2.join(paths.root, "app", `${name}.${ext}`);
|
|
56
|
+
if (fs.existsSync(file2)) return file2;
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
function writeGenerated(name, source) {
|
|
61
|
+
ensureKilnDir();
|
|
62
|
+
const target = path2.join(paths.kilnDir, name);
|
|
63
|
+
fs.writeFileSync(target, source);
|
|
64
|
+
return target;
|
|
65
|
+
}
|
|
66
|
+
function resolveEntries() {
|
|
67
|
+
writeGenerated("env.d.ts", ENV_TYPES);
|
|
68
|
+
const client = findUserEntry("client") ?? writeGenerated("client.tsx", DEFAULT_CLIENT);
|
|
69
|
+
const server = findUserEntry("server") ?? writeGenerated("server.ts", DEFAULT_SERVER);
|
|
70
|
+
return {
|
|
71
|
+
client,
|
|
72
|
+
server,
|
|
73
|
+
clientRel: path2.relative(paths.root, client).split(path2.sep).join("/")
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// packages/cli/src/env.ts
|
|
78
|
+
import { loadEnv } from "vite";
|
|
79
|
+
function loadEnvFiles(mode) {
|
|
80
|
+
const env = loadEnv(mode, paths.root, "");
|
|
81
|
+
for (const [key, value] of Object.entries(env)) {
|
|
82
|
+
if (process.env[key] === void 0) process.env[key] = value;
|
|
83
|
+
}
|
|
84
|
+
return env;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// packages/cli/src/log.ts
|
|
30
88
|
var useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
|
|
31
89
|
var sgr = (open, close) => (s) => useColor ? `\x1B[${open}m${s}\x1B[${close}m` : s;
|
|
32
90
|
var fg = (r, g, b) => sgr(`38;2;${r};${g};${b}`, "39");
|
|
@@ -36,6 +94,7 @@ var colors = {
|
|
|
36
94
|
red: sgr("31", "39"),
|
|
37
95
|
yellow: sgr("33", "39"),
|
|
38
96
|
cyan: sgr("36", "39"),
|
|
97
|
+
// Kiln palette
|
|
39
98
|
fire: fg(255, 122, 69),
|
|
40
99
|
ember: fg(255, 92, 122),
|
|
41
100
|
mint: fg(94, 234, 212),
|
|
@@ -56,8 +115,7 @@ var METHOD_COLORS = {
|
|
|
56
115
|
var methodColor = (m) => METHOD_COLORS[m] ?? colors.bold;
|
|
57
116
|
var statusColor = (s) => s >= 500 ? colors.ember : s >= 400 ? colors.yellow : s >= 300 ? colors.violet : colors.mint;
|
|
58
117
|
function gradient(text, from, to) {
|
|
59
|
-
if (!useColor)
|
|
60
|
-
return text;
|
|
118
|
+
if (!useColor) return text;
|
|
61
119
|
const chars = [...text];
|
|
62
120
|
const painted = chars.map((ch, i) => {
|
|
63
121
|
const t = chars.length < 2 ? 0 : i / (chars.length - 1);
|
|
@@ -67,15 +125,12 @@ function gradient(text, from, to) {
|
|
|
67
125
|
return `${painted}\x1B[39m`;
|
|
68
126
|
}
|
|
69
127
|
function formatDuration(ms) {
|
|
70
|
-
if (ms <
|
|
71
|
-
|
|
72
|
-
return `${(ms / 1000).toFixed(2)}s`;
|
|
128
|
+
if (ms < 1e3) return `${Math.round(ms)}ms`;
|
|
129
|
+
return `${(ms / 1e3).toFixed(2)}s`;
|
|
73
130
|
}
|
|
74
131
|
function formatBytes(bytes) {
|
|
75
|
-
if (bytes < 1024)
|
|
76
|
-
|
|
77
|
-
if (bytes < 1024 ** 2)
|
|
78
|
-
return `${(bytes / 1024).toFixed(1)} kB`;
|
|
132
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
133
|
+
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} kB`;
|
|
79
134
|
return `${(bytes / 1024 ** 2).toFixed(2)} MB`;
|
|
80
135
|
}
|
|
81
136
|
var log = {
|
|
@@ -84,10 +139,12 @@ var log = {
|
|
|
84
139
|
success: (msg) => console.log(` ${colors.mint("\u2714")} ${msg}`),
|
|
85
140
|
warn: (msg) => console.log(` ${colors.yellow("\u26A0")} ${colors.yellow(msg)}`),
|
|
86
141
|
error: (msg) => console.error(` ${colors.ember("\u2716")} ${colors.ember(msg)}`),
|
|
87
|
-
change: (
|
|
142
|
+
change: (file2) => console.log(` ${colors.violet("\u21BB")} ${colors.dim("changed")} ${file2}`),
|
|
88
143
|
request(method, pathname, status, time) {
|
|
89
144
|
const verb = methodColor(method)(method.padEnd(6));
|
|
90
|
-
console.log(
|
|
145
|
+
console.log(
|
|
146
|
+
` ${colors.gray("\u203A")} ${verb}${colors.bold(pathname)} ${statusColor(status)(String(status))} ${colors.gray(time)}`
|
|
147
|
+
);
|
|
91
148
|
}
|
|
92
149
|
};
|
|
93
150
|
function spinner(label) {
|
|
@@ -131,9 +188,10 @@ function box(lines, paint = colors.fire) {
|
|
|
131
188
|
const width = Math.max(...lines.map(visible)) + 4;
|
|
132
189
|
const top = paint(`\u256D${"\u2500".repeat(width)}\u256E`);
|
|
133
190
|
const bottom = paint(`\u2570${"\u2500".repeat(width)}\u256F`);
|
|
134
|
-
const body = lines.map(
|
|
135
|
-
|
|
136
|
-
|
|
191
|
+
const body = lines.map(
|
|
192
|
+
(l) => `${paint("\u2502")} ${l}${" ".repeat(width - visible(l) - 2)}${paint("\u2502")}`
|
|
193
|
+
);
|
|
194
|
+
console.log([top, ...body, bottom].map((l) => ` ${l}`).join("\n"));
|
|
137
195
|
}
|
|
138
196
|
function table(rows, headers) {
|
|
139
197
|
const all = [headers, ...rows];
|
|
@@ -152,234 +210,331 @@ function banner(version) {
|
|
|
152
210
|
`);
|
|
153
211
|
}
|
|
154
212
|
|
|
155
|
-
// src/
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
const file = CANDIDATES.map((f) => path2.join(paths.root, f)).find((f) => fs.existsSync(f));
|
|
159
|
-
if (!file)
|
|
160
|
-
return {};
|
|
161
|
-
const mod = await import(pathToFileURL(file).href);
|
|
162
|
-
const config = mod.default ?? {};
|
|
163
|
-
if (config.plugins?.length) {
|
|
164
|
-
log.step(`plugins: ${config.plugins.map((p) => p.name).join(", ")}`);
|
|
165
|
-
}
|
|
166
|
-
return config;
|
|
167
|
-
}
|
|
168
|
-
async function kilnPlugins() {
|
|
169
|
-
const config = await loadConfig();
|
|
170
|
-
return kiln({ pagesDir: paths.pagesDir, apiDir: paths.apiDir, plugins: config.plugins });
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// src/entries.ts
|
|
174
|
-
import fs2 from "fs";
|
|
175
|
-
import path3 from "path";
|
|
176
|
-
var EXTENSIONS = ["tsx", "ts", "jsx", "js"];
|
|
177
|
-
var ENV_TYPES = `// Generated by Kiln. Do not edit.
|
|
178
|
-
export {};
|
|
213
|
+
// packages/cli/src/errors.ts
|
|
214
|
+
import fs2 from "node:fs";
|
|
215
|
+
import path4 from "node:path";
|
|
179
216
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
217
|
+
// packages/cli/src/hints.ts
|
|
218
|
+
import path3 from "node:path";
|
|
219
|
+
var norm = (p) => p.replace(/\\/g, "/");
|
|
220
|
+
var rel = (file2) => norm(path3.relative(paths.root, file2));
|
|
221
|
+
var BROWSER_GLOBAL = /^(window|document|localStorage|sessionStorage|navigator|matchMedia|IntersectionObserver|ResizeObserver|location|history)$/;
|
|
222
|
+
function diagnose(error, frames) {
|
|
223
|
+
const hints = [];
|
|
224
|
+
const msg = error.message;
|
|
225
|
+
const layout = frames.find((f) => /_layout\.[jt]sx?$/.test(norm(f.file)));
|
|
226
|
+
const browserName = msg.match(/^(\w+) is not defined/)?.[1];
|
|
227
|
+
if (error.name === "ReferenceError" && browserName && BROWSER_GLOBAL.test(browserName)) {
|
|
228
|
+
hints.push({
|
|
229
|
+
title: `"${browserName}" is a browser API, but it ran while the server rendered the page`,
|
|
230
|
+
steps: [
|
|
231
|
+
layout ? `The code is in a layout: ${rel(layout.file)}. Layouts render on the server for server and universal pages.` : "The code runs during server rendering. Server and universal pages render on the server.",
|
|
232
|
+
"Move the code into useEffect, which runs only in the browser.",
|
|
233
|
+
"Or wrap the browser-only part in <ClientOnly fallback={...}> from @kiln-js/core.",
|
|
234
|
+
"If the whole page needs the browser, use the .client suffix for that page."
|
|
235
|
+
]
|
|
236
|
+
});
|
|
185
237
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
return createAppHandler({ assets });
|
|
196
|
-
}
|
|
197
|
-
`;
|
|
198
|
-
function ensureKilnDir() {
|
|
199
|
-
fs2.mkdirSync(paths.kilnDir, { recursive: true });
|
|
200
|
-
}
|
|
201
|
-
function findUserEntry(name) {
|
|
202
|
-
for (const ext of EXTENSIONS) {
|
|
203
|
-
const file = path3.join(paths.root, "app", `${name}.${ext}`);
|
|
204
|
-
if (fs2.existsSync(file))
|
|
205
|
-
return file;
|
|
238
|
+
if (/Cannot find module|Failed to resolve import|Could not resolve|Cannot find package/.test(msg)) {
|
|
239
|
+
hints.push({
|
|
240
|
+
title: "An import could not be resolved",
|
|
241
|
+
steps: [
|
|
242
|
+
"Check the path: relative paths start with ./ or ../, and file names are case-sensitive.",
|
|
243
|
+
"For packages, run bun install in the project root.",
|
|
244
|
+
"After adding a dependency, restart kiln dev."
|
|
245
|
+
]
|
|
246
|
+
});
|
|
206
247
|
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
}
|
|
215
|
-
function resolveEntries() {
|
|
216
|
-
writeGenerated("env.d.ts", ENV_TYPES);
|
|
217
|
-
const client = findUserEntry("client") ?? writeGenerated("client.tsx", DEFAULT_CLIENT);
|
|
218
|
-
const server = findUserEntry("server") ?? writeGenerated("server.ts", DEFAULT_SERVER);
|
|
219
|
-
return {
|
|
220
|
-
client,
|
|
221
|
-
server,
|
|
222
|
-
clientRel: path3.relative(paths.root, client).split(path3.sep).join("/")
|
|
223
|
-
};
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
// src/env.ts
|
|
227
|
-
import { loadEnv } from "vite";
|
|
228
|
-
function loadEnvFiles(mode) {
|
|
229
|
-
const env = loadEnv(mode, paths.root, "");
|
|
230
|
-
for (const [key, value] of Object.entries(env)) {
|
|
231
|
-
if (process.env[key] === undefined)
|
|
232
|
-
process.env[key] = value;
|
|
248
|
+
if (/must export "createHandler/.test(msg)) {
|
|
249
|
+
hints.push({
|
|
250
|
+
title: "The server entry does not export createHandler",
|
|
251
|
+
steps: [
|
|
252
|
+
"app/server.ts must export: export function createHandler(assets) { ... }",
|
|
253
|
+
"Use createAppHandler from @kiln-js/server inside it."
|
|
254
|
+
]
|
|
255
|
+
});
|
|
233
256
|
}
|
|
234
|
-
|
|
257
|
+
if (/server-only and cannot be imported/.test(msg)) {
|
|
258
|
+
hints.push({
|
|
259
|
+
title: "A .server module is imported by browser code",
|
|
260
|
+
steps: [
|
|
261
|
+
"Move the import into a loader or action, which the build removes from the browser bundle.",
|
|
262
|
+
"Or move the helper that uses it into a .server module."
|
|
263
|
+
]
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
if (/DATABASE_URL is not set/.test(msg)) {
|
|
267
|
+
hints.push({
|
|
268
|
+
title: "A required environment variable is missing",
|
|
269
|
+
steps: [
|
|
270
|
+
"Add DATABASE_URL to .env.local for local development.",
|
|
271
|
+
"On Vercel, add it under Settings \u2192 Environment Variables."
|
|
272
|
+
]
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
if (/Invalid environment/.test(msg)) {
|
|
276
|
+
hints.push({
|
|
277
|
+
title: "Environment validation failed",
|
|
278
|
+
steps: ["Each line under the message names a variable. Add it to .env.local or fix its value."]
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
if (error.name === "SyntaxError" && frames.some((f) => norm(f.file).endsWith(".md"))) {
|
|
282
|
+
hints.push({
|
|
283
|
+
title: "A Markdown file reached the JavaScript parser",
|
|
284
|
+
steps: [
|
|
285
|
+
"Add md() from @kiln-js/md to the plugins in vite.config.ts.",
|
|
286
|
+
"Restart kiln dev after changing the config."
|
|
287
|
+
]
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
if (/Hydration failed|did not match|Text content does not match|#418|#423|#425/.test(msg)) {
|
|
291
|
+
hints.push({
|
|
292
|
+
title: "The server and the browser rendered different HTML",
|
|
293
|
+
steps: [
|
|
294
|
+
"Common causes: Date.now(), Math.random(), toLocaleString(), and window checks during render.",
|
|
295
|
+
"Move those values into useEffect, or wrap them in <ClientOnly>."
|
|
296
|
+
]
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
if (/conflict: .* both map to/.test(msg)) {
|
|
300
|
+
hints.push({
|
|
301
|
+
title: "Two files map to the same URL",
|
|
302
|
+
steps: [
|
|
303
|
+
"Rename one of the files, or move it into a (group) folder if it should share a layout without changing the URL."
|
|
304
|
+
]
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
return hints;
|
|
235
308
|
}
|
|
236
309
|
|
|
237
|
-
// src/errors.ts
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
var norm = (p) => p.replace(/\\/g, "/");
|
|
241
|
-
var rootNorm = norm(paths.root);
|
|
310
|
+
// packages/cli/src/errors.ts
|
|
311
|
+
var norm2 = (p) => p.replace(/\\/g, "/");
|
|
312
|
+
var rootNorm = norm2(paths.root);
|
|
242
313
|
var toError = (err) => err instanceof Error ? err : new Error(String(err));
|
|
243
|
-
var
|
|
314
|
+
var rel2 = (file2) => norm2(path4.relative(paths.root, file2));
|
|
244
315
|
var esc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
245
|
-
var editorLink = (f) => `vscode://file/${encodeURI(
|
|
316
|
+
var editorLink = (f) => `vscode://file/${encodeURI(norm2(f.file))}:${f.line}:${f.column}`;
|
|
246
317
|
function parseFrames(stack) {
|
|
247
318
|
const frames = [];
|
|
248
|
-
for (const raw of stack.split(
|
|
249
|
-
`)) {
|
|
319
|
+
for (const raw of stack.split("\n")) {
|
|
250
320
|
const m = raw.trim().match(/^at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/);
|
|
251
|
-
if (!m)
|
|
252
|
-
continue;
|
|
321
|
+
if (!m) continue;
|
|
253
322
|
frames.push({
|
|
254
323
|
fn: m[1] ?? "<anonymous>",
|
|
255
|
-
|
|
324
|
+
// Dev URLs carry a ?t=timestamp suffix, which is not part of the path.
|
|
325
|
+
file: m[2].replace(/^file:\/\/\/?/, "").split("?")[0],
|
|
256
326
|
line: Number(m[3]),
|
|
257
327
|
column: Number(m[4])
|
|
258
328
|
});
|
|
259
329
|
}
|
|
260
330
|
return frames;
|
|
261
331
|
}
|
|
262
|
-
|
|
263
|
-
const n =
|
|
332
|
+
function isAppFrame(f) {
|
|
333
|
+
const n = norm2(f.file);
|
|
264
334
|
return n.startsWith(rootNorm) && !n.includes("/node_modules/");
|
|
265
|
-
}
|
|
335
|
+
}
|
|
266
336
|
function findOrigin(frames) {
|
|
267
|
-
return frames.find((f) =>
|
|
337
|
+
return frames.find((f) => isAppFrame(f) && fs2.existsSync(f.file));
|
|
268
338
|
}
|
|
269
|
-
function codeLines(f, radius =
|
|
339
|
+
function codeLines(f, radius = 3) {
|
|
270
340
|
try {
|
|
271
|
-
const lines =
|
|
341
|
+
const lines = fs2.readFileSync(f.file, "utf8").split(/\r?\n/);
|
|
272
342
|
const from = Math.max(1, f.line - radius);
|
|
273
343
|
const to = Math.min(lines.length, f.line + radius);
|
|
274
344
|
const out = [];
|
|
275
|
-
for (let n = from;n <= to; n++) {
|
|
276
|
-
out.push({ n, text: lines[n - 1] ?? "", hot: n === f.line });
|
|
277
|
-
}
|
|
345
|
+
for (let n = from; n <= to; n++) out.push({ n, text: lines[n - 1] ?? "", hot: n === f.line });
|
|
278
346
|
return out;
|
|
279
347
|
} catch {
|
|
280
348
|
return [];
|
|
281
349
|
}
|
|
282
350
|
}
|
|
351
|
+
function terminalCode(f) {
|
|
352
|
+
const lines = codeLines(f, 3);
|
|
353
|
+
const width = String(lines[lines.length - 1]?.n ?? 0).length;
|
|
354
|
+
const rows = [];
|
|
355
|
+
for (const l of lines) {
|
|
356
|
+
const num = String(l.n).padStart(width);
|
|
357
|
+
if (l.hot) {
|
|
358
|
+
rows.push(`${colors.red("\u25B8")} ${colors.red(num)} ${colors.gray("\u2502")} ${l.text}`);
|
|
359
|
+
rows.push(` ${" ".repeat(width)} ${colors.gray("\u2502")} ${" ".repeat(Math.max(0, f.column - 1))}${colors.red("^")}`);
|
|
360
|
+
} else {
|
|
361
|
+
rows.push(` ${colors.gray(num)} ${colors.gray("\u2502")} ${colors.gray(l.text)}`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return rows;
|
|
365
|
+
}
|
|
283
366
|
function printError(err, context) {
|
|
284
367
|
const error = toError(err);
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
368
|
+
const frames = parseFrames(error.stack ?? "");
|
|
369
|
+
const origin = findOrigin(frames);
|
|
370
|
+
const hints = diagnose(error, frames);
|
|
371
|
+
const appFrames = frames.filter(isAppFrame);
|
|
372
|
+
const hidden = frames.length - appFrames.length;
|
|
373
|
+
const c = colors;
|
|
374
|
+
const lines = [""];
|
|
375
|
+
lines.push(` ${c.red("\u2716")} ${c.bold(c.red(error.name))} ${c.bold(error.message)}`);
|
|
376
|
+
lines.push(` ${c.gray(context)}`);
|
|
289
377
|
if (origin) {
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
}
|
|
378
|
+
lines.push("");
|
|
379
|
+
lines.push(` ${c.gray("at")} ${c.cyan(`${rel2(origin.file)}:${origin.line}:${origin.column}`)}`);
|
|
380
|
+
lines.push("");
|
|
381
|
+
for (const row of terminalCode(origin)) lines.push(` ${row}`);
|
|
382
|
+
}
|
|
383
|
+
for (const hint of hints) {
|
|
384
|
+
lines.push("");
|
|
385
|
+
lines.push(` ${c.yellow("hint")} ${c.bold(hint.title)}`);
|
|
386
|
+
for (const step of hint.steps) lines.push(` ${c.gray("\u203A")} ${step}`);
|
|
387
|
+
}
|
|
388
|
+
if (appFrames.length > 0) {
|
|
389
|
+
lines.push("");
|
|
390
|
+
lines.push(` ${c.gray("stack")}`);
|
|
391
|
+
for (const f of appFrames.slice(0, 6)) {
|
|
392
|
+
lines.push(` ${c.dim(f.fn.padEnd(28))} ${c.gray(`${rel2(f.file)}:${f.line}`)}`);
|
|
299
393
|
}
|
|
300
394
|
}
|
|
301
|
-
|
|
395
|
+
if (hidden > 0) lines.push(` ${c.gray(`+ ${hidden} internal frames`)}`);
|
|
396
|
+
lines.push("");
|
|
397
|
+
console.error(lines.join("\n"));
|
|
398
|
+
}
|
|
399
|
+
var OVERLAY_CSS = `
|
|
400
|
+
:root {
|
|
401
|
+
--bg: #0e1116; --panel: #161b22; --line: #262d38; --text: #e6edf3; --muted: #8b949e;
|
|
402
|
+
--accent: #f85149; --link: #79c0ff; --warn: #e3b341; --hot: rgba(248, 81, 73, 0.14);
|
|
403
|
+
color-scheme: dark;
|
|
404
|
+
}
|
|
405
|
+
@media (prefers-color-scheme: light) {
|
|
406
|
+
:root {
|
|
407
|
+
--bg: #f6f8fa; --panel: #ffffff; --line: #d0d7de; --text: #1f2328; --muted: #656d76;
|
|
408
|
+
--accent: #cf222e; --link: #0550ae; --warn: #9a6700; --hot: rgba(207, 34, 46, 0.1);
|
|
409
|
+
color-scheme: light;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
* { box-sizing: border-box; }
|
|
413
|
+
body { margin: 0; background: var(--bg); color: var(--text);
|
|
414
|
+
font: 14px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
|
|
415
|
+
.overlay[hidden] { display: none; }
|
|
416
|
+
.bar { position: sticky; top: 0; z-index: 1; display: flex; align-items: center; gap: 16px;
|
|
417
|
+
padding: 10px 24px; background: var(--panel); border-bottom: 1px solid var(--line); flex-wrap: wrap; }
|
|
418
|
+
.brand { font-weight: 700; }
|
|
419
|
+
.route { display: flex; gap: 8px; align-items: center; color: var(--muted);
|
|
420
|
+
font: 13px ui-monospace, SFMono-Regular, Consolas, monospace; }
|
|
421
|
+
.method { color: var(--text); font-weight: 600; }
|
|
422
|
+
.actions { margin-left: auto; display: flex; gap: 8px; }
|
|
423
|
+
button { font: inherit; font-size: 13px; padding: 5px 10px; border-radius: 6px; cursor: pointer;
|
|
424
|
+
border: 1px solid var(--line); background: transparent; color: var(--text); }
|
|
425
|
+
main { max-width: 1040px; margin: 0 auto; padding: 28px 24px 64px; display: grid; gap: 16px; }
|
|
426
|
+
.kind { margin: 0; color: var(--accent); font: 600 12px ui-monospace, monospace;
|
|
427
|
+
text-transform: uppercase; letter-spacing: 0.08em; }
|
|
428
|
+
.hero h1 { margin: 6px 0 10px; font-size: 22px; line-height: 1.35; word-break: break-word; }
|
|
429
|
+
.where { color: var(--link); text-decoration: none; font: 13px ui-monospace, monospace; }
|
|
430
|
+
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
|
|
431
|
+
.card h2 { margin: 0; font-size: 14px; padding: 12px 16px; border-bottom: 1px solid var(--line); }
|
|
432
|
+
.hint { border-color: color-mix(in srgb, var(--warn) 45%, var(--line)); }
|
|
433
|
+
.hint h2 { color: var(--warn); }
|
|
434
|
+
.hint ul { margin: 0; padding: 12px 16px 14px 36px; }
|
|
435
|
+
.card-head { display: flex; justify-content: space-between; align-items: center; gap: 12px;
|
|
436
|
+
padding: 10px 16px; border-bottom: 1px solid var(--line); color: var(--muted); font-size: 13px; }
|
|
437
|
+
.open { color: var(--link); text-decoration: none; }
|
|
438
|
+
.code { overflow: auto; padding: 8px 0; font: 13px/1.7 ui-monospace, SFMono-Regular, Consolas, monospace; }
|
|
439
|
+
.ln { display: flex; white-space: pre; padding: 0 16px; }
|
|
440
|
+
.num { width: 48px; flex: none; color: var(--muted); user-select: none; }
|
|
441
|
+
.ln.hot { background: var(--hot); }
|
|
442
|
+
.ln.hot .txt { font-weight: 600; }
|
|
443
|
+
.caret-row .txt { color: var(--accent); }
|
|
444
|
+
.frames { margin: 0; padding: 8px 16px 12px 44px; }
|
|
445
|
+
.frames li { padding: 4px 0; }
|
|
446
|
+
.frames a { color: var(--link); text-decoration: none; font: 13px ui-monospace, monospace; word-break: break-all; }
|
|
447
|
+
.fn { color: var(--muted); margin-right: 10px; font: 13px ui-monospace, monospace; }
|
|
448
|
+
.none { color: var(--muted); list-style: none; margin-left: -28px; }
|
|
449
|
+
details.internal { border-top: 1px solid var(--line); }
|
|
450
|
+
details.internal summary { cursor: pointer; color: var(--muted); padding: 10px 16px; }
|
|
451
|
+
details.internal .frames { padding-top: 0; }
|
|
452
|
+
footer { text-align: center; color: var(--muted); font-size: 13px; }
|
|
453
|
+
`;
|
|
454
|
+
var OVERLAY_JS = `
|
|
455
|
+
(function () {
|
|
456
|
+
var raw = document.getElementById("raw").content.textContent;
|
|
457
|
+
var copy = document.getElementById("copy");
|
|
458
|
+
copy.onclick = function () {
|
|
459
|
+
if (!navigator.clipboard) return;
|
|
460
|
+
navigator.clipboard.writeText(raw).then(function () {
|
|
461
|
+
copy.textContent = "Copied";
|
|
462
|
+
setTimeout(function () { copy.textContent = "Copy stack"; }, 1500);
|
|
463
|
+
});
|
|
464
|
+
};
|
|
465
|
+
function hide() { document.querySelector(".overlay").hidden = true; }
|
|
466
|
+
document.getElementById("dismiss").onclick = hide;
|
|
467
|
+
document.addEventListener("keydown", function (e) { if (e.key === "Escape") hide(); });
|
|
468
|
+
})();
|
|
469
|
+
`;
|
|
470
|
+
function frameItem(f) {
|
|
471
|
+
return `<li><span class="fn">${esc(f.fn)}</span><a href="${editorLink(f)}">${esc(rel2(f.file))}:${f.line}:${f.column}</a></li>`;
|
|
472
|
+
}
|
|
473
|
+
function hintCard(h) {
|
|
474
|
+
return `<section class="card hint"><h2>${esc(h.title)}</h2><ul>${h.steps.map((s) => `<li>${esc(s)}</li>`).join("")}</ul></section>`;
|
|
475
|
+
}
|
|
476
|
+
function sourceCard(f) {
|
|
477
|
+
const rows = codeLines(f, 4).map((l) => {
|
|
478
|
+
const row = `<div class="ln${l.hot ? " hot" : ""}"><span class="num">${l.n}</span><span class="txt">${esc(l.text) || " "}</span></div>`;
|
|
479
|
+
if (!l.hot) return row;
|
|
480
|
+
const caret = `<div class="ln caret-row"><span class="num"></span><span class="txt" style="white-space:pre">${" ".repeat(
|
|
481
|
+
Math.max(0, f.column - 1)
|
|
482
|
+
)}<span>^</span></span></div>`;
|
|
483
|
+
return row + caret;
|
|
484
|
+
}).join("");
|
|
485
|
+
return `<section class="card">
|
|
486
|
+
<div class="card-head"><span>Source</span><a class="open" href="${editorLink(f)}">Open in editor \u2192</a></div>
|
|
487
|
+
<div class="code">${rows}</div>
|
|
488
|
+
</section>`;
|
|
302
489
|
}
|
|
303
490
|
function renderDevError(err, meta) {
|
|
304
491
|
const error = toError(err);
|
|
305
492
|
const frames = parseFrames(error.stack ?? "");
|
|
306
493
|
const origin = findOrigin(frames);
|
|
307
|
-
const
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
const stack = frames.map((f) => {
|
|
315
|
-
const internal = !isUserFile(f.file);
|
|
316
|
-
return `<li class="${internal ? "internal" : ""}">
|
|
317
|
-
<span class="fn">${esc(f.fn)}</span>
|
|
318
|
-
<a href="${editorLink(f)}">${esc(rel(f.file))}:${f.line}:${f.column}</a>
|
|
319
|
-
</li>`;
|
|
320
|
-
}).join("");
|
|
494
|
+
const hints = diagnose(error, frames);
|
|
495
|
+
const appFrames = frames.filter(isAppFrame);
|
|
496
|
+
const internal = frames.filter((f) => !isAppFrame(f));
|
|
497
|
+
const time = (/* @__PURE__ */ new Date()).toLocaleTimeString();
|
|
498
|
+
const where = origin ? `<a class="where" href="${editorLink(origin)}">${esc(rel2(origin.file))}:${origin.line}:${origin.column}</a>` : "";
|
|
499
|
+
const internalBlock = internal.length ? `<details class="internal"><summary>${internal.length} internal frames</summary><ol class="frames">${internal.map(frameItem).join("")}</ol></details>` : "";
|
|
500
|
+
const appList = appFrames.length ? appFrames.map(frameItem).join("") : `<li class="none">No frames from your code</li>`;
|
|
321
501
|
return `<!doctype html>
|
|
322
502
|
<html lang="en">
|
|
323
503
|
<head>
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
* { box-sizing: border-box; }
|
|
329
|
-
body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.6 ui-sans-serif, system-ui, sans-serif; }
|
|
330
|
-
header { padding: 28px 32px; background: linear-gradient(135deg, #7f1d1d, #1e1b4b); border-bottom: 1px solid var(--line); }
|
|
331
|
-
.badge { display: inline-block; font: 12px ui-monospace, monospace; padding: 2px 10px; border-radius: 999px; background: rgba(255,255,255,.12); margin-bottom: 10px; }
|
|
332
|
-
.kind { color: #fecaca; font: 13px ui-monospace, monospace; }
|
|
333
|
-
h1 { margin: 4px 0 0; font-size: 20px; color: #fff; word-break: break-word; }
|
|
334
|
-
main { padding: 24px 32px; display: grid; gap: 20px; max-width: 1100px; }
|
|
335
|
-
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
|
|
336
|
-
.card-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 10px 14px; border-bottom: 1px solid var(--line); font-weight: 600; }
|
|
337
|
-
a { color: var(--accent); text-decoration: none; font: 13px ui-monospace, monospace; }
|
|
338
|
-
a:hover { text-decoration: underline; }
|
|
339
|
-
.code { margin: 0; padding: 8px 0; overflow: auto; font: 13px/1.7 ui-monospace, Consolas, monospace; }
|
|
340
|
-
.ln { display: flex; white-space: pre; padding: 0 14px; }
|
|
341
|
-
.ln .num { width: 48px; color: var(--muted); user-select: none; flex-shrink: 0; }
|
|
342
|
-
.ln.hot { background: rgba(248,113,113,.18); }
|
|
343
|
-
.ln.hot .num, .ln.hot .txt { color: #fff; }
|
|
344
|
-
.stack { margin: 0; padding: 10px 14px; list-style: none; }
|
|
345
|
-
.stack li { padding: 5px 0; border-bottom: 1px dashed var(--line); }
|
|
346
|
-
.stack li:last-child { border-bottom: 0; }
|
|
347
|
-
.stack li.internal { opacity: .45; }
|
|
348
|
-
.fn { color: #c4b5fd; font: 13px ui-monospace, monospace; margin-right: 8px; }
|
|
349
|
-
button { background: var(--line); color: var(--text); border: 1px solid #343a48; border-radius: 6px; padding: 4px 10px; cursor: pointer; font: inherit; }
|
|
350
|
-
.hint { color: var(--muted); font-size: 12px; }
|
|
351
|
-
</style>
|
|
504
|
+
<meta charset="utf-8" />
|
|
505
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
506
|
+
<title>${esc(error.name)}: ${esc(error.message)}</title>
|
|
507
|
+
<style>${OVERLAY_CSS}</style>
|
|
352
508
|
</head>
|
|
353
509
|
<body>
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
510
|
+
<div class="overlay">
|
|
511
|
+
<header class="bar">
|
|
512
|
+
<span class="brand">Kiln</span>
|
|
513
|
+
<span class="route"><span class="method">${esc(meta.method)}</span>${esc(meta.pathname)}</span>
|
|
514
|
+
<span class="route">${esc(time)}</span>
|
|
515
|
+
<div class="actions">
|
|
516
|
+
<button id="copy" type="button">Copy stack</button>
|
|
517
|
+
<button id="dismiss" type="button">Dismiss</button>
|
|
518
|
+
</div>
|
|
519
|
+
</header>
|
|
520
|
+
<main>
|
|
521
|
+
<section class="hero">
|
|
522
|
+
<p class="kind">${esc(error.name)}</p>
|
|
358
523
|
<h1>${esc(error.message)}</h1>
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
<script>
|
|
374
|
-
document.getElementById("copy").onclick = async (e) => {
|
|
375
|
-
const text = document.getElementById("raw").content.textContent;
|
|
376
|
-
await navigator.clipboard.writeText(text);
|
|
377
|
-
e.target.textContent = "Copied";
|
|
378
|
-
};
|
|
379
|
-
document.addEventListener("keydown", (e) => {
|
|
380
|
-
if (e.key === "Escape") document.querySelector(".overlay").style.display = "none";
|
|
381
|
-
});
|
|
382
|
-
</script>
|
|
524
|
+
${where}
|
|
525
|
+
</section>
|
|
526
|
+
${hints.map(hintCard).join("")}
|
|
527
|
+
${origin ? sourceCard(origin) : ""}
|
|
528
|
+
<section class="card">
|
|
529
|
+
<div class="card-head"><span>Call stack</span><span>${appFrames.length} in your code</span></div>
|
|
530
|
+
<ol class="frames">${appList}</ol>
|
|
531
|
+
${internalBlock}
|
|
532
|
+
</section>
|
|
533
|
+
<footer>Save a file to reload. Press Esc to dismiss.</footer>
|
|
534
|
+
</main>
|
|
535
|
+
</div>
|
|
536
|
+
<template id="raw">${esc(error.stack ?? error.message)}</template>
|
|
537
|
+
<script>${OVERLAY_JS}</script>
|
|
383
538
|
</body>
|
|
384
539
|
</html>`;
|
|
385
540
|
}
|
|
@@ -387,57 +542,194 @@ function renderProdError(requestId) {
|
|
|
387
542
|
return `<!doctype html>
|
|
388
543
|
<html lang="en">
|
|
389
544
|
<head>
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
545
|
+
<meta charset="utf-8" />
|
|
546
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
547
|
+
<title>Server error</title>
|
|
548
|
+
<style>
|
|
549
|
+
:root { color-scheme: light dark; }
|
|
550
|
+
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #fafafa; color: #111;
|
|
551
|
+
font: 16px/1.6 system-ui, -apple-system, "Segoe UI", sans-serif; }
|
|
552
|
+
@media (prefers-color-scheme: dark) { body { background: #0e1116; color: #e6edf3; } }
|
|
553
|
+
main { max-width: 420px; padding: 32px; text-align: center; }
|
|
554
|
+
.status { margin: 0; font-size: 56px; font-weight: 700; color: #dc2626; }
|
|
555
|
+
.ref { font: 13px ui-monospace, monospace; opacity: 0.7; }
|
|
556
|
+
a { color: inherit; }
|
|
557
|
+
</style>
|
|
400
558
|
</head>
|
|
401
559
|
<body>
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
</
|
|
560
|
+
<main>
|
|
561
|
+
<p class="status">500</p>
|
|
562
|
+
<h1 style="font-size: 22px; margin: 8px 0;">Something went wrong</h1>
|
|
563
|
+
<p>The error was logged on the server.</p>
|
|
564
|
+
<p class="ref">Reference ${esc(requestId)}</p>
|
|
565
|
+
<p><a href="/">Back to home</a></p>
|
|
566
|
+
</main>
|
|
408
567
|
</body>
|
|
409
568
|
</html>`;
|
|
410
569
|
}
|
|
411
570
|
|
|
412
|
-
// src/
|
|
413
|
-
|
|
414
|
-
|
|
571
|
+
// packages/cli/src/versions.ts
|
|
572
|
+
import fs3 from "node:fs";
|
|
573
|
+
import path5 from "node:path";
|
|
574
|
+
import { createRequire } from "node:module";
|
|
575
|
+
var PACKAGES = ["core", "server", "client", "vite-plugin", "md", "adapter-vercel"];
|
|
576
|
+
function cliVersion() {
|
|
577
|
+
const file2 = new URL("../package.json", import.meta.url);
|
|
578
|
+
return JSON.parse(fs3.readFileSync(file2, "utf8")).version;
|
|
579
|
+
}
|
|
580
|
+
function findVersionProblems() {
|
|
581
|
+
const expected = cliVersion();
|
|
582
|
+
const req = createRequire(path5.join(paths.root, "package.json"));
|
|
583
|
+
const problems = [];
|
|
584
|
+
for (const short of PACKAGES) {
|
|
585
|
+
const name = `@kiln-js/${short}`;
|
|
586
|
+
let pkgPath;
|
|
587
|
+
try {
|
|
588
|
+
pkgPath = req.resolve(`${name}/package.json`);
|
|
589
|
+
} catch {
|
|
590
|
+
continue;
|
|
591
|
+
}
|
|
592
|
+
const found = JSON.parse(fs3.readFileSync(pkgPath, "utf8")).version;
|
|
593
|
+
if (found !== expected) {
|
|
594
|
+
problems.push({ name, found, location: path5.relative(paths.root, path5.dirname(pkgPath)) || "." });
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return problems;
|
|
598
|
+
}
|
|
599
|
+
function assertVersionsMatch() {
|
|
600
|
+
const problems = findVersionProblems();
|
|
601
|
+
if (problems.length === 0) return;
|
|
602
|
+
const expected = cliVersion();
|
|
603
|
+
const list = problems.map((p) => ` ${p.name} ${p.found} at ${p.location}`).join("\n");
|
|
604
|
+
throw new Error(
|
|
605
|
+
`The Kiln packages in this app do not match the CLI (${expected}):
|
|
606
|
+
${list}
|
|
607
|
+
|
|
608
|
+
Mixed versions cause "does not provide an export named" errors.
|
|
609
|
+
|
|
610
|
+
Fix:
|
|
611
|
+
1. Delete the stray installs: Remove-Item -Recurse -Force node_modules (in the folder printed above)
|
|
612
|
+
2. Run bun install at the monorepo root, so packages link to packages/
|
|
613
|
+
3. Run bun run dev from inside the app folder (for example examples\\kiln-docs)`
|
|
614
|
+
);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// packages/cli/src/preflight.ts
|
|
618
|
+
import fs4 from "node:fs";
|
|
619
|
+
import path6 from "node:path";
|
|
620
|
+
import { pathToFileURL } from "node:url";
|
|
621
|
+
var ENTRY_PACKAGES = ["@kiln-js/core", "@kiln-js/server", "@kiln-js/client", "@kiln-js/md"];
|
|
622
|
+
function resolvePackage(name) {
|
|
623
|
+
let dir = paths.root;
|
|
624
|
+
for (; ; ) {
|
|
625
|
+
const pkgDir = path6.join(dir, "node_modules", ...name.split("/"));
|
|
626
|
+
const pkgJson = path6.join(pkgDir, "package.json");
|
|
627
|
+
if (fs4.existsSync(pkgJson)) {
|
|
628
|
+
const json = JSON.parse(fs4.readFileSync(pkgJson, "utf8"));
|
|
629
|
+
const dot = json.exports?.["."];
|
|
630
|
+
const rel4 = (typeof dot === "string" ? dot : dot?.import) ?? json.module ?? json.main ?? "index.js";
|
|
631
|
+
return { file: path6.join(pkgDir, rel4) };
|
|
632
|
+
}
|
|
633
|
+
const parent = path6.dirname(dir);
|
|
634
|
+
if (parent === dir) return null;
|
|
635
|
+
dir = parent;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
async function preflightImports() {
|
|
639
|
+
const failures = [];
|
|
640
|
+
for (const name of ENTRY_PACKAGES) {
|
|
641
|
+
const resolved = resolvePackage(name);
|
|
642
|
+
if (!resolved) continue;
|
|
643
|
+
try {
|
|
644
|
+
await import(pathToFileURL(resolved.file).href);
|
|
645
|
+
} catch (err) {
|
|
646
|
+
failures.push({
|
|
647
|
+
name,
|
|
648
|
+
file: path6.relative(paths.root, resolved.file).replace(/\\/g, "/"),
|
|
649
|
+
message: err instanceof Error ? err.message : String(err)
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
if (failures.length === 0) return;
|
|
654
|
+
const lines = failures.map((f) => ` ${f.name} (${f.file})
|
|
655
|
+
${f.message}`).join("\n");
|
|
656
|
+
throw new Error(
|
|
657
|
+
`Kiln cannot load its own packages in this folder:
|
|
658
|
+
${lines}
|
|
659
|
+
|
|
660
|
+
The packages in use do not export what the app needs. This usually means an
|
|
661
|
+
old published copy is installed under this folder or a parent folder.
|
|
662
|
+
|
|
663
|
+
Fix:
|
|
664
|
+
1. Run Get-Command kiln -All and remove any global install:
|
|
665
|
+
npm uninstall -g @kiln-js/cli
|
|
666
|
+
bun remove -g @kiln-js/cli
|
|
667
|
+
2. Delete the stray folders reported above (node_modules and .kiln under examples\\).
|
|
668
|
+
3. From the monorepo root, run bun install and node scripts/build.mjs
|
|
669
|
+
4. From the app folder, run bun run dev`
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// packages/cli/src/dev.ts
|
|
674
|
+
function findAppFolders(base) {
|
|
675
|
+
try {
|
|
676
|
+
return fs5.readdirSync(base, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules").map((e) => path7.join(base, e.name)).filter((dir) => fs5.existsSync(path7.join(dir, "app", "pages")));
|
|
677
|
+
} catch {
|
|
678
|
+
return [];
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
function assertAppFolder() {
|
|
682
|
+
if (fs5.existsSync(paths.pagesDir)) return;
|
|
683
|
+
const found = findAppFolders(paths.root);
|
|
684
|
+
const hint = found.length > 0 ? `Found app folder(s) below this one. Run one of these instead:
|
|
685
|
+
` + found.map((d) => ` cd ${path7.relative(process.cwd(), d)} && kiln dev`).join("\n") : "Run kiln dev in the folder that contains package.json and app/pages.";
|
|
686
|
+
throw new Error(`No app/pages folder in ${paths.root}.
|
|
687
|
+
${hint}`);
|
|
688
|
+
}
|
|
689
|
+
function toError2(err) {
|
|
690
|
+
if (err instanceof Error) return err;
|
|
691
|
+
if (typeof err === "object" && err !== null) {
|
|
692
|
+
const { message, name } = err;
|
|
693
|
+
const error = new Error(String(message ?? "Unknown error"));
|
|
694
|
+
if (typeof name === "string") error.name = name;
|
|
695
|
+
return error;
|
|
696
|
+
}
|
|
697
|
+
return new Error(String(err));
|
|
698
|
+
}
|
|
699
|
+
function fixStack(vite, error) {
|
|
700
|
+
try {
|
|
701
|
+
vite.ssrFixStacktrace(error);
|
|
702
|
+
} catch {
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
function getHandlerFactory(mod, file2) {
|
|
415
706
|
const factory = mod.createHandler;
|
|
416
707
|
if (typeof factory !== "function") {
|
|
417
708
|
const exports = Object.keys(mod).join(", ") || "(none)";
|
|
418
|
-
throw new Error(`${
|
|
709
|
+
throw new Error(`${file2} must export "createHandler(assets)". Found exports: ${exports}`);
|
|
419
710
|
}
|
|
420
711
|
return factory;
|
|
421
712
|
}
|
|
422
713
|
async function toWebRequest(req, origin) {
|
|
423
|
-
const headers = new Headers;
|
|
714
|
+
const headers = new Headers();
|
|
424
715
|
for (const [key, value] of Object.entries(req.headers)) {
|
|
425
|
-
if (value ===
|
|
426
|
-
|
|
427
|
-
for (const v of Array.isArray(value) ? value : [value])
|
|
428
|
-
headers.append(key, v);
|
|
716
|
+
if (value === void 0) continue;
|
|
717
|
+
for (const v of Array.isArray(value) ? value : [value]) headers.append(key, v);
|
|
429
718
|
}
|
|
430
719
|
const init = { method: req.method, headers };
|
|
431
720
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
432
721
|
const chunks = [];
|
|
433
|
-
for await (const chunk of req)
|
|
434
|
-
chunks.push(chunk);
|
|
722
|
+
for await (const chunk of req) chunks.push(chunk);
|
|
435
723
|
init.body = Buffer.concat(chunks);
|
|
436
724
|
}
|
|
437
725
|
return new Request(new URL(req.url ?? "/", origin), init);
|
|
438
726
|
}
|
|
439
727
|
async function startDev(port) {
|
|
728
|
+
assertVersionsMatch();
|
|
729
|
+
await preflightImports();
|
|
730
|
+
assertAppFolder();
|
|
440
731
|
const startedAt = performance.now();
|
|
732
|
+
globalThis.__KILN_DEV__ = true;
|
|
441
733
|
loadEnvFiles("development");
|
|
442
734
|
const entries = resolveEntries();
|
|
443
735
|
const origin = `http://localhost:${port}`;
|
|
@@ -456,15 +748,16 @@ async function startDev(port) {
|
|
|
456
748
|
const body = isHtml ? await vite.transformIndexHtml(url, await response.text()) : Buffer.from(await response.arrayBuffer());
|
|
457
749
|
res.statusCode = response.status;
|
|
458
750
|
response.headers.forEach((value, key) => {
|
|
459
|
-
if (key !== "content-length")
|
|
460
|
-
res.setHeader(key, value);
|
|
751
|
+
if (key !== "content-length" && key !== "set-cookie") res.setHeader(key, value);
|
|
461
752
|
});
|
|
753
|
+
const cookies = response.headers.getSetCookie();
|
|
754
|
+
if (cookies.length) res.setHeader("set-cookie", cookies);
|
|
462
755
|
res.end(body);
|
|
463
756
|
lastRenderFailed = false;
|
|
464
757
|
log.request(req.method ?? "GET", pathname, response.status, formatDuration(performance.now() - start));
|
|
465
758
|
} catch (err) {
|
|
466
759
|
const error = toError2(err);
|
|
467
|
-
vite
|
|
760
|
+
fixStack(vite, error);
|
|
468
761
|
lastRenderFailed = true;
|
|
469
762
|
log.error(`${req.method} ${pathname} 500 ${formatDuration(performance.now() - start)}`);
|
|
470
763
|
printError(error, `${req.method} ${pathname}`);
|
|
@@ -483,18 +776,22 @@ async function startDev(port) {
|
|
|
483
776
|
}
|
|
484
777
|
const server = http.createServer((req, res) => {
|
|
485
778
|
vite.middlewares(req, res, () => {
|
|
486
|
-
handleSsr(req, res);
|
|
779
|
+
void handleSsr(req, res);
|
|
487
780
|
});
|
|
488
781
|
});
|
|
489
782
|
vite = await createViteServer({
|
|
490
783
|
root: paths.root,
|
|
491
784
|
appType: "custom",
|
|
492
|
-
plugins:
|
|
785
|
+
plugins: kiln({
|
|
786
|
+
pagesDir: paths.pagesDir,
|
|
787
|
+
apiDir: paths.apiDir,
|
|
788
|
+
appDir: path7.join(paths.root, "app")
|
|
789
|
+
}),
|
|
493
790
|
logLevel: "warn",
|
|
494
791
|
server: { middlewareMode: true, hmr: { server } }
|
|
495
792
|
});
|
|
496
|
-
vite.watcher.on("change", (
|
|
497
|
-
const shown =
|
|
793
|
+
vite.watcher.on("change", (file2) => {
|
|
794
|
+
const shown = file2.replace(paths.root, "").replace(/\\/g, "/");
|
|
498
795
|
log.change(shown);
|
|
499
796
|
if (lastRenderFailed) {
|
|
500
797
|
lastRenderFailed = false;
|
|
@@ -502,11 +799,14 @@ async function startDev(port) {
|
|
|
502
799
|
}
|
|
503
800
|
});
|
|
504
801
|
server.listen(port, () => {
|
|
505
|
-
box(
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
802
|
+
box(
|
|
803
|
+
[
|
|
804
|
+
colors.bold("Kiln dev server"),
|
|
805
|
+
`${colors.sky(origin)} ${colors.gray(`ready in ${formatDuration(performance.now() - startedAt)}`)}`,
|
|
806
|
+
colors.dim("press Ctrl+C to stop")
|
|
807
|
+
],
|
|
808
|
+
colors.fire
|
|
809
|
+
);
|
|
510
810
|
});
|
|
511
811
|
process.once("SIGINT", async () => {
|
|
512
812
|
log.info("Shutting down");
|
|
@@ -516,18 +816,18 @@ async function startDev(port) {
|
|
|
516
816
|
});
|
|
517
817
|
}
|
|
518
818
|
|
|
519
|
-
// src/build.ts
|
|
520
|
-
import
|
|
521
|
-
import
|
|
819
|
+
// packages/cli/src/build.ts
|
|
820
|
+
import fs6 from "node:fs";
|
|
821
|
+
import path8 from "node:path";
|
|
522
822
|
import { build } from "vite";
|
|
523
823
|
import { adaptVercel } from "@kiln-js/adapter-vercel";
|
|
824
|
+
import { kiln as kiln2 } from "@kiln-js/vite-plugin";
|
|
524
825
|
var TARGETS = ["none", "vercel"];
|
|
525
826
|
function dirSize(dir) {
|
|
526
|
-
if (!
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
return sum + (entry.isDirectory() ? dirSize(full) : fs4.statSync(full).size);
|
|
827
|
+
if (!fs6.existsSync(dir)) return 0;
|
|
828
|
+
return fs6.readdirSync(dir, { withFileTypes: true }).reduce((sum, entry) => {
|
|
829
|
+
const full = path8.join(dir, entry.name);
|
|
830
|
+
return sum + (entry.isDirectory() ? dirSize(full) : fs6.statSync(full).size);
|
|
531
831
|
}, 0);
|
|
532
832
|
}
|
|
533
833
|
async function runBuild(target = "none") {
|
|
@@ -537,37 +837,46 @@ async function runBuild(target = "none") {
|
|
|
537
837
|
const total = performance.now();
|
|
538
838
|
loadEnvFiles("production");
|
|
539
839
|
const entries = resolveEntries();
|
|
540
|
-
const plugins =
|
|
840
|
+
const plugins = kiln2({ pagesDir: paths.pagesDir, apiDir: paths.apiDir });
|
|
541
841
|
log.info(`Building for production ${colors.gray(`\xB7 target ${target}`)}`);
|
|
542
|
-
await task(
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
outDir: paths.serverOut,
|
|
560
|
-
emptyOutDir: true,
|
|
561
|
-
rollupOptions: { output: { entryFileNames: "server.js" } }
|
|
562
|
-
}
|
|
563
|
-
}));
|
|
564
|
-
if (target === "vercel") {
|
|
565
|
-
await task("vercel output", () => adaptVercel({
|
|
842
|
+
await task(
|
|
843
|
+
"client bundle",
|
|
844
|
+
() => build({
|
|
845
|
+
root: paths.root,
|
|
846
|
+
plugins,
|
|
847
|
+
logLevel: "warn",
|
|
848
|
+
build: {
|
|
849
|
+
outDir: paths.clientOut,
|
|
850
|
+
emptyOutDir: true,
|
|
851
|
+
manifest: true,
|
|
852
|
+
rollupOptions: { input: entries.client }
|
|
853
|
+
}
|
|
854
|
+
})
|
|
855
|
+
);
|
|
856
|
+
await task(
|
|
857
|
+
"server bundle",
|
|
858
|
+
() => build({
|
|
566
859
|
root: paths.root,
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
860
|
+
plugins,
|
|
861
|
+
logLevel: "warn",
|
|
862
|
+
build: {
|
|
863
|
+
ssr: entries.server,
|
|
864
|
+
outDir: paths.serverOut,
|
|
865
|
+
emptyOutDir: true,
|
|
866
|
+
rollupOptions: { output: { entryFileNames: "server.js" } }
|
|
867
|
+
}
|
|
868
|
+
})
|
|
869
|
+
);
|
|
870
|
+
if (target === "vercel") {
|
|
871
|
+
await task(
|
|
872
|
+
"vercel output",
|
|
873
|
+
() => adaptVercel({
|
|
874
|
+
root: paths.root,
|
|
875
|
+
clientOut: paths.clientOut,
|
|
876
|
+
serverOut: paths.serverOut,
|
|
877
|
+
clientRel: entries.clientRel
|
|
878
|
+
})
|
|
879
|
+
);
|
|
571
880
|
}
|
|
572
881
|
const lines = [
|
|
573
882
|
`${colors.bold("Build complete")} ${colors.gray(formatDuration(performance.now() - total))}`,
|
|
@@ -580,30 +889,47 @@ async function runBuild(target = "none") {
|
|
|
580
889
|
box(lines, colors.mint);
|
|
581
890
|
}
|
|
582
891
|
|
|
583
|
-
// src/start.ts
|
|
584
|
-
import
|
|
585
|
-
import
|
|
892
|
+
// packages/cli/src/start.ts
|
|
893
|
+
import fs8 from "node:fs";
|
|
894
|
+
import path10 from "node:path";
|
|
895
|
+
import { randomUUID } from "node:crypto";
|
|
896
|
+
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
586
897
|
|
|
587
|
-
// src/compress.ts
|
|
588
|
-
import
|
|
898
|
+
// packages/cli/src/compress.ts
|
|
899
|
+
import fs7 from "node:fs";
|
|
900
|
+
import path9 from "node:path";
|
|
901
|
+
import { brotliCompressSync, gzipSync, constants } from "node:zlib";
|
|
589
902
|
var COMPRESSIBLE = /^(text\/|application\/(javascript|json|xml|xhtml\+xml|wasm)|image\/svg\+xml)/;
|
|
590
903
|
var MIN_SIZE = 1024;
|
|
591
904
|
var MAX_CACHE = 64;
|
|
592
|
-
var
|
|
905
|
+
var MIME = {
|
|
906
|
+
".html": "text/html; charset=utf-8",
|
|
907
|
+
".js": "text/javascript; charset=utf-8",
|
|
908
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
909
|
+
".css": "text/css; charset=utf-8",
|
|
910
|
+
".json": "application/json; charset=utf-8",
|
|
911
|
+
".map": "application/json; charset=utf-8",
|
|
912
|
+
".txt": "text/plain; charset=utf-8",
|
|
913
|
+
".svg": "image/svg+xml",
|
|
914
|
+
".png": "image/png",
|
|
915
|
+
".jpg": "image/jpeg",
|
|
916
|
+
".jpeg": "image/jpeg",
|
|
917
|
+
".gif": "image/gif",
|
|
918
|
+
".webp": "image/webp",
|
|
919
|
+
".ico": "image/x-icon",
|
|
920
|
+
".woff": "font/woff",
|
|
921
|
+
".woff2": "font/woff2"
|
|
922
|
+
};
|
|
923
|
+
var staticCache = /* @__PURE__ */ new Map();
|
|
593
924
|
function cacheSet(key, value) {
|
|
594
|
-
if (staticCache.size >= MAX_CACHE)
|
|
595
|
-
staticCache.delete(staticCache.keys().next().value);
|
|
596
|
-
}
|
|
925
|
+
if (staticCache.size >= MAX_CACHE) staticCache.delete(staticCache.keys().next().value);
|
|
597
926
|
staticCache.set(key, value);
|
|
598
927
|
}
|
|
599
928
|
function pickEncoding(header) {
|
|
600
|
-
if (!header)
|
|
601
|
-
return null;
|
|
929
|
+
if (!header) return null;
|
|
602
930
|
const accepts = header.toLowerCase();
|
|
603
|
-
if (/\bbr\b/.test(accepts))
|
|
604
|
-
|
|
605
|
-
if (/\bgzip\b/.test(accepts))
|
|
606
|
-
return "gzip";
|
|
931
|
+
if (/\bbr\b/.test(accepts)) return "br";
|
|
932
|
+
if (/\bgzip\b/.test(accepts)) return "gzip";
|
|
607
933
|
return null;
|
|
608
934
|
}
|
|
609
935
|
function encode(body, encoding) {
|
|
@@ -613,27 +939,31 @@ function encode(body, encoding) {
|
|
|
613
939
|
async function compressResponse(req, res) {
|
|
614
940
|
const headers = new Headers(res.headers);
|
|
615
941
|
headers.append("vary", "Accept-Encoding");
|
|
616
|
-
const
|
|
942
|
+
const accept = req.headers.get("accept-encoding");
|
|
617
943
|
const type = headers.get("content-type") ?? "";
|
|
618
|
-
|
|
944
|
+
const skip = !res.body || req.method === "HEAD" || headers.has("content-encoding") || !COMPRESSIBLE.test(type) || !pickEncoding(accept);
|
|
945
|
+
if (skip || !res.body) return new Response(res.body, { status: res.status, headers });
|
|
946
|
+
if (!(accept ?? "").toLowerCase().includes("gzip")) {
|
|
619
947
|
return new Response(res.body, { status: res.status, headers });
|
|
620
948
|
}
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
headers.set("content-encoding", encoding);
|
|
626
|
-
headers.set("content-length", String(out.byteLength));
|
|
627
|
-
return new Response(out, { status: res.status, headers });
|
|
949
|
+
headers.delete("content-length");
|
|
950
|
+
headers.set("content-encoding", "gzip");
|
|
951
|
+
const gzipped = res.body.pipeThrough(new CompressionStream("gzip"));
|
|
952
|
+
return new Response(gzipped, { status: res.status, headers });
|
|
628
953
|
}
|
|
629
954
|
async function serveStatic(req, filePath) {
|
|
630
|
-
|
|
631
|
-
|
|
955
|
+
let stat;
|
|
956
|
+
try {
|
|
957
|
+
stat = await fs7.promises.stat(filePath);
|
|
958
|
+
} catch {
|
|
632
959
|
return null;
|
|
633
|
-
|
|
960
|
+
}
|
|
961
|
+
if (!stat.isFile()) return null;
|
|
962
|
+
const type = MIME[path9.extname(filePath).toLowerCase()] ?? "application/octet-stream";
|
|
963
|
+
const etag = `W/"${stat.size}-${stat.mtimeMs}"`;
|
|
634
964
|
const isHashed = /[\\/]assets[\\/]/.test(filePath);
|
|
635
965
|
const headers = new Headers({
|
|
636
|
-
"content-type":
|
|
966
|
+
"content-type": type,
|
|
637
967
|
etag,
|
|
638
968
|
"cache-control": isHashed ? "public, max-age=31536000, immutable" : "no-cache",
|
|
639
969
|
vary: "Accept-Encoding"
|
|
@@ -641,14 +971,16 @@ async function serveStatic(req, filePath) {
|
|
|
641
971
|
if (req.headers.get("if-none-match") === etag) {
|
|
642
972
|
return new Response(null, { status: 304, headers });
|
|
643
973
|
}
|
|
974
|
+
const raw = new Uint8Array(await fs7.promises.readFile(filePath));
|
|
644
975
|
const encoding = pickEncoding(req.headers.get("accept-encoding"));
|
|
645
|
-
if (!encoding || !COMPRESSIBLE.test(
|
|
646
|
-
|
|
976
|
+
if (!encoding || !COMPRESSIBLE.test(type) || raw.byteLength < MIN_SIZE) {
|
|
977
|
+
headers.set("content-length", String(raw.byteLength));
|
|
978
|
+
return new Response(raw, { headers });
|
|
647
979
|
}
|
|
648
980
|
const key = `${filePath}|${etag}|${encoding}`;
|
|
649
981
|
let body = staticCache.get(key);
|
|
650
982
|
if (!body) {
|
|
651
|
-
body = encode(
|
|
983
|
+
body = encode(raw, encoding);
|
|
652
984
|
cacheSet(key, body);
|
|
653
985
|
}
|
|
654
986
|
headers.set("content-encoding", encoding);
|
|
@@ -656,51 +988,111 @@ async function serveStatic(req, filePath) {
|
|
|
656
988
|
return new Response(body, { headers });
|
|
657
989
|
}
|
|
658
990
|
|
|
659
|
-
// src/
|
|
991
|
+
// packages/cli/src/runtime.ts
|
|
992
|
+
import http2 from "node:http";
|
|
993
|
+
var runtime = globalThis.Bun ? "bun" : "node";
|
|
994
|
+
var nodeVersion = process.versions.node;
|
|
995
|
+
function serve(port, fetch) {
|
|
996
|
+
if (runtime === "bun") {
|
|
997
|
+
const bun = globalThis.Bun;
|
|
998
|
+
const server2 = bun.serve({ port, fetch });
|
|
999
|
+
return { port, stop: () => server2.stop() };
|
|
1000
|
+
}
|
|
1001
|
+
const server = http2.createServer(async (req, res) => {
|
|
1002
|
+
try {
|
|
1003
|
+
await writeResponse(res, await fetch(await toRequest(req, port)));
|
|
1004
|
+
} catch (err) {
|
|
1005
|
+
console.error("[kiln] request failed", err);
|
|
1006
|
+
if (!res.headersSent) res.statusCode = 500;
|
|
1007
|
+
res.end("Internal Server Error");
|
|
1008
|
+
}
|
|
1009
|
+
});
|
|
1010
|
+
server.listen(port);
|
|
1011
|
+
return { port, stop: () => server.close() };
|
|
1012
|
+
}
|
|
1013
|
+
async function toRequest(req, port) {
|
|
1014
|
+
const headers = new Headers();
|
|
1015
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
1016
|
+
if (value === void 0) continue;
|
|
1017
|
+
for (const v of Array.isArray(value) ? value : [value]) headers.append(key, v);
|
|
1018
|
+
}
|
|
1019
|
+
const method = req.method ?? "GET";
|
|
1020
|
+
const init = { method, headers };
|
|
1021
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
1022
|
+
const chunks = [];
|
|
1023
|
+
for await (const chunk of req) chunks.push(chunk);
|
|
1024
|
+
init.body = Buffer.concat(chunks);
|
|
1025
|
+
}
|
|
1026
|
+
return new Request(new URL(req.url ?? "/", `http://localhost:${port}`), init);
|
|
1027
|
+
}
|
|
1028
|
+
async function writeResponse(res, response) {
|
|
1029
|
+
res.statusCode = response.status;
|
|
1030
|
+
response.headers.forEach((value, key) => {
|
|
1031
|
+
if (key !== "set-cookie") res.setHeader(key, value);
|
|
1032
|
+
});
|
|
1033
|
+
const cookies = response.headers.getSetCookie?.() ?? [];
|
|
1034
|
+
if (cookies.length) res.setHeader("set-cookie", cookies);
|
|
1035
|
+
if (!response.body) {
|
|
1036
|
+
res.end();
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
const reader = response.body.getReader();
|
|
1040
|
+
for (; ; ) {
|
|
1041
|
+
const { done, value } = await reader.read();
|
|
1042
|
+
if (done) break;
|
|
1043
|
+
res.write(value);
|
|
1044
|
+
}
|
|
1045
|
+
res.end();
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// packages/cli/src/start.ts
|
|
1049
|
+
function safeDecode(p) {
|
|
1050
|
+
try {
|
|
1051
|
+
return decodeURIComponent(p);
|
|
1052
|
+
} catch {
|
|
1053
|
+
return null;
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
660
1056
|
async function runStart(port) {
|
|
661
1057
|
const startedAt = performance.now();
|
|
662
1058
|
loadEnvFiles("production");
|
|
663
1059
|
const { clientRel } = resolveEntries();
|
|
664
|
-
const manifest = JSON.parse(
|
|
1060
|
+
const manifest = JSON.parse(fs8.readFileSync(path10.join(paths.clientOut, ".vite", "manifest.json"), "utf8"));
|
|
665
1061
|
const entry = manifest[clientRel];
|
|
666
|
-
if (!entry)
|
|
667
|
-
throw new Error(`No manifest entry for ${clientRel}. Run "kiln build" first.`);
|
|
1062
|
+
if (!entry) throw new Error(`No manifest entry for ${clientRel}. Run "kiln build" first.`);
|
|
668
1063
|
const assets = {
|
|
669
|
-
head: (entry.css ?? []).map((href) => `<link rel="stylesheet" href="/${href}">`).join(
|
|
670
|
-
`),
|
|
1064
|
+
head: (entry.css ?? []).map((href) => `<link rel="stylesheet" href="/${href}">`).join("\n"),
|
|
671
1065
|
entry: `/${entry.file}`
|
|
672
1066
|
};
|
|
673
|
-
const serverEntry = await import(pathToFileURL2(
|
|
1067
|
+
const serverEntry = await import(pathToFileURL2(path10.join(paths.serverOut, "server.js")).href);
|
|
674
1068
|
const handler = serverEntry.createHandler(assets);
|
|
675
|
-
const server =
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
if (
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
return asset;
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
const res = await compressResponse(req, await handler(req));
|
|
691
|
-
log.request(req.method, pathname, res.status, formatDuration(performance.now() - started));
|
|
692
|
-
return res;
|
|
693
|
-
} catch (err) {
|
|
694
|
-
log.error(`${req.method} ${pathname} 500 ${formatDuration(performance.now() - started)} [${requestId}]`);
|
|
695
|
-
printError(err, `${req.method} ${pathname} [${requestId}]`);
|
|
696
|
-
if (pathname.startsWith("/api/")) {
|
|
697
|
-
return Response.json({ error: "Internal Server Error", requestId }, { status: 500 });
|
|
1069
|
+
const server = serve(port, async (req) => {
|
|
1070
|
+
const started = performance.now();
|
|
1071
|
+
const { pathname } = new URL(req.url);
|
|
1072
|
+
const requestId = randomUUID().slice(0, 8);
|
|
1073
|
+
try {
|
|
1074
|
+
if (pathname !== "/") {
|
|
1075
|
+
const decoded = safeDecode(pathname);
|
|
1076
|
+
if (decoded === null) return new Response("Bad Request", { status: 400 });
|
|
1077
|
+
const filePath = path10.join(paths.clientOut, decoded);
|
|
1078
|
+
if (filePath.startsWith(paths.clientOut + path10.sep)) {
|
|
1079
|
+
const asset = await serveStatic(req, filePath);
|
|
1080
|
+
if (asset) return asset;
|
|
698
1081
|
}
|
|
699
|
-
return new Response(renderProdError(requestId), {
|
|
700
|
-
status: 500,
|
|
701
|
-
headers: { "content-type": "text/html; charset=utf-8" }
|
|
702
|
-
});
|
|
703
1082
|
}
|
|
1083
|
+
const res = await compressResponse(req, await handler(req));
|
|
1084
|
+
log.request(req.method, pathname, res.status, formatDuration(performance.now() - started));
|
|
1085
|
+
return res;
|
|
1086
|
+
} catch (err) {
|
|
1087
|
+
log.error(`${req.method} ${pathname} 500 ${formatDuration(performance.now() - started)} [${requestId}]`);
|
|
1088
|
+
printError(err, `${req.method} ${pathname} [${requestId}]`);
|
|
1089
|
+
if (pathname.startsWith("/api/")) {
|
|
1090
|
+
return Response.json({ error: "Internal Server Error", requestId }, { status: 500 });
|
|
1091
|
+
}
|
|
1092
|
+
return new Response(renderProdError(requestId), {
|
|
1093
|
+
status: 500,
|
|
1094
|
+
headers: { "content-type": "text/html; charset=utf-8" }
|
|
1095
|
+
});
|
|
704
1096
|
}
|
|
705
1097
|
});
|
|
706
1098
|
const shutdown = () => {
|
|
@@ -710,15 +1102,18 @@ async function runStart(port) {
|
|
|
710
1102
|
};
|
|
711
1103
|
process.once("SIGINT", shutdown);
|
|
712
1104
|
process.once("SIGTERM", shutdown);
|
|
713
|
-
box(
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
1105
|
+
box(
|
|
1106
|
+
[
|
|
1107
|
+
colors.bold("Kiln production server"),
|
|
1108
|
+
`${colors.sky(`http://localhost:${port}`)} ${colors.gray(`${runtime} \xB7 ready in ${formatDuration(performance.now() - startedAt)}`)}`
|
|
1109
|
+
],
|
|
1110
|
+
colors.mint
|
|
1111
|
+
);
|
|
717
1112
|
}
|
|
718
1113
|
|
|
719
|
-
// src/routes.ts
|
|
720
|
-
import
|
|
721
|
-
import
|
|
1114
|
+
// packages/cli/src/routes.ts
|
|
1115
|
+
import fs9 from "node:fs";
|
|
1116
|
+
import path11 from "node:path";
|
|
722
1117
|
import { scanRoutes, scanApi } from "@kiln-js/core/scan";
|
|
723
1118
|
var METHOD_RE = /export\s+(?:async\s+)?(?:function|const)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;
|
|
724
1119
|
var MODE_COLORS = {
|
|
@@ -726,9 +1121,9 @@ var MODE_COLORS = {
|
|
|
726
1121
|
server: colors.sky,
|
|
727
1122
|
client: colors.violet
|
|
728
1123
|
};
|
|
729
|
-
var
|
|
730
|
-
function methodsOf(
|
|
731
|
-
const src =
|
|
1124
|
+
var rel3 = (file2) => path11.relative(paths.root, file2).split(path11.sep).join("/");
|
|
1125
|
+
function methodsOf(file2) {
|
|
1126
|
+
const src = fs9.readFileSync(file2, "utf8");
|
|
732
1127
|
return [...src.matchAll(METHOD_RE)].map((m) => m[1]);
|
|
733
1128
|
}
|
|
734
1129
|
function printRoutes() {
|
|
@@ -739,7 +1134,7 @@ function printRoutes() {
|
|
|
739
1134
|
colors.bold(r.pattern),
|
|
740
1135
|
colors.gray("page"),
|
|
741
1136
|
MODE_COLORS[r.mode](r.mode),
|
|
742
|
-
colors.dim(
|
|
1137
|
+
colors.dim(rel3(r.file))
|
|
743
1138
|
]),
|
|
744
1139
|
...apis.map((r) => {
|
|
745
1140
|
const methods = methodsOf(r.file);
|
|
@@ -747,7 +1142,7 @@ function printRoutes() {
|
|
|
747
1142
|
colors.bold(r.pattern),
|
|
748
1143
|
colors.fire("api"),
|
|
749
1144
|
methods.map((m) => methodColor(m)(m)).join(" ") || colors.gray("none"),
|
|
750
|
-
colors.dim(
|
|
1145
|
+
colors.dim(rel3(r.file))
|
|
751
1146
|
];
|
|
752
1147
|
})
|
|
753
1148
|
];
|
|
@@ -755,12 +1150,12 @@ function printRoutes() {
|
|
|
755
1150
|
table(rows, ["PATTERN", "KIND", "MODE / METHODS", "FILE"]);
|
|
756
1151
|
}
|
|
757
1152
|
|
|
758
|
-
// src/create.ts
|
|
759
|
-
import
|
|
760
|
-
import
|
|
1153
|
+
// packages/cli/src/create.ts
|
|
1154
|
+
import fs10 from "node:fs";
|
|
1155
|
+
import path12 from "node:path";
|
|
761
1156
|
import inquirer from "inquirer";
|
|
762
1157
|
|
|
763
|
-
// src/templates.ts
|
|
1158
|
+
// packages/cli/src/templates.ts
|
|
764
1159
|
var SCOPE = "@kiln-js";
|
|
765
1160
|
var CLI_PACKAGE = "kiln";
|
|
766
1161
|
var KILN_VERSION = "0.1.3";
|
|
@@ -770,11 +1165,8 @@ var kilnDep = (linked) => linked ? "*" : `^${KILN_VERSION}`;
|
|
|
770
1165
|
var SUFFIX = { universal: "", server: ".server", client: ".client" };
|
|
771
1166
|
function homePage(name, mode) {
|
|
772
1167
|
const stateful = mode !== "server";
|
|
773
|
-
return `${stateful ?
|
|
774
|
-
|
|
775
|
-
` : ""}export default function Home() {
|
|
776
|
-
${stateful ? ` const [count, setCount] = useState(0);
|
|
777
|
-
` : ""} return (
|
|
1168
|
+
return `${stateful ? 'import { useState } from "react";\n\n' : ""}export default function Home() {
|
|
1169
|
+
${stateful ? " const [count, setCount] = useState(0);\n" : ""} return (
|
|
778
1170
|
<section>
|
|
779
1171
|
<kiln:title>Home \xB7 ${name}</kiln:title>
|
|
780
1172
|
<h1>Welcome to ${name}</h1>
|
|
@@ -803,8 +1195,7 @@ export default function Layout({ children }: { children: ReactNode }) {
|
|
|
803
1195
|
<nav>
|
|
804
1196
|
<Link href="/">Home</Link>{" "}
|
|
805
1197
|
<Link href="/about">About</Link>{" "}
|
|
806
|
-
${withBlog ?
|
|
807
|
-
<Link href="/pricing">Pricing</Link>` : ""}
|
|
1198
|
+
${withBlog ? '<Link href="/blog">Blog</Link>{" "}\n <Link href="/pricing">Pricing</Link>' : ""}
|
|
808
1199
|
</nav>
|
|
809
1200
|
<main>{children}</main>
|
|
810
1201
|
</>
|
|
@@ -908,15 +1299,9 @@ function projectFiles(o) {
|
|
|
908
1299
|
vite: VITE_VERSION
|
|
909
1300
|
}
|
|
910
1301
|
};
|
|
911
|
-
files["package.json"] = JSON.stringify(pkgJson, null, 2) +
|
|
912
|
-
`;
|
|
1302
|
+
files["package.json"] = JSON.stringify(pkgJson, null, 2) + "\n";
|
|
913
1303
|
files["tsconfig.json"] = TSCONFIG;
|
|
914
|
-
files[".gitignore"] =
|
|
915
|
-
dist
|
|
916
|
-
.kiln
|
|
917
|
-
.env.local
|
|
918
|
-
.vercel
|
|
919
|
-
`;
|
|
1304
|
+
files[".gitignore"] = "node_modules\ndist\n.kiln\n.env.local\n.vercel\n";
|
|
920
1305
|
files["app/index.css"] = CSS;
|
|
921
1306
|
files["app/pages/_layout.tsx"] = LAYOUT(withBlog);
|
|
922
1307
|
files[`app/pages/index${SUFFIX[o.defaultMode]}.tsx`] = homePage(o.name, o.defaultMode);
|
|
@@ -928,8 +1313,7 @@ dist
|
|
|
928
1313
|
files["app/pages/blog/[slug].tsx"] = BLOG_POST;
|
|
929
1314
|
files["app/pages/(marketing)/pricing.tsx"] = PRICING;
|
|
930
1315
|
}
|
|
931
|
-
if (o.api)
|
|
932
|
-
files["app/api/health.ts"] = HEALTH;
|
|
1316
|
+
if (o.api) files["app/api/health.ts"] = HEALTH;
|
|
933
1317
|
if (o.env) {
|
|
934
1318
|
files[".env"] = `# Exposed to the browser through import.meta.env
|
|
935
1319
|
KILN_PUBLIC_SITE_NAME=${o.name}
|
|
@@ -951,7 +1335,8 @@ export function createHandler(assets: KilnAssets) {
|
|
|
951
1335
|
return files;
|
|
952
1336
|
}
|
|
953
1337
|
|
|
954
|
-
// src/create.ts
|
|
1338
|
+
// packages/cli/src/create.ts
|
|
1339
|
+
import { spawn } from "node:child_process";
|
|
955
1340
|
async function runCreate(nameArg) {
|
|
956
1341
|
const answers = await inquirer.prompt([
|
|
957
1342
|
{
|
|
@@ -1017,8 +1402,8 @@ async function runCreate(nameArg) {
|
|
|
1017
1402
|
customEntries: extras.includes("entries"),
|
|
1018
1403
|
linked: answers.linked
|
|
1019
1404
|
};
|
|
1020
|
-
const dir =
|
|
1021
|
-
if (
|
|
1405
|
+
const dir = path12.resolve(process.cwd(), options.name);
|
|
1406
|
+
if (fs10.existsSync(dir) && fs10.readdirSync(dir).length > 0) {
|
|
1022
1407
|
const { overwrite } = await inquirer.prompt([
|
|
1023
1408
|
{
|
|
1024
1409
|
type: "confirm",
|
|
@@ -1033,24 +1418,25 @@ async function runCreate(nameArg) {
|
|
|
1033
1418
|
}
|
|
1034
1419
|
}
|
|
1035
1420
|
log.step(`Writing project to ${dir}`);
|
|
1036
|
-
for (const [
|
|
1037
|
-
const target =
|
|
1038
|
-
|
|
1039
|
-
|
|
1421
|
+
for (const [rel4, content] of Object.entries(projectFiles(options))) {
|
|
1422
|
+
const target = path12.join(dir, rel4);
|
|
1423
|
+
fs10.mkdirSync(path12.dirname(target), { recursive: true });
|
|
1424
|
+
fs10.writeFileSync(target, content);
|
|
1040
1425
|
}
|
|
1041
1426
|
log.success(`Created ${options.name}`);
|
|
1042
1427
|
if (answers.install) {
|
|
1043
1428
|
log.step("Installing dependencies");
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1429
|
+
await new Promise(async (resolve, reject) => {
|
|
1430
|
+
const proc = spawn("bun", ["install"], { cwd: dir, stdio: "inherit", shell: true });
|
|
1431
|
+
proc.on("exit", (code) => code === 0 ? resolve() : reject(new Error("bun install failed")));
|
|
1432
|
+
});
|
|
1047
1433
|
}
|
|
1048
1434
|
log.info(`Next: cd ${options.name} && bun run dev`);
|
|
1049
1435
|
}
|
|
1050
1436
|
|
|
1051
|
-
// src/generate.ts
|
|
1052
|
-
import
|
|
1053
|
-
import
|
|
1437
|
+
// packages/cli/src/generate.ts
|
|
1438
|
+
import fs11 from "node:fs";
|
|
1439
|
+
import path13 from "node:path";
|
|
1054
1440
|
import inquirer2 from "inquirer";
|
|
1055
1441
|
var SUFFIX2 = { universal: "", server: ".server", client: ".client" };
|
|
1056
1442
|
var ALL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
|
|
@@ -1070,6 +1456,7 @@ function pageTemplate(name, loader) {
|
|
|
1070
1456
|
const dataProp = loader ? "data" : "";
|
|
1071
1457
|
const props = loader ? "{ data, params }" : "{ params }";
|
|
1072
1458
|
const propType = loader ? "{ data: { title: string; slug: Record<string, string> }; params: Record<string, string> }" : "{ params: Record<string, string> }";
|
|
1459
|
+
void dataProp;
|
|
1073
1460
|
return `${loaderBlock}export default function ${comp}(${props}: ${propType}) {
|
|
1074
1461
|
return (
|
|
1075
1462
|
<section>
|
|
@@ -1096,8 +1483,7 @@ function apiTemplate(methods) {
|
|
|
1096
1483
|
});
|
|
1097
1484
|
return `import type { ApiContext } from "@kiln-js/server";
|
|
1098
1485
|
|
|
1099
|
-
${handlers.join(
|
|
1100
|
-
`)}`;
|
|
1486
|
+
${handlers.join("\n")}`;
|
|
1101
1487
|
}
|
|
1102
1488
|
var LAYOUT_TEMPLATE = `import type { ReactNode } from "react";
|
|
1103
1489
|
|
|
@@ -1106,11 +1492,9 @@ export default function Layout({ children }: { children: ReactNode }) {
|
|
|
1106
1492
|
}
|
|
1107
1493
|
`;
|
|
1108
1494
|
function targetFor(kind, name, mode) {
|
|
1109
|
-
if (kind === "page")
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
return path9.join(paths.apiDir, `${name}.ts`);
|
|
1113
|
-
return path9.join(paths.pagesDir, name, "_layout.tsx");
|
|
1495
|
+
if (kind === "page") return path13.join(paths.pagesDir, `${name}${SUFFIX2[mode]}.tsx`);
|
|
1496
|
+
if (kind === "api") return path13.join(paths.apiDir, `${name}.ts`);
|
|
1497
|
+
return path13.join(paths.pagesDir, name, "_layout.tsx");
|
|
1114
1498
|
}
|
|
1115
1499
|
async function runGenerate(kindArg, nameArg, opts = {}) {
|
|
1116
1500
|
resolveEntries();
|
|
@@ -1152,7 +1536,7 @@ async function runGenerate(kindArg, nameArg, opts = {}) {
|
|
|
1152
1536
|
])).mode;
|
|
1153
1537
|
}
|
|
1154
1538
|
let loader = !!opts.loader;
|
|
1155
|
-
if (kind === "page" && opts.loader ===
|
|
1539
|
+
if (kind === "page" && opts.loader === void 0 && mode !== "client") {
|
|
1156
1540
|
loader = (await inquirer2.prompt([
|
|
1157
1541
|
{ type: "confirm", name: "loader", message: "Add a loader?", default: false }
|
|
1158
1542
|
])).loader;
|
|
@@ -1172,27 +1556,278 @@ async function runGenerate(kindArg, nameArg, opts = {}) {
|
|
|
1172
1556
|
])).methods;
|
|
1173
1557
|
}
|
|
1174
1558
|
const invalid = methods.filter((m) => !ALL_METHODS.includes(m));
|
|
1175
|
-
if (invalid.length)
|
|
1176
|
-
|
|
1177
|
-
if (methods.length === 0)
|
|
1178
|
-
throw new Error("Pick at least one HTTP method");
|
|
1559
|
+
if (invalid.length) throw new Error(`Unsupported method(s): ${invalid.join(", ")}`);
|
|
1560
|
+
if (methods.length === 0) throw new Error("Pick at least one HTTP method");
|
|
1179
1561
|
}
|
|
1180
|
-
const
|
|
1181
|
-
if (
|
|
1182
|
-
throw new Error(`${
|
|
1562
|
+
const file2 = targetFor(kind, name, mode);
|
|
1563
|
+
if (fs11.existsSync(file2)) {
|
|
1564
|
+
throw new Error(`${path13.relative(paths.root, file2)} already exists`);
|
|
1183
1565
|
}
|
|
1184
1566
|
const content = kind === "page" ? pageTemplate(name, loader) : kind === "api" ? apiTemplate(methods) : LAYOUT_TEMPLATE;
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
log.success(`Created ${
|
|
1567
|
+
fs11.mkdirSync(path13.dirname(file2), { recursive: true });
|
|
1568
|
+
fs11.writeFileSync(file2, content);
|
|
1569
|
+
log.success(`Created ${path13.relative(paths.root, file2).replace(/\\/g, "/")}`);
|
|
1188
1570
|
log.info("Run `kiln routes` to see the new route.");
|
|
1189
1571
|
}
|
|
1190
1572
|
|
|
1191
|
-
// src/
|
|
1192
|
-
|
|
1573
|
+
// packages/cli/src/typecheck.ts
|
|
1574
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1575
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
1576
|
+
import path14 from "node:path";
|
|
1577
|
+
var LINE = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/;
|
|
1578
|
+
function tscPath() {
|
|
1579
|
+
const req = createRequire2(path14.join(paths.root, "package.json"));
|
|
1580
|
+
return path14.join(path14.dirname(req.resolve("typescript/package.json")), "bin", "tsc");
|
|
1581
|
+
}
|
|
1582
|
+
function runTsc() {
|
|
1583
|
+
return new Promise((resolve) => {
|
|
1584
|
+
const proc = spawn2(process.execPath, [tscPath(), "--noEmit", "-p", "tsconfig.json", "--pretty", "false"], {
|
|
1585
|
+
cwd: paths.root
|
|
1586
|
+
});
|
|
1587
|
+
let output = "";
|
|
1588
|
+
proc.stdout.on("data", (d) => output += d);
|
|
1589
|
+
proc.stderr.on("data", (d) => output += d);
|
|
1590
|
+
proc.on("close", () => resolve(output));
|
|
1591
|
+
});
|
|
1592
|
+
}
|
|
1593
|
+
async function runTypecheck() {
|
|
1594
|
+
resolveEntries();
|
|
1595
|
+
log.info("Typechecking");
|
|
1596
|
+
const started = performance.now();
|
|
1597
|
+
const output = await runTsc();
|
|
1598
|
+
const errors = output.split(/\r?\n/).map((line) => line.match(LINE)).filter((m) => m !== null);
|
|
1599
|
+
for (const [, file2, line, col, code, message] of errors) {
|
|
1600
|
+
const shown = path14.relative(paths.root, path14.resolve(paths.root, file2)).replace(/\\/g, "/");
|
|
1601
|
+
console.log(` ${colors.red("\u2716")} ${colors.cyan(`${shown}:${line}:${col}`)} ${colors.gray(code)}`);
|
|
1602
|
+
console.log(` ${message}`);
|
|
1603
|
+
}
|
|
1604
|
+
const time = formatDuration(performance.now() - started);
|
|
1605
|
+
if (errors.length === 0 && /error/i.test(output) === false) {
|
|
1606
|
+
log.success(`No type errors ${colors.gray(`(${time})`)}`);
|
|
1607
|
+
return 0;
|
|
1608
|
+
}
|
|
1609
|
+
if (errors.length === 0) {
|
|
1610
|
+
console.log(output.trim());
|
|
1611
|
+
return 1;
|
|
1612
|
+
}
|
|
1613
|
+
log.error(`${errors.length} type error${errors.length === 1 ? "" : "s"} ${colors.gray(`(${time})`)}`);
|
|
1614
|
+
return errors.length;
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
// packages/cli/src/doctor.ts
|
|
1618
|
+
import fs12 from "node:fs";
|
|
1619
|
+
import path15 from "node:path";
|
|
1620
|
+
import { scanRoutes as scanRoutes2 } from "@kiln-js/core/scan";
|
|
1621
|
+
var file = (rel4) => path15.join(paths.root, rel4);
|
|
1622
|
+
var exists = (rel4) => fs12.existsSync(file(rel4));
|
|
1623
|
+
var read = (rel4) => exists(rel4) ? fs12.readFileSync(file(rel4), "utf8") : "";
|
|
1624
|
+
function atLeast(version, min) {
|
|
1625
|
+
const a = version.split(".").map(Number);
|
|
1626
|
+
const b = min.split(".").map(Number);
|
|
1627
|
+
for (let i = 0; i < b.length; i++) {
|
|
1628
|
+
if ((a[i] ?? 0) !== b[i]) return (a[i] ?? 0) > b[i];
|
|
1629
|
+
}
|
|
1630
|
+
return true;
|
|
1631
|
+
}
|
|
1632
|
+
function appSourceContains(needle) {
|
|
1633
|
+
const walk = (dir) => {
|
|
1634
|
+
if (!fs12.existsSync(dir)) return false;
|
|
1635
|
+
for (const entry of fs12.readdirSync(dir, { withFileTypes: true })) {
|
|
1636
|
+
if (entry.name === "node_modules") continue;
|
|
1637
|
+
const full = path15.join(dir, entry.name);
|
|
1638
|
+
if (entry.isDirectory()) {
|
|
1639
|
+
if (walk(full)) return true;
|
|
1640
|
+
} else if (/\.(tsx?|jsx?|mdx?)$/.test(entry.name) && fs12.readFileSync(full, "utf8").includes(needle)) {
|
|
1641
|
+
return true;
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
return false;
|
|
1645
|
+
};
|
|
1646
|
+
return walk(file("app"));
|
|
1647
|
+
}
|
|
1648
|
+
function checks() {
|
|
1649
|
+
const out = [];
|
|
1650
|
+
if (runtime === "bun") {
|
|
1651
|
+
const version = globalThis.Bun.version;
|
|
1652
|
+
out.push({
|
|
1653
|
+
name: "Runtime",
|
|
1654
|
+
status: atLeast(version, "1.1.0") ? "ok" : "warn",
|
|
1655
|
+
detail: `Bun ${version}${atLeast(version, "1.1.0") ? "" : " (1.1 or later recommended)"}`
|
|
1656
|
+
});
|
|
1657
|
+
} else {
|
|
1658
|
+
const ok = Number(nodeVersion.split(".")[0]) >= 18;
|
|
1659
|
+
out.push({
|
|
1660
|
+
name: "Runtime",
|
|
1661
|
+
status: ok ? "ok" : "fail",
|
|
1662
|
+
detail: `Node ${nodeVersion}${ok ? "" : " (18 or later required)"}`
|
|
1663
|
+
});
|
|
1664
|
+
}
|
|
1665
|
+
out.push({
|
|
1666
|
+
name: "package.json",
|
|
1667
|
+
status: exists("package.json") ? "ok" : "fail",
|
|
1668
|
+
detail: exists("package.json") ? "found" : "missing. Run this inside a Kiln project."
|
|
1669
|
+
});
|
|
1670
|
+
out.push({
|
|
1671
|
+
name: "node_modules",
|
|
1672
|
+
status: exists("node_modules") ? "ok" : "fail",
|
|
1673
|
+
detail: exists("node_modules") ? "installed" : "missing. Run bun install."
|
|
1674
|
+
});
|
|
1675
|
+
out.push({
|
|
1676
|
+
name: "tsconfig.json",
|
|
1677
|
+
status: exists("tsconfig.json") ? "ok" : "warn",
|
|
1678
|
+
detail: exists("tsconfig.json") ? "found" : "missing. kiln typecheck needs it."
|
|
1679
|
+
});
|
|
1680
|
+
try {
|
|
1681
|
+
const routes = scanRoutes2(paths.pagesDir);
|
|
1682
|
+
out.push({
|
|
1683
|
+
name: "Routes",
|
|
1684
|
+
status: routes.length > 0 ? "ok" : "fail",
|
|
1685
|
+
detail: routes.length > 0 ? `${routes.length} page routes, no conflicts` : "no pages in app/pages"
|
|
1686
|
+
});
|
|
1687
|
+
} catch (err) {
|
|
1688
|
+
out.push({ name: "Routes", status: "fail", detail: err instanceof Error ? err.message : String(err) });
|
|
1689
|
+
}
|
|
1690
|
+
const pkg2 = read("package.json");
|
|
1691
|
+
out.push({
|
|
1692
|
+
name: "kiln dependency",
|
|
1693
|
+
status: pkg2.includes('"kiln"') ? "ok" : "warn",
|
|
1694
|
+
detail: pkg2.includes('"kiln"') ? "listed" : "add kiln to devDependencies"
|
|
1695
|
+
});
|
|
1696
|
+
out.push({
|
|
1697
|
+
name: "React copies",
|
|
1698
|
+
status: exists("node_modules/react-dom/node_modules/react") ? "warn" : "ok",
|
|
1699
|
+
detail: exists("node_modules/react-dom/node_modules/react") ? "two copies of React are installed. Hooks can break. Pin one version." : "one copy"
|
|
1700
|
+
});
|
|
1701
|
+
const usesDb = appSourceContains("DATABASE_URL");
|
|
1702
|
+
const envDefines = /^DATABASE_URL=/m.test(read(".env.local") + read(".env"));
|
|
1703
|
+
out.push({
|
|
1704
|
+
name: "DATABASE_URL",
|
|
1705
|
+
status: !usesDb || envDefines ? "ok" : "warn",
|
|
1706
|
+
detail: !usesDb ? "not used" : envDefines ? "set in .env files" : "used in code but not in .env.local"
|
|
1707
|
+
});
|
|
1708
|
+
const usesMd = appSourceContains("@kiln-js/md");
|
|
1709
|
+
const configHasMd = /\bmd\s*\(/.test(read("vite.config.ts") + read("vite.config.js"));
|
|
1710
|
+
out.push({
|
|
1711
|
+
name: "Markdown plugin",
|
|
1712
|
+
status: !usesMd || configHasMd ? "ok" : "warn",
|
|
1713
|
+
detail: !usesMd ? "not used" : configHasMd ? "registered in vite.config" : "imported but md() is not in vite.config"
|
|
1714
|
+
});
|
|
1715
|
+
const versionProblems = findVersionProblems();
|
|
1716
|
+
out.push({
|
|
1717
|
+
name: "Kiln versions",
|
|
1718
|
+
status: versionProblems.length ? "fail" : "ok",
|
|
1719
|
+
detail: versionProblems.length ? versionProblems.map((p) => `${p.name} ${p.found} (CLI ${cliVersion()})`).join(", ") : `all match ${cliVersion()}`
|
|
1720
|
+
});
|
|
1721
|
+
return out;
|
|
1722
|
+
}
|
|
1723
|
+
function runDoctor() {
|
|
1724
|
+
log.info("Checking this project");
|
|
1725
|
+
const results = checks();
|
|
1726
|
+
const icon = {
|
|
1727
|
+
ok: colors.mint("\u2714"),
|
|
1728
|
+
warn: colors.yellow("!"),
|
|
1729
|
+
fail: colors.red("\u2716")
|
|
1730
|
+
};
|
|
1731
|
+
const width = Math.max(...results.map((r) => r.name.length)) + 2;
|
|
1732
|
+
for (const r of results) {
|
|
1733
|
+
console.log(` ${icon[r.status]} ${r.name.padEnd(width)} ${colors.gray(r.detail)}`);
|
|
1734
|
+
}
|
|
1735
|
+
const fails = results.filter((r) => r.status === "fail").length;
|
|
1736
|
+
const warns = results.filter((r) => r.status === "warn").length;
|
|
1737
|
+
console.log("");
|
|
1738
|
+
if (fails) log.error(`${fails} problem${fails === 1 ? "" : "s"} to fix${warns ? `, ${warns} warning${warns === 1 ? "" : "s"}` : ""}`);
|
|
1739
|
+
else if (warns) log.warn(`No blocking problems, ${warns} warning${warns === 1 ? "" : "s"}`);
|
|
1740
|
+
else log.success("Everything looks good");
|
|
1741
|
+
return fails ? 1 : 0;
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
// packages/cli/src/test.ts
|
|
1745
|
+
import { createServer as createViteServer2 } from "vite";
|
|
1746
|
+
import { kiln as kiln3 } from "@kiln-js/vite-plugin";
|
|
1747
|
+
import { scanRoutes as scanRoutes3 } from "@kiln-js/core/scan";
|
|
1748
|
+
function samplePath(pattern) {
|
|
1749
|
+
const parts = pattern.split("/").filter(Boolean).map((seg) => seg.startsWith(":") ? "example" : seg.startsWith("*") ? "a/b" : seg);
|
|
1750
|
+
return "/" + parts.join("/");
|
|
1751
|
+
}
|
|
1752
|
+
async function runTests(filters) {
|
|
1753
|
+
loadEnvFiles("development");
|
|
1754
|
+
const entries = resolveEntries();
|
|
1755
|
+
const origin = "http://localhost";
|
|
1756
|
+
const vite = await createViteServer2({
|
|
1757
|
+
root: paths.root,
|
|
1758
|
+
appType: "custom",
|
|
1759
|
+
plugins: kiln3({ pagesDir: paths.pagesDir, apiDir: paths.apiDir, appDir: "app" }),
|
|
1760
|
+
logLevel: "silent",
|
|
1761
|
+
server: { middlewareMode: true, hmr: false }
|
|
1762
|
+
});
|
|
1763
|
+
const results = [];
|
|
1764
|
+
try {
|
|
1765
|
+
const mod = await vite.ssrLoadModule(entries.server);
|
|
1766
|
+
const handler = mod.createHandler({
|
|
1767
|
+
head: "",
|
|
1768
|
+
entry: `/${entries.clientRel}`
|
|
1769
|
+
});
|
|
1770
|
+
const routes = scanRoutes3(paths.pagesDir).filter((r) => r.mode !== "client");
|
|
1771
|
+
const selected = routes.filter((r) => {
|
|
1772
|
+
const url = samplePath(r.pattern);
|
|
1773
|
+
return filters.length === 0 || filters.some((f) => url.startsWith(f));
|
|
1774
|
+
});
|
|
1775
|
+
log.info(`Rendering ${selected.length} page${selected.length === 1 ? "" : "s"}`);
|
|
1776
|
+
for (const route of selected) {
|
|
1777
|
+
const url = samplePath(route.pattern);
|
|
1778
|
+
const started = performance.now();
|
|
1779
|
+
const ms = () => performance.now() - started;
|
|
1780
|
+
try {
|
|
1781
|
+
const res = await handler(new Request(origin + url));
|
|
1782
|
+
const body = await res.text();
|
|
1783
|
+
const problems = [];
|
|
1784
|
+
const warnings = [];
|
|
1785
|
+
if (res.status >= 500) problems.push(`HTTP ${res.status} from the server`);
|
|
1786
|
+
if (res.status === 404) warnings.push("404 for the sample URL. Add fixture data if this page needs it.");
|
|
1787
|
+
if (body.trim().length === 0) problems.push("empty response body");
|
|
1788
|
+
if (/<title>Kiln App<\/title>/.test(body)) warnings.push("no <kiln:title>, so the default title is used");
|
|
1789
|
+
if (body.includes("Internal Server Error")) problems.push("the error page was rendered");
|
|
1790
|
+
results.push({ url, status: res.status, ms: ms(), problems, warnings });
|
|
1791
|
+
} catch (err) {
|
|
1792
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
1793
|
+
vite.ssrFixStacktrace(error);
|
|
1794
|
+
const hints = diagnose(error, parseFrames(error.stack ?? "")).map((h) => h.title);
|
|
1795
|
+
results.push({
|
|
1796
|
+
url,
|
|
1797
|
+
status: "error",
|
|
1798
|
+
ms: ms(),
|
|
1799
|
+
problems: [`${error.name}: ${error.message}`, ...hints.map((h) => `hint: ${h}`)],
|
|
1800
|
+
warnings: []
|
|
1801
|
+
});
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
} finally {
|
|
1805
|
+
await vite.close();
|
|
1806
|
+
}
|
|
1807
|
+
printResults(results);
|
|
1808
|
+
const failed = results.filter((r) => r.problems.length > 0).length;
|
|
1809
|
+
return failed;
|
|
1810
|
+
}
|
|
1811
|
+
function printResults(results) {
|
|
1812
|
+
for (const r of results) {
|
|
1813
|
+
const ok = r.problems.length === 0;
|
|
1814
|
+
const status = r.status === "error" ? colors.red("ERR") : r.status >= 500 ? colors.red(String(r.status)) : colors.mint(String(r.status));
|
|
1815
|
+
console.log(` ${ok ? colors.mint("\u2714") : colors.red("\u2716")} ${r.url.padEnd(28)} ${status} ${colors.gray(formatDuration(r.ms))}`);
|
|
1816
|
+
for (const p of r.problems) console.log(` ${colors.red("\u2716")} ${p}`);
|
|
1817
|
+
for (const w of r.warnings) console.log(` ${colors.yellow("!")} ${w}`);
|
|
1818
|
+
}
|
|
1819
|
+
const failed = results.filter((r) => r.problems.length > 0).length;
|
|
1820
|
+
console.log("");
|
|
1821
|
+
if (failed) log.error(`${failed} of ${results.length} page${results.length === 1 ? "" : "s"} failed`);
|
|
1822
|
+
else log.success(`All ${results.length} page${results.length === 1 ? "" : "s"} rendered`);
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1825
|
+
// packages/cli/src/index.ts
|
|
1826
|
+
var VERSION = "0.1.5";
|
|
1193
1827
|
var run = (fn) => async (...args) => {
|
|
1194
1828
|
try {
|
|
1195
|
-
await fn(...args);
|
|
1829
|
+
const result = await fn(...args);
|
|
1830
|
+
if (typeof result === "number" && result !== 0) process.exitCode = result;
|
|
1196
1831
|
} catch (err) {
|
|
1197
1832
|
printError(err, "while running kiln");
|
|
1198
1833
|
process.exitCode = 1;
|
|
@@ -1200,14 +1835,18 @@ var run = (fn) => async (...args) => {
|
|
|
1200
1835
|
};
|
|
1201
1836
|
var cli = cac("kiln");
|
|
1202
1837
|
cli.command("create [name]", "Scaffold a new Kiln app").action(run((name) => runCreate(name)));
|
|
1203
|
-
cli.command("dev", "Start the dev server with SSR and HMR").option("--port <port>", "Port to listen on", { default:
|
|
1838
|
+
cli.command("dev", "Start the dev server with SSR and HMR").option("--port <port>", "Port to listen on", { default: 3e3 }).action(run((o) => startDev(Number(o.port))));
|
|
1204
1839
|
cli.command("build", "Build client and server bundles").option("--target <target>", "Deploy target: none | vercel", { default: "none" }).action(run((o) => runBuild(o.target)));
|
|
1205
|
-
cli.command("start", "Serve the production build").option("--port <port>", "Port to listen on", { default:
|
|
1840
|
+
cli.command("start", "Serve the production build").option("--port <port>", "Port to listen on", { default: 3e3 }).action(run((o) => runStart(Number(o.port))));
|
|
1206
1841
|
cli.command("routes", "Print the route table").action(run(() => printRoutes()));
|
|
1207
|
-
cli.command("generate [kind] [name]", "Generate a page, API route, or layout").alias("g").option("--mode <mode>", "Page mode: universal | server | client").option("--loader", "Add a loader to a page").option("--methods <methods>", "API methods, comma-separated (GET,POST)").action(run(
|
|
1842
|
+
cli.command("generate [kind] [name]", "Generate a page, API route, or layout").alias("g").option("--mode <mode>", "Page mode: universal | server | client").option("--loader", "Add a loader to a page").option("--methods <methods>", "API methods, comma-separated (GET,POST)").action(run(
|
|
1843
|
+
(kind, name, options) => runGenerate(kind, name, options)
|
|
1844
|
+
));
|
|
1845
|
+
cli.command("typecheck", "Run TypeScript over the project").action(run(() => runTypecheck()));
|
|
1846
|
+
cli.command("doctor", "Check the project and its environment").action(run(() => runDoctor()));
|
|
1847
|
+
cli.command("test [...paths]", "Render every page and report errors").action(run((paths2) => runTests(paths2 ?? [])));
|
|
1208
1848
|
var first = process.argv[2];
|
|
1209
|
-
if (first && !first.startsWith("-"))
|
|
1210
|
-
banner(VERSION);
|
|
1849
|
+
if (first && !first.startsWith("-")) banner(VERSION);
|
|
1211
1850
|
cli.help();
|
|
1212
1851
|
cli.version(VERSION);
|
|
1213
1852
|
cli.parse();
|