Compare commits

...

4 commits

Author SHA1 Message Date
unknown
141149e794 Some more work 2022-06-23 15:07:06 -04:00
unknown
cebad76cad Start of streaming 2022-06-23 14:32:27 -04:00
unknown
5f32bf9ef9 Adds a changeset 2022-06-23 09:10:52 -04:00
unknown
c1c7c3f31b Remove post-rendering head injection 2022-06-23 09:06:30 -04:00
31 changed files with 2158 additions and 1967 deletions

View file

@ -0,0 +1,11 @@
---
'astro': patch
---
Moves head injection to happen during rendering
This change makes it so that head injection; to insert component stylesheets, hoisted scripts, for example, to happen during rendering than as a post-rendering step.
This is to enable streaming. This change will only be noticeable if you are rendering your `<head>` element inside of a framework component. If that is the case then the head items will be injected before the first non-head element in an Astro file instead.
In the future we may offer a `<Astro.Head>` component as a way to control where these scripts/styles are inserted.

View file

@ -0,0 +1,4 @@
<html>
<head><title>Preact component</title></head>
<body><slot></slot></body>
</html>

View file

@ -1,4 +1,5 @@
---
layout: ../components/Layout.astro
setup: |
import Counter from '../components/Counter.jsx';
import PreactComponent from '../components/JSXComponent.jsx';

View file

@ -0,0 +1,4 @@
<html>
<head><title>React component</title></head>
<body><slot></slot></body>
</html>

View file

@ -1,4 +1,5 @@
---
layout: ../components/Layout.astro
setup: |
import Counter from '../components/Counter.jsx';
import ReactComponent from '../components/JSXComponent.jsx';

View file

@ -0,0 +1,4 @@
<html>
<head><title>Solid component</title></head>
<body><slot></slot></body>
</html>

View file

@ -1,4 +1,5 @@
---
layout: ../components/Layout.astro
setup: |
import Counter from '../components/Counter.jsx';
import SolidComponent from '../components/SolidComponent.jsx';

View file

@ -0,0 +1,4 @@
<html>
<head><title>Solid component</title></head>
<body><slot></slot></body>
</html>

View file

@ -1,4 +1,5 @@
---
layout: ../components/Layout.astro
setup: |
import Counter from '../components/Counter.svelte';
import SvelteComponent from '../components/SvelteComponent.svelte';

View file

@ -78,7 +78,7 @@
"test:e2e:match": "playwright test -g"
},
"dependencies": {
"@astrojs/compiler": "^0.16.1",
"@astrojs/compiler": "^0.17.0",
"@astrojs/language-server": "^0.13.4",
"@astrojs/markdown-remark": "^0.11.3",
"@astrojs/prism": "0.4.1",
@ -105,7 +105,6 @@
"gray-matter": "^4.0.3",
"html-entities": "^2.3.3",
"html-escaper": "^3.0.3",
"htmlparser2": "^7.2.0",
"kleur": "^4.1.4",
"magic-string": "^0.25.9",
"micromorph": "^0.1.2",

View file

@ -1004,7 +1004,6 @@ export interface SSRElement {
export interface SSRMetadata {
renderers: SSRLoadedRenderer[];
pathname: string;
needsHydrationStyles: boolean;
}
export interface SSRResult {

View file

@ -94,7 +94,7 @@ export class App {
}
}
const result = await render({
const response = await render({
links,
logging: this.#logging,
markdown: manifest.markdown,
@ -119,17 +119,7 @@ export class App {
request,
});
if (result.type === 'response') {
return result.response;
}
let html = result.html;
let init = result.response;
let headers = init.headers as Headers;
let bytes = this.#encoder.encode(html);
headers.set('Content-Type', 'text/html');
headers.set('Content-Length', bytes.byteLength.toString());
return new Response(bytes, init);
return response;
}
async #callEndpoint(

View file

@ -251,13 +251,14 @@ async function generatePath(
}
body = result.body;
} else {
const result = await render(options);
const response = await render(options);
// If there's a redirect or something, just do nothing.
if (result.type !== 'html') {
if (response.status !== 200 || !response.body) {
return;
}
body = result.html;
body = await response.text();
}
const outFolder = getOutFolder(astroConfig, pathname, pageData.route.type);

View file

@ -85,9 +85,7 @@ export interface RenderOptions {
export async function render(
opts: RenderOptions
): Promise<
{ type: 'html'; html: string; response: ResponseInit } | { type: 'response'; response: Response }
> {
): Promise<Response> {
const {
links,
styles,
@ -144,38 +142,11 @@ export async function render(
ssr,
});
let page: Awaited<ReturnType<typeof renderPage>>;
if (!Component.isAstroComponentFactory) {
const props: Record<string, any> = { ...(pageProps ?? {}), 'server:root': true };
const html = await renderComponent(result, Component.name, Component, props, null);
page = {
type: 'html',
html: html.toString(),
};
return new Response(html.toString(), result.response);
} else {
page = await renderPage(result, Component, pageProps, null);
return await renderPage(result, Component, pageProps, null);
}
if (page.type === 'response') {
return page;
}
let html = page.html;
// handle final head injection if it hasn't happened already
if (html.indexOf('<!--astro:head:injected-->') == -1) {
html = (await renderHead(result)) + html;
}
// cleanup internal state flags
html = html.replace('<!--astro:head:injected-->', '');
// inject <!doctype html> if missing (TODO: is a more robust check needed for comments, etc.?)
if (!/<!doctype html/i.test(html)) {
html = '<!DOCTYPE html>\n' + html;
}
return {
type: 'html',
html,
response: result.response,
};
}

View file

@ -1,109 +0,0 @@
import type * as vite from 'vite';
import htmlparser2 from 'htmlparser2';
/** Inject tags into HTML (note: for best performance, group as many tags as possible into as few calls as you can) */
export function injectTags(html: string, tags: vite.HtmlTagDescriptor[]): string {
let output = html;
if (!tags.length) return output;
const pos = { 'head-prepend': -1, head: -1, 'body-prepend': -1, body: -1 };
// parse html
const parser = new htmlparser2.Parser({
onopentag(tagname) {
if (tagname === 'head') pos['head-prepend'] = parser.endIndex + 1;
if (tagname === 'body') pos['body-prepend'] = parser.endIndex + 1;
},
onclosetag(tagname) {
if (tagname === 'head') pos['head'] = parser.startIndex;
if (tagname === 'body') pos['body'] = parser.startIndex;
},
});
parser.write(html);
parser.end();
// inject
const lastToFirst = Object.entries(pos).sort((a, b) => b[1] - a[1]);
lastToFirst.forEach(([name, i]) => {
if (i === -1) {
// if page didnt generate <head> or <body>, guess
if (name === 'head-prepend' || name === 'head') i = 0;
if (name === 'body-prepend' || name === 'body') i = html.length;
}
let selected = tags.filter(({ injectTo }) => {
if (name === 'head-prepend' && !injectTo) {
return true; // "head-prepend" is the default
} else {
return injectTo === name;
}
});
if (!selected.length) return;
output = output.substring(0, i) + serializeTags(selected) + html.substring(i);
});
return output;
}
type Resource = Record<string, string>;
/** Collect resources (scans final, rendered HTML so expressions have been applied) */
export function collectResources(html: string): Resource[] {
let resources: Resource[] = [];
const parser = new htmlparser2.Parser({
// <link> tags are self-closing, so only use onopentag (avoid onattribute or onclosetag)
onopentag(tagname, attrs) {
if (tagname === 'link') resources.push(attrs);
},
});
parser.write(html);
parser.end();
return resources;
}
// -------------------------------------------------------------------------------
// Everything below © Vite. Rather than invent our own tag creating API, we borrow
// Vites `transformIndexHtml()` API for ease-of-use and consistency. But we need
// to borrow a few private methods in Vite to make that available here.
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/html.ts
//
// See LICENSE for more info.
// -------------------------------------------------------------------------------
const unaryTags = new Set(['link', 'meta', 'base']);
function serializeTag({ tag, attrs, children }: vite.HtmlTagDescriptor, indent = ''): string {
if (unaryTags.has(tag)) {
return `<${tag}${serializeAttrs(attrs)}>`;
} else {
return `<${tag}${serializeAttrs(attrs)}>${serializeTags(
children,
incrementIndent(indent)
)}</${tag}>`;
}
}
function serializeTags(tags: vite.HtmlTagDescriptor['children'], indent = ''): string {
if (typeof tags === 'string') {
return tags;
} else if (tags && tags.length) {
return tags.map((tag) => `${indent}${serializeTag(tag, indent)}\n`).join('');
}
return '';
}
function serializeAttrs(attrs: vite.HtmlTagDescriptor['attrs']): string {
let res = '';
for (const key in attrs) {
if (typeof attrs[key] === 'boolean') {
res += attrs[key] ? ` ${key}` : ``;
} else {
res += ` ${key}=${JSON.stringify(attrs[key])}`;
}
}
return res;
}
function incrementIndent(indent = '') {
return `${indent}${indent[0] === '\t' ? '\t' : ' '}`;
}

View file

@ -1,5 +1,5 @@
import { fileURLToPath } from 'url';
import type { HtmlTagDescriptor, ViteDevServer } from 'vite';
import type { ViteDevServer } from 'vite';
import type {
AstroConfig,
AstroRenderer,
@ -17,7 +17,6 @@ import { RouteCache } from '../route-cache.js';
import { createModuleScriptElementWithSrcSet } from '../ssr-element.js';
import { collectMdMetadata } from '../util.js';
import { getStylesForURL } from './css.js';
import { injectTags } from './html.js';
import { resolveClientDevPath } from './resolve.js';
export interface SSROptions {
@ -45,10 +44,6 @@ export interface SSROptions {
export type ComponentPreload = [SSRLoadedRenderer[], ComponentInstance];
export type RenderResponse =
| { type: 'html'; html: string; response: ResponseInit }
| { type: 'response'; response: Response };
const svelteStylesRE = /svelte\?svelte&type=style/;
async function loadRenderer(
@ -99,7 +94,7 @@ export async function render(
renderers: SSRLoadedRenderer[],
mod: ComponentInstance,
ssrOpts: SSROptions
): Promise<RenderResponse> {
): Promise<Response> {
const {
astroConfig,
filePath,
@ -167,7 +162,7 @@ export async function render(
});
});
let content = await coreRender({
let response = await coreRender({
links,
styles,
logging,
@ -191,32 +186,13 @@ export async function render(
ssr: isBuildingToSSR(astroConfig),
});
if (route?.type === 'endpoint' || content.type === 'response') {
return content;
}
// inject tags
const tags: HtmlTagDescriptor[] = [];
// add injected tags
let html = injectTags(content.html, tags);
// inject <!doctype html> if missing (TODO: is a more robust check needed for comments, etc.?)
if (!/<!doctype html/i.test(html)) {
html = '<!DOCTYPE html>\n' + content;
}
return {
type: 'html',
html,
response: content.response,
};
return response;
}
export async function ssr(
preloadedComponent: ComponentPreload,
ssrOpts: SSROptions
): Promise<RenderResponse> {
): Promise<Response> {
const [renderers, mod] = preloadedComponent;
return await render(renderers, mod, ssrOpts); // NOTE: without "await", errors wont get caught below
}

View file

@ -221,7 +221,6 @@ ${extra}`
},
resolve,
_metadata: {
needsHydrationStyles: false,
renderers,
pathname,
},

View file

@ -11,6 +11,7 @@ import type {
import { escapeHTML, HTMLString, markHTMLString } from './escape.js';
import { extractDirectives, generateHydrateScript } from './hydration.js';
import { createResponse } from './response.js';
import {
determineIfNeedsHydrationScript,
determinesIfNeedsDirectiveScript,
@ -40,19 +41,21 @@ const svgEnumAttributes = /^(autoReverse|externalResourcesRequired|focusable|pre
// INVESTIGATE: Can we have more specific types both for the argument and output?
// If these are intentional, add comments that these are intention and why.
// Or maybe type UserValue = any; ?
async function _render(child: any): Promise<any> {
async function * _render(child: any): AsyncIterable<any> {
child = await child;
if (child instanceof HTMLString) {
return child;
yield child;
} else if (Array.isArray(child)) {
return markHTMLString((await Promise.all(child.map((value) => _render(value)))).join(''));
for(const value of child) {
yield markHTMLString(await _render(value));
}
} else if (typeof child === 'function') {
// Special: If a child is a function, call it automatically.
// This lets you do {() => ...} without the extra boilerplate
// of wrapping it in a function and calling it.
return _render(child());
yield * _render(child());
} else if (typeof child === 'string') {
return markHTMLString(escapeHTML(child));
yield markHTMLString(escapeHTML(child));
} else if (!child && child !== 0) {
// do nothing, safe to ignore falsey values.
}
@ -62,9 +65,11 @@ async function _render(child: any): Promise<any> {
child instanceof AstroComponent ||
Object.prototype.toString.call(child) === '[object AstroComponent]'
) {
return markHTMLString(await renderAstroComponent(child));
yield * renderAstroComponent(child);
} else if(typeof child === 'object' && Symbol.asyncIterator in child) {
yield * child;
} else {
return child;
yield child;
}
}
@ -83,7 +88,7 @@ export class AstroComponent {
return 'AstroComponent';
}
*[Symbol.iterator]() {
async *[Symbol.asyncIterator]() {
const { htmlParts, expressions } = this;
for (let i = 0; i < htmlParts.length; i++) {
@ -91,7 +96,7 @@ export class AstroComponent {
const expression = expressions[i];
yield markHTMLString(html);
yield _render(expression);
yield * _render(expression);
}
}
}
@ -120,9 +125,14 @@ export function createComponent(cb: AstroComponentFactory) {
return cb;
}
export async function renderSlot(_result: any, slotted: string, fallback?: any) {
export async function renderSlot(_result: any, slotted: string, fallback?: any): Promise<string> {
if (slotted) {
return await _render(slotted);
let iterator = _render(slotted);
let content = '';
for await(const chunk of iterator) {
content += chunk;
}
return markHTMLString(content);
}
return fallback;
}
@ -307,13 +317,17 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr
// This is a custom element without a renderer. Because of that, render it
// as a string and the user is responsible for adding a script tag for the component definition.
if (!html && typeof Component === 'string') {
html = await renderAstroComponent(
const iterable = renderAstroComponent(
await render`<${Component}${internalSpreadAttributes(props)}${markHTMLString(
(children == null || children == '') && voidElementNames.test(Component)
? `/>`
: `>${children == null ? '' : children}</${Component}>`
)}`
);
html = '';
for await(const chunk of iterable) {
html += chunk;
}
}
if (!hydration) {
@ -334,7 +348,6 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr
{ renderer: renderer!, result, astroId, props },
metadata as Required<AstroComponentMetadata>
);
result._metadata.needsHydrationStyles = true;
// Render a template if no fragment is provided.
const needsAstroTemplate = children && !/<\/?astro-fragment\>/.test(html);
@ -563,16 +576,6 @@ Update your code to remove this warning.`);
return handler.call(mod, proxy, request);
}
async function replaceHeadInjection(result: SSRResult, html: string): Promise<string> {
let template = html;
// <!--astro:head--> injected by compiler
// Must be handled at the end of the rendering process
if (template.indexOf('<!--astro:head-->') > -1) {
template = template.replace('<!--astro:head-->', await renderHead(result));
}
return template;
}
// Calls a component and renders it into a string of HTML
export async function renderToString(
result: SSRResult,
@ -586,8 +589,11 @@ export async function renderToString(
throw response;
}
let template = await renderAstroComponent(Component);
return template;
let html = '';
for await(const chunk of renderAstroComponent(Component)) {
html += chunk;
}
return html;
}
export async function renderPage(
@ -595,29 +601,40 @@ export async function renderPage(
componentFactory: AstroComponentFactory,
props: any,
children: any
): Promise<{ type: 'html'; html: string } | { type: 'response'; response: Response }> {
): Promise<Response> {
try {
const response = await componentFactory(result, props, children);
const factoryReturnValue = await componentFactory(result, props, children);
if (isAstroComponent(response)) {
let template = await renderAstroComponent(response);
const html = await replaceHeadInjection(result, template);
return {
type: 'html',
html,
};
if (isAstroComponent(factoryReturnValue)) {
let iterable = renderAstroComponent(factoryReturnValue);
let stream = new ReadableStream({
start(controller) {
async function read() {
let i = 0;
for await(const chunk of iterable) {
let html = chunk.toString();
if(i === 0) {
if (!/<!doctype html/i.test(html)) {
controller.enqueue('<!DOCTYPE html>\n');
}
}
controller.enqueue(html);
i++;
}
controller.close();
}
read();
}
});
let init = result.response;
let response = createResponse(stream, init);
return response;
} else {
return {
type: 'response',
response,
};
return factoryReturnValue;
}
} catch (err) {
if (err instanceof Response) {
return {
type: 'response',
response: err,
};
return err;
} else {
throw err;
}
@ -633,47 +650,44 @@ const uniqueElements = (item: any, index: number, all: any[]) => {
);
};
// Renders a page to completion by first calling the factory callback, waiting for its result, and then appending
// styles and scripts into the head.
const alreadyHeadRenderedResults = new WeakSet<SSRResult>();
export async function renderHead(result: SSRResult): Promise<string> {
alreadyHeadRenderedResults.add(result);
const styles = Array.from(result.styles)
.filter(uniqueElements)
.map((style) => renderElement('style', style));
let needsHydrationStyles = result._metadata.needsHydrationStyles;
const scripts = Array.from(result.scripts)
.filter(uniqueElements)
.map((script, i) => {
if ('data-astro-component-hydration' in script.props) {
needsHydrationStyles = true;
}
return renderElement('script', script);
});
if (needsHydrationStyles) {
styles.push(
renderElement('style', {
props: {},
children: 'astro-island, astro-fragment { display: contents; }',
})
);
}
const links = Array.from(result.links)
.filter(uniqueElements)
.map((link) => renderElement('link', link, false));
return markHTMLString(
links.join('\n') + styles.join('\n') + scripts.join('\n') + '\n' + '<!--astro:head:injected-->'
links.join('\n') + styles.join('\n') + scripts.join('\n')
);
}
export async function renderAstroComponent(component: InstanceType<typeof AstroComponent>) {
let template = [];
// This function is called by Astro components that do not contain a <head> component
// This accomodates the fact that using a <head> is optional in Astro, so this
// is called before a component's first non-head HTML element. If the head was
// already injected it is a noop.
export function maybeRenderHead(result: SSRResult): string | Promise<string> {
if(alreadyHeadRenderedResults.has(result)) {
return '';
}
return renderHead(result);
}
export async function * renderAstroComponent(component: InstanceType<typeof AstroComponent>): AsyncIterable<string> {
for await (const value of component) {
if (value || value === 0) {
template.push(value);
for await(const chunk of _render(value)) {
yield markHTMLString(chunk);
}
}
}
return markHTMLString(await _render(template));
}
function componentIsHTMLElement(Component: unknown) {

View file

@ -0,0 +1,69 @@
const isNodeJS = typeof process === 'object' && Object.prototype.toString.call(process);
let RuntimeResponse: typeof Response | undefined;
function createResponseClass() {
RuntimeResponse = class extends Response {
#isStream: boolean;
#body: any;
constructor(body?: BodyInit | null, init?: ResponseInit) {
let isStream = body instanceof ReadableStream;
super(isStream ? null : body, init);
this.#isStream = isStream;
this.#body = body;
}
get body() {
return this.#body;
}
async text(): Promise<string> {
if(this.#isStream && isNodeJS) {
let body = this.#body as ReadableStream<string>;
let reader = body.getReader();
let text = '';
while(true) {
let r = await reader.read();
if(r.value) {
text += r.value.toString();
}
if(r.done) {
break;
}
}
return text;
}
return super.text();
}
async arrayBuffer(): Promise<ArrayBuffer> {
if(this.#isStream && isNodeJS) {
let body = this.#body as ReadableStream<string>;
let reader = body.getReader();
let encoder = new TextEncoder();
let chunks: number[] = [];
while(true) {
let r = await reader.read();
if(r.value) {
chunks.push(...encoder.encode(r.value));
}
if(r.done) {
break;
}
}
return Uint8Array.from(chunks);
}
return super.arrayBuffer();
}
}
return RuntimeResponse;
}
export function createResponse(body?: BodyInit | null, init?: ResponseInit) {
if(typeof RuntimeResponse === 'undefined') {
return new (createResponseClass())(body, init);
}
return new RuntimeResponse(body, init);
}

View file

@ -59,7 +59,7 @@ export function getPrescripts(type: PrescriptType, directive: string): string {
// deps to be loaded immediately.
switch (type) {
case 'both':
return `<script>${getDirectiveScriptText(directive) + islandScript}</script>`;
return `<style>astro-island,astro-fragment{display:contents}</style><script>${getDirectiveScriptText(directive) + islandScript}</script>`;
case 'directive':
return `<script>${getDirectiveScriptText(directive)}</script>`;
}

View file

@ -1,15 +1,16 @@
import type http from 'http';
import { Readable } from 'stream';
import stripAnsi from 'strip-ansi';
import type * as vite from 'vite';
import type { AstroConfig, ManifestData } from '../@types/astro';
import type { SSROptions } from '../core/render/dev/index';
import { Readable } from 'stream';
import stripAnsi from 'strip-ansi';
import { call as callEndpoint } from '../core/endpoint/dev/index.js';
import { fixViteErrorMessage } from '../core/errors.js';
import { error, info, LogOptions, warn } from '../core/logger/core.js';
import * as msg from '../core/messages.js';
import { appendForwardSlash } from '../core/path.js';
import { getParamsAndProps, GetParamsAndPropsError } from '../core/render/core.js';
import type { RenderResponse, SSROptions } from '../core/render/dev/index';
import { preload, ssr } from '../core/render/dev/index.js';
import { RouteCache } from '../core/render/route-cache.js';
import { createRequest } from '../core/request.js';
@ -75,7 +76,12 @@ async function writeWebResponse(res: http.ServerResponse, webResponse: Response)
res.writeHead(status, _headers);
if (body) {
if (body instanceof Readable) {
if(Symbol.for('astro.responseBody') in webResponse) {
let stream = (webResponse as any)[Symbol.for('astro.responseBody')];
for await(const chunk of stream) {
res.write(chunk.toString());
}
} else if (body instanceof Readable) {
body.pipe(res);
return;
} else {
@ -93,23 +99,10 @@ async function writeWebResponse(res: http.ServerResponse, webResponse: Response)
}
async function writeSSRResult(
result: RenderResponse,
res: http.ServerResponse,
statusCode: 200 | 404
webResponse: Response,
res: http.ServerResponse
) {
if (result.type === 'response') {
const { response } = result;
await writeWebResponse(res, response);
return;
}
const { html, response: init } = result;
const headers = init.headers as Headers;
headers.set('Content-Type', 'text/html; charset=utf-8');
headers.set('Content-Length', Buffer.byteLength(html, 'utf-8').toString());
return writeWebResponse(res, new Response(html, init));
return writeWebResponse(res, webResponse);
}
async function handle404Response(
@ -296,7 +289,7 @@ async function handleRequest(
routeCache,
viteServer,
});
return await writeSSRResult(result, res, statusCode);
return await writeSSRResult(result, res);
} else {
return handle404Response(origin, config, req, res);
}
@ -326,7 +319,7 @@ async function handleRequest(
}
} else {
const result = await ssr(preloadedComponent, options);
return await writeSSRResult(result, res, statusCode);
return await writeSSRResult(result, res);
}
} catch (_err) {
const err = fixViteErrorMessage(createSafeError(_err), viteServer);

View file

@ -65,7 +65,7 @@ describe('CSS', function () {
it('Using hydrated components adds astro-island styles', async () => {
const inline = $('style').html();
expect(inline).to.include('display: contents');
expect(inline).to.include('display:contents');
});
it('<style lang="sass">', async () => {

View file

@ -40,4 +40,10 @@ describe('Partial HTML', async () => {
const allInjectedStyles = $('style[data-astro-injected]').text().replace(/\s*/g, '');
expect(allInjectedStyles).to.match(/h1{color:red;}/);
});
it('pages with a head, injection happens inside', async () => {
const html = await fixture.fetch('/with-head').then((res) => res.text());
const $ = cheerio.load(html);
expect($('style')).to.have.lengthOf(1);
});
});

View file

@ -0,0 +1,9 @@
<html>
<head>
<title>testing</title>
<style>body { color: blue; }</style>
</head>
<body>
<h1>testing</h1>
</body>
</html>

View file

@ -0,0 +1,7 @@
---
import { wait } from '../wait';
await wait(10);
---
<header>
<h1>My Site</h1>
</header>

View file

@ -0,0 +1,28 @@
---
import Header from '../components/Header.astro';
import { wait } from '../wait';
async function * list(callback: (num: number) => any) {
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for(const num of nums) {
await wait(20);
yield callback(num);
}
}
---
<html>
<head><title>Testing</title></head>
<body>
<h1>Title</h1>
<section>
<Header />
</section>
<ul>
{list(num => (
<li>Number {num}</li>
))}
</ul>
</body>
</html>

View file

@ -0,0 +1,4 @@
export function wait(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}

View file

@ -0,0 +1,73 @@
import { isWindows, loadFixture } from './test-utils.js';
import { expect } from 'chai';
import testAdapter from './test-adapter.js';
import * as cheerio from 'cheerio';
describe('Streaming', () => {
if (isWindows) return;
/** @type {import('./test-utils').Fixture} */
let fixture;
before(async () => {
fixture = await loadFixture({
root: './fixtures/streaming/',
adapter: testAdapter(),
experimental: {
ssr: true,
},
});
});
describe('Development', () => {
/** @type {import('./test-utils').DevServer} */
let devServer;
before(async () => {
devServer = await fixture.startDevServer();
});
after(async () => {
await devServer.stop();
});
it('Body is chunked', async () => {
let res = await fixture.fetch('/');
let chunks = [];
for await(const bytes of res.body) {
let chunk = bytes.toString('utf-8');
chunks.push(chunk);
}
expect(chunks.length).to.be.greaterThan(1);
});
});
describe('Production', () => {
before(async () => {
await fixture.build();
});
it('Can get the full html body', async () => {
const app = await fixture.loadTestAdapterApp();
const request = new Request('http://example.com/');
const response = await app.render(request);
const html = await response.text();
const $ = cheerio.load(html);
expect($('header h1')).to.have.a.lengthOf(1);
expect($('ul li')).to.have.a.lengthOf(10);
});
it('Body is chunked', async () => {
const app = await fixture.loadTestAdapterApp();
const request = new Request('http://example.com/');
const response = await app.render(request);
let chunks = [];
for await(const bytes of response.body) {
let chunk = bytes.toString('utf-8');
chunks.push(chunk);
}
expect(chunks.length).to.be.greaterThan(1);
});
});
});

View file

@ -1,5 +1,5 @@
export { pathToPosix } from './lib/utils';
export { AbortController, AbortSignal, alert, atob, Blob, btoa, ByteLengthQueuingStrategy, cancelAnimationFrame, cancelIdleCallback, CanvasRenderingContext2D, CharacterData, clearTimeout, Comment, CountQueuingStrategy, CSSStyleSheet, CustomElementRegistry, CustomEvent, Document, DocumentFragment, DOMException, Element, Event, EventTarget, fetch, File, FormData, Headers, HTMLBodyElement, HTMLCanvasElement, HTMLDivElement, HTMLDocument, HTMLElement, HTMLHeadElement, HTMLHtmlElement, HTMLImageElement, HTMLSpanElement, HTMLStyleElement, HTMLTemplateElement, HTMLUnknownElement, Image, ImageData, IntersectionObserver, MediaQueryList, MutationObserver, Node, NodeFilter, NodeIterator, OffscreenCanvas, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, Request, requestAnimationFrame, requestIdleCallback, ResizeObserver, Response, setTimeout, ShadowRoot, structuredClone, StyleSheet, Text, TransformStream, TreeWalker, URLPattern, Window, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter } from './mod.js';
export { AbortController, AbortSignal, alert, atob, Blob, btoa, ByteLengthQueuingStrategy, cancelAnimationFrame, cancelIdleCallback, CanvasRenderingContext2D, CharacterData, clearTimeout, Comment, CountQueuingStrategy, CSSStyleSheet, CustomElementRegistry, CustomEvent, Document, DocumentFragment, DOMException, Element, Event, EventTarget, fetch, File, FormData, Headers, HTMLBodyElement, HTMLCanvasElement, HTMLDivElement, HTMLDocument, HTMLElement, HTMLHeadElement, HTMLHtmlElement, HTMLImageElement, HTMLSpanElement, HTMLStyleElement, HTMLTemplateElement, HTMLUnknownElement, Image, ImageData, IntersectionObserver, MediaQueryList, MutationObserver, Node, NodeFilter, NodeIterator, OffscreenCanvas, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, Request, requestAnimationFrame, requestIdleCallback, ResizeObserver, Response, setTimeout, ShadowRoot, structuredClone, StyleSheet, Text, TransformStream, TreeWalker, URLPattern, Window, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter, } from './mod.js';
export declare const polyfill: {
(target: any, options?: PolyfillOptions): any;
internals(target: any, name: string): any;

File diff suppressed because it is too large Load diff