Avatar

vladimyr

107 public vals
Joined August 5, 2023

Val Shot

Generate val source code screenshot using sourcecodeshots.com

⚠️ This service is offered for personal use under a reasonable usage policy as stated here: https://sourcecodeshots.com/docs

📣 Special thanks to @pomdtr for their help and contributions!

Usage

https://vladimyr-valshot.web.val.run/v/<author>/<val>

Example

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
// SPDX-License-Identifier: 0BSD
import { fetchVal } from "https://esm.town/v/vladimyr/fetchVal";
import { serveReadme } from "https://esm.town/v/vladimyr/serveReadme";
import { toHonoHandler } from "https://esm.town/v/vladimyr/toHonoHandler";
import { Hono } from "npm:hono";
import ky from "npm:ky";
const router = new Hono();
router.get("/", toHonoHandler(serveReadme(import.meta.url)));
router.get("/v/:author/:name", async (c) => {
const { author, name } = c.req.param();
const query = c.req.query();
const { code } = await fetchVal(author, name);
const imageURL = await createScreenshot(code, query.theme);
return c.redirect(imageURL.href);
});
export default router.fetch;
export async function createScreenshot(code: string, theme: string = "dark-plus"): Promise<URL> {
const apiUrl = "https://sourcecodeshots.com/api/image/permalink";
const { url } = await ky.post(apiUrl, {
json: {
code,
settings: { language: "tsx", theme },
},
}).json();
return new URL(url);
}
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
// SPDX-License-Identifier: 0BSD
import { extractValInfo } from "https://esm.town/v/pomdtr/extractValInfo?v=26";
import { gfm } from "https://esm.town/v/pomdtr/gfm?v=24";
import { appendFragment } from "https://esm.town/v/vladimyr/appendFragment";
import { fetchVal } from "https://esm.town/v/vladimyr/fetchVal";
import { linkifyReadme } from "https://esm.town/v/vladimyr/linkifyReadme";
export type HtmlProcessor = (html: string, author: string, name: string) => Promise<string>;
export function serveReadme(
valUrl: string | URL,
transformHtml: HtmlProcessor = decorateHtml,
) {
return async (): Promise<Response> => {
const { author, name } = extractValInfo(valUrl);
const { readme } = await fetchVal(author, name);
if (!readme) {
return new Response(null, { status: 404 });
}
let html = await readmeToHtml(readme, author, name);
html = await transformHtml(html, author, name);
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
};
}
export { decorateHtml as transformHtml };
async function decorateHtml(html: string, author: string, name: string) {
html = await appendCodeOnValTownRibbon(html, author, name);
html = await appendPersonalizedFooter(html);
return html;
}
export async function appendCodeOnValTownRibbon(html: string, author: string, name: string) {
const { ribbonElement } = await import("https://esm.town/v/andreterron/codeOnVT_ribbonElement?v=7");
const fragment = ribbonElement({ val: { handle: author, name } });
return appendFragment(fragment, html);
}
export async function appendPersonalizedFooter(html: string) {
const { MyFooter: createMyFooter } = await import("https://esm.town/v/vladimyr/MyFooter");
const style = `<style>
footer .logo-white,
footer .logo-black {
background: none;
}
/* hack to remove underline under logo */
footer a + a:hover {
text-decoration: none !important;
}
</style>`;
const footer = await createMyFooter();
const fragment = style + footer;
return appendFragment(fragment, html);
}
async function readmeToHtml(readme: string, author: string, name: string) {
return linkifyReadme(
await gfm(readme, {
title: `${name} | @${author} | Val Town`,
favicon: new URL("https://www.val.town/favicon.svg"),
}),
);
}

Insecure SSL Cert Fetch

This will be useful if you're getting a invalid peer certificate: UnknownIssuer error.

If you need to make a fetch request to a website with a dubious or non-standard SSL certificate, you can use this proxy we made on Cloudflare workers (which doesn't verify SSL certs): https://unsecure-fetch.val-town.workers.dev/

Create valimport { insecureFetch } from "https://esm.town/v/stevekrouse/insecureFetch"; const url = "https://assignment-api.uspto.gov/patent/basicSearch?query=1234567&fields=main&rows=20"; const data = await insecureFetch(url) const text = await data.text(); console.log(text)
1
2
3
4
5
6
7
export function insecureFetch(input: string | URL | Request, init?: RequestInit) {
const origReq = new Request(input, init);
const proxyURL = new URL("https://unsecure-fetch.val-town.workers.dev");
proxyURL.searchParams.set("url", origReq.url);
const req = new Request(proxyURL, origReq);
return globalThis.fetch(req);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { API_URL } from "https://esm.town/v/std/API_URL";
/**
* Wraps the JavaScript Fetch function to anonymize where the request is
* coming from ([Docs ↗](https://docs.val.town/std/fetch))
*
* @param {string | URL | Request} input - The resource to fetch.
* @param {RequestInit} [requestInit] - Optional configuration data (HTTP
* method, headers, etc) ([Docs ↗](https://deno.land/api@v1.42.1?s=RequestInit))
*/
export async function fetch(input: string | URL | Request, requestInit?: RequestInit) {
const origReq = new Request(input, requestInit);
const url = new URL("/v1/fetch", API_URL);
url.searchParams.set("url", origReq.url);
const req = new Request(url, origReq);
req.headers.set("X-Valtown-Authorization", `Bearer ${Deno.env.get("valtown")}`);
return globalThis.fetch(req);
}
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
import { WASI } from "npm:@antonz/runno";
const code = `
print(_VERSION)
print("Hello world")
function sum(a, b)
return a + b
end
print(sum(2, 3))
`;
const url = "https://unpkg.com/@antonz/lua-wasi/dist/lua.wasm";
const result = await WASI.start(fetch(url), {
args: ["lua", "/program.lua"],
stdout: (out) => console.log(out),
stderr: (err) => console.error(err),
fs: {
"/program.lua": {
path: "/program.lua",
timestamps: {
access: new Date(),
change: new Date(),
modification: new Date(),
},
mode: "string",
content: code,
},
},
});
if (result.exitCode !== 0) {
Deno.exit(result.exitCode);
}
// console.log(`exit code = ${result.exitCode}`);
1
2
3
4
5
6
7
8
9
10
11
12
import { shortenURL } from "https://esm.town/v/vladimyr/dubShortenURL";
import { fetchVal } from "https://esm.town/v/vladimyr/fetchVal";
import { newValURL } from "https://esm.town/v/vladimyr/newValURL";
const { code } = await fetchVal("vladimyr", "newValURL");
const valURL = newValURL(code);
console.log(valURL.href);
// ==> https://www.val.town/new?code64=aW1wb3J0IHsgYmFzZTY0IGFzIGI2NCB9IGZyb20gIm5wbTptdWx0aWZvcm1hdHMvYmFzZXMvYmFzZTY0IjsKCmV4cG9ydCBmdW5jdGlvbiBuZXdWYWxVUkwoY29kZTogc3RyaW5nLCBiYXNlNjQgPSB0cnVlKSB7CiAgY29uc3QgdXJsID0gbmV3IFVSTCgiaHR0cHM6Ly93d3cudmFsLnRvd
const expiringShortURL = await shortenURL(valURL);
console.log(expiringShortURL.href);
// ==> https://dub.sh/<key>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { base64 as b64 } from "npm:multiformats/bases/base64";
export function newValURL(code?: string, base64 = true) {
const url = new URL("https://www.val.town/new");
if (!code) {
return url;
}
if (!base64) {
url.searchParams.set("code", code);
return url;
}
// @see: https://www.val.town/v/easrng/playground?v=343#L703-704
const bytes = new TextEncoder().encode(code);
url.searchParams.set("code64", b64.baseEncode(bytes));
return url;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// SPDX-License-Identifier: 0BSD
import ky from "npm:ky";
export async function convertUrlToDataURL(url: string | URL): Promise<string> {
const blob = await ky.get(url).blob();
return convertBlobToDataURL(blob);
}
export function convertBlobToDataURL(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", () => resolve(reader.result.toString()));
reader.addEventListener("error", () => reject(reader.error));
reader.readAsDataURL(blob);
});
}
1
2
3
4
5
// SPDX-License-Identifier: 0BSD
import type { MiddlewareHandler } from "npm:hono";
export const toHonoHandler =
(handler: (req?: Request) => Promise<Response>): MiddlewareHandler => async (c) => (c.res = await handler(c.req.raw));
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
// SPDX-License-Identifier: 0BSD
import "npm:linkifyjs";
import "npm:linkify-plugin-hashtag";
import "npm:linkify-plugin-mention";
import linkify from "npm:linkify-html";
export const linkifyReadme = (html: string) =>
linkify(html, {
ignoreTags: ["head", "script", "style", "code"],
rel: "nofollow noreferrer noopener",
formatHref: {
mention(input) {
input = input.substring(1);
if (input.includes("/")) {
const valURL = new URL(`https://www.val.town/v/${input}`);
return valURL.href;
}
const profileURL = new URL(`https://www.val.town/u/${input}`);
return profileURL.href;
},
hashtag(input) {
const searchURL = new URL("https://www.val.town/search");
searchURL.searchParams.set("q", input);
return searchURL.href;
},
},
});