Skip to content

Commit 7f4227d

Browse files
committed
refactor: extract start methods intro runtime folder
1 parent 234e4fd commit 7f4227d

File tree

4 files changed

+131
-131
lines changed

4 files changed

+131
-131
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
2+
3+
// export const GET = create

packages/pranx/src/cmd/start.ts

Lines changed: 10 additions & 131 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,12 @@
1-
import {
2-
OUTPUT_BUNDLE_BROWSER_DIR,
3-
OUTPUT_BUNDLE_SERVER_DIR,
4-
PUBLIC_USER_DIR,
5-
SERVER_MANIFEST_OUTPUT_PATH,
6-
SITE_MANIFEST_OUTPUT_PATH,
7-
} from "@/build/constants.js";
8-
import { filePathToRoutingPath } from "@/build/filepath-to-routing-path.js";
9-
import { generate_html_template } from "@/build/generate_html_template.js";
1+
import { SERVER_MANIFEST_OUTPUT_PATH } from "@/build/constants.js";
2+
import { defineServeStaticHandler } from "@/runtime/define-serve-static.js";
3+
import { define_ssr_handlers } from "@/runtime/define-ssr-handlers.js";
104
import { logger } from "@/utils/logger.js";
115
import { measureTime } from "@/utils/time-perf.js";
126
import fse from "fs-extra";
13-
import {
14-
defineHandler,
15-
type EventHandlerRequest,
16-
H3,
17-
type H3Event,
18-
html,
19-
serve,
20-
serveStatic,
21-
} from "h3";
7+
import { H3, serve } from "h3";
228
import kleur from "kleur";
23-
import { readFile, stat } from "node:fs/promises";
24-
import { extname, join, resolve } from "pathe";
25-
import { Fragment, h } from "preact";
26-
import { renderToStringAsync } from "preact-render-to-string";
27-
import type { HYDRATE_DATA, PageModule, SERVER_MANIFEST, ServerEntryModule } from "types/index.js";
9+
import type { SERVER_MANIFEST } from "types/index.js";
2810

2911
export async function start() {
3012
measureTime("pranx-start");
@@ -37,116 +19,13 @@ export async function start() {
3719

3820
const app = new H3();
3921

40-
await attach_server_side_pages_to_app(server_manifest, app);
22+
await define_ssr_handlers(server_manifest, app);
4123

42-
app.on("GET", "**", (event) => createServeStatic(event));
24+
app.on("GET", "**", (event) => defineServeStaticHandler(event));
4325

44-
const SERVER = serve(app, { port: PORT });
26+
const server_instance = serve(app, { port: PORT });
4527

46-
await SERVER.ready();
28+
await server_instance.ready();
4729

48-
const START_TIME = measureTime("pranx-start");
49-
50-
logger.success(`Start in ${START_TIME} ms`);
30+
logger.success(`Start in ${measureTime("pranx-start")} ms`);
5131
}
52-
53-
const createServeStatic = (event: H3Event<EventHandlerRequest>) =>
54-
serveStatic(event, {
55-
indexNames: ["/index.html"],
56-
57-
getContents: async (id) => {
58-
const target_file = join(OUTPUT_BUNDLE_BROWSER_DIR, id);
59-
const target_public_file = join(PUBLIC_USER_DIR, id);
60-
61-
const existsTargetFile = await fse.exists(target_file);
62-
63-
const buffer = await readFile(existsTargetFile ? target_file : target_public_file);
64-
65-
return new Uint8Array(buffer);
66-
},
67-
68-
getMeta: async (id) => {
69-
const target_file = join(OUTPUT_BUNDLE_BROWSER_DIR, id);
70-
const target_public_file = join(PUBLIC_USER_DIR, id);
71-
72-
const existsTargetFile = await fse.exists(target_file);
73-
74-
const stats = await stat(existsTargetFile ? target_file : target_public_file).catch(() => {});
75-
76-
if (stats?.isFile()) {
77-
return stats;
78-
}
79-
80-
return undefined;
81-
},
82-
83-
headers: {
84-
"Cache-Control": "public, max-age=2592000, immutable", // agresive caching
85-
"Expires": new Date(Date.now() + 2592000000).toUTCString(), // one month
86-
},
87-
});
88-
89-
const attach_server_side_pages_to_app = async (server_manifest: SERVER_MANIFEST, app: H3) => {
90-
for (const route of server_manifest.routes) {
91-
if (route.rendering_kind === "server-side") {
92-
let server_entry_module: ServerEntryModule | null = null;
93-
server_entry_module = (await import(server_manifest.entry_server)) as ServerEntryModule;
94-
95-
const file_absolute = resolve(join(OUTPUT_BUNDLE_SERVER_DIR, "pages", route.module));
96-
const { default: page, getServerSideProps } = (await import(file_absolute)) as PageModule;
97-
98-
const hydrate_data = (await fse.readJSON(SITE_MANIFEST_OUTPUT_PATH)) as HYDRATE_DATA;
99-
const url_for_routing_match = filePathToRoutingPath(route.path, false);
100-
101-
app.on(
102-
"GET",
103-
url_for_routing_match,
104-
defineHandler(async (event) => {
105-
// For files that match with dynamic routes
106-
if (extname(event.url.pathname.split("/").at(-1) || "")) {
107-
return createServeStatic(event);
108-
}
109-
110-
let props_to_return = {};
111-
112-
if (getServerSideProps) {
113-
props_to_return = await getServerSideProps({
114-
event,
115-
});
116-
}
117-
118-
event.res.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
119-
120-
if (event.url.searchParams.get("props") === "only") {
121-
return {
122-
props: props_to_return,
123-
};
124-
}
125-
126-
const target_route_index = hydrate_data.routes.findIndex((r) => r.path === route.path);
127-
128-
if (target_route_index === -1 || !hydrate_data.routes[target_route_index]) {
129-
logger.error(`Route not found in hydrate data: ${route.path}`);
130-
event.res.status = 500;
131-
return html(event, "Internal Server Error");
132-
}
133-
134-
hydrate_data.routes[target_route_index].props = props_to_return;
135-
136-
const page_prerendered = await renderToStringAsync(
137-
h(server_entry_module?.default || Fragment, {}, h(page, props_to_return, null))
138-
);
139-
140-
const html_string = generate_html_template({
141-
page_prerendered,
142-
hydrate_data_as_string: JSON.stringify(hydrate_data),
143-
minify: true,
144-
css: route.css,
145-
});
146-
147-
return html(event, html_string);
148-
})
149-
);
150-
}
151-
}
152-
};
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { OUTPUT_BUNDLE_BROWSER_DIR, PUBLIC_USER_DIR } from "@/build/constants.js";
2+
import fse from "fs-extra";
3+
import { type EventHandlerRequest, type H3Event, serveStatic } from "h3";
4+
import { join } from "pathe";
5+
6+
export const defineServeStaticHandler = (event: H3Event<EventHandlerRequest>) =>
7+
serveStatic(event, {
8+
indexNames: ["/index.html"],
9+
10+
getContents: async (id) => {
11+
const target_file = join(OUTPUT_BUNDLE_BROWSER_DIR, id);
12+
const target_public_file = join(PUBLIC_USER_DIR, id);
13+
14+
const existsTargetFile = await fse.exists(target_file);
15+
16+
const buffer = await fse.readFile(existsTargetFile ? target_file : target_public_file);
17+
18+
return new Uint8Array(buffer);
19+
},
20+
21+
getMeta: async (id) => {
22+
const target_file = join(OUTPUT_BUNDLE_BROWSER_DIR, id);
23+
const target_public_file = join(PUBLIC_USER_DIR, id);
24+
25+
const existsTargetFile = await fse.exists(target_file);
26+
27+
const stats = await fse
28+
.stat(existsTargetFile ? target_file : target_public_file)
29+
.catch(() => {});
30+
31+
if (stats?.isFile()) {
32+
return stats;
33+
}
34+
35+
return undefined;
36+
},
37+
38+
headers: {
39+
"Cache-Control": "public, max-age=2592000, immutable", // agresive caching
40+
"Expires": new Date(Date.now() + 2592000000).toUTCString(), // one month
41+
},
42+
});
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { OUTPUT_BUNDLE_SERVER_DIR, SITE_MANIFEST_OUTPUT_PATH } from "@/build/constants.js";
2+
import { filePathToRoutingPath } from "@/build/filepath-to-routing-path.js";
3+
import { generate_html_template } from "@/build/generate_html_template.js";
4+
import { defineServeStaticHandler } from "@/runtime/define-serve-static.js";
5+
import { logger } from "@/utils/logger.js";
6+
import fse from "fs-extra";
7+
import { defineHandler, type H3, html } from "h3";
8+
import { extname, join, resolve } from "pathe";
9+
import { Fragment, h } from "preact";
10+
import { renderToStringAsync } from "preact-render-to-string";
11+
import type { HYDRATE_DATA, PageModule, SERVER_MANIFEST, ServerEntryModule } from "types/index.js";
12+
13+
export const define_ssr_handlers = async (server_manifest: SERVER_MANIFEST, app: H3) => {
14+
for (const route of server_manifest.routes) {
15+
if (route.rendering_kind !== "server-side") continue;
16+
17+
let server_entry_module: ServerEntryModule | null = null;
18+
server_entry_module = (await import(server_manifest.entry_server)) as ServerEntryModule;
19+
20+
const file_absolute = resolve(join(OUTPUT_BUNDLE_SERVER_DIR, "pages", route.module));
21+
const { default: page, getServerSideProps } = (await import(file_absolute)) as PageModule;
22+
23+
const hydrate_data = (await fse.readJSON(SITE_MANIFEST_OUTPUT_PATH)) as HYDRATE_DATA;
24+
const url_for_routing_match = filePathToRoutingPath(route.path, false);
25+
26+
app.on(
27+
"GET",
28+
url_for_routing_match,
29+
defineHandler(async (event) => {
30+
// For files that match with dynamic routes
31+
if (extname(event.url.pathname.split("/").at(-1) || "")) {
32+
return defineServeStaticHandler(event);
33+
}
34+
35+
let props_to_return = {};
36+
37+
if (getServerSideProps) {
38+
props_to_return = await getServerSideProps({
39+
event,
40+
});
41+
}
42+
43+
event.res.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
44+
45+
if (event.url.searchParams.get("props") === "only") {
46+
return {
47+
props: props_to_return,
48+
};
49+
}
50+
51+
const target_route_index = hydrate_data.routes.findIndex((r) => r.path === route.path);
52+
53+
if (target_route_index === -1 || !hydrate_data.routes[target_route_index]) {
54+
logger.error(`Route not found in hydrate data: ${route.path}`);
55+
event.res.status = 500;
56+
return html(event, "Internal Server Error");
57+
}
58+
59+
hydrate_data.routes[target_route_index].props = props_to_return;
60+
61+
const page_prerendered = await renderToStringAsync(
62+
h(server_entry_module?.default || Fragment, {}, h(page, props_to_return, null))
63+
);
64+
65+
const html_string = generate_html_template({
66+
page_prerendered,
67+
hydrate_data_as_string: JSON.stringify(hydrate_data),
68+
minify: true,
69+
css: route.css,
70+
});
71+
72+
return html(event, html_string);
73+
})
74+
);
75+
}
76+
};

0 commit comments

Comments
 (0)