Avatar

@wilt

7 likes22 public vals
Joined January 12, 2023

Get limit random public domain images from the Art Institute of Chicago

Readme
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
import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41";
export const artICGetRandom = (limit: number = 1) =>
fetchJSON("https://api.artic.edu/api/v1/search", {
method: "POST",
headers: {
"AIC-User-Agent": "https://www.val.town/v/wilt.artICGetRandom",
},
body: JSON.stringify({
resources: "artworks",
fields: [
"id",
"title",
"artist_title",
"image_id",
"date_display",
"thumbnail",
],
limit,
boost: false,
query: {
function_score: {
query: {
bool: {
filter: [
{ term: { is_public_domain: true } },
{ exists: { field: "image_id" } },
{ exists: { field: "thumbnail.alt_text" } },
],
},
},
boost_mode: "replace",
random_score: { field: "id", seed: Date.now() },
},
},
}),
}).then((resp) => ({
...resp.info,
art: resp.data.map((item) => ({
...item,
image_url:
`${resp.config.iiif_url}/${item.image_id}/full/843,/0/default.jpg`,
art_url: `${resp.config.website_url}/artworks/${item.id}`,
})),
}));

Programmatically get the API URLs for the val that calls this val. For example:

// @wilt.myCoolVal:
const myCoolVal = @wilt.thisUrl("web");
}
// returns:
// https://wilt-myCoolVal.web.val.run

If targetVal is passed as entry, returns the URL of the very first val in the current call stack. For example:

// @wilt.myFirstCoolVal:
const myFirstCoolVal = @wilt.mySecondCoolVal());
}
// @wilt.mySecondCoolVal:
const mySecondCoolVal = () => {
  return @wilt.thisUrl("web", "entry");
}
// Running @wilt.myFirstCoolVal returns:
// https://wilt-myFirstCoolVal.web.val.run
Readme
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
export const thisUrl = (
urlType: "web" | "run" | "express" | "email" | "source",
targetVal?: "current" | "entry" = "current",
): string => {
// inlined from @easrng.thisReference
const stackRefs = new Error().stack.match(/@@({.+?})@@/g).map((e) =>
JSON.parse(e.slice(2, -2))
);
const targetRefIndex = targetVal === "entry" ? stackRefs.length - 1 : 1;
const { userHandle, valName } = stackRefs[targetRefIndex];
switch (urlType) {
case "web":
return `https://${userHandle}-${valName}.web.val.run`;
case "run":
return `https://api.val.town/v1/run/${userHandle}.${valName}`;
case "express":
return `https://${userHandle}-${valName}.express.val.run`;
case "email":
return `mailto:${userHandle}.${valName}@valtown.email`;
case "source":
return `https://www.val.town/v/${userHandle}.${valName}`;
default:
throw new Error(`Unsupported type argument: ${urlType}`);
}
};
1
2
3
4
5
6
7
8
9
10
11
import { getYoutubeLinkFromPage } from "https://esm.town/v/wilt/getYoutubeLinkFromPage";
export async function getYoutubeLinkFromPageAPI(req: Request) {
const url = new URL(req.url).searchParams.get("url");
if (!url || url === "undefined")
return new Response("", { status: 400, statusText: "Bad Request" });
return Response.json({
page: url,
youtube: await getYoutubeLinkFromPage(url),
});
}
1
2
3
4
5
6
7
8
9
export const apiTest = async (arg: Request) => {
return Response.json({
ok: true,
t: typeof arg,
i: arg instanceof Request,
// headers: Object.fromEntries(arg.headers.entries()),
// params: @neverstew.queryParams(arg),
});
};
1
2
3
4
5
6
7
8
import { fetch } from "https://esm.town/v/std/fetch";
export async function getYoutubeLinkFromPage(url: string) {
const resp = await fetch(url);
const htmlText = await resp.text();
const match = htmlText.match(/https:\/\/youtube.com\/[^"]+/);
return Array.isArray(match) ? match[0] : match;
}
1
2
3
4
5
6
import { untitled_goldLungfish } from "https://esm.town/v/wilt/untitled_goldLungfish";
export let untitled_tealYak = (req, res) => {
res.status(200);
res.send(untitled_goldLungfish);
};
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
import { pug } from "https://esm.town/v/wilt/pug";
export let untitled_goldLungfish = pug(
`
doctype html
html(lang="en")
head
title= pageTitle
script(type='text/javascript').
if (foo) bar(1 + 5);
body
h1 Pug - node template engine
#container.col
if youAreUsingPug
p You are amazing
else
p Get on it!
p.
Pug is a terse and simple templating language with a
strong focus on performance and powerful features.
`,
{
pageTitle: "pugTest",
youAreUsingPug: true,
},
);

Pug HTML Template Renderer

This function is equivalent to pug.render - it takes a Pug template string and renders it to an HTML string. import(npm:pug) doesn't work in Val.Town due to Pug's usage of new Function, which is forbidden for security reasons, so this function uses Val.Town's eval API instead.

Example

const myEndpoint = async (req: express.Request, res: express.Response) => {
  const html = await @wilt.pug("p Hello #{name}!", {name: "Pug"});
  res.status(200);
  res.send(html);
}
Readme
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
import { fetch } from "https://esm.town/v/std/fetch";
export async function pug(
templateStr: string,
args = {},
// Not sure why anyone would use this callback, but it's included for compatibility with pug.render
callback = ((html: string) => html),
): Promise<string> {
const pugLexer = import("npm:pug-lexer");
const pugParser = import("npm:pug-parser");
const pugCodegen = import("npm:pug-code-gen");
const lexer = new (await pugLexer).Lexer(templateStr);
const parser = new (await pugParser).Parser(lexer.getTokens());
const { default: genCode } = await pugCodegen;
const pugFnStr = genCode(parser.parse(), { inlineRuntimeFunctions: true });
const evalResp = await fetch("https://api.val.town/v1/eval", {
method: "POST",
body: JSON.stringify({
code: `(args) => { ${pugFnStr} return template(args); }`,
args: [args],
}),
});
const renderedHtml = (await evalResp.text()).trim().slice(1, -1);
return callback(renderedHtml);
}
1
2
3
4
export async function emojify(input: string): Promise<string> {
const { emojify } = await import("npm:emojify-lyrics");
return emojify(input);
}
1
2
3
4
5
6
7
export async function toDatesWithTz(
dateStrings: string[],
timeZone: string,
): Promise<Date[]> {
const { toDate } = await import("npm:date-fns-tz");
return dateStrings.map((s) => toDate(s, { timeZone }));
}