Skip to content

Commit 85879c0

Browse files
committed
feat: support trusted-types api
1 parent c06a84e commit 85879c0

1 file changed

Lines changed: 27 additions & 1 deletion

File tree

packages/fresh/src/runtime/client/partials.ts

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,29 @@ import type { PartialStateJson } from "../server/preact_hooks.ts";
2424
import { parse } from "../../jsonify/parse.ts";
2525
import { INTERNAL_PREFIX, PARTIAL_SEARCH_PARAM } from "../../constants.ts";
2626

27+
type FreshTrustedTypes = { createHTML(s: string): string };
28+
type TrustedTypesWindow = {
29+
trustedTypes?: {
30+
createPolicy(name: string, v: FreshTrustedTypes): FreshTrustedTypes;
31+
};
32+
};
33+
34+
const freshTrustedTypes: FreshTrustedTypes = (() => {
35+
const noop = { createHTML: (s: string) => s };
36+
const window = globalThis as TrustedTypesWindow;
37+
if (!window.trustedTypes) return noop;
38+
try {
39+
return window.trustedTypes.createPolicy(
40+
"fresh-partials",
41+
{
42+
createHTML: (s: string) => s,
43+
},
44+
);
45+
} catch (_e) {
46+
return noop;
47+
}
48+
})();
49+
2750
export const PARTIAL_ATTR = "f-partial";
2851

2952
class NoPartialsError extends Error {}
@@ -402,7 +425,10 @@ export async function applyPartials(res: Response): Promise<void> {
402425
const id = res.headers.get("X-Fresh-Id");
403426

404427
const resText = await res.text();
405-
const doc = new DOMParser().parseFromString(resText, "text/html") as Document;
428+
const doc = new DOMParser().parseFromString(
429+
freshTrustedTypes.createHTML(resText),
430+
"text/html",
431+
) as Document;
406432

407433
const state = doc.querySelector(`#__FRSH_STATE_${id}`);
408434
let allProps: DeserializedProps = [];

0 commit comments

Comments
 (0)