Skip to content

Commit

Permalink
Revert "Revert "refactor: new prod server & new dev server" (#5629)" (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
yimingjfe committed Apr 11, 2024
1 parent 61828c0 commit e8c8c5d
Show file tree
Hide file tree
Showing 314 changed files with 6,988 additions and 12,482 deletions.
22 changes: 22 additions & 0 deletions .changeset/fluffy-deers-walk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
'@modern-js/plugin-data-loader': minor
'@modern-js/runtime': minor
'@modern-js/plugin-testing': minor
'@modern-js/plugin-polyfill': minor
'@modern-js/plugin-express': minor
'@modern-js/runtime-utils': minor
'@modern-js/plugin-server': minor
'@modern-js/app-tools': minor
'@modern-js/prod-server': minor
'@modern-js/plugin-koa': minor
'@modern-js/uni-builder': minor
'@modern-js/plugin-bff': minor
'@modern-js/plugin-ssg': minor
'@modern-js/server': minor
'@modern-js/types': minor
'@modern-js/utils': minor
'@modern-js/server-core': minor
---

refactor: refactor server
refactor: 重构 server
31 changes: 25 additions & 6 deletions packages/cli/plugin-bff/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from 'path';
import { ApiRouter } from '@modern-js/bff-core';
import { API_DIR, isProd, requireExistModule } from '@modern-js/utils';
import type { ServerPlugin } from '@modern-js/server-core';
import { type ServerPlugin } from '@modern-js/server-core';
import { API_APP_NAME } from './constants';

type SF = (args: any) => void;
Expand All @@ -25,9 +25,11 @@ export default (): ServerPlugin => ({
const storage = new Storage();
const transformAPI = createTransformAPI(storage);
let apiAppPath = '';
let apiRouter: ApiRouter;
return {
prepare() {
const { appDirectory, distDirectory } = api.useAppContext();
const appContext = api.useAppContext();
const { appDirectory, distDirectory } = appContext;
const root = isProd() ? distDirectory : appDirectory;
const apiPath = path.resolve(root || process.cwd(), API_DIR);
apiAppPath = path.resolve(apiPath, API_APP_NAME);
Expand All @@ -36,25 +38,42 @@ export default (): ServerPlugin => ({
if (apiMod && typeof apiMod === 'function') {
apiMod(transformAPI);
}

const { middlewares } = storage;
api.setAppContext({
...appContext,
apiMiddlewares: middlewares,
});
},
reset() {
storage.reset();
const appContext = api.useAppContext();
const newApiModule = requireExistModule(apiAppPath);
if (newApiModule && typeof newApiModule === 'function') {
newApiModule(transformAPI);
}

const { middlewares } = storage;
api.setAppContext({
...appContext,
apiMiddlewares: middlewares,
});
},
gather({ addAPIMiddleware }) {
storage.middlewares.forEach(mid => {
addAPIMiddleware(mid);
onApiChange(changes) {
const apiHandlerInfos = apiRouter.getApiHandlers();
const appContext = api.useAppContext();
api.setAppContext({
...appContext,
apiHandlerInfos,
});
return changes;
},
prepareApiServer(props, next) {
const { pwd, prefix, httpMethodDecider } = props;
const apiDir = path.resolve(pwd, API_DIR);
const appContext = api.useAppContext();
const { apiDirectory, lambdaDirectory } = appContext;
const apiRouter = new ApiRouter({
apiRouter = new ApiRouter({
appDir: pwd,
apiDir: (apiDirectory as string) || apiDir,
lambdaDir: lambdaDirectory as string,
Expand Down
11 changes: 1 addition & 10 deletions packages/cli/plugin-data-loader/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
],
"version": "2.48.5",
"engines": {
"node": ">=14.17.6"
"node": ">=16.2.0"
},
"jsnext:source": "./src/runtime/index.ts",
"types": "./src/runtime/index.ts",
Expand All @@ -29,11 +29,6 @@
"jsnext:source": "./src/cli/loader.ts",
"default": "./dist/cjs/cli/loader.js"
},
"./server": {
"types": "./dist/types/server/index.d.ts",
"jsnext:source": "./src/server/index.ts",
"default": "./dist/cjs/server/index.js"
},
"./runtime": {
"types": "./dist/types/runtime/index.d.ts",
"jsnext:source": "./src/runtime/index.ts",
Expand All @@ -45,9 +40,6 @@
"loader": [
"./dist/types/cli/loader.d.ts"
],
"server": [
"./dist/types/server/index.d.ts"
],
"runtime": [
"./dist/types/runtime/index.d.ts"
]
Expand All @@ -64,7 +56,6 @@
"@babel/core": "^7.23.2",
"@modern-js/utils": "workspace:*",
"@modern-js/runtime-utils": "workspace:*",
"@remix-run/node": "^1.12.0",
"path-to-regexp": "^6.2.0",
"@swc/helpers": "0.5.3"
},
Expand Down
7 changes: 5 additions & 2 deletions packages/cli/plugin-data-loader/src/cli/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ export default async function loader(
) {
this.cacheable();
const target = this._compiler?.options.target;
if (target === 'node') {
if (target === 'node' || (Array.isArray(target) && target.includes('node'))) {
return source;
}
if (target === 'webworker') {
if (
target === 'webworker' ||
(Array.isArray(target) && target.includes('webworker'))
) {
return source;
}

Expand Down
118 changes: 28 additions & 90 deletions packages/cli/plugin-data-loader/src/runtime/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { IncomingMessage, ServerResponse } from 'http';
import type { NestedRoute, ServerRoute } from '@modern-js/types';
import {
installGlobals,
writeReadableStreamToWritable,
Response as NodeResponse,
} from '@remix-run/node';
import type {
Logger,
NestedRoute,
Reporter,
ServerRoute,
} from '@modern-js/types';
import {
createStaticHandler,
UNSAFE_DEFERRED_SYMBOL as DEFERRED_SYMBOL,
Expand All @@ -15,7 +14,6 @@ import { transformNestedRoutes } from '@modern-js/runtime-utils/browser';
import { isPlainObject } from '@modern-js/utils/lodash';
import {
matchEntry,
ServerContext,
createRequestContext,
reporterCtx,
} from '@modern-js/runtime-utils/node';
Expand All @@ -24,15 +22,12 @@ import { LOADER_REPORTER_NAME } from '@modern-js/utils/universal/constants';
import { CONTENT_TYPE_DEFERRED, LOADER_ID_PARAM } from '../common/constants';
import { createDeferredReadableStream } from './response';

// Polyfill Web Fetch API
installGlobals();

const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
export function isRedirectResponse(status: number): boolean {
return redirectStatusCodes.has(status);
}

export function isResponse(value: any): value is NodeResponse {
export function isResponse(value: any): value is Response {
return (
value != null &&
typeof value.status === 'number' &&
Expand All @@ -53,101 +48,43 @@ function convertModernRedirectResponse(headers: Headers, basename: string) {
newHeaders.set('X-Modernjs-Redirect', redirectUrl);
newHeaders.delete('Location');

return new NodeResponse(null, {
return new Response(null, {
status: 204,
headers: newHeaders,
});
}

const createLoaderHeaders = (
requestHeaders: IncomingMessage['headers'],
): Headers => {
const headers = new Headers();

for (const [key, values] of Object.entries(requestHeaders)) {
if (values) {
if (Array.isArray(values)) {
for (const value of values) {
headers.append(key, value);
}
} else {
headers.set(key, values);
}
}
}

return headers;
};

const createRequest = (context: ServerContext) => {
const origin = `${context.protocol}://${context.host}`;
// eslint-disable-next-line node/prefer-global/url
const url = new URL(context.url, origin);

const controller = new AbortController();

const init: {
[key: string]: unknown;
} = {
method: context.method,
headers: createLoaderHeaders(context.headers),
signal: controller.signal,
};

if (!['GET', 'HEAD'].includes(context.method.toUpperCase())) {
init.body = context.req;
}

const request = new Request(url.href, init);

return request;
};

const sendLoaderResponse = async (
res: ServerResponse,
nodeResponse: NodeResponse,
) => {
res.statusMessage = nodeResponse.statusText;
res.statusCode = nodeResponse.status;

for (const [key, value] of nodeResponse.headers.entries()) {
res.setHeader(key, value);
}

if (nodeResponse.body) {
await writeReadableStreamToWritable(nodeResponse.body, res);
} else {
res.end();
}
};

export const handleRequest = async ({
context,
request,
serverRoutes,
routes: routesConfig,
context,
}: {
context: ServerContext;
request: Request;
serverRoutes: ServerRoute[];
routes: NestedRoute[];
}) => {
const { query } = context;
const routeId = query[LOADER_ID_PARAM] as string;
const entry = matchEntry(context.path, serverRoutes);

context: {
logger: Logger;
reporter?: Reporter;
};
}): Promise<Response | void> => {
// eslint-disable-next-line node/prefer-global/url
const url = new URL(request.url);
const routeId = url.searchParams.get(LOADER_ID_PARAM) as string;
const entry = matchEntry(url.pathname, serverRoutes);
// LOADER_ID_PARAM is the indicator for CSR data loader request.
if (!routeId || !entry) {
return;
}

const basename = entry.urlPath;
const end = time();
const { res, logger, reporter } = context;
const { logger, reporter } = context;
const routes = transformNestedRoutes(routesConfig, reporter);
const { queryRoute } = createStaticHandler(routes, {
basename,
});

const request = createRequest(context);
const requestContext = createRequestContext();
// initial requestContext
// 1. inject reporter
Expand Down Expand Up @@ -182,17 +119,19 @@ export const handleRequest = async ({
const headers = new Headers(init.headers);
headers.set('Content-Type', `${CONTENT_TYPE_DEFERRED}; charset=UTF-8`);
init.headers = headers;
response = new NodeResponse(body, init);
response = new Response(body, init);
}
} else {
response = isResponse(response)
? response
: new NodeResponse(JSON.stringify(response), {
: new Response(JSON.stringify(response), {
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
});
}
const cost = end();
reporter?.reportTiming(`${LOADER_REPORTER_NAME}-navigation`, cost);
} catch (error) {
const message = isRouteErrorResponse(error) ? error.data : String(error);
if (error instanceof Error) {
Expand All @@ -201,15 +140,14 @@ export const handleRequest = async ({
logger?.error(message);
}

response = new NodeResponse(message, {
response = new Response(message, {
status: 500,
headers: {
'Content-Type': 'text/plain',
},
});
}

const cost = end();
reporter.reportTiming(`${LOADER_REPORTER_NAME}-navigation`, cost);
await sendLoaderResponse(res, response);
// eslint-disable-next-line consistent-return
return response as unknown as Response;
};
51 changes: 0 additions & 51 deletions packages/cli/plugin-data-loader/src/server/index.ts

This file was deleted.

Loading

0 comments on commit e8c8c5d

Please sign in to comment.