Skip to content

Commit

Permalink
chore: don't have the middleware inside the manifest
Browse files Browse the repository at this point in the history
  • Loading branch information
ematipico committed May 30, 2023
1 parent 7f98f46 commit f6072df
Show file tree
Hide file tree
Showing 6 changed files with 17 additions and 31 deletions.
27 changes: 11 additions & 16 deletions packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
createStylesheetElementSet,
} from '../render/ssr-element.js';
import { matchRoute } from '../routing/match.js';
import type { SinglePageBuiltModule } from '../build/types';
export { deserializeManifest } from './common.js';

const clientLocalsSymbol = Symbol.for('astro.locals');
Expand Down Expand Up @@ -138,22 +139,20 @@ export class App {
}

let page = await this.#manifest.pageMap.get(routeData.component)!();
let mod = await page.page();

if (routeData.type === 'page') {
let response = await this.#renderPage(request, routeData, mod, defaultStatus);
let response = await this.#renderPage(request, routeData, page, defaultStatus);

// If there was a known error code, try sending the according page (e.g. 404.astro / 500.astro).
if (response.status === 500 || response.status === 404) {
const errorPageData = matchRoute('/' + response.status, this.#manifestData);
if (errorPageData && errorPageData.route !== routeData.route) {
page = await this.#manifest.pageMap.get(errorPageData.component)!();
mod = await page.page();
try {
let errorResponse = await this.#renderPage(
request,
errorPageData,
mod,
page,
response.status
);
return errorResponse;
Expand All @@ -162,7 +161,7 @@ export class App {
}
return response;
} else if (routeData.type === 'endpoint') {
return this.#callEndpoint(request, routeData, mod, defaultStatus);
return this.#callEndpoint(request, routeData, page, defaultStatus);
} else {
throw new Error(`Unsupported route type [${routeData.type}].`);
}
Expand All @@ -175,7 +174,7 @@ export class App {
async #renderPage(
request: Request,
routeData: RouteData,
mod: ComponentInstance,
page: SinglePageBuiltModule,
status = 200
): Promise<Response> {
const url = new URL(request.url);
Expand All @@ -200,6 +199,7 @@ export class App {
}

try {
const mod = (await page.page()) as any;
const renderContext = await createRenderContext({
request,
origin: url.origin,
Expand All @@ -210,7 +210,7 @@ export class App {
links,
route: routeData,
status,
mod: mod as any,
mod,
env: this.#env,
});

Expand All @@ -221,7 +221,7 @@ export class App {
site: this.#env.site,
adapterName: this.#env.adapterName,
});
const onRequest = this.#manifest.middleware?.onRequest;
const onRequest = page.middleware?.onRequest;
let response;
if (onRequest) {
response = await callMiddleware<Response>(
Expand Down Expand Up @@ -254,11 +254,12 @@ export class App {
async #callEndpoint(
request: Request,
routeData: RouteData,
mod: ComponentInstance,
page: SinglePageBuiltModule,
status = 200
): Promise<Response> {
const url = new URL(request.url);
const pathname = '/' + this.removeBase(url.pathname);
const mod = await page.page();
const handler = mod as unknown as EndpointHandler;

const ctx = await createRenderContext({
Expand All @@ -271,13 +272,7 @@ export class App {
mod: handler as any,
});

const result = await callEndpoint(
handler,
this.#env,
ctx,
this.#logging,
this.#manifest.middleware
);
const result = await callEndpoint(handler, this.#env, ctx, this.#logging, page.middleware);

if (result.type === 'response') {
if (result.response.headers.get('X-Astro-Response') === 'Not-Found') {
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/app/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MarkdownRenderingOptions } from '@astrojs/markdown-remark';
import type {
AstroMiddlewareInstance,
ComponentInstance,
RouteData,
SerializedRouteData,
SSRComponentMetadata,
Expand Down Expand Up @@ -49,7 +50,6 @@ export interface SSRManifest {
entryModules: Record<string, string>;
assets: Set<string>;
componentMetadata: SSRResult['componentMetadata'];
middleware?: AstroMiddlewareInstance<unknown>;
}

export type SerializedSSRManifest = Omit<
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/core/build/plugins/plugin-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ function vitePluginPages(opts: StaticBuildOptions, internals: BuildInternals): V

const middlewareModule = await this.resolve(MIDDLEWARE_MODULE_ID);
if (middlewareModule) {
imports.push(`import * as _middleware from "${middlewareModule.id}";`);
exports.push(`export const middleware = _middleware;`);
imports.push(`import * as middleware from "${middlewareModule.id}";`);
exports.push(`export { middleware };`);
}

return `${imports.join('\n')}${exports.join('\n')}`;
Expand Down
7 changes: 0 additions & 7 deletions packages/astro/src/core/build/plugins/plugin-ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,6 @@ function vitePluginSSR(
const imports: string[] = [];
const contents: string[] = [];
const exports: string[] = [];
let middleware;
const middlewareModule = await this.resolve(MIDDLEWARE_MODULE_ID);
if (middlewareModule) {
imports.push(`import * as _middleware from "${middlewareModule.id}"`);
middleware = 'middleware: _middleware';
}
let i = 0;
const pageMap: string[] = [];

Expand Down Expand Up @@ -81,7 +75,6 @@ import { _privateSetManifestDontUseThis } from 'astro:ssr-manifest';
const _manifest = Object.assign(_deserializeManifest('${manifestReplace}'), {
pageMap,
renderers,
${middleware}
});
_privateSetManifestDontUseThis(_manifest);
const _args = ${adapter.args ? JSON.stringify(adapter.args) : 'undefined'};
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/core/build/static-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,9 @@ async function ssrBuild(
return makeAstroPageEntryPointFileName(chunkInfo.facadeModuleId);
} else if (
// checks if the path of the module we have middleware, e.g. middleware.js / middleware/index.js
chunkInfo.facadeModuleId?.includes('middleware') &&
chunkInfo.moduleIds.find((m) => m.includes('middleware')) !== undefined &&
// checks if the file actually export the `onRequest` function
chunkInfo.exports.includes('onRequest')
chunkInfo.exports.includes('_middleware')
) {
return 'middleware.mjs';
} else if (chunkInfo.facadeModuleId === SSR_VIRTUAL_MODULE_ID) {
Expand Down
4 changes: 1 addition & 3 deletions packages/astro/test/middleware.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,7 @@ describe('Middleware API in PROD mode, SSR', () => {
fixture = await loadFixture({
root: './fixtures/middleware-dev/',
output: 'server',
adapter: testAdapter({
// exports: ['manifest', 'createApp', 'middleware'],
}),
adapter: testAdapter({}),
});
await fixture.build();
});
Expand Down

0 comments on commit f6072df

Please sign in to comment.