Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: remove experimental flag middleware #7109

Merged
merged 17 commits into from
Jun 5, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/young-flies-allow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': minor
---

Remove experimental flag for the middleware
2 changes: 1 addition & 1 deletion examples/middleware/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ export default defineConfig({
mode: 'standalone',
}),
experimental: {
middleware: true,
middleware: true
},
});
22 changes: 0 additions & 22 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ export interface CLIFlags {
drafts?: boolean;
open?: boolean;
experimentalAssets?: boolean;
experimentalMiddleware?: boolean;
ematipico marked this conversation as resolved.
Show resolved Hide resolved
}

export interface BuildConfig {
Expand Down Expand Up @@ -1121,27 +1120,6 @@ export interface AstroUserConfig {
*/
customClientDirectives?: boolean;

/**
* @docs
* @name experimental.middleware
* @type {boolean}
* @default `false`
* @version 2.4.0
* @description
* Enable experimental support for Astro middleware.
*
* To enable this feature, set `experimental.middleware` to `true` in your Astro config:
*
* ```js
* {
* experimental: {
* middleware: true,
* },
* }
* ```
*/
middleware?: boolean;

/**
* @docs
* @name experimental.hybridOutput
Expand Down
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
8 changes: 1 addition & 7 deletions packages/astro/src/core/build/plugins/plugin-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { Plugin as VitePlugin } from 'vite';
import { MIDDLEWARE_PATH_SEGMENT_NAME } from '../../constants.js';
import { addRollupInput } from '../add-rollup-input.js';
import type { BuildInternals } from '../internal.js';
import type { AstroBuildPlugin } from '../plugin';
import type { StaticBuildOptions } from '../types';
Expand All @@ -13,14 +12,9 @@ export function vitePluginMiddleware(
): VitePlugin {
return {
name: '@astro/plugin-middleware',
options(options) {
if (opts.settings.config.experimental.middleware) {
return addRollupInput(options, [MIDDLEWARE_MODULE_ID]);
}
},

async resolveId(id) {
if (id === MIDDLEWARE_MODULE_ID && opts.settings.config.experimental.middleware) {
if (id === MIDDLEWARE_MODULE_ID) {
const middlewareId = await this.resolve(
`${opts.settings.config.srcDir.pathname}/${MIDDLEWARE_PATH_SEGMENT_NAME}`
);
Expand Down
7 changes: 4 additions & 3 deletions packages/astro/src/core/build/plugins/plugin-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,10 @@ function vitePluginPages(opts: StaticBuildOptions, internals: BuildInternals): V
imports.push(`import { renderers } from "${RENDERERS_MODULE_ID}";`);
exports.push(`export { renderers };`);

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

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

Expand Down Expand Up @@ -80,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
5 changes: 0 additions & 5 deletions packages/astro/src/core/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,6 @@ export function resolveFlags(flags: Partial<Flags>): CLIFlags {
drafts: typeof flags.drafts === 'boolean' ? flags.drafts : undefined,
experimentalAssets:
typeof flags.experimentalAssets === 'boolean' ? flags.experimentalAssets : undefined,
experimentalMiddleware:
typeof flags.experimentalMiddleware === 'boolean' ? flags.experimentalMiddleware : undefined,
};
}

Expand Down Expand Up @@ -139,9 +137,6 @@ function mergeCLIFlags(astroConfig: AstroUserConfig, flags: CLIFlags) {
// TODO: Come back here and refactor to remove this expected error.
astroConfig.server.open = flags.open;
}
if (typeof flags.experimentalMiddleware === 'boolean') {
astroConfig.experimental.middleware = true;
}
return astroConfig;
}

Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/core/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,6 @@ export const AstroConfigSchema = z.object({
.enum(['always', 'auto', 'never'])
.optional()
.default(ASTRO_CONFIG_DEFAULTS.experimental.inlineStylesheets),
middleware: z.oboolean().optional().default(ASTRO_CONFIG_DEFAULTS.experimental.middleware),
hybridOutput: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.experimental.hybridOutput),
})
.passthrough()
Expand Down
8 changes: 3 additions & 5 deletions packages/astro/src/vite-plugin-astro-server/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,9 @@ export async function handleRoute(
request,
route,
};
if (env.settings.config.experimental.middleware) {
const middleware = await loadMiddleware(env.loader, env.settings.config.srcDir);
if (middleware) {
options.middleware = middleware;
}
const middleware = await loadMiddleware(env.loader, env.settings.config.srcDir);
if (middleware) {
options.middleware = middleware;
}
// Route successfully matched! Render it.
if (route.type === 'endpoint') {
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