@pracht/cli 1.1.5 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,27 +1,27 @@
1
1
  import { cpSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
 
4
- import { DEFAULT_SECURITY_HEADERS, VERSION } from "./constants.js";
4
+ import { VERSION } from "./constants.js";
5
5
 
6
6
  const ROUTE_STATE_REQUEST_HEADER = "x-pracht-route-state-request";
7
7
 
8
- export function setDefaultSecurityHeaders(res, headers = {}) {
9
- for (const [key, value] of Object.entries({
10
- ...DEFAULT_SECURITY_HEADERS,
11
- ...headers,
12
- })) {
13
- res.setHeader(key, value);
14
- }
8
+ interface VercelBuildOutputOptions {
9
+ functionName?: string;
10
+ headersManifest?: Record<string, Record<string, string>>;
11
+ isgRoutes: string[];
12
+ regions?: string[];
13
+ root: string;
14
+ staticRoutes: string[];
15
15
  }
16
16
 
17
17
  export function writeVercelBuildOutput({
18
18
  functionName,
19
19
  headersManifest = {},
20
+ isgRoutes,
20
21
  regions,
21
22
  root,
22
23
  staticRoutes,
23
- isgRoutes,
24
- }) {
24
+ }: VercelBuildOutputOptions): string {
25
25
  const outputDir = join(root, ".vercel/output");
26
26
  const staticDir = join(outputDir, "static");
27
27
  const functionDir = join(outputDir, "functions", `${functionName || "render"}.func`);
@@ -49,9 +49,19 @@ export function writeVercelBuildOutput({
49
49
  return ".vercel/output";
50
50
  }
51
51
 
52
- function createVercelOutputConfig({ functionName, headersManifest, staticRoutes, isgRoutes }) {
52
+ function createVercelOutputConfig({
53
+ functionName,
54
+ headersManifest,
55
+ staticRoutes,
56
+ isgRoutes,
57
+ }: {
58
+ functionName?: string;
59
+ headersManifest: Record<string, Record<string, string>>;
60
+ isgRoutes: string[];
61
+ staticRoutes: string[];
62
+ }): Record<string, unknown> {
53
63
  const target = `/${functionName || "render"}`;
54
- const routes = [
64
+ const routes: Record<string, unknown>[] = [
55
65
  {
56
66
  dest: target,
57
67
  has: [{ type: "header", key: ROUTE_STATE_REQUEST_HEADER, value: "1" }],
@@ -76,7 +86,7 @@ function createVercelOutputConfig({ functionName, headersManifest, staticRoutes,
76
86
  routes.push({ handle: "filesystem" });
77
87
  routes.push({ dest: target, src: "/(.*)" });
78
88
 
79
- const headers = [
89
+ const headers: Record<string, unknown>[] = [
80
90
  {
81
91
  headers: [
82
92
  {
@@ -111,8 +121,8 @@ function createVercelOutputConfig({ functionName, headersManifest, staticRoutes,
111
121
  };
112
122
  }
113
123
 
114
- function createVercelFunctionConfig({ regions }) {
115
- const config = {
124
+ function createVercelFunctionConfig({ regions }: { regions?: string[] }): Record<string, unknown> {
125
+ const config: Record<string, unknown> = {
116
126
  entrypoint: "server.js",
117
127
  runtime: "edge",
118
128
  };
@@ -124,11 +134,11 @@ function createVercelFunctionConfig({ regions }) {
124
134
  return config;
125
135
  }
126
136
 
127
- function sortStaticRoutes(routes) {
137
+ function sortStaticRoutes(routes: string[]): string[] {
128
138
  return [...new Set(routes)].sort((left, right) => right.length - left.length);
129
139
  }
130
140
 
131
- function routeToRouteExpression(route) {
141
+ function routeToRouteExpression(route: string): string {
132
142
  if (route === "/") {
133
143
  return "^/$";
134
144
  }
@@ -136,7 +146,7 @@ function routeToRouteExpression(route) {
136
146
  return `^${escapeRegex(route)}/?$`;
137
147
  }
138
148
 
139
- function routeToStaticHtmlPath(route) {
149
+ function routeToStaticHtmlPath(route: string): string {
140
150
  if (route === "/") {
141
151
  return "/index.html";
142
152
  }
@@ -144,10 +154,10 @@ function routeToStaticHtmlPath(route) {
144
154
  return `${route}/index.html`;
145
155
  }
146
156
 
147
- function routeToHeaderSource(route) {
157
+ function routeToHeaderSource(route: string): string {
148
158
  return route === "/" ? "/" : route;
149
159
  }
150
160
 
151
- function escapeRegex(value) {
161
+ function escapeRegex(value: string): string {
152
162
  return value.replace(/[|\\{}()[\]^$+*?.-]/g, "\\$&");
153
163
  }
@@ -0,0 +1,137 @@
1
+ import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+
4
+ import { defineCommand } from "citty";
5
+ import { build as viteBuild } from "vite";
6
+
7
+ import { readClientBuildAssets } from "../build-metadata.js";
8
+ import { writeVercelBuildOutput } from "../build-shared.js";
9
+
10
+ export default defineCommand({
11
+ meta: {
12
+ name: "build",
13
+ description: "Production build (client + server)",
14
+ },
15
+ async run() {
16
+ const root = process.cwd();
17
+
18
+ console.log("\n Building client...\n");
19
+ await viteBuild({
20
+ root,
21
+ build: {
22
+ outDir: "dist",
23
+ manifest: true,
24
+ rollupOptions: {
25
+ input: "virtual:pracht/client",
26
+ },
27
+ },
28
+ });
29
+
30
+ console.log("\n Building server...\n");
31
+ await viteBuild({
32
+ root,
33
+ build: {
34
+ outDir: "dist/server",
35
+ ssr: "virtual:pracht/server",
36
+ },
37
+ });
38
+
39
+ const serverEntry = resolve(root, "dist/server/server.js");
40
+ let clientDir: string;
41
+ if (existsSync(resolve(root, "dist/client/.vite/manifest.json"))) {
42
+ clientDir = resolve(root, "dist/client");
43
+ } else {
44
+ clientDir = resolve(root, "dist/client");
45
+ const distRoot = resolve(root, "dist");
46
+ mkdirSync(clientDir, { recursive: true });
47
+ for (const entry of readdirSync(distRoot)) {
48
+ if (entry === "server" || entry === "client") continue;
49
+ const sourcePath = join(distRoot, entry);
50
+ const destinationPath = join(clientDir, entry);
51
+ cpSync(sourcePath, destinationPath, { recursive: true });
52
+ rmSync(sourcePath, { force: true, recursive: true });
53
+ }
54
+ }
55
+
56
+ const publicDir = resolve(root, "public");
57
+ if (existsSync(publicDir)) {
58
+ cpSync(publicDir, clientDir, { recursive: true });
59
+ }
60
+
61
+ if (existsSync(serverEntry)) {
62
+ const serverMod = await import(serverEntry);
63
+ const { prerenderApp } = serverMod;
64
+ const { clientEntryUrl, cssManifest, jsManifest } = readClientBuildAssets(root);
65
+
66
+ const { pages, isgManifest } = await prerenderApp({
67
+ app: serverMod.resolvedApp,
68
+ clientEntryUrl: clientEntryUrl ?? undefined,
69
+ cssManifest,
70
+ jsManifest,
71
+ registry: serverMod.registry,
72
+ withISGManifest: true,
73
+ });
74
+ const headersManifest: Record<string, Record<string, string>> = Object.fromEntries(
75
+ pages.map((page: { path: string; headers?: Record<string, string> }) => [
76
+ page.path,
77
+ page.headers ?? {},
78
+ ]),
79
+ );
80
+
81
+ if (pages.length > 0) {
82
+ console.log(`\n Prerendering ${pages.length} SSG/ISG route(s)...\n`);
83
+ for (const page of pages) {
84
+ const filePath =
85
+ page.path === "/"
86
+ ? join(clientDir, "index.html")
87
+ : join(clientDir, page.path, "index.html");
88
+
89
+ mkdirSync(dirname(filePath), { recursive: true });
90
+ writeFileSync(filePath, page.html, "utf-8");
91
+ console.log(` ${page.path} → ${filePath.replace(root + "/", "")}`);
92
+ }
93
+ }
94
+
95
+ if (Object.keys(headersManifest).length > 0) {
96
+ const headersManifestJson = `${JSON.stringify(headersManifest, null, 2)}\n`;
97
+ writeFileSync(
98
+ resolve(root, "dist/server/headers-manifest.json"),
99
+ headersManifestJson,
100
+ "utf-8",
101
+ );
102
+ mkdirSync(resolve(clientDir, "_pracht"), { recursive: true });
103
+ writeFileSync(resolve(clientDir, "_pracht/headers.json"), headersManifestJson, "utf-8");
104
+ }
105
+
106
+ if (Object.keys(isgManifest).length > 0) {
107
+ const isgManifestPath = resolve(root, "dist/server/isg-manifest.json");
108
+ writeFileSync(isgManifestPath, JSON.stringify(isgManifest, null, 2), "utf-8");
109
+ console.log(
110
+ `\n ISG manifest → dist/server/isg-manifest.json (${Object.keys(isgManifest).length} route(s))\n`,
111
+ );
112
+ }
113
+
114
+ if (serverMod.buildTarget === "cloudflare") {
115
+ console.log("\n Cloudflare worker → dist/server/server.js\n");
116
+ console.log(" Deploy with: wrangler deploy\n");
117
+ }
118
+
119
+ if (serverMod.buildTarget === "vercel") {
120
+ const outputPath = writeVercelBuildOutput({
121
+ functionName: serverMod.vercelFunctionName,
122
+ isgRoutes: Object.keys(isgManifest),
123
+ headersManifest,
124
+ regions: serverMod.vercelRegions,
125
+ root,
126
+ staticRoutes: pages
127
+ .map((page: { path: string }) => page.path)
128
+ .filter((path: string) => !(path in isgManifest)),
129
+ });
130
+
131
+ console.log(`\n Vercel build output → ${outputPath}\n`);
132
+ }
133
+ }
134
+
135
+ console.log("\n Build complete.\n");
136
+ },
137
+ });
@@ -0,0 +1,27 @@
1
+ import { defineCommand } from "citty";
2
+ import { createServer } from "vite";
3
+
4
+ export default defineCommand({
5
+ meta: {
6
+ name: "dev",
7
+ description: "Start development server with HMR",
8
+ },
9
+ args: {
10
+ port: {
11
+ type: "positional",
12
+ description: "Port number",
13
+ required: false,
14
+ },
15
+ },
16
+ async run({ args }) {
17
+ const port = parseInt(process.env.PORT || args.port || "3000", 10);
18
+
19
+ const server = await createServer({
20
+ root: process.cwd(),
21
+ server: { port },
22
+ });
23
+
24
+ await server.listen();
25
+ server.printUrls();
26
+ },
27
+ });
@@ -0,0 +1,33 @@
1
+ import { defineCommand } from "citty";
2
+
3
+ import { runDoctor } from "../verification.js";
4
+
5
+ export default defineCommand({
6
+ meta: {
7
+ name: "doctor",
8
+ description: "Validate app wiring",
9
+ },
10
+ args: {
11
+ json: {
12
+ type: "boolean",
13
+ description: "Output as JSON",
14
+ },
15
+ },
16
+ async run({ args }) {
17
+ const report = runDoctor(process.cwd());
18
+
19
+ if (args.json) {
20
+ console.log(JSON.stringify(report, null, 2));
21
+ } else {
22
+ console.log(`Pracht doctor (${report.mode} mode)`);
23
+ for (const check of report.checks) {
24
+ console.log(`${check.status.toUpperCase().padEnd(5)} ${check.message}`);
25
+ }
26
+ console.log(report.ok ? "\nNo blocking issues found." : "\nBlocking issues found.");
27
+ }
28
+
29
+ if (!report.ok) {
30
+ process.exitCode = 1;
31
+ }
32
+ },
33
+ });