1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { delay } from "https://deno.land/x/delay@v0.2.0/mod.ts";
import { htmlAsync, htmlResponseAsync, rawHtmlAsync } from "https://esm.town/v/postpostscript/htmlAsync";
import { assertEquals, assertInstanceOf, testContext } from "https://esm.town/v/postpostscript/test";
const { test, it, run } = testContext({
name: "htmlAsync",
concurrent: true,
verbose: true,
});
function assertStringEquals(a, b, ...args) {
assertEquals(a.toString(), b.toString(), ...args);
}
async function getDelayed<T>(value: T) {
await delay(Math.random() * 1000);
return value;
}
test("htmlAsync", async () => {
assertStringEquals(
await htmlAsync`<script>&gt;`,
`<script>&gt;`,
"text in template is unchanged",
);
assertStringEquals(
await htmlAsync`${getDelayed("<script>&gt;")}`,
`&lt;script&gt;&amp;gt;`,
"unsafe values are escaped",
);
assertStringEquals(
await htmlAsync`${htmlAsync`<script>`}`,
`<script>`,
"safe htmlAsync in replacement is unchanged",
);
assertStringEquals(
await htmlAsync`${rawHtmlAsync`${getDelayed("<script>")}`}`,
`<script>`,
"rawHtmlAsync in replacement is unchanged",
);
assertStringEquals(
await htmlAsync`${[getDelayed("<script>"), getDelayed("alert(1)"), "</script>"]}`,
"&lt;script&gt;alert(1)&lt;/script&gt;",
"array values are sanitized and inserted",
);
});
test("rawHtmlAsync", async () => {
assertStringEquals(
await rawHtmlAsync`${getDelayed("<script>")}`,
"<script>",
"text in template is unchanged",
);
assertStringEquals(
await rawHtmlAsync`${[getDelayed("<script>"), getDelayed("alert(1)"), getDelayed("</script>")]}`,
"<script>alert(1)</script>",
"array values are inserted",
);
});
test("htmlResponseAsync", async () => {
assertInstanceOf(
await htmlResponseAsync`<script></script>`,
Response,
);
assertStringEquals(
await (await htmlResponseAsync`<script></script>`).text(),
"<script></script>",
"text in template is unchanged",
);
assertStringEquals(
await (await htmlResponseAsync`${getDelayed("<script>")}`).text(),
`&lt;script&gt;`,
"unsafe values are escaped",
);
assertStringEquals(
await (await htmlResponseAsync`${htmlAsync`<script>`}`).text(),
`<script>`,
"safe htmlAsync in replacement is unchanged",
);
assertStringEquals(
await (await htmlResponseAsync`${[getDelayed("<script>"), getDelayed("alert(1)"), getDelayed("</script>")]}`)
.text(),
"&lt;script&gt;alert(1)&lt;/script&gt;",
"array values are sanitized and inserted",
);
});
assertEquals(true, await run(), "all tests pass");
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.