96 lines
2.6 KiB
JavaScript
96 lines
2.6 KiB
JavaScript
import { markHTMLString } from "../escape.js";
|
|
import {
|
|
determineIfNeedsHydrationScript,
|
|
determinesIfNeedsDirectiveScript,
|
|
getPrescripts
|
|
} from "../scripts.js";
|
|
import { renderAllHeadContent } from "./head.js";
|
|
import { isSlotString } from "./slot.js";
|
|
const Fragment = Symbol.for("astro:fragment");
|
|
const Renderer = Symbol.for("astro:renderer");
|
|
const encoder = new TextEncoder();
|
|
const decoder = new TextDecoder();
|
|
function stringifyChunk(result, chunk) {
|
|
if (typeof chunk.type === "string") {
|
|
const instruction = chunk;
|
|
switch (instruction.type) {
|
|
case "directive": {
|
|
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);
|
|
return markHTMLString(prescripts);
|
|
} else {
|
|
return "";
|
|
}
|
|
}
|
|
case "head": {
|
|
if (result._metadata.hasRenderedHead) {
|
|
return "";
|
|
}
|
|
return renderAllHeadContent(result);
|
|
}
|
|
case "maybe-head": {
|
|
if (result._metadata.hasRenderedHead || result._metadata.headInTree) {
|
|
return "";
|
|
}
|
|
return renderAllHeadContent(result);
|
|
}
|
|
default: {
|
|
if (chunk instanceof Response) {
|
|
return "";
|
|
}
|
|
throw new Error(`Unknown chunk type: ${chunk.type}`);
|
|
}
|
|
}
|
|
} else {
|
|
if (isSlotString(chunk)) {
|
|
let out = "";
|
|
const c = chunk;
|
|
if (c.instructions) {
|
|
for (const instr of c.instructions) {
|
|
out += stringifyChunk(result, instr);
|
|
}
|
|
}
|
|
out += chunk.toString();
|
|
return out;
|
|
}
|
|
return chunk.toString();
|
|
}
|
|
}
|
|
class HTMLParts {
|
|
constructor() {
|
|
this.parts = "";
|
|
}
|
|
append(part, result) {
|
|
if (ArrayBuffer.isView(part)) {
|
|
this.parts += decoder.decode(part);
|
|
} else {
|
|
this.parts += stringifyChunk(result, part);
|
|
}
|
|
}
|
|
toString() {
|
|
return this.parts;
|
|
}
|
|
toArrayBuffer() {
|
|
return encoder.encode(this.parts);
|
|
}
|
|
}
|
|
function chunkToByteArray(result, chunk) {
|
|
if (chunk instanceof Uint8Array) {
|
|
return chunk;
|
|
}
|
|
let stringified = stringifyChunk(result, chunk);
|
|
return encoder.encode(stringified.toString());
|
|
}
|
|
export {
|
|
Fragment,
|
|
HTMLParts,
|
|
Renderer,
|
|
chunkToByteArray,
|
|
decoder,
|
|
encoder,
|
|
stringifyChunk
|
|
};
|