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

Server islands tests #11405

Merged
merged 7 commits into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion examples/server-islands/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
},
"devDependencies": {
"@astrojs/node": "^8.2.6",
"@astrojs/react": "workspace:*",
"@astrojs/react": "^3.6.0",
"@astrojs/tailwind": "^5.1.0",
"@fortawesome/fontawesome-free": "^6.5.2",
"@tailwindcss/forms": "^0.5.7",
Expand Down
17 changes: 0 additions & 17 deletions examples/server-islands/src/components/Cart.astro

This file was deleted.

15 changes: 0 additions & 15 deletions examples/server-islands/src/components/Cart.tsx

This file was deleted.

24 changes: 0 additions & 24 deletions examples/server-islands/src/components/Header.astro

This file was deleted.

3 changes: 1 addition & 2 deletions examples/server-islands/src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import '../base.css';
import AddToCart from '../components/AddToCart';
import PersonalBar from '../components/PersonalBar.astro';
import '@fortawesome/fontawesome-free/css/all.min.css';
---
<!DOCTYPE html>
<html lang="en">
Expand All @@ -19,8 +20,6 @@ import PersonalBar from '../components/PersonalBar.astro';
<link
href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Roboto:wght@400;500;700&display=swap"
rel="stylesheet">

<link rel="stylesheet" href="../../node_modules/@fortawesome/fontawesome-free/css/all.min.css">
</head>

<body>
Expand Down
11 changes: 0 additions & 11 deletions examples/server-islands/src/pages/old-index.astro

This file was deleted.

11 changes: 11 additions & 0 deletions packages/astro/e2e/fixtures/server-islands/astro.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import mdx from '@astrojs/mdx';
import react from '@astrojs/react';
import { defineConfig } from 'astro/config';
import nodejs from '@astrojs/node';

// https://astro.build/config
export default defineConfig({
output: 'hybrid',
adapter: nodejs({ mode: 'standalone' }),
integrations: [react(), mdx()],
});
16 changes: 16 additions & 0 deletions packages/astro/e2e/fixtures/server-islands/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "@e2e/server-islands",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "astro dev"
},
"dependencies": {
"@astrojs/react": "workspace:*",
"astro": "workspace:*",
"@astrojs/mdx": "workspace:*",
"@astrojs/node": "workspace:*",
"react": "^18.3.1",
"react-dom": "^18.3.1"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---
---
<h2 id="island">I am an island</h2>
12 changes: 12 additions & 0 deletions packages/astro/e2e/fixtures/server-islands/src/pages/index.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
import Island from '../components/Island.astro';
---

<html>
<head>
<!-- Head Stuff -->
</head>
<body>
<Island server:defer />
</body>
</html>
3 changes: 3 additions & 0 deletions packages/astro/e2e/fixtures/server-islands/src/pages/mdx.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import Island from '../components/Island.astro';

<Island server:defer />
59 changes: 59 additions & 0 deletions packages/astro/e2e/server-islands.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { expect } from '@playwright/test';
import { testFactory } from './test-utils.js';

const test = testFactory({ root: './fixtures/server-islands/' });

test.describe('Server islands', () => {
test.describe('Development', () => {
let devServer;

test.beforeAll(async ({ astro }) => {
devServer = await astro.startDevServer();
});

test.afterAll(async () => {
await devServer.stop();
});

test('Load content from the server', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/'));
let el = page.locator('#island');

await expect(el, 'element rendered').toBeVisible();
await expect(el, 'should have content').toHaveText('I am an island');
});

test('Can be in an MDX file', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/mdx'));
let el = page.locator('#island');

await expect(el, 'element rendered').toBeVisible();
await expect(el, 'should have content').toHaveText('I am an island');
});
});

test.describe('Production', () => {
let previewServer;

test.beforeAll(async ({ astro }) => {
// Playwright's Node version doesn't have these functions, so stub them.
process.stdout.clearLine = () => {};
process.stdout.cursorTo = () => {};
await astro.build();
previewServer = await astro.preview();
});

test.afterAll(async () => {
await previewServer.stop();
});

test('Only one component in prod', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/'));

let el = page.locator('#island');

await expect(el, 'element rendered').toBeVisible();
await expect(el, 'should have content').toHaveText('I am an island');
});
});
});
2 changes: 2 additions & 0 deletions packages/astro/src/core/app/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export function deserializeManifest(serializedManifest: SerializedSSRManifest):
const componentMetadata = new Map(serializedManifest.componentMetadata);
const inlinedScripts = new Map(serializedManifest.inlinedScripts);
const clientDirectives = new Map(serializedManifest.clientDirectives);
const serverIslandNameMap = new Map(serializedManifest.serverIslandNameMap);

return {
// in case user middleware exists, this no-op middleware will be reassigned (see plugin-ssr.ts)
Expand All @@ -29,5 +30,6 @@ export function deserializeManifest(serializedManifest: SerializedSSRManifest):
inlinedScripts,
clientDirectives,
routes,
serverIslandNameMap,
};
}
4 changes: 2 additions & 2 deletions packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
} from '../path.js';
import { RenderContext } from '../render-context.js';
import { createAssetLink } from '../render/ssr-element.js';
import { ensure404Route } from '../routing/astro-designed-error-pages.js';
import { injectDefaultRoutes } from '../routing/default.js';
import { matchRoute } from '../routing/match.js';
import { createOriginCheckMiddleware } from './middlewares.js';
import { AppPipeline } from './pipeline.js';
Expand Down Expand Up @@ -87,7 +87,7 @@ export class App {

constructor(manifest: SSRManifest, streaming = true) {
this.#manifest = manifest;
this.#manifestData = ensure404Route({
this.#manifestData = injectDefaultRoutes({
routes: manifest.routes.map((route) => route.routeData),
});
this.#baseWithoutTrailingSlash = removeTrailingForwardSlash(this.#manifest.base);
Expand Down
18 changes: 8 additions & 10 deletions packages/astro/src/core/app/pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,8 @@ import type {
} from '../../@types/astro.js';
import { Pipeline } from '../base-pipeline.js';
import type { SinglePageBuiltModule } from '../build/types.js';
import { DEFAULT_404_COMPONENT } from '../constants.js';
import { RewriteEncounteredAnError } from '../errors/errors-data.js';
import { AstroError } from '../errors/index.js';
import { RedirectSinglePageBuiltModule } from '../redirects/component.js';
import { createModuleScriptElement, createStylesheetElementSet } from '../render/ssr-element.js';
import { DEFAULT_404_ROUTE } from '../routing/astro-designed-error-pages.js';
import { findRouteToRewrite } from '../routing/rewrite.js';

export class AppPipeline extends Pipeline {
Expand Down Expand Up @@ -103,13 +99,15 @@ export class AppPipeline extends Pipeline {
}

async getModuleForRoute(route: RouteData): Promise<SinglePageBuiltModule> {
if (route.component === DEFAULT_404_COMPONENT) {
return {
page: async () =>
({ default: () => new Response(null, { status: 404 }) }) as ComponentInstance,
renderers: [],
};
for(const defaultRoute of this.defaultRoutes) {
if(route.component === defaultRoute.component) {
return {
page: () => Promise.resolve(defaultRoute.instance),
renderers: []
};
}
}

if (route.type === 'redirect') {
return RedirectSinglePageBuiltModule;
} else {
Expand Down
3 changes: 2 additions & 1 deletion packages/astro/src/core/app/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,12 @@ export type SSRManifestI18n = {

export type SerializedSSRManifest = Omit<
SSRManifest,
'middleware' | 'routes' | 'assets' | 'componentMetadata' | 'inlinedScripts' | 'clientDirectives'
'middleware' | 'routes' | 'assets' | 'componentMetadata' | 'inlinedScripts' | 'clientDirectives' | 'serverIslandNameMap'
> & {
routes: SerializedRouteInfo[];
assets: string[];
componentMetadata: [string, SSRComponentMetadata][];
inlinedScripts: [string, string][];
clientDirectives: [string, string][];
serverIslandNameMap: [string, string][];
};
8 changes: 7 additions & 1 deletion packages/astro/src/core/base-pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { AstroError } from './errors/errors.js';
import { AstroErrorData } from './errors/index.js';
import type { Logger } from './logger/core.js';
import { RouteCache } from './render/route-cache.js';
import { createDefaultRoutes } from './routing/default.js';

/**
* The `Pipeline` represents the static parts of rendering that do not change between requests.
Expand Down Expand Up @@ -52,7 +53,12 @@ export abstract class Pipeline {
* Used for `Astro.site`.
*/
readonly site = manifest.site ? new URL(manifest.site) : undefined,
readonly callSetGetEnv = true
readonly callSetGetEnv = true,
/**
* Array of built-in, internal, routes.
* Used to find the route module
*/
readonly defaultRoutes = createDefaultRoutes(manifest, new URL(import.meta.url))
) {
this.internalMiddleware = [];
// We do use our middleware only if the user isn't using the manual setup
Expand Down
1 change: 1 addition & 0 deletions packages/astro/src/core/build/plugins/plugin-manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ function buildManifest(
buildFormat: settings.config.build.format,
checkOrigin: settings.config.security?.checkOrigin ?? false,
rewritingEnabled: settings.config.experimental.rewriting,
serverIslandNameMap: Array.from(settings.serverIslandNameMap),
experimentalEnvGetSecretEnabled:
settings.config.experimental.env !== undefined &&
(settings.adapter?.supportedAstroFeatures.envGetSecret ?? 'unsupported') !== 'unsupported',
Expand Down
3 changes: 3 additions & 0 deletions packages/astro/src/core/build/plugins/plugin-ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { SSR_MANIFEST_VIRTUAL_MODULE_ID } from './plugin-manifest.js';
import { MIDDLEWARE_MODULE_ID } from './plugin-middleware.js';
import { ASTRO_PAGE_MODULE_ID } from './plugin-pages.js';
import { RENDERERS_MODULE_ID } from './plugin-renderers.js';
import { VIRTUAL_ISLAND_MAP_ID } from '../../server-islands/vite-plugin-server-islands.js';
import { getComponentFromVirtualModulePageName, getVirtualModulePageName } from './util.js';

export const SSR_VIRTUAL_MODULE_ID = '@astrojs-ssr-virtual-entry';
Expand Down Expand Up @@ -249,12 +250,14 @@ function generateSSRCode(adapter: AstroAdapter, middlewareId: string) {
`import { manifest as defaultManifest } from '${SSR_MANIFEST_VIRTUAL_MODULE_ID}';`,
`import * as serverEntrypointModule from '${adapter.serverEntrypoint}';`,
edgeMiddleware ? `` : `import { onRequest as middleware } from '${middlewareId}';`,
`import { serverIslandMap } from '${VIRTUAL_ISLAND_MAP_ID}';`
];

const contents = [
edgeMiddleware ? `const middleware = (_, next) => next()` : '',
`const _manifest = Object.assign(defaultManifest, {`,
` ${pageMap},`,
` serverIslandMap,`,
` renderers,`,
` middleware`,
`});`,
Expand Down
15 changes: 12 additions & 3 deletions packages/astro/src/core/server-islands/endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export function ensureServerIslandRoute(manifest: ManifestData) {
[{ content: '_server-islands', dynamic: false, spread: false }],
[{ content: 'name', dynamic: true, spread: false }]
],
// eslint-disable-next-line
pattern: /^\/_server-islands\/([^/]+?)$/,
prerender: false,
isIndex: false,
Expand All @@ -41,12 +42,19 @@ export function createEndpoint(manifest: SSRManifest) {
const request = result.request;
const raw = await request.text();
const data = JSON.parse(raw) as RenderOptions;
const componentId = params.name! as string;
if(!params.name) {
return new Response(null, {
status: 400,
statusText: 'Bad request'
});
}
const componentId = params.name;

const imp = manifest.serverIslandMap?.get(componentId);
if(!imp) {
return new Response('Not found', {
status: 404
return new Response(null, {
status: 404,
statusText: 'Not found'
});
}

Expand All @@ -62,6 +70,7 @@ export function createEndpoint(manifest: SSRManifest) {

const instance: ComponentInstance = {
default: page,
partial: true,
};

return instance;
Expand Down
Loading
Loading