Skip to content

Commit

Permalink
rebase
Browse files Browse the repository at this point in the history
  • Loading branch information
ematipico committed Jun 12, 2023
1 parent 09b412d commit 0e7d932
Show file tree
Hide file tree
Showing 11 changed files with 75 additions and 84 deletions.
16 changes: 8 additions & 8 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -844,22 +844,22 @@ export interface AstroUserConfig {

/**
* @docs
* @name build.mode
* @type {string}
* @default {'server' | 'serverless'}
* @name build.ssrMode
* @type {'server' | 'serverless'}
* @default {'server'}
* @description
* Defines how the SSR should be bundled. SSR code for "server"
* Defines how the SSR code should be bundled. SSR code for "server"
* will be built in one single file.
*
* When "serverless" is specified, Astro will emit a file for each page.
* When "serverless" is passed, Astro will emit a file for each page.
* Each file emitted will render only one page. The pages will be emitted
* inside a `pages/` directory, and emitted file will keep the same file paths
* inside a `dist/pages/` directory, and the emitted files will keep the same file paths
* of the `src/pages` directory.
*
* Each emitted file will be prefixed with `entry`. You can use {@link build.serverlessEntryPrefix}
* to change the prefix.
*
* Inside the `dist/` directory, the pages
* Inside the `dist/` directory, the pages will look like this:
* ```plaintext
* ├── pages
* │ ├── blog
Expand All @@ -876,7 +876,7 @@ export interface AstroUserConfig {
* }
* ```
*/
mode?: 'server' | 'serverless';
ssrMode?: 'server' | 'serverless';
};

/**
Expand Down
23 changes: 13 additions & 10 deletions packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
SSRElement,
SSRBaseManifest,
} from '../../@types/astro';
import type { RouteInfo, SSRServerlessManifest, SSRServerManifest } from './types';
import type { RouteInfo, SSRServerManifest } from './types';

import mime from 'mime';
import type { SinglePageBuiltModule } from '../build/types';
Expand Down Expand Up @@ -150,7 +150,6 @@ export class App {
}

let mod = await this.#getModuleForRoute(routeData);
let mod = await this.#retrievePage(routeData);

if (routeData.type === 'page' || routeData.type === 'redirect') {
let response = await this.#renderPage(request, routeData, mod, defaultStatus);
Expand All @@ -159,7 +158,6 @@ export class App {
if (response.status === 500 || response.status === 404) {
const errorRouteData = matchRoute('/' + response.status, this.#manifestData);
if (errorRouteData && errorRouteData.route !== routeData.route) {
mod = await this.#retrievePage(errorPageData);
mod = await this.#getModuleForRoute(errorRouteData);
try {
let errorResponse = await this.#renderPage(
Expand Down Expand Up @@ -188,14 +186,19 @@ export class App {
if (route.type === 'redirect') {
return RedirectSinglePageBuiltModule;
} else {
const importComponentInstance = this.#manifest.pageMap.get(route.component);
if (!importComponentInstance) {
throw new Error(
`Unexpectedly unable to find a component instance for route ${route.route}`
);
if (isSsrServerManifest(this.#manifest)) {
const importComponentInstance = this.#manifest.pageMap.get(route.component);
if (!importComponentInstance) {
throw new Error(
`Unexpectedly unable to find a component instance for route ${route.route}`
);
}
const pageModule = await importComponentInstance();
return pageModule;
} else {
const importComponentInstance = this.#manifest.pageModule;
return importComponentInstance;
}
const built = await importComponentInstance();
return built;
}
}

Expand Down
3 changes: 1 addition & 2 deletions packages/astro/src/core/app/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export type SerializedRouteInfo = Omit<RouteInfo, 'routeData'> & {
routeData: SerializedRouteData;
};

type ImportComponentInstance = () => Promise<SinglePageBuiltModule>;
export type ImportComponentInstance = () => Promise<SinglePageBuiltModule>;

export type SSRBaseManifest = SSRServerManifest | SSRServerlessManifest;

Expand All @@ -50,7 +50,6 @@ export type SSRServerManifest = {
entryModules: Record<string, string>;
assets: Set<string>;
componentMetadata: SSRResult['componentMetadata'];
middleware?: AstroMiddlewareInstance<unknown>;
pageModule?: undefined;
pageMap: Map<ComponentPath, ImportComponentInstance>;
};
Expand Down
21 changes: 19 additions & 2 deletions packages/astro/src/core/build/plugins/plugin-pages.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getVirtualModulePageNameFromPath, getPathFromVirtualModulePageName } from './util.js';
import { getPathFromVirtualModulePageName, ASTRO_PAGE_EXTENSION_POST_PATTERN } from './util.js';
import type { Plugin as VitePlugin } from 'vite';
import { routeIsRedirect } from '../../redirects/index.js';
import { addRollupInput } from '../add-rollup-input.js';
Expand All @@ -7,10 +7,27 @@ import type { AstroBuildPlugin } from '../plugin';
import type { StaticBuildOptions } from '../types';
import { MIDDLEWARE_MODULE_ID } from './plugin-middleware.js';
import { RENDERERS_MODULE_ID } from './plugin-renderers.js';
import { extname } from 'node:path';

export const ASTRO_PAGE_MODULE_ID = '@astro-page:';
export const ASTRO_PAGE_RESOLVED_MODULE_ID = '\0' + ASTRO_PAGE_MODULE_ID;

/**
* 1. We add a fixed prefix, which is used as virtual module naming convention;
* 2. We replace the dot that belongs extension with an arbitrary string.
*
* @param path
*/
export function getVirtualModulePageNameFromPath(path: string) {
// we mask the extension, so this virtual file
// so rollup won't trigger other plugins in the process
const extension = extname(path);
return `${ASTRO_PAGE_MODULE_ID}${path.replace(
extension,
extension.replace('.', ASTRO_PAGE_EXTENSION_POST_PATTERN)
)}`;
}

export function getVirtualModulePageIdFromPath(path: string) {
const name = getVirtualModulePageNameFromPath(path);
return '\x00' + name;
Expand All @@ -28,7 +45,7 @@ function vitePluginPages(opts: StaticBuildOptions, internals: BuildInternals): V
if (routeIsRedirect(pageData.route)) {
continue;
}
inputs.add(getVirtualModulePageNameFromPath(ASTRO_PAGE_MODULE_ID, path));
inputs.add(getVirtualModulePageNameFromPath(path));
}

return addRollupInput(options, Array.from(inputs));
Expand Down
64 changes: 9 additions & 55 deletions packages/astro/src/core/build/plugins/plugin-ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ import { addRollupInput } from '../add-rollup-input.js';
import { getOutFile, getOutFolder } from '../common.js';
import { cssOrder, mergeInlineCss, type BuildInternals } from '../internal.js';
import type { AstroBuildPlugin } from '../plugin';
import type { StaticBuildOptions } from '../types';
import { getVirtualModulePageNameFromPath } from './plugin-pages.js';
import type { OutputChunk, StaticBuildOptions } from '../types';
import { MIDDLEWARE_MODULE_ID } from './plugin-middleware.js';
import { getPathFromVirtualModulePageName, getVirtualModulePageNameFromPath } from './util.js';
Expand Down Expand Up @@ -107,15 +105,13 @@ export function pluginSSRServer(
options: StaticBuildOptions,
internals: BuildInternals
): AstroBuildPlugin {
const ssr =
options.settings.config.output === 'server' || isHybridOutput(options.settings.config);
const ssr = isServerLikeOutput(options.settings.config);
return {
build: 'ssr',
hooks: {
'build:before': () => {
let vitePlugin =
// config.build object is optional, so we check NOT EQUAL against "serverless" instead
ssr && options.settings.config.build?.mode !== 'serverless'
ssr && options.settings.config.build.ssrMode === 'server'
? vitePluginSSRServer(internals, options.settings.adapter!, options)
: undefined;

Expand All @@ -129,7 +125,7 @@ export function pluginSSRServer(
return;
}

if (options.settings.config.build?.mode === 'serverless') {
if (options.settings.config.build.ssrMode === 'serverless') {
return;
}

Expand Down Expand Up @@ -158,7 +154,7 @@ function vitePluginSSRServerless(
name: '@astrojs/vite-plugin-astro-ssr-serverless',
enforce: 'post',
options(opts) {
if (options.settings.config.build?.mode === 'serverless') {
if (options.settings.config.build.ssrMode === 'serverless') {
const inputs: Set<string> = new Set();

for (const path of Object.keys(options.allPages)) {
Expand Down Expand Up @@ -232,14 +228,13 @@ export function pluginSSRServerless(
options: StaticBuildOptions,
internals: BuildInternals
): AstroBuildPlugin {
const ssr =
options.settings.config.output === 'server' || isHybridOutput(options.settings.config);
const ssr = isServerLikeOutput(options.settings.config);
return {
build: 'ssr',
hooks: {
'build:before': () => {
let vitePlugin =
ssr && options.settings.config.build.mode === 'serverless'
ssr && options.settings.config.build.ssrMode === 'serverless'
? vitePluginSSRServerless(internals, options.settings.adapter!, options)
: undefined;

Expand All @@ -252,7 +247,7 @@ export function pluginSSRServerless(
if (!ssr) {
return;
}
if (options.settings.config.build?.mode === 'server') {
if (options.settings.config.build.ssrMode === 'server') {
return;
}

Expand All @@ -275,13 +270,8 @@ export function pluginSSRServerless(
function generateSSRCode(config: AstroConfig, adapter: AstroAdapter) {
const imports: string[] = [];
const contents: string[] = [];
let middleware;
if (config.experimental?.middleware === true) {
imports.push(`import * as _middleware from "${MIDDLEWARE_MODULE_ID}";`);
middleware = 'middleware: _middleware';
}
let pageMap;
if (config.build.mode === 'serverless') {
if (config.build.ssrMode === 'serverless') {
pageMap = 'pageModule';
} else {
pageMap = 'pageMap';
Expand Down Expand Up @@ -335,7 +325,7 @@ export async function injectManifest(
internals: BuildInternals,
chunk: Readonly<OutputChunk>
) {
if (buildOpts.settings.config.build.mode === 'serverless') {
if (buildOpts.settings.config.build.ssrMode === 'serverless') {
if (internals.ssrServerlessEntryChunks.size === 0) {
throw new Error(`Did not generate an entry chunk for SSR in serverless mode`);
}
Expand Down Expand Up @@ -475,39 +465,3 @@ function buildManifest(

return ssrManifest;
}

export function pluginSSR(
options: StaticBuildOptions,
internals: BuildInternals
): AstroBuildPlugin {
const ssr = isServerLikeOutput(options.settings.config);
return {
build: 'ssr',
hooks: {
'build:before': () => {
let vitePlugin = ssr
? vitePluginSSR(internals, options.settings.adapter!, options)
: undefined;

return {
enforce: 'after-user-plugins',
vitePlugin,
};
},
'build:post': async ({ mutate }) => {
if (!ssr) {
return;
}

if (!internals.ssrEntryChunk) {
throw new Error(`Did not generate an entry chunk for SSR`);
}
// Mutate the filename
internals.ssrEntryChunk.fileName = options.settings.config.build.serverEntry;

const code = await injectManifest(options, internals);
mutate(internals.ssrEntryChunk, 'server', code);
},
},
};
}
12 changes: 9 additions & 3 deletions packages/astro/src/core/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const ASTRO_CONFIG_DEFAULTS: AstroUserConfig & any = {
redirects: true,
inlineStylesheets: 'never',
serverlessEntryPrefix: 'entry',
mode: 'server',
ssrMode: 'server',
},
compressHTML: false,
server: {
Expand Down Expand Up @@ -126,7 +126,10 @@ export const AstroConfigSchema = z.object({
.string()
.optional()
.default(ASTRO_CONFIG_DEFAULTS.build.serverlessEntryPrefix),
mode: z.enum(['server', 'serverless']).optional().default(ASTRO_CONFIG_DEFAULTS.build.server),
ssrMode: z
.enum(['server', 'serverless'])
.optional()
.default(ASTRO_CONFIG_DEFAULTS.build.ssrMode),
})
.optional()
.default({}),
Expand Down Expand Up @@ -290,7 +293,10 @@ export function createRelativeSchema(cmd: string, fileProtocolRoot: URL) {
.string()
.optional()
.default(ASTRO_CONFIG_DEFAULTS.build.serverlessEntryPrefix),
mode: z.enum(['server', 'serverless']).optional().default(ASTRO_CONFIG_DEFAULTS.build.mode),
ssrMode: z
.enum(['server', 'serverless'])
.optional()
.default(ASTRO_CONFIG_DEFAULTS.build.ssrMode),
})
.optional()
.default({}),
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/test/fixtures/ssr-request/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { defineConfig } from 'astro/config';
// https://astro.build/config
export default defineConfig({
build: {
mode: "serverless"
ssrMode: "server"
}
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { defineConfig } from 'astro/config';
export default defineConfig({
build: {
mode: "serverless"
ssrMode: "serverless"
},
output: "server"
})
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { defineConfig } from 'astro/config';
export default defineConfig({
build: {
mode: "serverless"
ssrMode: "serverless"
},
output: "server"
})
2 changes: 1 addition & 1 deletion packages/astro/test/ssr-serverless-manifest.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { loadFixture } from './test-utils.js';
import testAdapter from './test-adapter.js';
import * as cheerio from 'cheerio';

describe('astro:ssr-manifest', () => {
describe('astro:ssr-manifest, serverless', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;

Expand Down
12 changes: 12 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 0e7d932

Please sign in to comment.