major: import Fresh 2.0 code (#2449)

🎉
This commit is contained in:
Marvin Hagemeister
2024-05-24 09:40:08 +02:00
committed by GitHub
parent 990357629e
commit 287929e4d2
958 changed files with 15794 additions and 28287 deletions
-20
View File
@@ -1,20 +0,0 @@
import { ComponentChildren, VNode } from "preact";
export interface PartialProps {
children?: ComponentChildren;
/**
* The name of the partial. This value must be unique across partials.
*/
name: string;
/**
* Define how the new HTML should be applied.
* @default {"replace"}
*/
mode?: "replace" | "prepend" | "append";
}
export function Partial(props: PartialProps): VNode {
// deno-lint-ignore no-explicit-any
return props.children as any;
}
Partial.displayName = "Partial";
-46
View File
@@ -1,46 +0,0 @@
import { VNode } from "preact";
import { DATA_ANCESTOR, DATA_CURRENT } from "../constants.ts";
export const enum UrlMatchKind {
None,
Ancestor,
Current,
}
export function matchesUrl(current: string, needle: string): UrlMatchKind {
let href = new URL(needle, "http://localhost").pathname;
if (href !== "/" && href.endsWith("/")) {
href = href.slice(0, -1);
}
if (current !== "/" && current.endsWith("/")) {
current = current.slice(0, -1);
}
if (current === href) {
return UrlMatchKind.Current;
} else if (current.startsWith(href + "/") || href === "/") {
return UrlMatchKind.Ancestor;
}
return UrlMatchKind.None;
}
/**
* Mark active or ancestor link
* Note: This function is used both on the server and the client
*/
export function setActiveUrl(vnode: VNode, pathname: string): void {
const props = vnode.props as Record<string, unknown>;
const hrefProp = props.href;
if (typeof hrefProp === "string" && hrefProp.startsWith("/")) {
const match = matchesUrl(pathname, hrefProp);
if (match === UrlMatchKind.Current) {
props[DATA_CURRENT] = "true";
props["aria-current"] = "page";
} else if (match === UrlMatchKind.Ancestor) {
props[DATA_ANCESTOR] = "true";
props["aria-current"] = "true";
}
}
}
+17 -2
View File
@@ -1,2 +1,17 @@
// Note: in the client build this file is replaced with a file exporting a static string
export { BUILD_ID } from "../server/build_id.ts";
import { encodeHex } from "@std/encoding/hex";
export const DENO_DEPLOYMENT_ID = Deno.env.get("DENO_DEPLOYMENT_ID");
const deploymentId = DENO_DEPLOYMENT_ID ||
// For CI
Deno.env.get("GITHUB_SHA") ||
crypto.randomUUID();
const buildIdHash = await crypto.subtle.digest(
"SHA-1",
new TextEncoder().encode(deploymentId),
);
export let BUILD_ID = encodeHex(buildIdHash);
export function setBuildId(buildId: string) {
BUILD_ID = buildId;
}
@@ -1,3 +1,7 @@
import "preact/debug";
export * from "./mod.tsx";
import { IS_BROWSER } from "../shared.ts";
let ws: WebSocket;
let revision = 0;
@@ -67,8 +71,6 @@ function connect() {
ws.addEventListener("error", handleError);
}
connect();
function disconnect() {
ws.removeEventListener("open", onOpenWs);
ws.removeEventListener("close", onCloseWs);
@@ -108,21 +110,25 @@ function handleError(e: Event) {
}
}
addEventListener("message", (ev) => {
if (ev.origin !== location.origin) return;
if (typeof ev.data !== "string" || ev.data !== "close-error-overlay") {
return;
}
if (IS_BROWSER) {
connect();
document.querySelector("#fresh-error-overlay")?.remove();
});
addEventListener("message", (ev) => {
if (ev.origin !== location.origin) return;
if (typeof ev.data !== "string" || ev.data !== "close-error-overlay") {
return;
}
// Disconnect when the tab becomes inactive and re-connect when it
// becomes active again
addEventListener("visibilitychange", () => {
if (document.hidden) {
disconnect();
} else {
connect();
}
});
document.querySelector("#fresh-error-overlay")?.remove();
});
// Disconnect when the tab becomes inactive and re-connect when it
// becomes active again
addEventListener("visibilitychange", () => {
if (document.hidden) {
disconnect();
} else {
connect();
}
});
}
+4
View File
@@ -0,0 +1,4 @@
import "./polyfills.ts";
import "./partials.ts";
export { asset, IS_BROWSER, Partial, type PartialProps } from "../shared.ts";
export { boot, revive } from "./reviver.ts";
+507
View File
@@ -0,0 +1,507 @@
import { type ComponentChildren, h } from "preact";
import {
CLIENT_NAV_ATTR,
DATA_ANCESTOR,
DATA_CURRENT,
matchesUrl,
PartialMode,
UrlMatchKind,
} from "../shared_internal.tsx";
import {
ACTIVE_PARTIALS,
copyOldChildren,
CUSTOM_PARSER,
type DeserializedProps,
domToVNode,
ISLAND_REGISTRY,
Marker,
maybeHideMarker,
PartialComp,
} from "./reviver.ts";
import { createRootFragment, isCommentNode, isElementNode } from "./reviver.ts";
import type { PartialStateJson } from "../server/preact_hooks.tsx";
import { parse } from "../../jsonify/parse.ts";
import { INTERNAL_PREFIX } from "../../constants.ts";
export const PARTIAL_ATTR = "f-partial";
export const PARTIAL_SEARCH_PARAM = "fresh-partial";
class NoPartialsError extends Error {}
export interface FreshHistoryState {
index: number;
scrollX: number;
scrollY: number;
}
function checkClientNavEnabled(el: HTMLElement) {
const setting = el.closest(`[${CLIENT_NAV_ATTR}]`);
if (setting === null) return false;
return setting.getAttribute(CLIENT_NAV_ATTR) !== "false";
}
// Keep track of history state to apply forward or backward animations
let index = history.state?.index || 0;
if (!history.state) {
const state: FreshHistoryState = {
index,
scrollX,
scrollY,
};
history.replaceState(state, document.title);
}
function maybeUpdateHistory(nextUrl: URL) {
// Only add history entry when URL is new. Still apply
// the partials because sometimes users click a link to
// "refresh" the current page.
if (nextUrl.href !== globalThis.location.href) {
const state: FreshHistoryState = {
index,
scrollX: globalThis.scrollX,
scrollY: globalThis.scrollY,
};
// Store current scroll position
history.replaceState({ ...state }, "", location.href);
// Now store the new position
index++;
state.scrollX = 0;
state.scrollY = 0;
history.pushState(state, "", nextUrl.href);
}
}
document.addEventListener("click", async (e) => {
let el = e.target;
if (el && el instanceof HTMLElement) {
const originalEl = el;
// Check if we clicked inside an anchor link
if (el.nodeName !== "A") {
el = el.closest("a");
}
if (
// Check that we're still dealing with an anchor tag
el && el instanceof HTMLAnchorElement &&
// Check if it's an internal link
el.href && (!el.target || el.target === "_self") &&
el.origin === location.origin &&
// Check if it was a left click and not a right click
e.button === 0 &&
// Check that the user doesn't press a key combo to open the
// link in a new tab or something
!(e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.button) &&
// Check that the event isn't aborted already
!e.defaultPrevented
) {
const partial = el.getAttribute(PARTIAL_ATTR);
// Check if the user opted out of client side navigation or if
// we're doing a fragment navigation.
if (
el.getAttribute("href")?.startsWith("#") ||
!checkClientNavEnabled(el)
) {
return;
}
// deno-lint-ignore no-explicit-any
const indicator = (el as any)._freshIndicator;
if (indicator !== undefined) {
indicator.value = true;
}
e.preventDefault();
const nextUrl = new URL(el.href);
try {
maybeUpdateHistory(nextUrl);
const partialUrl = new URL(
partial ? partial : nextUrl.href,
location.href,
);
await fetchPartials(partialUrl);
updateLinks(nextUrl);
scrollTo({ left: 0, top: 0, behavior: "instant" });
} finally {
if (indicator !== undefined) {
indicator.value = false;
}
}
} else {
let button: HTMLButtonElement | HTMLElement | null = originalEl;
// Check if we clicked on a button
if (button.nodeName !== "A") {
button = button.closest("button");
}
if (
button !== null && button instanceof HTMLButtonElement &&
(button.type !== "submit" || button.form === null)
) {
const partial = button.getAttribute(PARTIAL_ATTR);
// Check if the user opted out of client side navigation.
if (
partial === null ||
!checkClientNavEnabled(button)
) {
return;
}
const partialUrl = new URL(
partial,
location.href,
);
await fetchPartials(partialUrl);
}
}
}
});
addEventListener("popstate", async (e) => {
// When state is `null` then the browser navigated to a document
// fragment. In this case we do nothing.
if (e.state === null) {
// Reset to browser default
if (history.scrollRestoration) {
history.scrollRestoration = "auto";
}
return;
}
const state: FreshHistoryState = history.state;
const nextIdx = state.index ?? index + 1;
index = nextIdx;
const setting = document.querySelector(`[${CLIENT_NAV_ATTR}]`);
if (setting === null || setting.getAttribute(CLIENT_NAV_ATTR) === "false") {
location.reload();
return;
}
// We need to keep track of that ourselves since we do client side
// navigation.
if (history.scrollRestoration) {
history.scrollRestoration = "manual";
}
const url = new URL(location.href, location.origin);
try {
await fetchPartials(url);
updateLinks(url);
scrollTo({
left: state.scrollX ?? 0,
top: state.scrollY ?? 0,
behavior: "instant",
});
} catch (err) {
// If the response didn't contain a partial, then we can only
// do a reload.
if (err instanceof NoPartialsError) {
location.reload();
return;
}
throw err;
}
});
// Form submit
document.addEventListener("submit", async (e) => {
const el = e.target;
if (el !== null && el instanceof HTMLFormElement && !e.defaultPrevented) {
if (
// Check if form has client nav enabled
!checkClientNavEnabled(el) ||
// Bail out if submitter is set and client nav is disabled
(e.submitter !== null && !checkClientNavEnabled(e.submitter))
) {
return;
}
const lowerMethod =
e.submitter?.getAttribute("formmethod")?.toLowerCase() ??
el.method.toLowerCase();
if (
lowerMethod !== "get" && lowerMethod !== "post" &&
lowerMethod !== "dialog"
) {
return;
}
const action = e.submitter?.getAttribute(PARTIAL_ATTR) ??
e.submitter?.getAttribute("formaction") ??
el.getAttribute(PARTIAL_ATTR) ?? el.action;
if (action !== "") {
e.preventDefault();
const url = new URL(action, location.href);
let init: RequestInit | undefined;
// GET method appends form data via url search params
if (lowerMethod === "get") {
// TODO: Looks like constructor type for URLSearchParam is wrong
// deno-lint-ignore no-explicit-any
const qs = new URLSearchParams(new FormData(el) as any);
qs.forEach((value, key) => url.searchParams.set(key, value));
} else {
init = { body: new FormData(el), method: lowerMethod };
}
maybeUpdateHistory(url);
await fetchPartials(url, init);
}
}
});
function updateLinks(url: URL) {
document.querySelectorAll("a").forEach((link) => {
const match = matchesUrl(url.pathname, link.href);
if (match === UrlMatchKind.Current) {
link.setAttribute(DATA_CURRENT, "true");
link.setAttribute("aria-current", "page");
link.removeAttribute(DATA_ANCESTOR);
} else if (match === UrlMatchKind.Ancestor) {
link.setAttribute(DATA_ANCESTOR, "true");
link.setAttribute("aria-current", "true");
link.removeAttribute(DATA_CURRENT);
} else {
link.removeAttribute(DATA_CURRENT);
link.removeAttribute(DATA_ANCESTOR);
link.removeAttribute("aria-current");
}
});
}
async function fetchPartials(url: URL, init: RequestInit = {}) {
init.redirect = "follow";
url.searchParams.set(PARTIAL_SEARCH_PARAM, "true");
const res = await fetch(url, init);
await applyPartials(res);
}
interface PartialReviveCtx {
foundPartials: number;
}
/**
* Apply partials from a HTML response
*/
export async function applyPartials(res: Response): Promise<void> {
const contentType = res.headers.get("Content-Type");
if (contentType !== "text/html; charset=utf-8") {
throw new Error(`Unable to process partial response.`);
}
const id = res.headers.get("X-Fresh-Id");
const resText = await res.text();
const doc = new DOMParser().parseFromString(resText, "text/html") as Document;
const state = doc.querySelector(`#__FRSH_STATE_${id}`);
let allProps: DeserializedProps = [];
if (state !== null) {
const json = JSON.parse(state.textContent!) as PartialStateJson;
const promises: Promise<void>[] = [];
allProps = parse<DeserializedProps>(json.props, CUSTOM_PARSER);
for (let i = 0; i < json.islands.length; i++) {
const island = json.islands[i];
promises.push(
import(island.chunk).then((mod) => {
ISLAND_REGISTRY.set(island.name, mod[island.exportName]);
}),
);
}
await Promise.all(promises);
}
const ctx: PartialReviveCtx = {
foundPartials: 0,
};
if (doc.title) {
document.title = doc.title;
}
// Needs to be converted to an array otherwise somehow <link>-tags
// are missing.
Array.from(doc.head.childNodes).forEach((childNode) => {
const child = childNode as HTMLElement;
if (child.nodeName === "TITLE") return;
if (child.nodeName === "META") {
const meta = child as HTMLMetaElement;
// Ignore charset which is usually set site wide anyway
if (meta.hasAttribute("charset")) return;
const name = meta.name;
if (name !== "") {
const existing = document.head.querySelector(`meta[name="${name}"]`) as
| HTMLMetaElement
| null;
if (existing !== null) {
if (existing.content !== meta.content) {
existing.content = meta.content;
}
} else {
document.head.appendChild(meta);
}
} else {
const property = child.getAttribute("property");
const existing = document.head.querySelector(
`meta[property="${property}"]`,
) as HTMLMetaElement | null;
if (existing !== null) {
if (existing.content !== meta.content) {
existing.content = meta.content;
}
} else {
document.head.appendChild(meta);
}
}
} else if (child.nodeName === "LINK") {
const link = child as HTMLLinkElement;
if (link.rel === "modulepreload") return;
if (link.rel === "stylesheet") {
// The `href` attribute may be root relative. This ensures
// that they both have the same format
const existing = Array.from(document.head.querySelectorAll("link"))
.find((existingLink) => existingLink.href === link.href);
if (existing === undefined) {
document.head.appendChild(link);
}
}
} else if (child.nodeName === "SCRIPT") {
const script = child as HTMLScriptElement;
if (script.src === `${INTERNAL_PREFIX}/fresh-runtime.js`) return;
// TODO: What to do with script tags?
} else if (child.nodeName === "STYLE") {
const style = child as HTMLStyleElement;
// TODO: Do we need a smarter merging strategy?
// Don't overwrie existing style sheets that are flagged as unique
if (style.id === "") {
document.head.appendChild(style);
}
}
});
revivePartials(ctx, allProps, doc.body);
if (ctx.foundPartials === 0) {
throw new NoPartialsError(
`Found no partials in HTML response. Please make sure to render at least one partial. Requested url: ${res.url}`,
);
}
}
function revivePartials(
ctx: PartialReviveCtx,
allProps: DeserializedProps,
node: Element,
) {
let startNode = null;
let sib: ChildNode | null = node.firstChild;
let partialCount = 0;
let partialName = "";
let partialKey = "";
let partialMode = PartialMode.Replace;
while (sib !== null) {
if (isCommentNode(sib)) {
const comment = sib.data;
const parts = comment.split(":");
if (parts[0] === "frsh") {
sib = maybeHideMarker(sib);
}
if (parts[0] === "frsh" && parts[1] === "partial") {
if (++partialCount === 1) {
startNode = sib;
partialName = parts[2];
partialMode = +parts[3] as PartialMode;
partialKey = parts[4];
}
} else if (comment === "/frsh:partial") {
ctx.foundPartials++;
// Skip hydrating nested partials, only hydrate the outer one
if (--partialCount > 0) {
sib = sib.nextSibling;
continue;
}
// Create a fake DOM node that spans the partial we discovered.
// We need to include the partial markers itself for _walkInner
// to register them.
const container = createRootFragment(
node,
startNode as Comment,
sib as Comment,
);
const root = h(PartialComp, {
key: partialKey !== "" ? partialKey : undefined,
name: partialName,
mode: partialMode,
children: null,
});
domToVNode(
allProps,
[root],
[Marker.Partial],
container,
sib as Comment,
);
const instance = ACTIVE_PARTIALS.get(partialName);
if (instance === undefined) {
console.warn(`Partial "${partialName}" not found. Skipping...`);
// Partial doesn't exist on the current page
} else {
if (partialMode === PartialMode.Replace) {
instance.props.children = root.props.children;
} else if (partialMode === PartialMode.Append) {
const active = ACTIVE_PARTIALS.get(partialName);
if (active !== undefined) {
copyOldChildren(instance.props, active.props.children);
(instance.props.children as ComponentChildren[]).push(
root.props.children,
);
} else {
instance.props.children = root.props.children;
}
} else if (partialMode === PartialMode.Prepend) {
const active = ACTIVE_PARTIALS.get(partialName);
if (active !== undefined) {
copyOldChildren(instance.props, active.props.children);
(instance.props.children as ComponentChildren[]).unshift(
root.props.children,
);
} else {
instance.props.children = root.props.children;
}
}
instance.setState({});
}
}
} else if (partialCount === 0 && isElementNode(sib)) {
// Do not recurse if we know that we are inisde a partial
revivePartials(ctx, allProps, sib);
}
sib = sib.nextSibling;
}
}
@@ -0,0 +1,9 @@
import { options } from "preact";
import { assetHashingHook } from "../shared_internal.tsx";
import { BUILD_ID } from "../build_id.ts";
const oldVNodeHook = options.vnode;
options.vnode = (vnode) => {
assetHashingHook(vnode, BUILD_ID);
oldVNodeHook?.(vnode);
};
+567
View File
@@ -0,0 +1,567 @@
import {
Component,
type ComponentChildren,
type ComponentType,
Fragment,
h,
render,
type VNode,
} from "preact";
import { type CustomParser, parse } from "../../jsonify/parse.ts";
import { signal } from "@preact/signals";
import { DATA_FRESH_KEY, PartialMode } from "../shared_internal.tsx";
const enum RootKind {
Island,
Partial,
}
interface IslandReq {
kind: RootKind.Island;
name: string;
propsIdx: number;
key: string | null;
start: Comment | Text;
end: Comment | Text | null;
}
interface PartialReq {
kind: RootKind.Partial;
name: string;
key: string | null;
start: Comment | Text;
end: Comment | Text | null;
}
interface ReviveContext {
roots: Array<IslandReq | PartialReq>;
stack: Array<PartialReq | IslandReq>;
slots: Map<number, { name: string; start: Comment; end: Comment | null }>;
slotIdStack: number[];
}
interface SlotRef {
kind: typeof SLOT_SYMBOL;
name: string;
id: number;
}
const SLOT_SYMBOL = Symbol.for("_FRESH_SLOT");
function isSlotRef(x: unknown): x is SlotRef {
return x !== null && typeof x === "object" && "kind" in x &&
x.kind === SLOT_SYMBOL;
}
export type DeserializedProps = {
props: Record<string, unknown>;
slots: SlotRef[];
}[];
export const ACTIVE_PARTIALS = new Map<string, PartialComp>();
export class PartialComp extends Component<
{ children?: ComponentChildren; mode: PartialMode; name: string }
> {
componentDidMount() {
ACTIVE_PARTIALS.set(this.props.name, this);
}
render() {
return this.props.children;
}
}
PartialComp.displayName = "Partial";
export function revive(
props: Record<string, unknown>,
component: ComponentType,
container: HTMLElement,
slots: ReviveContext["slots"],
allProps: DeserializedProps,
) {
const _render = () => {
for (const propName in props) {
const value = props[propName];
if (isSlotRef(value)) {
const marker = slots.get(value.id);
if (marker !== undefined) {
const root = h(Fragment, null);
const slotContainer = createRootFragment(
container,
marker.start,
marker.end!,
);
domToVNode(
allProps,
[root],
[Marker.Slot],
slotContainer,
marker.end!,
);
props[propName] = root;
} else {
const template = document.querySelector(
`#frsh-${value.id}-${value.name}`,
) as HTMLTemplateElement | null;
if (template !== null) {
const root = h(Fragment, null);
domToVNode(allProps, [root], [Marker.Slot], template.content, null);
props[propName] = root;
}
}
}
}
// TODO: explore hydrate?
render(h(component, props), container as unknown as HTMLElement);
};
// deno-lint-ignore no-window
"scheduler" in window
// `scheduler.postTask` is async but that can easily
// fire in the background. We don't want waiting for
// the hydration of an island block us.
// @ts-ignore scheduler API is not in types yet
? scheduler!.postTask(_render)
: setTimeout(_render, 0);
}
export const ISLAND_REGISTRY = new Map<string, ComponentType>();
export const CUSTOM_PARSER: CustomParser = {
Signal: (value: unknown) => signal(value),
Slot: (value: { name: string; id: number }): SlotRef => {
return { kind: SLOT_SYMBOL, name: value.name, id: value.id };
},
};
export function createReviveCtx(): ReviveContext {
return {
roots: [],
stack: [],
slots: new Map(),
slotIdStack: [],
};
}
export function boot(
initialIslands: Record<string, ComponentType>,
islandProps: string,
) {
const ctx = createReviveCtx();
_walkInner(ctx, document.body);
const keys = Object.keys(initialIslands);
for (let i = 0; i < keys.length; i++) {
const name = keys[i];
ISLAND_REGISTRY.set(name, initialIslands[name]);
}
const allProps = parse<DeserializedProps>(
islandProps,
CUSTOM_PARSER,
);
for (let i = 0; i < ctx.roots.length; i++) {
const root = ctx.roots[i];
const container = createRootFragment(
// deno-lint-ignore no-explicit-any
root.start.parentNode as any,
root.start,
root.end!,
);
if (root.kind === RootKind.Island) {
const props = allProps[root.propsIdx].props;
const component = ISLAND_REGISTRY.get(root.name)!;
revive(props, component, container, ctx.slots, allProps);
} else if (root.kind === RootKind.Partial) {
const props: Record<string, unknown> = {
name: root.name,
children: null,
};
const domRoot = h(Fragment, null);
domToVNode(allProps, [domRoot], [Marker.Partial], container, root.end!);
props.children = domRoot.props.children;
// deno-lint-ignore no-explicit-any
revive(props, PartialComp as any, container, ctx.slots, allProps);
}
}
}
const SHOW_MARKERS = false;
interface FreshMarker extends Text {
_frshMarker: string;
}
export function isFreshMarkerText(node: Node): node is FreshMarker {
return node.nodeType === Node.TEXT_NODE &&
// deno-lint-ignore no-explicit-any
typeof (node as any)._frshMarker === "string";
}
/**
* Replace comment markers with empty text nodes to hide them
* in DevTools. This is done to avoid user confusion.
*/
export function maybeHideMarker(marker: Comment): Comment | Text {
if (SHOW_MARKERS) return marker;
const text = new Text("") as FreshMarker;
text._frshMarker = marker.data;
marker.parentNode!.insertBefore(text, marker);
marker.remove();
return text;
}
function _walkInner(
ctx: ReviveContext,
node: Node | Comment,
) {
if (isElementNode(node)) {
// No need to traverse into <script> or <style> tags.
// No need to traverse deeper if we found a slotStart marker.
// We'll parse slots later when the island is revived.
if (
node.nodeName === "SCRIPT" || node.nodeName === "STYLE" ||
ctx.slotIdStack.length > 0
) {
return;
}
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
_walkInner(ctx, child);
}
} else if (isCommentNode(node)) {
const comment = node.data;
if (comment.startsWith("frsh:")) {
node = maybeHideMarker(node);
const parts = comment.split(":");
const kind = parts[1];
if (kind === "island") {
const name = parts[2];
const propsIdx = parts[3];
const key = parts[4];
const found: IslandReq = {
kind: RootKind.Island,
name,
propsIdx: Number(propsIdx),
key: key === "" ? null : key,
start: node as Comment,
end: null,
};
if (ctx.stack.length === 0) {
ctx.roots.push(found);
}
ctx.stack.push(found);
} else if (kind === "slot") {
const id = +parts[2];
const slotName = parts[3];
ctx.slotIdStack.push(id);
ctx.slots.set(id, {
name: slotName,
start: node as Comment,
end: null,
});
} else if (kind === "partial") {
const name = parts[2];
const key = parts[3];
const found: PartialReq = {
kind: RootKind.Partial,
name,
key: key === "" ? null : key,
start: node as Comment,
end: null,
};
if (ctx.stack.length === 0) {
ctx.roots.push(found);
}
ctx.stack.push(found);
}
} else if (comment === "/frsh:island" || comment === "/frsh:partial") {
node = maybeHideMarker(node);
const item = ctx.stack.pop();
if (item !== undefined) {
item.end = node as Comment;
}
} else if (comment === "/frsh:slot") {
node = maybeHideMarker(node);
const item = ctx.slotIdStack.pop();
if (item !== undefined) {
ctx.slots.get(item)!.end = node as Comment;
}
}
}
}
export const enum Marker {
Island,
Partial,
Slot,
}
interface ServerSlotProps {
name: string;
id: number;
children?: ComponentChildren;
}
// deno-lint-ignore no-explicit-any
function ServerSlot(props: ServerSlotProps): any {
return props.children;
}
export function domToVNode(
allProps: DeserializedProps,
// deno-lint-ignore no-explicit-any
vnodeStack: VNode<any>[],
markerStack: Marker[],
node: Text | Comment | Node | DocumentFragment,
end: Text | Comment | null,
): void {
let sib: Node | ChildNode | null = node;
while (sib !== null) {
if (sib === end) return;
// deno-lint-ignore no-explicit-any
if ((sib as any)._frshRootFrag || sib instanceof DocumentFragment) {
const firstChild = sib.firstChild;
if (firstChild !== null) {
domToVNode(allProps, vnodeStack, markerStack, firstChild, end);
}
} else if (isElementNode(sib)) {
const props: Record<string, unknown> = {};
for (let i = 0; i < sib.attributes.length; i++) {
const attr = sib.attributes[i];
if (attr.nodeName === DATA_FRESH_KEY) {
props.key = attr.nodeValue;
continue;
}
// Boolean attributes are always `true` when present.
// See: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML
props[attr.nodeName] =
// deno-lint-ignore no-explicit-any
typeof (sib as any)[attr.nodeName] === "boolean"
? true
: attr.nodeValue;
}
const vnode = h(sib.localName, props);
const marker = markerStack.at(-1);
const appendVNode = marker === Marker.Slot || marker === Marker.Partial;
if (appendVNode) {
addVNodeChild(vnodeStack.at(-1)!, vnode);
vnodeStack.push(vnode);
}
const firstChild = sib.firstChild;
if (firstChild !== null) {
domToVNode(allProps, vnodeStack, markerStack, firstChild, end);
}
if (appendVNode) {
vnodeStack.pop();
}
} else if (isCommentNode(sib) || isFreshMarkerText(sib)) {
const comment = isFreshMarkerText(sib) ? sib._frshMarker : sib.data;
if (comment.startsWith("frsh:")) {
const parts = comment.split(":");
const kind = parts[1];
if (kind === "island") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Island);
const name = parts[2];
const propsIdx = parts[3];
const key = parts[4];
const island = ISLAND_REGISTRY.get(name);
if (island === undefined) {
throw new Error(`Encountered unknown island: ${name}`);
}
const props = allProps[+propsIdx].props;
props.key = key === "" ? undefined : key;
// deno-lint-ignore no-explicit-any
const islandVNode = h<any>(island, props);
addVNodeChild(vnodeStack.at(-1)!, islandVNode);
vnodeStack.push(islandVNode);
} else if (kind === "slot") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Slot);
const id = +parts[2];
const slotName = parts[3];
const key = parts[4];
const vnode = h(ServerSlot, {
key: key === "" ? undefined : key,
id,
name: slotName,
children: [],
});
const parentVNode = vnodeStack.at(-1)!;
if (slotName === "children") {
addVNodeChild(parentVNode, vnode);
} else {
parentVNode.props[slotName] = vnode;
}
vnodeStack.push(vnode);
} else if (kind === "partial") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Partial);
const name = parts[2];
const mode = +parts[3] as PartialMode;
const key = parts[4];
// deno-lint-ignore no-explicit-any
let vnode: VNode<any> = h(PartialComp, {
name,
key: key === "" ? undefined : key,
mode,
});
const parentVNode = vnodeStack.at(-1);
if (parentVNode !== undefined) {
addVNodeChild(parentVNode, vnode);
}
if (mode === PartialMode.Append) {
const active = ACTIVE_PARTIALS.get(name);
if (active !== undefined) {
copyOldChildren(vnode.props, active.props.children);
const wrapper = h(Fragment, null);
addVNodeChild(vnode, wrapper);
vnode = wrapper;
}
} else if (mode === PartialMode.Prepend) {
const active = ACTIVE_PARTIALS.get(name);
if (active !== undefined) {
copyOldChildren(vnode.props, active.props.children);
const wrapper = h(Fragment, null);
if (!vnode.props.children) {
vnode.props.children = [];
}
// deno-lint-ignore no-explicit-any
(vnode.props.children as Array<VNode<any> | string>).unshift(
wrapper,
);
vnode = wrapper;
}
}
vnodeStack.push(vnode);
} else if (kind === "key") {
if (!SHOW_MARKERS) {
const current = sib;
sib = sib.nextSibling;
current.remove();
}
const vnode = h(Fragment, { key: parts[2] });
addVNodeChild(vnodeStack.at(-1)!, vnode);
vnodeStack.push(vnode);
continue;
}
} else if (
comment === "/frsh:island" || comment === "/frsh:slot" ||
comment === "/frsh:partial"
) {
vnodeStack.pop();
markerStack.pop();
sib = maybeHideMarker(sib);
} else if (comment === "/frsh:key") {
vnodeStack.pop();
sib = maybeHideMarker(sib);
}
} else if (isTextNode(sib)) {
const marker = markerStack.at(-1);
if (marker === Marker.Slot || marker === Marker.Partial) {
addVNodeChild(vnodeStack.at(-1)!, sib.data);
}
}
sib = sib.nextSibling;
}
}
// deno-lint-ignore no-explicit-any
function addVNodeChild(parent: VNode<any>, child: VNode<any> | string) {
if (!parent.props.children) {
parent.props.children = [];
}
// deno-lint-ignore no-explicit-any
(parent.props.children as Array<VNode<any> | string>).push(child);
}
export function copyOldChildren(
props: Record<string, unknown>,
oldChildren: ComponentChildren,
) {
props.children = oldChildren !== undefined && oldChildren !== null
? Array.isArray(oldChildren) ? oldChildren : [oldChildren]
: [];
}
export function isCommentNode(node: Node): node is Comment {
return node.nodeType === Node.COMMENT_NODE;
}
export function isTextNode(node: Node): node is Text {
return node.nodeType === Node.TEXT_NODE;
}
export function isElementNode(node: Node): node is HTMLElement {
return node.nodeType === Node.ELEMENT_NODE && !("_frshRootFrag" in node);
}
export function createRootFragment(
parent: Element,
startMarker: Text | Comment,
// We need an end marker for islands because multiple
// islands can share the same parent node. Since
// islands are root-level render calls any calls to
// `.appendChild` would lead to a wrong result.
endMarker: Text | Comment,
): HTMLElement & { _frshRootFrag: boolean } {
// @ts-ignore this is fine
return {
_frshRootFrag: true,
nodeType: 1,
parentNode: parent,
nextSibling: null,
get firstChild() {
const child = startMarker.nextSibling;
if (child === endMarker) return null;
return child;
},
get childNodes() {
const children: ChildNode[] = [];
let child = startMarker.nextSibling;
while (child !== null && child !== endMarker) {
children.push(child);
child = child.nextSibling;
}
return children;
},
insertBefore(node: Node, child: Node | null) {
parent.insertBefore(node, child ?? endMarker);
},
appendChild(child: Node) {
// We cannot blindly call `.append()` as that would add
// the new child to the very end of the parent node. This
// leads to ordering issues when the multiple islands
// share the same parent node.
parent.insertBefore(child, endMarker);
},
removeChild(child: Node) {
parent.removeChild(child);
},
// deno-lint-ignore no-explicit-any
} as any;
}
-140
View File
@@ -1,140 +0,0 @@
import { createContext } from "preact";
import { useContext } from "preact/hooks";
export const SELF = "'self'";
export const UNSAFE_INLINE = "'unsafe-inline'";
export const UNSAFE_EVAL = "'unsafe-eval'";
export const UNSAFE_HASHES = "'unsafe-hashes'";
export const NONE = "'none'";
export const STRICT_DYNAMIC = "'strict-dynamic'";
export function nonce(val: string) {
return `'nonce-${val}'`;
}
export interface ContentSecurityPolicy {
directives: ContentSecurityPolicyDirectives;
reportOnly: boolean;
}
export interface ContentSecurityPolicyDirectives {
// Fetch directives
/**
* Defines the valid sources for web workers and nested browsing contexts
* loaded using elements such as <frame> and <iframe>.
*/
childSrc?: string[];
/**
* Restricts the URLs which can be loaded using script interfaces.
*/
connectSrc?: string[];
/**
* Serves as a fallback for the other fetch directives.
*/
defaultSrc?: string[];
/**
* Specifies valid sources for fonts loaded using @font-face.
*/
fontSrc?: string[];
/**
* Specifies valid sources for nested browsing contexts loading using elements
* such as <frame> and <iframe>.
*/
frameSrc?: string[];
/**
* Specifies valid sources of images and favicons.
*/
imgSrc?: string[];
/**
* Specifies valid sources of application manifest files.
*/
manifestSrc?: string[];
/**
* Specifies valid sources for loading media using the <audio> , <video> and
* <track> elements.
*/
mediaSrc?: string[];
/**
* Specifies valid sources for the <object>, <embed>, and <applet> elements.
*/
objectSrc?: string[];
/**
* Specifies valid sources to be prefetched or prerendered.
*/
prefetchSrc?: string[];
/**
* Specifies valid sources for JavaScript.
*/
scriptSrc?: string[];
/**
* Specifies valid sources for JavaScript <script> elements.
*/
scriptSrcElem?: string[];
/**
* Specifies valid sources for JavaScript inline event handlers.
*/
scriptSrcAttr?: string[];
/**
* Specifies valid sources for stylesheets.
*/
styleSrc?: string[];
/**
* Specifies valid sources for stylesheets <style> elements and <link>
* elements with rel="stylesheet".
*/
styleSrcElem?: string[];
/**
* Specifies valid sources for inline styles applied to individual DOM
* elements.
*/
styleSrcAttr?: string[];
/**
* Specifies valid sources for Worker, SharedWorker, or ServiceWorker scripts.
*/
workerSrc?: string[];
// Document directives
/**
* Restricts the URLs which can be used in a document's <base> element.
*/
baseUri?: string[];
/**
* Enables a sandbox for the requested resource similar to the <iframe>
* sandbox attribute.
*/
sandbox?: string[];
// Navigation directives
/**
* Restricts the URLs which can be used as the target of a form submissions
* from a given context.
*/
formAction?: string[];
/**
* Specifies valid parents that may embed a page using <frame>, <iframe>,
* <object>, <embed>, or <applet>.
*/
frameAncestors?: string[];
/**
* Restricts the URLs to which a document can initiate navigation by any
* means, including <form> (if form-action is not specified), <a>,
* window.location, window.open, etc.
*/
navigateTo?: string[];
/**
* The URI to report CSP violations to.
*/
reportUri?: string;
}
export const CSP_CONTEXT = createContext<ContentSecurityPolicy | undefined>(
undefined,
);
export function useCSP(mutator: (csp: ContentSecurityPolicy) => void) {
const csp = useContext(CSP_CONTEXT);
if (csp) {
mutator(csp);
}
}
-75
View File
@@ -1,75 +0,0 @@
export const KEY = "_f";
interface Signal<T> {
peek(): T;
value: T;
}
function b64decode(b64: string): Uint8Array {
const binString = atob(b64);
const size = binString.length;
const bytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
bytes[i] = binString.charCodeAt(i);
}
return bytes;
}
const INVALID_REFERENCE_ERROR = "Invalid reference";
function getPropertyFromPath(o: object, path: string[]): object {
for (const key of path) {
if (key === null) continue;
if (key !== "value" && !Object.hasOwn(o, key)) {
throw new Error(INVALID_REFERENCE_ERROR);
}
// deno-lint-ignore no-explicit-any
o = (o as any)[key];
}
return o;
}
export function deserialize(
str: string,
signal?: <T>(a: T) => Signal<T>,
): unknown {
function reviver(this: unknown, _key: string, value: unknown): unknown {
if (typeof value === "object" && value && KEY in value) {
// deno-lint-ignore no-explicit-any
const v: any = value;
if (v[KEY] === "s") {
return signal!(v.v);
}
if (v[KEY] === "b") {
return BigInt(v.d);
}
if (v[KEY] === "u8a") {
return b64decode(v.d);
}
if (v[KEY] === "l") {
const val = v.v;
val[KEY] = v.k;
return val;
}
throw new Error(`Unknown key: ${v[KEY]}`);
}
return value;
}
const { v, r } = JSON.parse(str, reviver);
const references = (r ?? []) as [string[], ...string[][]][];
for (const [targetPath, ...refPaths] of references) {
const target = getPropertyFromPath(v, targetPath);
for (const refPath of refPaths) {
if (refPath.length === 0) throw new Error(INVALID_REFERENCE_ERROR);
// set the reference to the target object
const parent = getPropertyFromPath(v, refPath.slice(0, -1));
const key = refPath[refPath.length - 1]!;
if (key !== "value" && !Object.hasOwn(parent, key)) {
throw new Error(INVALID_REFERENCE_ERROR);
}
// deno-lint-ignore no-explicit-any
(parent as any)[key] = target;
}
}
return v;
}
-1
View File
@@ -1 +0,0 @@
export { deserialize } from "../deserializer.ts";
File diff suppressed because it is too large Load Diff
-2
View File
@@ -1,2 +0,0 @@
import "preact/debug";
export * from "./main.ts";
-1
View File
@@ -1 +0,0 @@
export { signal } from "@preact/signals";
-22
View File
@@ -1,22 +0,0 @@
import { ComponentChildren, createContext } from "preact";
import { useContext } from "preact/hooks";
export interface HeadProps {
children: ComponentChildren;
}
export const HEAD_CONTEXT = createContext<ComponentChildren[]>([]);
export function Head(props: HeadProps) {
let context: ComponentChildren[];
try {
context = useContext(HEAD_CONTEXT);
} catch (err) {
throw new Error(
"<Head> component is not supported in the browser, or during suspense renders.",
{ cause: err },
);
}
context.push(props.children);
return null;
}
+16
View File
@@ -0,0 +1,16 @@
import type { FunctionComponent } from "preact";
import type { FreshContext } from "../../context.ts";
/**
* The mode Fresh can run in.
*/
export type Mode = "development" | "build" | "production";
export let MODE: Mode = "production";
export function setMode(mode: Mode) {
MODE = mode;
}
export type PageProps<Data = unknown, T = unknown> =
& Omit<FreshContext<Data, T>, "next" | "redirect" | "next">
& { Component: FunctionComponent };
+532
View File
@@ -0,0 +1,532 @@
import {
type Component,
type ComponentChildren,
type ComponentType,
Fragment,
h,
isValidElement,
type Options as PreactOptions,
options as preactOptions,
type VNode,
} from "preact";
import type { Signal } from "@preact/signals";
import type { Stringifiers } from "../../jsonify/stringify.ts";
import type { FreshContext } from "../../context.ts";
import { asset, Partial, type PartialProps } from "../shared.ts";
import { stringify } from "../../jsonify/stringify.ts";
import type { ServerIslandRegistry } from "../../context.ts";
import type { Island } from "../../context.ts";
import {
assetHashingHook,
CLIENT_NAV_ATTR,
DATA_FRESH_KEY,
PartialMode,
setActiveUrl,
} from "../shared_internal.tsx";
import type { BuildCache } from "../../build_cache.ts";
import { BUILD_ID } from "../build_id.ts";
import { DEV_ERROR_OVERLAY_URL } from "../../constants.ts";
import {
getCodeFrame,
} from "../../dev/middlewares/error_overlay/code_frame.tsx";
import * as colors from "@std/fmt/colors";
import { escape as escapeHtml } from "@std/html";
const enum OptionsType {
ATTR = "attr",
VNODE = "vnode",
HOOK = "__h",
DIFF = "__b",
RENDER = "__r",
DIFFED = "diffed",
ERROR = "__e",
}
interface InternalPreactOptions extends PreactOptions {
[OptionsType.ATTR](name: string, value: unknown): string | void;
[OptionsType.VNODE](vnode: InternalVNode): void;
[OptionsType.HOOK](component: Component, index: number, type: number): void;
[OptionsType.DIFF](vnode: InternalVNode): void;
[OptionsType.RENDER](vnode: InternalVNode): void;
[OptionsType.DIFFED](vnode: InternalVNode): void;
[OptionsType.ERROR](
error: unknown,
vnode: InternalVNode,
oldVNode: InternalVNode,
): void;
}
interface InternalVNode extends VNode {
__c: Component | null;
__: InternalVNode | null;
}
// deno-lint-ignore no-explicit-any
const options: InternalPreactOptions = preactOptions as any;
export class RenderState {
nonce: string;
partialDepth = 0;
partialCount = 0;
error: Error | null = null;
// deno-lint-ignore no-explicit-any
slots: Array<{ id: number; name: string; vnode: VNode<any> } | null> = [];
basePath = ""; // FIXME
// deno-lint-ignore no-explicit-any
islandProps: any[] = [];
islands = new Set<Island>();
// deno-lint-ignore no-explicit-any
encounteredPartials = new Set<any>();
owners = new Map<VNode, VNode>();
ownerStack: InternalVNode[] = [];
// TODO: merge into bitmask field
renderedHtmlTag = false;
renderedHtmlBody = false;
renderedHtmlHead = false;
hasRuntimeScript = false;
constructor(
public ctx: FreshContext<unknown, unknown>,
public islandRegistry: ServerIslandRegistry,
public buildCache: BuildCache,
public partialId: string,
) {
this.nonce = crypto.randomUUID().replace(/-/g, "");
}
clear() {
this.islands.clear();
this.encounteredPartials.clear();
this.owners.clear();
this.slots = [];
this.islandProps = [];
this.ownerStack = [];
}
}
let RENDER_STATE: RenderState | null = null;
export function setRenderState(state: RenderState | null) {
RENDER_STATE = state;
}
const oldVNodeHook = options[OptionsType.VNODE];
options[OptionsType.VNODE] = (vnode) => {
if (RENDER_STATE !== null) {
RENDER_STATE.owners.set(vnode, RENDER_STATE!.ownerStack.at(-1)!);
if (vnode.type === "a") {
setActiveUrl(vnode, RENDER_STATE.ctx.url.pathname);
}
}
assetHashingHook(vnode, BUILD_ID);
if (typeof vnode.type === "function") {
if (vnode.type === Partial) {
const props = vnode.props as PartialProps;
const key = normalizeKey(vnode.key ?? "");
const mode = !props.mode || props.mode === "replace"
? PartialMode.Replace
: props.mode === "append"
? PartialMode.Append
: PartialMode.Prepend;
props.children = wrapWithMarker(
props.children,
"partial",
`${props.name}:${mode}:${key}`,
);
}
} else if (typeof vnode.type === "string") {
if (vnode.type === "body") {
const scripts = h(FreshScripts, null);
if (vnode.props.children == null) {
vnode.props.children = scripts;
} else if (Array.isArray(vnode.props.children)) {
vnode.props.children.push(scripts);
} else {
vnode.props.children = [vnode.props.children, scripts];
}
}
if (CLIENT_NAV_ATTR in vnode.props) {
vnode.props[CLIENT_NAV_ATTR] = String(vnode.props[CLIENT_NAV_ATTR]);
}
}
oldVNodeHook?.(vnode);
};
const oldAttrHook = options[OptionsType.ATTR];
options[OptionsType.ATTR] = (name, value) => {
if (name === CLIENT_NAV_ATTR) {
return `${CLIENT_NAV_ATTR}="${String(Boolean(value))}"`;
} else if (name === "key") {
return `${DATA_FRESH_KEY}="${escapeHtml(String(value))}"`;
}
return oldAttrHook?.(name, value);
};
const PATCHED = new WeakSet<VNode>();
function normalizeKey(str: string) {
return str.replaceAll(":", "_");
}
const oldDiff = options[OptionsType.DIFF];
options[OptionsType.DIFF] = (vnode) => {
if (RENDER_STATE !== null) {
patcher: if (
typeof vnode.type === "function" && vnode.type !== Fragment
) {
if (vnode.type === Partial) {
RENDER_STATE.partialDepth++;
const name = (vnode.props as PartialProps).name;
if (typeof name === "string") {
if (RENDER_STATE.encounteredPartials.has(name)) {
throw new Error(
`Rendered response contains duplicate partial name: "${name}"`,
);
}
RENDER_STATE.encounteredPartials.add(name);
}
if (hasIslandOwner(RENDER_STATE, vnode)) {
throw new Error(
`<Partial> components cannot be used inside islands.`,
);
}
} else if (
!PATCHED.has(vnode) && !hasIslandOwner(RENDER_STATE, vnode)
) {
const island = RENDER_STATE.islandRegistry.get(vnode.type);
if (island === undefined) {
// Not an island, but we might need to preserve keys
if (vnode.key !== undefined) {
const key = normalizeKey(vnode.key ?? "");
const originalType = vnode.type;
vnode.type = (props) => {
const child = h(originalType, props);
PATCHED.add(child);
return wrapWithMarker(child, "key", key);
};
}
break patcher;
}
const { islands, islandProps } = RENDER_STATE;
islands.add(island);
const originalType = vnode.type;
vnode.type = (props) => {
for (const name in props) {
// deno-lint-ignore no-explicit-any
const value = (props as any)[name];
if (
name === "children" || (isValidElement(value) && !isSignal(value))
) {
const slotId = RENDER_STATE!.slots.length;
RENDER_STATE!.slots.push({ id: slotId, name, vnode: value });
// deno-lint-ignore no-explicit-any
(props as any)[name] = h(Slot, {
name,
id: slotId,
}, value);
}
}
const propsIdx = islandProps.push({ slots: [], props }) - 1;
const child = h(originalType, props);
PATCHED.add(child);
const key = normalizeKey(vnode.key ?? "");
return wrapWithMarker(
child,
"island",
`${island!.name}:${propsIdx}:${key}`,
);
};
}
} else if (typeof vnode.type === "string") {
switch (vnode.type) {
case "html":
RENDER_STATE!.renderedHtmlTag = true;
break;
case "head":
RENDER_STATE!.renderedHtmlHead = true;
break;
case "body":
RENDER_STATE!.renderedHtmlBody = true;
break;
}
if (
vnode.key !== undefined &&
(RENDER_STATE!.partialDepth > 0 || hasIslandOwner(RENDER_STATE!, vnode))
) {
(vnode.props as Record<string, unknown>)[DATA_FRESH_KEY] = String(
vnode.key,
);
}
}
}
oldDiff?.(vnode);
};
const oldRender = options[OptionsType.RENDER];
options[OptionsType.RENDER] = (vnode) => {
if (
typeof vnode.type === "function" && vnode.type !== Fragment &&
RENDER_STATE !== null
) {
RENDER_STATE.ownerStack.push(vnode);
}
oldRender?.(vnode);
};
const oldDiffed = options[OptionsType.DIFFED];
options[OptionsType.DIFFED] = (vnode) => {
if (
typeof vnode.type === "function" && vnode.type !== Fragment &&
RENDER_STATE !== null
) {
RENDER_STATE.ownerStack.pop();
if (vnode.type === Partial) {
RENDER_STATE.partialDepth--;
}
}
oldDiffed?.(vnode);
};
interface SlotProps {
name: string;
id: number;
children?: ComponentChildren;
}
function Slot(props: SlotProps) {
if (RENDER_STATE !== null) {
RENDER_STATE.slots[props.id] = null;
}
return wrapWithMarker(props.children, "slot", `${props.id}:${props.name}`);
}
/**
* Check if the current component was rendered in an island
*/
function hasIslandOwner(current: RenderState, vnode: VNode): boolean {
let tmpVNode = vnode;
let owner;
while ((owner = current.owners.get(tmpVNode)) !== undefined) {
if (current.islandRegistry.has(owner.type as ComponentType)) {
return true;
}
tmpVNode = owner;
}
return false;
}
function wrapWithMarker(
vnode: ComponentChildren,
kind: string,
markerText: string,
) {
return h(
Fragment,
null,
h(Fragment, {
// @ts-ignore unstable property is not typed
UNSTABLE_comment: `frsh:${kind}:${markerText}`,
}),
vnode,
h(Fragment, {
// @ts-ignore unstable property is not typed
UNSTABLE_comment: "/frsh:" + kind,
}),
);
}
// deno-lint-ignore no-explicit-any
function isSignal(x: any): x is Signal {
return (
x !== null &&
typeof x === "object" &&
typeof x.peek === "function" &&
"value" in x
);
}
// deno-lint-ignore no-explicit-any
function isVNode(x: any): x is VNode {
return x !== null && typeof x === "object" && "type" in x && "ref" in x &&
"__k" in x &&
isValidElement(x);
}
const stringifiers: Stringifiers = {
Signal: (value: unknown) => {
return isSignal(value) ? value.peek() : undefined;
},
Slot: (value: unknown) => {
if (isVNode(value) && value.type === Slot) {
const props = value.props as SlotProps;
return {
name: props.name,
id: props.id,
};
}
},
};
export function FreshScripts() {
if (RENDER_STATE === null) return null;
if (RENDER_STATE.hasRuntimeScript) {
return null;
}
RENDER_STATE.hasRuntimeScript = true;
const { slots } = RENDER_STATE;
// Remaining slots must be rendered before creating the Fresh runtime
// script, so that we have the full list of islands rendered
return (
<>
{slots.map((slot) => {
if (slot === null) return null;
// FIXME: Wait for https://github.com/preactjs/preact/pull/4334 to be
// released
return h(
"template",
{ key: slot.id, id: `frsh-${slot.id}-${slot.name}` },
slot.vnode,
// deno-lint-ignore no-explicit-any
) as VNode<any>;
})}
<FreshRuntimeScript />
</>
);
}
export interface PartialStateJson {
islands: {
name: string;
chunk: string;
exportName: string;
}[];
props: string;
}
function FreshRuntimeScript() {
const { islands, nonce, ctx, islandProps, partialId, buildCache } =
RENDER_STATE!;
const basePath = ctx.config.basePath;
const islandArr = Array.from(islands);
if (ctx.url.searchParams.has("fresh-partial")) {
const islands = islandArr.map((island) => {
const chunk = buildCache.getIslandChunkName(island.name);
if (chunk === null) {
throw new Error(
`Could not find chunk for ${island.name} ${island.file}#${island.exportName}`,
);
}
return {
exportName: island.exportName,
chunk: asset(chunk),
name: island.name,
};
});
const serializedProps = stringify(islandProps, stringifiers);
const json: PartialStateJson = {
islands,
props: serializedProps,
};
return (
<script
id={`__FRSH_STATE_${partialId}`}
type="application/json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(json) }}
/>
);
} else {
const islandImports = islandArr.map((island) => {
const chunk = buildCache.getIslandChunkName(island.name);
if (chunk === null) {
throw new Error(
`Could not find chunk for ${island.name} ${island.file}#${island.exportName}`,
);
}
const named = island.exportName === "default"
? island.name
: `{ ${island.exportName} }`;
return `import ${named} from "${asset(chunk)}";`;
}).join("");
const islandObj = "{" + islandArr.map((island) => island.name)
.join(",") +
"}";
const serializedProps = JSON.stringify(
stringify(islandProps, stringifiers),
);
const runtimeUrl = asset(`${basePath}/fresh-runtime.js`);
const scriptContent =
`import { boot } from "${runtimeUrl}";${islandImports}boot(${islandObj},${serializedProps});`;
return (
<>
<script
type="module"
nonce={nonce}
dangerouslySetInnerHTML={{
__html: scriptContent,
}}
/>
<ShowErrorOverlay />
</>
);
}
}
export function ShowErrorOverlay() {
if (RENDER_STATE === null) return null;
const { ctx } = RENDER_STATE;
const error = ctx.error;
if (error === null || error === undefined) return null;
const basePath = ctx.config.basePath;
const searchParams = new URLSearchParams();
if (typeof error === "object") {
if ("message" in error) {
searchParams.append("message", String(error.message));
}
if ("stack" in error && typeof error.stack === "string") {
searchParams.append("stack", error.stack);
const codeFrame = getCodeFrame(error.stack, ctx.config.root);
if (codeFrame !== undefined) {
searchParams.append("code-frame", colors.stripAnsiCode(codeFrame));
}
}
} else {
searchParams.append("message", String(error));
}
return (
<iframe
id="fresh-error-overlay"
src={`${basePath}${DEV_ERROR_OVERLAY_URL}?${searchParams.toString()}`}
style="unset: all; position: fixed; top: 0; left: 0; z-index: 99999; width: 100%; height: 100%; border: none;"
/>
);
}
+54
View File
@@ -0,0 +1,54 @@
import type { ComponentChildren, VNode } from "preact";
import { BUILD_ID } from "./build_id.ts";
import { assetInternal, assetSrcSetInternal } from "./shared_internal.tsx";
/**
* Returns true when the current runtime is the browser and false otherwise. This is used for guard runtime-dependent code.
* Shorthand for the following:
* `typeof document !== "undefined"`
*
* @example
* ```
* if (IS_BROWSER) {
* alert('This is running in the browser!');
* } else {
* console.log('This code is running on the server, no access to window or alert');
* }
* ```
*
* Without this guard, alert pauses the server until return is pressed in the console.
*/
export const IS_BROWSER = typeof document !== "undefined";
/**
* Create a "locked" asset path. This differs from a plain path in that it is
* specific to the current version of the application, and as such can be safely
* served with a very long cache lifetime (1 year).
*/
export function asset(path: string): string {
return assetInternal(path, BUILD_ID);
}
/** Apply the `asset` function to urls in a `srcset` attribute. */
export function assetSrcSet(srcset: string): string {
return assetSrcSetInternal(srcset, BUILD_ID);
}
export interface PartialProps {
children?: ComponentChildren;
/**
* The name of the partial. This value must be unique across partials.
*/
name: string;
/**
* Define how the new HTML should be applied.
* @default {"replace"}
*/
mode?: "replace" | "prepend" | "append";
}
export function Partial(props: PartialProps): VNode {
// deno-lint-ignore no-explicit-any
return props.children as any;
}
Partial.displayName = "Partial";
+122
View File
@@ -0,0 +1,122 @@
import type { VNode } from "preact";
export const DATA_CURRENT = "data-current";
export const DATA_ANCESTOR = "data-ancestor";
export const DATA_FRESH_KEY = "data-frsh-key";
export const CLIENT_NAV_ATTR = "f-client-nav";
export const ASSET_CACHE_BUST_KEY = "__frsh_c";
export const enum UrlMatchKind {
None,
Ancestor,
Current,
}
export function matchesUrl(current: string, needle: string): UrlMatchKind {
let href = new URL(needle, "http://localhost").pathname;
if (href !== "/" && href.endsWith("/")) {
href = href.slice(0, -1);
}
if (current !== "/" && current.endsWith("/")) {
current = current.slice(0, -1);
}
if (current === href) {
return UrlMatchKind.Current;
} else if (current.startsWith(href + "/") || href === "/") {
return UrlMatchKind.Ancestor;
}
return UrlMatchKind.None;
}
/**
* Mark active or ancestor link
* Note: This function is used both on the server and the client
*/
export function setActiveUrl(vnode: VNode, pathname: string): void {
const props = vnode.props as Record<string, unknown>;
const hrefProp = props.href;
if (typeof hrefProp === "string" && hrefProp.startsWith("/")) {
const match = matchesUrl(pathname, hrefProp);
if (match === UrlMatchKind.Current) {
props[DATA_CURRENT] = "true";
props["aria-current"] = "page";
} else if (match === UrlMatchKind.Ancestor) {
props[DATA_ANCESTOR] = "true";
props["aria-current"] = "true";
}
}
}
export const enum PartialMode {
Replace,
Append,
Prepend,
}
/**
* Create a "locked" asset path. This differs from a plain path in that it is
* specific to the current version of the application, and as such can be safely
* served with a very long cache lifetime (1 year).
*/
export function assetInternal(path: string, buildId: string): string {
if (!path.startsWith("/") || path.startsWith("//")) return path;
try {
const url = new URL(path, "https://freshassetcache.local");
if (
url.protocol !== "https:" || url.host !== "freshassetcache.local" ||
url.searchParams.has(ASSET_CACHE_BUST_KEY)
) {
return path;
}
url.searchParams.set(ASSET_CACHE_BUST_KEY, buildId);
return url.pathname + url.search + url.hash;
} catch (err) {
console.warn(
`Failed to create asset() URL, falling back to regular path ('${path}'):`,
err,
);
return path;
}
}
/** Apply the `asset` function to urls in a `srcset` attribute. */
export function assetSrcSetInternal(srcset: string, buildId: string): string {
if (srcset.includes("(")) return srcset; // Bail if the srcset contains complicated syntax.
const parts = srcset.split(",");
const constructed = [];
for (const part of parts) {
const trimmed = part.trimStart();
const leadingWhitespace = part.length - trimmed.length;
if (trimmed === "") return srcset; // Bail if the srcset is malformed.
let urlEnd = trimmed.indexOf(" ");
if (urlEnd === -1) urlEnd = trimmed.length;
const leading = part.substring(0, leadingWhitespace);
const url = trimmed.substring(0, urlEnd);
const trailing = trimmed.substring(urlEnd);
constructed.push(leading + assetInternal(url, buildId) + trailing);
}
return constructed.join(",");
}
export function assetHashingHook(
vnode: VNode<{
src?: string;
srcset?: string;
["data-fresh-disable-lock"]?: boolean;
}>,
buildId: string,
) {
if (vnode.type === "img" || vnode.type === "source") {
const { props } = vnode;
if (props["data-fresh-disable-lock"]) return;
if (typeof props.src === "string") {
props.src = assetInternal(props.src, buildId);
}
if (typeof props.srcset === "string") {
props.srcset = assetSrcSetInternal(props.srcset, buildId);
}
}
}
-87
View File
@@ -1,87 +0,0 @@
import { VNode } from "preact";
import { BUILD_ID } from "./build_id.ts";
export const INTERNAL_PREFIX = "/_frsh";
export const ASSET_CACHE_BUST_KEY = "__frsh_c";
/**
* Returns true when the current runtime is the browser and false otherwise. This is used for guard runtime-dependent code.
* Shorthand for the following:
* `typeof document !== "undefined"`
*
* @example
* ```
* if (IS_BROWSER) {
* alert('This is running in the browser!');
* } else {
* console.log('This code is running on the server, no access to window or alert');
* }
* ```
*
* Without this guard, alert pauses the server until return is pressed in the console.
*/
export const IS_BROWSER = typeof document !== "undefined";
/**
* Create a "locked" asset path. This differs from a plain path in that it is
* specific to the current version of the application, and as such can be safely
* served with a very long cache lifetime (1 year).
*/
export function asset(path: string): string {
if (!path.startsWith("/") || path.startsWith("//")) return path;
try {
const url = new URL(path, "https://freshassetcache.local");
if (
url.protocol !== "https:" || url.host !== "freshassetcache.local" ||
url.searchParams.has(ASSET_CACHE_BUST_KEY)
) {
return path;
}
url.searchParams.set(ASSET_CACHE_BUST_KEY, BUILD_ID);
return url.pathname + url.search + url.hash;
} catch (err) {
console.warn(
`Failed to create asset() URL, falling back to regular path ('${path}'):`,
err,
);
return path;
}
}
/** Apply the `asset` function to urls in a `srcset` attribute. */
export function assetSrcSet(srcset: string): string {
if (srcset.includes("(")) return srcset; // Bail if the srcset contains complicated syntax.
const parts = srcset.split(",");
const constructed = [];
for (const part of parts) {
const trimmed = part.trimStart();
const leadingWhitespace = part.length - trimmed.length;
if (trimmed === "") return srcset; // Bail if the srcset is malformed.
let urlEnd = trimmed.indexOf(" ");
if (urlEnd === -1) urlEnd = trimmed.length;
const leading = part.substring(0, leadingWhitespace);
const url = trimmed.substring(0, urlEnd);
const trailing = trimmed.substring(urlEnd);
constructed.push(leading + asset(url) + trailing);
}
return constructed.join(",");
}
export function assetHashingHook(
vnode: VNode<{
src?: string;
srcset?: string;
["data-fresh-disable-lock"]?: boolean;
}>,
) {
if (vnode.type === "img" || vnode.type === "source") {
const { props } = vnode;
if (props["data-fresh-disable-lock"]) return;
if (typeof props.src === "string") {
props.src = asset(props.src);
}
if (typeof props.srcset === "string") {
props.srcset = assetSrcSet(props.srcset);
}
}
}
-59
View File
@@ -1,59 +0,0 @@
import { assertEquals } from "../../tests/deps.ts";
import { asset, assetSrcSet } from "./utils.ts";
import { BUILD_ID } from "./build_id.ts";
Deno.test("asset", () => {
assertEquals(asset("/test.png"), `/test.png?__frsh_c=${BUILD_ID}`);
assertEquals(asset("/test?f=1"), `/test?f=1&__frsh_c=${BUILD_ID}`);
assertEquals(asset("/test#foo"), `/test?__frsh_c=${BUILD_ID}#foo`);
assertEquals(asset("/test?f=1#foo"), `/test?f=1&__frsh_c=${BUILD_ID}#foo`);
assertEquals(asset("./test.png"), "./test.png");
assertEquals(asset("//example.com/logo.png"), "//example.com/logo.png");
assertEquals(asset("/test.png?__frsh_c=1"), "/test.png?__frsh_c=1");
assertEquals(
asset("https://example.com/logo.png"),
"https://example.com/logo.png",
);
});
Deno.test("assetSrcSet", () => {
assertEquals(assetSrcSet("/img.png"), `/img.png?__frsh_c=${BUILD_ID}`);
assertEquals(
assetSrcSet("/img.png, /img.png 2x"),
`/img.png?__frsh_c=${BUILD_ID}, /img.png?__frsh_c=${BUILD_ID} 2x`,
);
assertEquals(assetSrcSet("/img.png 1x"), `/img.png?__frsh_c=${BUILD_ID} 1x`);
assertEquals(
assetSrcSet("/img.png 1x, /img.png 2x"),
`/img.png?__frsh_c=${BUILD_ID} 1x, /img.png?__frsh_c=${BUILD_ID} 2x`,
);
assertEquals(
assetSrcSet("/img.png 1.5x, /img.png 3x"),
`/img.png?__frsh_c=${BUILD_ID} 1.5x, /img.png?__frsh_c=${BUILD_ID} 3x`,
);
//test with queries
assertEquals(
assetSrcSet("/img.png?w=140, /img.png?w=200 2x"),
`/img.png?w=140&__frsh_c=${BUILD_ID}, /img.png?w=200&__frsh_c=${BUILD_ID} 2x`,
);
// test with extra spaces
assertEquals(
assetSrcSet("/img-s.png 300w, /img-l.png 600w , /img-xl.png 900w"),
`/img-s.png?__frsh_c=${BUILD_ID} 300w, /img-l.png?__frsh_c=${BUILD_ID} 600w , /img-xl.png?__frsh_c=${BUILD_ID} 900w`,
);
// test with ( syntax
assertEquals(
assetSrcSet("/img.png ( 140,0w)"),
"/img.png ( 140,0w)",
);
// test with invalid parts
assertEquals(
assetSrcSet("/img.png,, /img-s.png 300w"),
"/img.png,, /img-s.png 300w",
);
});