full site update

This commit is contained in:
2025-07-24 18:46:24 +02:00
parent bfe2b90d8d
commit 37a6e0ab31
6912 changed files with 540482 additions and 361712 deletions

View File

@@ -1,4 +1,4 @@
import type { PropagationHint } from '../../@types/astro.js';
import type { PropagationHint } from '../../types/public/internal.js';
import type { AstroComponentFactory } from './render/index.js';
interface CreateComponentOptions {
factory: AstroComponentFactory;

View File

@@ -1,2 +1,2 @@
import type { AstroGlobalPartial } from '../../@types/astro.js';
import type { AstroGlobalPartial } from '../../types/public/context.js';
export declare function createAstro(site: string | undefined): AstroGlobalPartial;

View File

@@ -2,6 +2,8 @@ import { ASTRO_VERSION } from "../../core/constants.js";
import { AstroError, AstroErrorData } from "../../core/errors/index.js";
function createAstroGlobFn() {
const globHandler = (importMetaGlobResult) => {
console.warn(`Astro.glob is deprecated and will be removed in a future major version of Astro.
Use import.meta.glob instead: https://vitejs.dev/guide/features.html#glob-import`);
if (typeof importMetaGlobResult === "string") {
throw new AstroError({
...AstroErrorData.AstroGlobUsedOutside,

View File

@@ -0,0 +1 @@
export declare const ISLAND_STYLES = "astro-island,astro-slot,astro-static-slot{display:contents}";

View File

@@ -0,0 +1,4 @@
const ISLAND_STYLES = "astro-island,astro-slot,astro-static-slot{display:contents}";
export {
ISLAND_STYLES
};

View File

@@ -1,4 +1,7 @@
import type { APIContext, EndpointHandler } from '../../@types/astro.js';
import type { Logger } from '../../core/logger/core.js';
import type { APIRoute } from '../../types/public/common.js';
import type { APIContext } from '../../types/public/context.js';
/** Renders an endpoint request to completion, returning the body. */
export declare function renderEndpoint(mod: EndpointHandler, context: APIContext, ssr: boolean, logger: Logger): Promise<Response>;
export declare function renderEndpoint(mod: {
[method: string]: APIRoute;
}, context: APIContext, isPrerendered: boolean, logger: Logger): Promise<Response>;

View File

@@ -1,17 +1,20 @@
import { bold } from "kleur/colors";
import { REROUTABLE_STATUS_CODES, REROUTE_DIRECTIVE_HEADER } from "../../core/constants.js";
import { EndpointDidNotReturnAResponse } from "../../core/errors/errors-data.js";
import { AstroError } from "../../core/errors/errors.js";
async function renderEndpoint(mod, context, ssr, logger) {
import { EndpointDidNotReturnAResponse } from "../../core/errors/errors-data.js";
async function renderEndpoint(mod, context, isPrerendered, logger) {
const { request, url } = context;
const method = request.method.toUpperCase();
const handler = mod[method] ?? mod["ALL"];
if (!ssr && ssr === false && method !== "GET") {
let handler = mod[method] ?? mod["ALL"];
if (!handler && method === "HEAD" && mod["GET"]) {
handler = mod["GET"];
}
if (isPrerendered && !["GET", "HEAD"].includes(method)) {
logger.warn(
"router",
`${url.pathname} ${bold(
method
)} requests are not available for a static site. Update your config to \`output: 'server'\` or \`output: 'hybrid'\` to enable.`
)} requests are not available in static endpoints. Mark this page as server-rendered (\`export const prerender = false;\`) or update your config to \`output: 'server'\` to make all your pages server-rendered by default.`
);
}
if (handler === void 0) {
@@ -47,6 +50,9 @@ Found handlers: ${Object.keys(mod).map((exp) => JSON.stringify(exp)).join(", ")}
}
}
}
if (method === "HEAD") {
return new Response(null, response);
}
return response;
}
export {

View File

@@ -1,5 +1,4 @@
import { escape } from 'html-escaper';
export declare const escapeHTML: typeof escape;
export declare const escapeHTML: (str: string) => string;
export declare class HTMLBytes extends Uint8Array {
}
/**

View File

@@ -1,4 +1,4 @@
import type { AstroComponentMetadata, SSRElement, SSRLoadedRenderer, SSRResult } from '../../@types/astro.js';
import type { AstroComponentMetadata, SSRElement, SSRLoadedRenderer, SSRResult } from '../../types/public/internal.js';
export interface HydrationMetadata {
directive: string;
value: string;

View File

@@ -37,6 +37,8 @@ function extractDirectives(inputProps, clientDirectives) {
extracted.hydration.componentExport.value = value;
break;
}
// This is a special prop added to prove that the client hydration method
// was added statically.
case "client:component-hydration": {
break;
}
@@ -95,7 +97,9 @@ async function generateHydrateScript(scriptOptions, metadata) {
island.props["component-url"] = await result.resolve(decodeURI(componentUrl));
if (renderer.clientEntrypoint) {
island.props["component-export"] = componentExport.value;
island.props["renderer-url"] = await result.resolve(decodeURI(renderer.clientEntrypoint));
island.props["renderer-url"] = await result.resolve(
decodeURI(renderer.clientEntrypoint.toString())
);
island.props["props"] = escapeHTML(serializeProps(props, metadata));
}
island.props["ssr"] = "";

View File

@@ -3,8 +3,9 @@ export { createAstro } from './astro-global.js';
export { renderEndpoint } from './endpoint.js';
export { escapeHTML, HTMLBytes, HTMLString, isHTMLString, markHTMLString, unescapeHTML, } from './escape.js';
export { renderJSX } from './jsx.js';
export { addAttribute, createHeadAndContent, defineScriptVars, Fragment, maybeRenderHead, renderTemplate as render, renderComponent, Renderer as Renderer, renderHead, renderHTMLElement, renderPage, renderScript, renderScriptElement, renderSlot, renderSlotToString, renderTemplate, renderToString, renderUniqueStylesheet, voidElementNames, } from './render/index.js';
export type { AstroComponentFactory, AstroComponentInstance, ComponentSlots, RenderInstruction, } from './render/index.js';
export { addAttribute, createHeadAndContent, defineScriptVars, Fragment, maybeRenderHead, Renderer as Renderer, renderComponent, renderHead, renderHTMLElement, renderPage, renderScript, renderScriptElement, renderSlot, renderSlotToString, renderTemplate as render, renderTemplate, renderToString, renderUniqueStylesheet, voidElementNames, } from './render/index.js';
export type { ServerIslandComponent } from './render/server-islands.js';
export { createTransitionScope, renderTransition } from './transition.js';
export declare function mergeSlots(...slotted: unknown[]): Record<string, () => any>;
export declare function spreadAttributes(values?: Record<any, any>, _name?: string, { class: scopedClassName }?: {

View File

@@ -16,9 +16,8 @@ import {
defineScriptVars,
Fragment,
maybeRenderHead,
renderTemplate,
renderComponent,
Renderer,
renderComponent,
renderHead,
renderHTMLElement,
renderPage,
@@ -26,6 +25,7 @@ import {
renderScriptElement,
renderSlot,
renderSlotToString,
renderTemplate,
renderTemplate as renderTemplate2,
renderToString,
renderUniqueStylesheet,
@@ -33,7 +33,7 @@ import {
} from "./render/index.js";
import { createTransitionScope, renderTransition } from "./transition.js";
import { markHTMLString as markHTMLString2 } from "./escape.js";
import { Renderer as Renderer2, addAttribute as addAttribute2 } from "./render/index.js";
import { addAttribute as addAttribute2, Renderer as Renderer2 } from "./render/index.js";
function mergeSlots(...slotted) {
const slots = {};
for (const slot of slotted) {
@@ -67,7 +67,7 @@ function spreadAttributes(values = {}, _name, { class: scopedClassName } = {}) {
}
}
for (const [key, value] of Object.entries(values)) {
output += addAttribute2(value, key, true);
output += addAttribute2(value, key, true, _name);
}
return markHTMLString2(output);
}

View File

@@ -1,2 +1,2 @@
import type { SSRResult } from '../../@types/astro.js';
import type { SSRResult } from '../../types/public/internal.js';
export declare function renderJSX(result: SSRResult, vnode: any): Promise<any>;

View File

@@ -1,12 +1,12 @@
import { AstroJSX, isVNode } from "../../jsx-runtime/index.js";
import {
HTMLString,
escapeHTML,
HTMLString,
markHTMLString,
renderToString,
spreadAttributes,
voidElementNames
} from "./index.js";
import { isAstroComponentFactory } from "./render/astro/factory.js";
import { renderComponentToString } from "./render/component.js";
const ClientOnlyPlaceholder = "astro-client-only";
const hasTriedRenderComponentSymbol = Symbol("hasTriedRenderComponent");
@@ -39,7 +39,7 @@ Did you forget to import the component or is it possible there is a typo?`);
}
case vnode.type === Symbol.for("astro:fragment"):
return renderJSX(result, vnode.props.children);
case vnode.type.isAstroComponentFactory: {
case isAstroComponentFactory(vnode.type): {
let props = {};
let slots = {};
for (const [key, value] of Object.entries(vnode.props ?? {})) {
@@ -49,10 +49,13 @@ Did you forget to import the component or is it possible there is a typo?`);
props[key] = value;
}
}
const str = await renderToString(result, vnode.type, props, slots);
if (str instanceof Response) {
throw str;
}
const str = await renderComponentToString(
result,
vnode.type.name,
vnode.type,
props,
slots
);
const html = markHTMLString(str);
return html;
}

View File

@@ -1,2 +1,2 @@
import { type RenderDestination } from './common.js';
export declare function renderChild(destination: RenderDestination, child: any): Promise<void>;
export declare function renderChild(destination: RenderDestination, child: any): void | Promise<void>;

View File

@@ -3,44 +3,93 @@ import { isPromise } from "../util.js";
import { isAstroComponentInstance, isRenderTemplateResult } from "./astro/index.js";
import { isRenderInstance } from "./common.js";
import { SlotString } from "./slot.js";
import { renderToBufferDestination } from "./util.js";
async function renderChild(destination, child) {
import { createBufferedRenderer } from "./util.js";
function renderChild(destination, child) {
if (isPromise(child)) {
child = await child;
return child.then((x) => renderChild(destination, x));
}
if (child instanceof SlotString) {
destination.write(child);
} else if (isHTMLString(child)) {
return;
}
if (isHTMLString(child)) {
destination.write(child);
} else if (Array.isArray(child)) {
const childRenders = child.map((c) => {
return renderToBufferDestination((bufferDestination) => {
return renderChild(bufferDestination, c);
});
});
for (const childRender of childRenders) {
if (!childRender) continue;
await childRender.renderToFinalDestination(destination);
}
} else if (typeof child === "function") {
await renderChild(destination, child());
} else if (typeof child === "string") {
return;
}
if (Array.isArray(child)) {
return renderArray(destination, child);
}
if (typeof child === "function") {
return renderChild(destination, child());
}
if (!child && child !== 0) {
return;
}
if (typeof child === "string") {
destination.write(markHTMLString(escapeHTML(child)));
} else if (!child && child !== 0) {
} else if (isRenderInstance(child)) {
await child.render(destination);
} else if (isRenderTemplateResult(child)) {
await child.render(destination);
} else if (isAstroComponentInstance(child)) {
await child.render(destination);
} else if (ArrayBuffer.isView(child)) {
return;
}
if (isRenderInstance(child)) {
return child.render(destination);
}
if (isRenderTemplateResult(child)) {
return child.render(destination);
}
if (isAstroComponentInstance(child)) {
return child.render(destination);
}
if (ArrayBuffer.isView(child)) {
destination.write(child);
} else if (typeof child === "object" && (Symbol.asyncIterator in child || Symbol.iterator in child)) {
for await (const value of child) {
await renderChild(destination, value);
return;
}
if (typeof child === "object" && (Symbol.asyncIterator in child || Symbol.iterator in child)) {
if (Symbol.asyncIterator in child) {
return renderAsyncIterable(destination, child);
}
} else {
destination.write(child);
return renderIterable(destination, child);
}
destination.write(child);
}
function renderArray(destination, children) {
const flushers = children.map((c) => {
return createBufferedRenderer(destination, (bufferDestination) => {
return renderChild(bufferDestination, c);
});
});
const iterator = flushers[Symbol.iterator]();
const iterate = () => {
for (; ; ) {
const { value: flusher, done } = iterator.next();
if (done) {
break;
}
const result = flusher.flush();
if (isPromise(result)) {
return result.then(iterate);
}
}
};
return iterate();
}
function renderIterable(destination, children) {
const iterator = children[Symbol.iterator]();
const iterate = () => {
for (; ; ) {
const { value, done } = iterator.next();
if (done) {
break;
}
const result = renderChild(destination, value);
if (isPromise(result)) {
return result.then(iterate);
}
}
};
return iterate();
}
async function renderAsyncIterable(destination, children) {
for await (const value of children) {
await renderChild(destination, value);
}
}
export {

View File

@@ -1,7 +1,7 @@
import type { PropagationHint, SSRResult } from '../../../../@types/astro.js';
import type { HeadAndContent } from './head-and-content.js';
import type { PropagationHint, SSRResult } from '../../../../types/public/internal.js';
import type { HeadAndContent, ThinHead } from './head-and-content.js';
import type { RenderTemplateResult } from './render-template.js';
export type AstroFactoryReturnValue = RenderTemplateResult | Response | HeadAndContent;
export type AstroFactoryReturnValue = RenderTemplateResult | Response | HeadAndContent | ThinHead;
export interface AstroComponentFactory {
(result: any, props: any, slots: any): AstroFactoryReturnValue | Promise<AstroFactoryReturnValue>;
isAstroComponentFactory?: boolean;
@@ -10,3 +10,4 @@ export interface AstroComponentFactory {
}
export declare function isAstroComponentFactory(obj: any): obj is AstroComponentFactory;
export declare function isAPropagatingComponent(result: SSRResult, factory: AstroComponentFactory): boolean;
export declare function getPropagationHint(result: SSRResult, factory: AstroComponentFactory): PropagationHint;

View File

@@ -2,13 +2,18 @@ function isAstroComponentFactory(obj) {
return obj == null ? false : obj.isAstroComponentFactory === true;
}
function isAPropagatingComponent(result, factory) {
const hint = getPropagationHint(result, factory);
return hint === "in-tree" || hint === "self";
}
function getPropagationHint(result, factory) {
let hint = factory.propagation || "none";
if (factory.moduleId && result.componentMetadata.has(factory.moduleId) && hint === "none") {
hint = result.componentMetadata.get(factory.moduleId).propagation;
}
return hint === "in-tree" || hint === "self";
return hint;
}
export {
getPropagationHint,
isAPropagatingComponent,
isAstroComponentFactory
};

View File

@@ -5,6 +5,13 @@ export type HeadAndContent = {
head: string;
content: RenderTemplateResult;
};
/**
* A head that doesn't contain any content
*/
export type ThinHead = {
[headAndContentSym]: true;
};
export declare function isHeadAndContent(obj: unknown): obj is HeadAndContent;
export declare function createHeadAndContent(head: string, content: RenderTemplateResult): HeadAndContent;
export declare function createThinHead(): ThinHead;
export {};

View File

@@ -9,7 +9,13 @@ function createHeadAndContent(head, content) {
content
};
}
function createThinHead() {
return {
[headAndContentSym]: true
};
}
export {
createHeadAndContent,
createThinHead,
isHeadAndContent
};

View File

@@ -1,7 +1,7 @@
export { isAstroComponentFactory } from './factory.js';
export type { AstroComponentFactory } from './factory.js';
export { isAstroComponentFactory } from './factory.js';
export { createHeadAndContent, isHeadAndContent } from './head-and-content.js';
export { createAstroComponentInstance, isAstroComponentInstance } from './instance.js';
export type { AstroComponentInstance } from './instance.js';
export { isRenderTemplateResult, renderTemplate } from './render-template.js';
export { createAstroComponentInstance, isAstroComponentInstance } from './instance.js';
export { renderToReadableStream, renderToString } from './render.js';
export { isRenderTemplateResult, renderTemplate } from './render-template.js';

View File

@@ -1,8 +1,8 @@
import { isAstroComponentFactory } from "./factory.js";
import { createHeadAndContent, isHeadAndContent } from "./head-and-content.js";
import { createAstroComponentInstance, isAstroComponentInstance } from "./instance.js";
import { isRenderTemplateResult, renderTemplate } from "./render-template.js";
import { renderToReadableStream, renderToString } from "./render.js";
import { isRenderTemplateResult, renderTemplate } from "./render-template.js";
export {
createAstroComponentInstance,
createHeadAndContent,

View File

@@ -1,7 +1,7 @@
import type { SSRResult } from '../../../../@types/astro.js';
import type { ComponentSlots } from '../slot.js';
import type { AstroComponentFactory } from './factory.js';
import type { SSRResult } from '../../../../types/public/internal.js';
import type { RenderDestination } from '../common.js';
import type { ComponentSlots } from '../slot.js';
import type { AstroComponentFactory, AstroFactoryReturnValue } from './factory.js';
type ComponentProps = Record<string | number, any>;
declare const astroComponentInstanceSym: unique symbol;
export declare class AstroComponentInstance {
@@ -12,8 +12,9 @@ export declare class AstroComponentInstance {
private readonly factory;
private returnValue;
constructor(result: SSRResult, props: ComponentProps, slots: ComponentSlots, factory: AstroComponentFactory);
init(result: SSRResult): Promise<import("./factory.js").AstroFactoryReturnValue>;
render(destination: RenderDestination): Promise<void>;
init(result: SSRResult): AstroFactoryReturnValue | Promise<AstroFactoryReturnValue>;
render(destination: RenderDestination): void | Promise<void>;
private renderImpl;
}
export declare function createAstroComponentInstance(result: SSRResult, displayName: string, factory: AstroComponentFactory, props: ComponentProps, slots?: any): AstroComponentInstance;
export declare function isAstroComponentInstance(obj: unknown): obj is AstroComponentInstance;

View File

@@ -27,8 +27,10 @@ class AstroComponentInstance {
};
}
}
async init(result) {
if (this.returnValue !== void 0) return this.returnValue;
init(result) {
if (this.returnValue !== void 0) {
return this.returnValue;
}
this.returnValue = this.factory(result, this.props, this.slotValues);
if (isPromise(this.returnValue)) {
this.returnValue.then((resolved) => {
@@ -38,19 +40,26 @@ class AstroComponentInstance {
}
return this.returnValue;
}
async render(destination) {
const returnValue = await this.init(this.result);
render(destination) {
const returnValue = this.init(this.result);
if (isPromise(returnValue)) {
return returnValue.then((x) => this.renderImpl(destination, x));
}
return this.renderImpl(destination, returnValue);
}
renderImpl(destination, returnValue) {
if (isHeadAndContent(returnValue)) {
await returnValue.content.render(destination);
return returnValue.content.render(destination);
} else {
await renderChild(destination, returnValue);
return renderChild(destination, returnValue);
}
}
}
function validateComponentProps(props, displayName) {
function validateComponentProps(props, clientDirectives, displayName) {
if (props != null) {
const directives = [...clientDirectives.keys()].map((directive) => `client:${directive}`);
for (const prop of Object.keys(props)) {
if (prop.startsWith("client:")) {
if (directives.includes(prop)) {
console.warn(
`You are attempting to render <${displayName} ${prop} />, but ${displayName} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.`
);
@@ -59,7 +68,7 @@ function validateComponentProps(props, displayName) {
}
}
function createAstroComponentInstance(result, displayName, factory, props, slots = {}) {
validateComponentProps(props, displayName);
validateComponentProps(props, result.clientDirectives, displayName);
const instance = new AstroComponentInstance(result, props, slots, factory);
if (isAPropagatingComponent(result, factory)) {
result._metadata.propagators.add(instance);

View File

@@ -6,7 +6,7 @@ export declare class RenderTemplateResult {
expressions: any[];
private error;
constructor(htmlParts: TemplateStringsArray, expressions: unknown[]);
render(destination: RenderDestination): Promise<void>;
render(destination: RenderDestination): void | Promise<void>;
}
export declare function isRenderTemplateResult(obj: unknown): obj is RenderTemplateResult;
export declare function renderTemplate(htmlParts: TemplateStringsArray, ...expressions: any[]): RenderTemplateResult;

View File

@@ -1,7 +1,7 @@
import { markHTMLString } from "../../escape.js";
import { isPromise } from "../../util.js";
import { renderChild } from "../any.js";
import { renderToBufferDestination } from "../util.js";
import { createBufferedRenderer } from "../util.js";
const renderTemplateResultSym = Symbol.for("astro.renderTemplateResult");
class RenderTemplateResult {
[renderTemplateResultSym] = true;
@@ -23,22 +23,32 @@ class RenderTemplateResult {
return expression;
});
}
async render(destination) {
const expRenders = this.expressions.map((exp) => {
return renderToBufferDestination((bufferDestination) => {
render(destination) {
const flushers = this.expressions.map((exp) => {
return createBufferedRenderer(destination, (bufferDestination) => {
if (exp || exp === 0) {
return renderChild(bufferDestination, exp);
}
});
});
for (let i = 0; i < this.htmlParts.length; i++) {
const html = this.htmlParts[i];
const expRender = expRenders[i];
destination.write(markHTMLString(html));
if (expRender) {
await expRender.renderToFinalDestination(destination);
let i = 0;
const iterate = () => {
while (i < this.htmlParts.length) {
const html = this.htmlParts[i];
const flusher = flushers[i];
i++;
if (html) {
destination.write(markHTMLString(html));
}
if (flusher) {
const result = flusher.flush();
if (isPromise(result)) {
return result.then(iterate);
}
}
}
}
};
return iterate();
}
}
function isRenderTemplateResult(obj) {

View File

@@ -1,5 +1,6 @@
import type { RouteData, SSRResult } from '../../../../@types/astro.js';
import type { RouteData, SSRResult } from '../../../../types/public/internal.js';
import type { AstroComponentFactory } from './factory.js';
export declare function renderToString(result: SSRResult, componentFactory: AstroComponentFactory, props: any, children: any, isPage?: boolean, route?: RouteData): Promise<string | Response>;
export declare function renderToReadableStream(result: SSRResult, componentFactory: AstroComponentFactory, props: any, children: any, isPage?: boolean, route?: RouteData): Promise<ReadableStream | Response>;
export declare function bufferHeadContent(result: SSRResult): Promise<void>;
export declare function renderToAsyncIterable(result: SSRResult, componentFactory: AstroComponentFactory, props: any, children: any, isPage?: boolean, route?: RouteData): Promise<AsyncIterable<Uint8Array> | Response>;

View File

@@ -1,4 +1,5 @@
import { AstroError, AstroErrorData } from "../../../../core/errors/index.js";
import { isPromise } from "../../util.js";
import { chunkToByteArray, chunkToString, encoder } from "../common.js";
import { promiseWithResolvers } from "../util.js";
import { isHeadAndContent } from "./head-and-content.js";
@@ -123,7 +124,7 @@ async function bufferHeadContent(result) {
break;
}
const returnValue = await value.init(result);
if (isHeadAndContent(returnValue)) {
if (isHeadAndContent(returnValue) && returnValue.head) {
result._metadata.extraHead.push(returnValue.head);
}
}
@@ -206,12 +207,10 @@ async function renderToAsyncIterable(result, componentFactory, props, children,
}
}
};
const renderPromise = templateResult.render(destination);
renderPromise.then(() => {
renderingComplete = true;
next?.resolve();
}).catch((err) => {
const renderResult = toPromise(() => templateResult.render(destination));
renderResult.catch((err) => {
error = err;
}).finally(() => {
renderingComplete = true;
next?.resolve();
});
@@ -221,7 +220,16 @@ async function renderToAsyncIterable(result, componentFactory, props, children,
}
};
}
function toPromise(fn) {
try {
const result = fn();
return isPromise(result) ? result : Promise.resolve(result);
} catch (err) {
return Promise.reject(err);
}
}
export {
bufferHeadContent,
renderToAsyncIterable,
renderToReadableStream,
renderToString

View File

@@ -1,6 +1,6 @@
import type { SSRResult } from '../../../@types/astro.js';
import type { RenderInstruction } from './instruction.js';
import type { SSRResult } from '../../../types/public/internal.js';
import type { HTMLBytes, HTMLString } from '../escape.js';
import type { RenderInstruction } from './instruction.js';
import { type SlotString } from './slot.js';
/**
* Possible chunk types to be written to the destination, and it'll

View File

@@ -6,6 +6,7 @@ import {
} from "../scripts.js";
import { renderAllHeadContent } from "./head.js";
import { isRenderInstruction } from "./instruction.js";
import { renderServerIslandRuntime } from "./server-islands.js";
import { isSlotString } from "./slot.js";
const Fragment = Symbol.for("astro:fragment");
const Renderer = Symbol.for("astro:renderer");
@@ -19,9 +20,11 @@ function stringifyChunk(result, chunk) {
const { hydration } = instruction;
let needsHydrationScript = hydration && determineIfNeedsHydrationScript(result);
let needsDirectiveScript = hydration && determinesIfNeedsDirectiveScript(result, hydration.directive);
let prescriptType = needsHydrationScript ? "both" : needsDirectiveScript ? "directive" : null;
if (prescriptType) {
let prescripts = getPrescripts(result, prescriptType, hydration.directive);
if (needsHydrationScript) {
let prescripts = getPrescripts(result, "both", hydration.directive);
return markHTMLString(prescripts);
} else if (needsDirectiveScript) {
let prescripts = getPrescripts(result, "directive", hydration.directive);
return markHTMLString(prescripts);
} else {
return "";
@@ -48,6 +51,13 @@ function stringifyChunk(result, chunk) {
}
return "";
}
case "server-island-runtime": {
if (result._metadata.hasRenderedServerIslandRuntime) {
return "";
}
result._metadata.hasRenderedServerIslandRuntime = true;
return renderServerIslandRuntime();
}
default: {
throw new Error(`Unknown chunk type: ${chunk.type}`);
}

View File

@@ -1,8 +1,8 @@
import type { RouteData, SSRResult } from '../../../@types/astro.js';
import type { RouteData, SSRResult } from '../../../types/public/internal.js';
import { type RenderInstance } from './common.js';
import { type ComponentSlots } from './slot.js';
declare const needsHeadRenderingSymbol: unique symbol;
export declare function renderComponent(result: SSRResult, displayName: string, Component: unknown, props: Record<string | number, any>, slots?: ComponentSlots): Promise<RenderInstance>;
export declare function renderComponent(result: SSRResult, displayName: string, Component: unknown, props: Record<string | number, any>, slots?: ComponentSlots): RenderInstance | Promise<RenderInstance>;
export declare function renderComponentToString(result: SSRResult, displayName: string, Component: unknown, props: Record<string | number, any>, slots?: any, isPage?: boolean, route?: RouteData): Promise<string>;
export type NonAstroPageComponent = {
name: string;

View File

@@ -1,4 +1,3 @@
import { createRenderInstruction } from "./instruction.js";
import { clsx } from "clsx";
import { AstroError, AstroErrorData } from "../../../core/errors/index.js";
import { markHTMLString } from "../escape.js";
@@ -9,19 +8,21 @@ import { isPromise } from "../util.js";
import { isAstroComponentFactory } from "./astro/factory.js";
import { renderTemplate } from "./astro/index.js";
import { createAstroComponentInstance } from "./astro/instance.js";
import { bufferHeadContent } from "./astro/render.js";
import {
chunkToString,
Fragment,
Renderer,
chunkToString
Renderer
} from "./common.js";
import { componentIsHTMLElement, renderHTMLElement } from "./dom.js";
import { maybeRenderHead } from "./head.js";
import { containsServerDirective, renderServerIsland } from "./server-islands.js";
import { renderSlotToString, renderSlots } from "./slot.js";
import { createRenderInstruction } from "./instruction.js";
import { containsServerDirective, ServerIslandComponent } from "./server-islands.js";
import { renderSlots, renderSlotToString } from "./slot.js";
import { formatList, internalSpreadAttributes, renderElement, voidElementNames } from "./util.js";
const needsHeadRenderingSymbol = Symbol.for("astro.needsHeadRendering");
const rendererAliases = /* @__PURE__ */ new Map([["solid", "solid-js"]]);
const clientOnlyValues = /* @__PURE__ */ new Set(["solid-js", "react", "preact", "vue", "svelte", "lit"]);
const clientOnlyValues = /* @__PURE__ */ new Set(["solid-js", "react", "preact", "vue", "svelte"]);
function guessRenderers(componentUrl) {
const extname = componentUrl?.split(".").pop();
switch (extname) {
@@ -39,8 +40,7 @@ function guessRenderers(componentUrl) {
"@astrojs/preact",
"@astrojs/solid-js",
"@astrojs/vue",
"@astrojs/svelte",
"@astrojs/lit"
"@astrojs/svelte"
];
}
}
@@ -210,12 +210,6 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr
}
} else {
if (metadata.hydrate === "only") {
const rendererName = rendererAliases.has(metadata.hydrateArgs) ? rendererAliases.get(metadata.hydrateArgs) : metadata.hydrateArgs;
if (!clientOnlyValues.has(rendererName)) {
console.warn(
`The client:only directive for ${metadata.displayName} is not recognized. The renderer ${renderer.name} will be used. If you intended to use a different renderer, please provide a valid client:only directive.`
);
}
html = await renderSlotToString(result, slots?.fallback);
} else {
const componentRenderStartTime = performance.now();
@@ -230,21 +224,13 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr
componentServerRenderEndTime = performance.now() - componentRenderStartTime;
}
}
if (renderer && !renderer.clientEntrypoint && renderer.name !== "@astrojs/lit" && metadata.hydrate) {
throw new AstroError({
...AstroErrorData.NoClientEntrypoint,
message: AstroErrorData.NoClientEntrypoint.message(
displayName,
metadata.hydrate,
renderer.name
)
});
}
if (!html && typeof Component === "string") {
const Tag = sanitizeElementName(Component);
const childSlots = Object.values(children).join("");
const renderTemplateResult = renderTemplate`<${Tag}${internalSpreadAttributes(
props
props,
true,
Tag
)}${markHTMLString(
childSlots === "" && voidElementNames.test(Tag) ? `/>` : `>${childSlots}</${Tag}>`
)}`;
@@ -359,30 +345,34 @@ async function renderHTMLComponent(result, Component, _props, slots = {}) {
}
function renderAstroComponent(result, displayName, Component, props, slots = {}) {
if (containsServerDirective(props)) {
return renderServerIsland(result, displayName, props, slots);
const serverIslandComponent = new ServerIslandComponent(result, props, slots, displayName);
result._metadata.propagators.add(serverIslandComponent);
return serverIslandComponent;
}
const instance = createAstroComponentInstance(result, displayName, Component, props, slots);
return {
async render(destination) {
await instance.render(destination);
render(destination) {
return instance.render(destination);
}
};
}
async function renderComponent(result, displayName, Component, props, slots = {}) {
function renderComponent(result, displayName, Component, props, slots = {}) {
if (isPromise(Component)) {
Component = await Component.catch(handleCancellation);
return Component.catch(handleCancellation).then((x) => {
return renderComponent(result, displayName, x, props, slots);
});
}
if (isFragmentComponent(Component)) {
return await renderFragmentComponent(result, slots).catch(handleCancellation);
return renderFragmentComponent(result, slots).catch(handleCancellation);
}
props = normalizeProps(props);
if (isHTMLComponent(Component)) {
return await renderHTMLComponent(result, Component, props, slots).catch(handleCancellation);
return renderHTMLComponent(result, Component, props, slots).catch(handleCancellation);
}
if (isAstroComponentFactory(Component)) {
return renderAstroComponent(result, displayName, Component, props, slots);
}
return await renderFrameworkComponent(result, displayName, Component, props, slots).catch(
return renderFrameworkComponent(result, displayName, Component, props, slots).catch(
handleCancellation
);
function handleCancellation(e) {
@@ -427,6 +417,9 @@ async function renderComponentToString(result, displayName, Component, props, sl
}
};
const renderInstance = await renderComponent(result, displayName, Component, props, slots);
if (containsServerDirective(props)) {
await bufferHeadContent(result);
}
await renderInstance.render(destination);
} catch (e) {
if (AstroError.is(e) && !e.loc) {

View File

@@ -0,0 +1,2 @@
import type { SSRResult } from '../../../types/public/index.js';
export declare function renderCspContent(result: SSRResult): string;

35
node_modules/astro/dist/runtime/server/render/csp.js generated vendored Normal file
View File

@@ -0,0 +1,35 @@
function renderCspContent(result) {
const finalScriptHashes = /* @__PURE__ */ new Set();
const finalStyleHashes = /* @__PURE__ */ new Set();
for (const scriptHash of result.scriptHashes) {
finalScriptHashes.add(`'${scriptHash}'`);
}
for (const styleHash of result.styleHashes) {
finalStyleHashes.add(`'${styleHash}'`);
}
for (const styleHash of result._metadata.extraStyleHashes) {
finalStyleHashes.add(`'${styleHash}'`);
}
for (const scriptHash of result._metadata.extraScriptHashes) {
finalScriptHashes.add(`'${scriptHash}'`);
}
let directives = "";
if (result.directives.length > 0) {
directives = result.directives.join(";") + ";";
}
let scriptResources = "'self'";
if (result.scriptResources.length > 0) {
scriptResources = result.scriptResources.map((r) => `${r}`).join(" ");
}
let styleResources = "'self'";
if (result.styleResources.length > 0) {
styleResources = result.styleResources.map((r) => `${r}`).join(" ");
}
const strictDynamic = result.isStrictDynamic ? ` 'strict-dynamic'` : "";
const scriptSrc = `script-src ${scriptResources} ${Array.from(finalScriptHashes).join(" ")}${strictDynamic};`;
const styleSrc = `style-src ${styleResources} ${Array.from(finalStyleHashes).join(" ")};`;
return `${directives} ${scriptSrc} ${styleSrc}`;
}
export {
renderCspContent
};

View File

@@ -1,3 +1,3 @@
import type { SSRResult } from '../../../@types/astro.js';
import type { SSRResult } from '../../../types/public/internal.js';
export declare function componentIsHTMLElement(Component: unknown): boolean;
export declare function renderHTMLElement(result: SSRResult, constructor: typeof HTMLElement, props: any, slots: any): Promise<string>;

View File

@@ -1,4 +1,4 @@
import type { SSRResult } from '../../../@types/astro.js';
import type { SSRResult } from '../../../types/public/internal.js';
import type { MaybeRenderHeadInstruction, RenderHeadInstruction } from './instruction.js';
export declare function renderAllHeadContent(result: SSRResult): any;
export declare function renderHead(): RenderHeadInstruction;

View File

@@ -1,4 +1,5 @@
import { markHTMLString } from "../escape.js";
import { renderCspContent } from "./csp.js";
import { createRenderInstruction } from "./instruction.js";
import { renderElement } from "./util.js";
const uniqueElements = (item, index, all) => {
@@ -8,15 +9,32 @@ const uniqueElements = (item, index, all) => {
};
function renderAllHeadContent(result) {
result._metadata.hasRenderedHead = true;
let content = "";
if (result.shouldInjectCspMetaTags && result.cspDestination === "meta") {
content += renderElement(
"meta",
{
props: {
"http-equiv": "content-security-policy",
content: renderCspContent(result)
},
children: ""
},
false
);
}
const styles = Array.from(result.styles).filter(uniqueElements).map(
(style) => style.props.rel === "stylesheet" ? renderElement("link", style) : renderElement("style", style)
);
result.styles.clear();
const scripts = Array.from(result.scripts).filter(uniqueElements).map((script) => {
if (result.userAssetsBase) {
script.props.src = (result.base === "/" ? "" : result.base) + result.userAssetsBase + script.props.src;
}
return renderElement("script", script, false);
});
const links = Array.from(result.links).filter(uniqueElements).map((link) => renderElement("link", link, false));
let content = styles.join("\n") + links.join("\n") + scripts.join("\n");
content += styles.join("\n") + links.join("\n") + scripts.join("\n");
if (result._metadata.extraHead.length > 0) {
for (const part of result._metadata.extraHead) {
content += part;

View File

@@ -1,12 +1,12 @@
export { createHeadAndContent, renderTemplate, renderToString } from './astro/index.js';
export type { AstroComponentFactory, AstroComponentInstance } from './astro/index.js';
export { Fragment, Renderer, chunkToByteArray, chunkToString } from './common.js';
export { createHeadAndContent, renderTemplate, renderToString } from './astro/index.js';
export { chunkToByteArray, chunkToString, Fragment, Renderer } from './common.js';
export { renderComponent, renderComponentToString } from './component.js';
export { renderScript } from './script.js';
export { renderHTMLElement } from './dom.js';
export { maybeRenderHead, renderHead } from './head.js';
export type { RenderInstruction } from './instruction.js';
export { renderPage } from './page.js';
export { renderSlot, renderSlotToString, type ComponentSlots } from './slot.js';
export { renderScript } from './script.js';
export { type ComponentSlots, renderSlot, renderSlotToString } from './slot.js';
export { renderScriptElement, renderUniqueStylesheet } from './tags.js';
export { addAttribute, defineScriptVars, voidElementNames } from './util.js';

View File

@@ -1,10 +1,10 @@
import { createHeadAndContent, renderTemplate, renderToString } from "./astro/index.js";
import { Fragment, Renderer, chunkToByteArray, chunkToString } from "./common.js";
import { chunkToByteArray, chunkToString, Fragment, Renderer } from "./common.js";
import { renderComponent, renderComponentToString } from "./component.js";
import { renderScript } from "./script.js";
import { renderHTMLElement } from "./dom.js";
import { maybeRenderHead, renderHead } from "./head.js";
import { renderPage } from "./page.js";
import { renderScript } from "./script.js";
import { renderSlot, renderSlotToString } from "./slot.js";
import { renderScriptElement, renderUniqueStylesheet } from "./tags.js";
import { addAttribute, defineScriptVars, voidElementNames } from "./util.js";

View File

@@ -18,9 +18,9 @@ export type RendererHydrationScriptInstruction = {
export type MaybeRenderHeadInstruction = {
type: 'maybe-head';
};
export type RenderInstruction = RenderDirectiveInstruction | RenderHeadInstruction | MaybeRenderHeadInstruction | RendererHydrationScriptInstruction;
export declare function createRenderInstruction(instruction: RenderDirectiveInstruction): RenderDirectiveInstruction;
export declare function createRenderInstruction(instruction: RendererHydrationScriptInstruction): RendererHydrationScriptInstruction;
export declare function createRenderInstruction(instruction: RenderHeadInstruction): RenderHeadInstruction;
export declare function createRenderInstruction(instruction: MaybeRenderHeadInstruction): MaybeRenderHeadInstruction;
export type ServerIslandRuntimeInstruction = {
type: 'server-island-runtime';
};
export type RenderInstruction = RenderDirectiveInstruction | RenderHeadInstruction | MaybeRenderHeadInstruction | RendererHydrationScriptInstruction | ServerIslandRuntimeInstruction;
export declare function createRenderInstruction<T extends RenderInstruction>(instruction: T): T;
export declare function isRenderInstruction(chunk: any): chunk is RenderInstruction;

View File

@@ -1,4 +1,4 @@
import type { RouteData, SSRResult } from '../../../@types/astro.js';
import type { RouteData, SSRResult } from '../../../types/public/internal.js';
import { type NonAstroPageComponent } from './component.js';
import type { AstroComponentFactory } from './index.js';
export declare function renderPage(result: SSRResult, componentFactory: AstroComponentFactory | NonAstroPageComponent, props: any, children: any, streaming: boolean, route?: RouteData): Promise<Response>;

View File

@@ -1,7 +1,8 @@
import { renderComponentToString } from "./component.js";
import { isAstroComponentFactory } from "./astro/index.js";
import { renderToAsyncIterable, renderToReadableStream, renderToString } from "./astro/render.js";
import { encoder } from "./common.js";
import { renderComponentToString } from "./component.js";
import { renderCspContent } from "./csp.js";
import { isDeno, isNode } from "./util.js";
async function renderPage(result, componentFactory, props, children, streaming, route) {
if (!isAstroComponentFactory(componentFactory)) {
@@ -17,11 +18,15 @@ async function renderPage(result, componentFactory, props, children, streaming,
route
);
const bytes = encoder.encode(str);
const headers2 = new Headers([
["Content-Type", "text/html"],
["Content-Length", bytes.byteLength.toString()]
]);
if (result.cspDestination === "header" || result.cspDestination === "adapter") {
headers2.set("content-security-policy", renderCspContent(result));
}
return new Response(bytes, {
headers: new Headers([
["Content-Type", "text/html; charset=utf-8"],
["Content-Length", bytes.byteLength.toString()]
])
headers: headers2
});
}
result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false;
@@ -46,21 +51,28 @@ async function renderPage(result, componentFactory, props, children, streaming,
if (body instanceof Response) return body;
const init = result.response;
const headers = new Headers(init.headers);
if (result.shouldInjectCspMetaTags && result.cspDestination === "header" || result.cspDestination === "adapter") {
headers.set("content-security-policy", renderCspContent(result));
}
if (!streaming && typeof body === "string") {
body = encoder.encode(body);
headers.set("Content-Length", body.byteLength.toString());
}
if (route?.component.endsWith(".md")) {
headers.set("Content-Type", "text/html; charset=utf-8");
}
let status = init.status;
let statusText = init.statusText;
if (route?.route === "/404") {
status = 404;
if (statusText === "OK") {
statusText = "Not Found";
}
} else if (route?.route === "/500") {
status = 500;
if (statusText === "OK") {
statusText = "Internal Server Error";
}
}
if (status) {
return new Response(body, { ...init, headers, status });
return new Response(body, { ...init, headers, status, statusText });
} else {
return new Response(body, { ...init, headers });
}

View File

@@ -1,4 +1,4 @@
import type { SSRResult } from '../../../@types/astro.js';
import type { SSRResult } from '../../../types/public/internal.js';
/**
* Relies on the `renderScript: true` compiler option
* @experimental

View File

@@ -11,7 +11,9 @@ async function renderScript(result, id) {
}
}
const resolved = await result.resolve(id);
return markHTMLString(`<script type="module" src="${resolved}"></script>`);
return markHTMLString(
`<script type="module" src="${result.userAssetsBase ? (result.base === "/" ? "" : result.base) + result.userAssetsBase : ""}${resolved}"></script>`
);
}
export {
renderScript

View File

@@ -1,5 +1,24 @@
import type { SSRResult } from '../../../@types/astro.js';
import type { RenderInstance } from './common.js';
import type { SSRResult } from '../../../types/public/internal.js';
import { type ThinHead } from './astro/head-and-content.js';
import type { RenderDestination } from './common.js';
import { type ComponentSlots } from './slot.js';
export declare function containsServerDirective(props: Record<string | number, any>): boolean;
export declare function renderServerIsland(result: SSRResult, _displayName: string, props: Record<string | number, any>, slots: ComponentSlots): RenderInstance;
export declare class ServerIslandComponent {
result: SSRResult;
props: Record<string | number, any>;
slots: ComponentSlots;
displayName: string;
hostId: string | undefined;
islandContent: string | undefined;
componentPath: string | undefined;
componentExport: string | undefined;
componentId: string | undefined;
constructor(result: SSRResult, props: Record<string | number, any>, slots: ComponentSlots, displayName: string);
init(): Promise<ThinHead>;
render(destination: RenderDestination): Promise<void>;
getComponentPath(): string;
getComponentExport(): string;
getHostId(): Promise<string>;
getIslandContent(): Promise<string>;
}
export declare const renderServerIslandRuntime: () => string;

View File

@@ -1,5 +1,8 @@
import { encryptString } from "../../../core/encryption.js";
import { encryptString, generateCspDigest } from "../../../core/encryption.js";
import { markHTMLString } from "../escape.js";
import { renderChild } from "./any.js";
import { createThinHead } from "./astro/head-and-content.js";
import { createRenderInstruction } from "./instruction.js";
import { renderSlotToString } from "./slot.js";
const internalProps = /* @__PURE__ */ new Set([
"server:component-path",
@@ -10,74 +13,176 @@ const internalProps = /* @__PURE__ */ new Set([
function containsServerDirective(props) {
return "server:component-directive" in props;
}
const SCRIPT_RE = /<\/script/giu;
const COMMENT_RE = /<!--/gu;
const SCRIPT_REPLACER = "<\\/script";
const COMMENT_REPLACER = "\\u003C!--";
function safeJsonStringify(obj) {
return JSON.stringify(obj).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029").replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\//g, "\\u002f");
return JSON.stringify(obj).replace(SCRIPT_RE, SCRIPT_REPLACER).replace(COMMENT_RE, COMMENT_REPLACER);
}
function renderServerIsland(result, _displayName, props, slots) {
return {
async render(destination) {
const componentPath = props["server:component-path"];
const componentExport = props["server:component-export"];
const componentId = result.serverIslandNameMap.get(componentPath);
if (!componentId) {
throw new Error(`Could not find server component name`);
function createSearchParams(componentExport, encryptedProps, slots) {
const params = new URLSearchParams();
params.set("e", componentExport);
params.set("p", encryptedProps);
params.set("s", slots);
return params;
}
function isWithinURLLimit(pathname, params) {
const url = pathname + "?" + params.toString();
const chars = url.length;
return chars < 2048;
}
class ServerIslandComponent {
result;
props;
slots;
displayName;
hostId;
islandContent;
componentPath;
componentExport;
componentId;
constructor(result, props, slots, displayName) {
this.result = result;
this.props = props;
this.slots = slots;
this.displayName = displayName;
}
async init() {
const content = await this.getIslandContent();
if (this.result.cspDestination) {
this.result._metadata.extraScriptHashes.push(
await generateCspDigest(SERVER_ISLAND_REPLACER, this.result.cspAlgorithm)
);
const contentDigest = await generateCspDigest(content, this.result.cspAlgorithm);
this.result._metadata.extraScriptHashes.push(contentDigest);
}
return createThinHead();
}
async render(destination) {
const hostId = await this.getHostId();
const islandContent = await this.getIslandContent();
destination.write(createRenderInstruction({ type: "server-island-runtime" }));
destination.write("<!--[if astro]>server-island-start<![endif]-->");
for (const name in this.slots) {
if (name === "fallback") {
await renderChild(destination, this.slots.fallback(this.result));
}
for (const key2 of Object.keys(props)) {
if (internalProps.has(key2)) {
delete props[key2];
}
}
destination.write(
`<script type="module" data-astro-rerun data-island-id="${hostId}">${islandContent}</script>`
);
}
getComponentPath() {
if (this.componentPath) {
return this.componentPath;
}
const componentPath = this.props["server:component-path"];
if (!componentPath) {
throw new Error(`Could not find server component path`);
}
this.componentPath = componentPath;
return componentPath;
}
getComponentExport() {
if (this.componentExport) {
return this.componentExport;
}
const componentExport = this.props["server:component-export"];
if (!componentExport) {
throw new Error(`Could not find server component export`);
}
this.componentExport = componentExport;
return componentExport;
}
async getHostId() {
if (!this.hostId) {
this.hostId = await crypto.randomUUID();
}
return this.hostId;
}
async getIslandContent() {
if (this.islandContent) {
return this.islandContent;
}
const componentPath = this.getComponentPath();
const componentExport = this.getComponentExport();
const componentId = this.result.serverIslandNameMap.get(componentPath);
if (!componentId) {
throw new Error(`Could not find server component name`);
}
for (const key2 of Object.keys(this.props)) {
if (internalProps.has(key2)) {
delete this.props[key2];
}
destination.write("<!--[if astro]>server-island-start<![endif]-->");
const renderedSlots = {};
for (const name in slots) {
if (name !== "fallback") {
const content = await renderSlotToString(result, slots[name]);
renderedSlots[name] = content.toString();
} else {
await renderChild(destination, slots.fallback(result));
}
}
const renderedSlots = {};
for (const name in this.slots) {
if (name !== "fallback") {
const content = await renderSlotToString(this.result, this.slots[name]);
renderedSlots[name] = content.toString();
}
const key = await result.key;
const propsEncrypted = await encryptString(key, JSON.stringify(props));
const hostId = crypto.randomUUID();
const slash = result.base.endsWith("/") ? "" : "/";
const serverIslandUrl = `${result.base}${slash}_server-islands/${componentId}${result.trailingSlash === "always" ? "/" : ""}`;
destination.write(`<script async type="module" data-island-id="${hostId}">
let componentId = ${safeJsonStringify(componentId)};
let componentExport = ${safeJsonStringify(componentExport)};
let script = document.querySelector('script[data-island-id="${hostId}"]');
let data = {
componentExport,
}
const key = await this.result.key;
const propsEncrypted = Object.keys(this.props).length === 0 ? "" : await encryptString(key, JSON.stringify(this.props));
const hostId = await this.getHostId();
const slash = this.result.base.endsWith("/") ? "" : "/";
let serverIslandUrl = `${this.result.base}${slash}_server-islands/${componentId}${this.result.trailingSlash === "always" ? "/" : ""}`;
const potentialSearchParams = createSearchParams(
componentExport,
propsEncrypted,
safeJsonStringify(renderedSlots)
);
const useGETRequest = isWithinURLLimit(serverIslandUrl, potentialSearchParams);
if (useGETRequest) {
serverIslandUrl += "?" + potentialSearchParams.toString();
this.result._metadata.extraHead.push(
markHTMLString(
`<link rel="preload" as="fetch" href="${serverIslandUrl}" crossorigin="anonymous">`
)
);
}
const method = useGETRequest ? (
// GET request
`let response = await fetch('${serverIslandUrl}');`
) : (
// POST request
`let data = {
componentExport: ${safeJsonStringify(componentExport)},
encryptedProps: ${safeJsonStringify(propsEncrypted)},
slots: ${safeJsonStringify(renderedSlots)},
};
let response = await fetch('${serverIslandUrl}', {
method: 'POST',
body: JSON.stringify(data),
});
if (script) {
if(response.status === 200 && response.headers.get('content-type') === 'text/html') {
let html = await response.text();
// Swap!
while(script.previousSibling &&
script.previousSibling.nodeType !== 8 &&
script.previousSibling.data !== '[if astro]>server-island-start<![endif]') {
script.previousSibling.remove();
}
script.previousSibling?.remove();
let frag = document.createRange().createContextualFragment(html);
script.before(frag);
});`
);
this.islandContent = `${method}replaceServerIsland('${hostId}', response);`;
return this.islandContent;
}
}
script.remove();
}
</script>`);
}
};
}
export {
containsServerDirective,
renderServerIsland
const renderServerIslandRuntime = () => {
return `<script>${SERVER_ISLAND_REPLACER}</script>`;
};
const SERVER_ISLAND_REPLACER = markHTMLString(
`async function replaceServerIsland(id, r) {
let s = document.querySelector(\`script[data-island-id="\${id}"]\`);
// If there's no matching script, or the request fails then return
if (!s || r.status !== 200 || r.headers.get('content-type')?.split(';')[0].trim() !== 'text/html') return;
// Load the HTML before modifying the DOM in case of errors
let html = await r.text();
// Remove any placeholder content before the island script
while (s.previousSibling && s.previousSibling.nodeType !== 8 && s.previousSibling.data !== '[if astro]>server-island-start<![endif]')
s.previousSibling.remove();
s.previousSibling?.remove();
// Insert the new HTML
s.before(document.createRange().createContextualFragment(html));
// Remove the script. Prior to v5.4.2, this was the trick to force rerun of scripts. Keeping it to minimize change to the existing behavior.
s.remove();
}`.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("//")).join(" ")
);
export {
ServerIslandComponent,
containsServerDirective,
renderServerIslandRuntime
};

View File

@@ -1,8 +1,8 @@
import type { SSRResult } from '../../../@types/astro.js';
import { renderTemplate } from './astro/render-template.js';
import type { RenderInstruction } from './instruction.js';
import type { SSRResult } from '../../../types/public/internal.js';
import { HTMLString } from '../escape.js';
import { renderTemplate } from './astro/render-template.js';
import { type RenderInstance } from './common.js';
import type { RenderInstruction } from './instruction.js';
type RenderTemplateResult = ReturnType<typeof renderTemplate>;
export type ComponentSlots = Record<string, ComponentSlotValue>;
export type ComponentSlotValue = (result: SSRResult) => RenderTemplateResult | Promise<RenderTemplateResult>;

View File

@@ -1,6 +1,6 @@
import { renderTemplate } from "./astro/render-template.js";
import { HTMLString, markHTMLString, unescapeHTML } from "../escape.js";
import { renderChild } from "./any.js";
import { renderTemplate } from "./astro/render-template.js";
import { chunkToString } from "./common.js";
const slotString = Symbol.for("astro:slot-string");
class SlotString extends HTMLString {

View File

@@ -1,4 +1,4 @@
import type { SSRElement, SSRResult } from '../../../@types/astro.js';
import type { StylesheetAsset } from '../../../core/app/types.js';
import type { SSRElement, SSRResult } from '../../../types/public/internal.js';
export declare function renderScriptElement({ props, children }: SSRElement): string;
export declare function renderUniqueStylesheet(result: SSRResult, sheet: StylesheetAsset): string | undefined;

View File

@@ -1,34 +1,41 @@
import type { SSRElement } from '../../../@types/astro.js';
import type { RenderFunction } from './common.js';
import type { SSRElement } from '../../../types/public/internal.js';
import type { RenderDestination, RenderFunction } from './common.js';
export declare const voidElementNames: RegExp;
export declare const toAttributeString: (value: any, shouldEscape?: boolean) => any;
export declare const toStyleString: (obj: Record<string, any>) => string;
export declare function defineScriptVars(vars: Record<any, any>): any;
export declare function formatList(values: string[]): string;
export declare function addAttribute(value: any, key: string, shouldEscape?: boolean): any;
export declare function internalSpreadAttributes(values: Record<any, any>, shouldEscape?: boolean): any;
export declare function addAttribute(value: any, key: string, shouldEscape?: boolean, tagName?: string): any;
export declare function internalSpreadAttributes(values: Record<any, any>, shouldEscape: boolean | undefined, tagName: string): any;
export declare function renderElement(name: string, { props: _props, children }: SSRElement, shouldEscape?: boolean): string;
/**
* Executes the `bufferRenderFunction` to prerender it into a buffer destination, and return a promise
* with an object containing the `renderToFinalDestination` function to flush the buffer to the final
* with an object containing the `flush` function to flush the buffer to the final
* destination.
*
* @example
* ```ts
* // Render components in parallel ahead of time
* const finalRenders = [ComponentA, ComponentB].map((comp) => {
* return renderToBufferDestination(async (bufferDestination) => {
* return createBufferedRenderer(finalDestination, async (bufferDestination) => {
* await renderComponentToDestination(bufferDestination);
* });
* });
* // Render array of components serially
* for (const finalRender of finalRenders) {
* await finalRender.renderToFinalDestination(finalDestination);
* await finalRender.flush();
* }
* ```
*/
export declare function renderToBufferDestination(bufferRenderFunction: RenderFunction): {
renderToFinalDestination: RenderFunction;
};
export declare function createBufferedRenderer(destination: RenderDestination, renderFunction: RenderFunction): RendererFlusher;
export interface RendererFlusher {
/**
* Flushes the current renderer to the underlying renderer.
*
* See example of `createBufferedRenderer` for usage.
*/
flush(): void | Promise<void>;
}
export declare const isNode: boolean;
export declare const isDeno: boolean;
export type PromiseWithResolvers<T> = {

View File

@@ -1,9 +1,8 @@
import { clsx } from "clsx";
import { HTMLString, markHTMLString } from "../escape.js";
import { isPromise } from "../util.js";
const voidElementNames = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i;
const htmlBooleanAttributes = /^(?:allowfullscreen|async|autofocus|autoplay|checked|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|loop|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|selected|itemscope)$/i;
const htmlEnumAttributes = /^(?:contenteditable|draggable|spellcheck|value)$/i;
const svgEnumAttributes = /^(?:autoReverse|externalResourcesRequired|focusable|preserveAlpha)$/i;
const htmlBooleanAttributes = /^(?:allowfullscreen|async|autofocus|autoplay|checked|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|inert|loop|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|selected|itemscope)$/i;
const AMPERSAND_REGEX = /&/g;
const DOUBLE_QUOTE_REGEX = /"/g;
const STATIC_DIRECTIVES = /* @__PURE__ */ new Set(["set:html", "set:text"]);
@@ -34,14 +33,17 @@ function formatList(values) {
}
return `${values.slice(0, -1).join(", ")} or ${values[values.length - 1]}`;
}
function addAttribute(value, key, shouldEscape = true) {
if (value == null) {
return "";
function isCustomElement(tagName) {
return tagName.includes("-");
}
function handleBooleanAttribute(key, value, shouldEscape, tagName) {
if (tagName && isCustomElement(tagName)) {
return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`);
}
if (value === false) {
if (htmlEnumAttributes.test(key) || svgEnumAttributes.test(key)) {
return markHTMLString(` ${key}="false"`);
}
return markHTMLString(value ? ` ${key}` : "");
}
function addAttribute(value, key, shouldEscape = true, tagName = "") {
if (value == null) {
return "";
}
if (STATIC_DIRECTIVES.has(key)) {
@@ -73,16 +75,24 @@ Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the
if (typeof value === "string" && value.includes("&") && isHttpUrl(value)) {
return markHTMLString(` ${key}="${toAttributeString(value, false)}"`);
}
if (value === true && (key.startsWith("data-") || htmlBooleanAttributes.test(key))) {
return markHTMLString(` ${key}`);
} else {
return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`);
if (htmlBooleanAttributes.test(key)) {
return handleBooleanAttribute(key, value, shouldEscape, tagName);
}
if (value === "") {
return markHTMLString(` ${key}`);
}
if (key === "popover" && typeof value === "boolean") {
return handleBooleanAttribute(key, value, shouldEscape, tagName);
}
if (key === "download" && typeof value === "boolean") {
return handleBooleanAttribute(key, value, shouldEscape, tagName);
}
return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`);
}
function internalSpreadAttributes(values, shouldEscape = true) {
function internalSpreadAttributes(values, shouldEscape = true, tagName) {
let output = "";
for (const [key, value] of Object.entries(values)) {
output += addAttribute(value, key, shouldEscape);
output += addAttribute(value, key, shouldEscape, tagName);
}
return markHTMLString(output);
}
@@ -99,9 +109,9 @@ function renderElement(name, { props: _props, children = "" }, shouldEscape = tr
}
}
if ((children == null || children == "") && voidElementNames.test(name)) {
return `<${name}${internalSpreadAttributes(props, shouldEscape)}>`;
return `<${name}${internalSpreadAttributes(props, shouldEscape, name)}>`;
}
return `<${name}${internalSpreadAttributes(props, shouldEscape)}>${children}</${name}>`;
return `<${name}${internalSpreadAttributes(props, shouldEscape, name)}>${children}</${name}>`;
}
const noop = () => {
};
@@ -109,28 +119,38 @@ class BufferedRenderer {
chunks = [];
renderPromise;
destination;
constructor(bufferRenderFunction) {
this.renderPromise = bufferRenderFunction(this);
Promise.resolve(this.renderPromise).catch(noop);
/**
* Determines whether buffer has been flushed
* to the final destination.
*/
flushed = false;
constructor(destination, renderFunction) {
this.destination = destination;
this.renderPromise = renderFunction(this);
if (isPromise(this.renderPromise)) {
Promise.resolve(this.renderPromise).catch(noop);
}
}
write(chunk) {
if (this.destination) {
if (this.flushed) {
this.destination.write(chunk);
} else {
this.chunks.push(chunk);
}
}
async renderToFinalDestination(destination) {
for (const chunk of this.chunks) {
destination.write(chunk);
flush() {
if (this.flushed) {
throw new Error("The render buffer has already been flushed.");
}
this.destination = destination;
await this.renderPromise;
this.flushed = true;
for (const chunk of this.chunks) {
this.destination.write(chunk);
}
return this.renderPromise;
}
}
function renderToBufferDestination(bufferRenderFunction) {
const renderer = new BufferedRenderer(bufferRenderFunction);
return renderer;
function createBufferedRenderer(destination, renderFunction) {
return new BufferedRenderer(destination, renderFunction);
}
const isNode = typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]";
const isDeno = typeof Deno !== "undefined";
@@ -157,6 +177,7 @@ function isHttpUrl(url) {
}
export {
addAttribute,
createBufferedRenderer,
defineScriptVars,
formatList,
internalSpreadAttributes,
@@ -164,7 +185,7 @@ export {
isNode,
promiseWithResolvers,
renderElement,
renderToBufferDestination,
toAttributeString,
toStyleString,
voidElementNames
};

View File

@@ -1,5 +1,5 @@
import type { SSRResult } from '../../@types/astro.js';
import type { SSRResult } from '../../types/public/internal.js';
export declare function determineIfNeedsHydrationScript(result: SSRResult): boolean;
export declare function determinesIfNeedsDirectiveScript(result: SSRResult, directive: string): boolean;
export type PrescriptType = null | 'both' | 'directive';
export type PrescriptType = 'both' | 'directive';
export declare function getPrescripts(result: SSRResult, type: PrescriptType, directive: string): string;

View File

@@ -1,6 +1,6 @@
import islandScriptDev from "./astro-island.prebuilt-dev.js";
import islandScript from "./astro-island.prebuilt.js";
const ISLAND_STYLES = `<style>astro-island,astro-slot,astro-static-slot{display:contents}</style>`;
import islandScriptDev from "./astro-island.prebuilt-dev.js";
import { ISLAND_STYLES } from "./astro-island-styles.js";
function determineIfNeedsHydrationScript(result) {
if (result._metadata.hasHydrationScript) {
return false;
@@ -25,13 +25,10 @@ function getDirectiveScriptText(result, directive) {
function getPrescripts(result, type, directive) {
switch (type) {
case "both":
return `${ISLAND_STYLES}<script>${getDirectiveScriptText(result, directive)};${process.env.NODE_ENV === "development" ? islandScriptDev : islandScript}</script>`;
return `<style>${ISLAND_STYLES}</style><script>${getDirectiveScriptText(result, directive)}</script><script>${process.env.NODE_ENV === "development" ? islandScriptDev : islandScript}</script>`;
case "directive":
return `<script>${getDirectiveScriptText(result, directive)}</script>`;
case null:
break;
}
return "";
}
export {
determineIfNeedsHydrationScript,

View File

@@ -1,2 +1,2 @@
import type { AstroComponentMetadata } from '../../@types/astro.js';
import type { AstroComponentMetadata } from '../../types/public/internal.js';
export declare function serializeProps(props: any, metadata: AstroComponentMetadata): string;

View File

@@ -1,4 +1,5 @@
import type { SSRResult, TransitionAnimationPair, TransitionAnimationValue } from '../../@types/astro.js';
import type { SSRResult } from '../../types/public/internal.js';
import type { TransitionAnimationPair, TransitionAnimationValue } from '../../types/public/view-transitions.js';
export declare function createTransitionScope(result: SSRResult, hash: string): string;
export declare function renderTransition(result: SSRResult, hash: string, animationName: TransitionAnimationValue | undefined, transitionName: string): string;
export declare function createAnimationScope(transitionName: string, animations: Record<string, TransitionAnimationPair>): {

View File

@@ -56,7 +56,8 @@ function renderTransition(result, hash, animationName, transitionName) {
sheet.addAnimationRaw("new", "animation: none; mix-blend-mode: normal;");
sheet.addModern("group", "animation: none");
}
result._metadata.extraHead.push(markHTMLString(`<style>${sheet.toString()}</style>`));
const css = sheet.toString();
result._metadata.extraHead.push(markHTMLString(`<style>${css}</style>`));
return scope;
}
function createAnimationScope(transitionName, animations) {