Skip to content

Commit

Permalink
Merge branch 'next' into jsx-framework-readmes
Browse files Browse the repository at this point in the history
  • Loading branch information
sarah11918 authored Aug 21, 2023
2 parents 92d2b83 + 767eb68 commit 5849893
Show file tree
Hide file tree
Showing 20 changed files with 245 additions and 203 deletions.
26 changes: 26 additions & 0 deletions .changeset/yellow-tips-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'astro': patch
---

Deprecate returning simple objects from endpoints. Endpoints should only return a `Response`.

To return a result with a custom encoding not supported by a `Response`, you can use the `ResponseWithEncoding` utility class instead.

Before:

```ts
export function GET() {
return {
body: '...',
encoding: 'binary',
};
}
```

After:

```ts
export function GET({ ResponseWithEncoding }) {
return new ResponseWithEncoding('...', undefined, 'binary');
}
```
8 changes: 5 additions & 3 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import type { LogOptions, LoggerLevel } from '../core/logger/core';
import type { AstroIntegrationLogger } from '../core/logger/core';
import type { AstroComponentFactory, AstroComponentInstance } from '../runtime/server';
import type { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from './../core/constants.js';
import type { ResponseWithEncoding } from '../core/endpoint/index.js';

export type {
MarkdownHeading,
Expand Down Expand Up @@ -608,7 +609,7 @@ export interface AstroUserConfig {
* @docs
* @name scopedStyleStrategy
* @type {('where' | 'class' | 'attribute')}
* @default `'where'`
* @default `'attribute'`
* @version 2.4
* @description
*
Expand All @@ -619,7 +620,7 @@ export interface AstroUserConfig {
*
* Using `'class'` is helpful when you want to ensure that element selectors within an Astro component override global style defaults (e.g. from a global stylesheet).
* Using `'where'` gives you more control over specifity, but requires that you use higher-specifity selectors, layers, and other tools to control which selectors are applied.
* Using `'attribute'` is useful in case there's manipulation of the class attributes, so the styling emitted by Astro doesn't go in conflict with the user's business logic.
* Using 'attribute' is useful when you are manipulating the `class` attribute of elements and need to avoid conflicts between your own styling logic and Astro's application of styles.
*/
scopedStyleStrategy?: 'where' | 'class' | 'attribute';

Expand Down Expand Up @@ -1963,12 +1964,13 @@ export interface APIContext<Props extends Record<string, any> = Record<string, a
* ```
*/
locals: App.Locals;
ResponseWithEncoding: typeof ResponseWithEncoding;
}

export type EndpointOutput =
| {
body: Body;
encoding?: Exclude<BufferEncoding, 'binary'>;
encoding?: BufferEncoding;
}
| {
body: Uint8Array;
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ export class App {
}
}

if (SSRRoutePipeline.isResponse(response, routeData.type)) {
if (routeData.type === 'page' || routeData.type === 'redirect') {
if (STATUS_CODES.has(response.status)) {
return this.#renderError(request, {
response,
Expand Down
34 changes: 4 additions & 30 deletions packages/astro/src/core/app/ssrPipeline.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import type { Environment } from '../render';
import type { EndpointCallResult } from '../endpoint/index.js';
import mime from 'mime';
import { attachCookiesToResponse } from '../cookies/index.js';
import { Pipeline } from '../pipeline.js';

/**
Expand All @@ -16,39 +13,16 @@ export class EndpointNotFoundError extends Error {
}

export class SSRRoutePipeline extends Pipeline {
#encoder = new TextEncoder();

constructor(env: Environment) {
super(env);
this.setEndpointHandler(this.#ssrEndpointHandler);
}

// This function is responsible for handling the result coming from an endpoint.
async #ssrEndpointHandler(request: Request, response: EndpointCallResult): Promise<Response> {
if (response.type === 'response') {
if (response.response.headers.get('X-Astro-Response') === 'Not-Found') {
throw new EndpointNotFoundError(response.response);
}
return response.response;
} else {
const url = new URL(request.url);
const headers = new Headers();
const mimeType = mime.getType(url.pathname);
if (mimeType) {
headers.set('Content-Type', `${mimeType};charset=utf-8`);
} else {
headers.set('Content-Type', 'text/plain;charset=utf-8');
}
const bytes =
response.encoding !== 'binary' ? this.#encoder.encode(response.body) : response.body;
headers.set('Content-Length', bytes.byteLength.toString());

const newResponse = new Response(bytes, {
status: 200,
headers,
});
attachCookiesToResponse(newResponse, response.cookies);
return newResponse;
async #ssrEndpointHandler(request: Request, response: Response): Promise<Response> {
if (response.headers.get('X-Astro-Response') === 'Not-Found') {
throw new EndpointNotFoundError(response);
}
return response
}
}
54 changes: 3 additions & 51 deletions packages/astro/src/core/build/buildPipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ import { ASTRO_PAGE_RESOLVED_MODULE_ID } from './plugins/plugin-pages.js';
import { RESOLVED_SPLIT_MODULE_ID } from './plugins/plugin-ssr.js';
import { ASTRO_PAGE_EXTENSION_POST_PATTERN } from './plugins/util.js';
import type { SSRManifest } from '../app/types';
import type { AstroConfig, AstroSettings, RouteType, SSRLoadedRenderer } from '../../@types/astro';
import type { AstroConfig, AstroSettings, SSRLoadedRenderer } from '../../@types/astro';
import { getOutputDirectory, isServerLikeOutput } from '../../prerender/utils.js';
import type { EndpointCallResult } from '../endpoint';
import { createEnvironment } from '../render/index.js';
import { BEFORE_HYDRATION_SCRIPT_ID } from '../../vite-plugin-scripts/index.js';
import { createAssetLink } from '../render/ssr-element.js';
import type { BufferEncoding } from 'vfile';

/**
* This pipeline is responsible to gather the files emitted by the SSR build and generate the pages by executing these files.
Expand All @@ -20,10 +18,6 @@ export class BuildPipeline extends Pipeline {
#internals: BuildInternals;
#staticBuildOptions: StaticBuildOptions;
#manifest: SSRManifest;
#currentEndpointBody?: {
body: string | Uint8Array;
encoding: BufferEncoding;
};

constructor(
staticBuildOptions: StaticBuildOptions,
Expand Down Expand Up @@ -163,49 +157,7 @@ export class BuildPipeline extends Pipeline {
return pages;
}

async #handleEndpointResult(request: Request, response: EndpointCallResult): Promise<Response> {
if (response.type === 'response') {
if (!response.response.body) {
return new Response(null);
}
const ab = await response.response.arrayBuffer();
const body = new Uint8Array(ab);
this.#currentEndpointBody = {
body: body,
encoding: 'utf-8',
};
return response.response;
} else {
if (response.encoding) {
this.#currentEndpointBody = {
body: response.body,
encoding: response.encoding,
};
const headers = new Headers();
headers.set('X-Astro-Encoding', response.encoding);
return new Response(response.body, {
headers,
});
} else {
return new Response(response.body);
}
}
}

async computeBodyAndEncoding(
routeType: RouteType,
response: Response
): Promise<{
body: string | Uint8Array;
encoding: BufferEncoding;
}> {
const encoding = response.headers.get('X-Astro-Encoding') ?? 'utf-8';
if (this.#currentEndpointBody) {
const currentEndpointBody = this.#currentEndpointBody;
this.#currentEndpointBody = undefined;
return currentEndpointBody;
} else {
return { body: await response.text(), encoding: encoding as BufferEncoding };
}
async #handleEndpointResult(_: Request, response: Response): Promise<Response> {
return response;
}
}
12 changes: 4 additions & 8 deletions packages/astro/src/core/build/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,20 +567,16 @@ async function generatePath(pathname: string, gopts: GeneratePathOptions, pipeli
} else {
// If there's no body, do nothing
if (!response.body) return;
const result = await pipeline.computeBodyAndEncoding(renderContext.route.type, response);
body = result.body;
encoding = result.encoding;
body = Buffer.from(await response.arrayBuffer());
encoding = (response.headers.get('X-Astro-Encoding') as BufferEncoding | null) ?? 'utf-8';
}

const outFolder = getOutFolder(pipeline.getConfig(), pathname, pageData.route.type);
const outFile = getOutFile(pipeline.getConfig(), outFolder, pathname, pageData.route.type);
pageData.route.distURL = outFile;
const possibleEncoding = response.headers.get('X-Astro-Encoding');
if (possibleEncoding) {
encoding = possibleEncoding as BufferEncoding;
}

await fs.promises.mkdir(outFolder, { recursive: true });
await fs.promises.writeFile(outFile, body, encoding ?? 'utf-8');
await fs.promises.writeFile(outFile, body, encoding);
}

/**
Expand Down
Loading

0 comments on commit 5849893

Please sign in to comment.