Search
codeOnValTown
@andreterron
Code on Val Town Adds a "Code on Val Town" ribbon to your page. This lets your website visitors navigate to the code behind it. This uses github-fork-ribbon-css under the hood. Usage Here are 2 different ways to add the "Code on Val Town" ribbon: 1. Wrap your fetch handler (recommended) import { modifyFetchHandler } from "https://esm.town/v/andreterron/codeOnValTown?v=50";
import { html } from "https://esm.town/v/stevekrouse/html?v=5";
export default modifyFetchHandler(async (req: Request): Promise<Response> => {
return html(`<h2>Hello world!</h2>`);
}); Example: @andreterron/openable_handler 2. Wrap your HTML string import { modifyHtmlString } from "https://esm.town/v/andreterron/codeOnValTown?v=50";
import { html } from "https://esm.town/v/stevekrouse/html?v=5";
export default async (req: Request): Promise<Response> => {
return html(modifyHtmlString(`<h2>Hello world!</h2>`));
}; Example: @andreterron/openable_html Other ways We made sure this was very modular, so you can also add the ribbon using these methods: Get the element string directly: @andreterron/codeOnVT_ribbonElement Modify an HTTP Response: @andreterron/codeOnVT_modifyResponse Use .pipeThrough to append to a stream: @andreterron/InjectCodeOnValTownStream Customization Linking to the val These functions infer the val using the call stack or the request URL. If the inference isn't working, or if you want to ensure it links to a specific val, pass the val argument: modifyFetchHandler(handler, {val: { handle: "andre", name: "foo" }}) modifyHtmlString("<html>...", {val: { handle: "andre", name: "foo" }}) Styling You can set the style parameter to a css string to customize the ribbon. Check out github-fork-ribbon-css to learn more about how to style the element. modifyFetchHandler(handler, {style: ".github-fork-ribbon:before { background-color: #333; }"}) modifyHtmlString("<html>...", {style: ".github-fork-ribbon:before { background-color: #333; }"}) Here's how you can hide the ribbon on small screens: modifyFetchHandler(handler, {style: `@media (max-width: 768px) {
.github-fork-ribbon {
display: none !important;
}
}`}) To-dos [ ] Let users customize the ribbon. Some ideas are the text, color or placement.
Script
# Code on Val Town
![Screenshot 2024-02-27 at 1.25.46 PM.png](https://imagedelivery.net/iHX6Ovru0O7AjmyT5yZRoA/6b67bb0a-d80f-4f3d-5b17-57b5378b3e00/public)
Adds a "Code on Val Town" ribbon to your page. This lets your website visitors navigate to the code behind it.
This uses [github-fork-ribbon-css](https://github.com/simonwhitaker/github-fork-ribbon-css) under the hood.
## Usage
Here are 2 different ways to add the "Code on Val Town" ribbon:
* @param bodyText HTML string that will be used to inject the element.
* @param val Define which val should open. Defaults to the root reference
export function modifyHtmlString(
bodyText: string,
messageBoard
@jdan
An interactive, runnable TypeScript val by jdan
HTTP
export function messageBoard(req, res) {
// make sure u change this or else i'll get your messages
const action = "https://jdan-writeMessage.express.val.run";
res.send(`
<table border="2" cellpadding="4">
<thead>
<tr>
<th>Name</th>
<th>Message</th>
</tr>
web_Fdwbcen36v
@dhvanil
An interactive, runnable TypeScript val by dhvanil
HTTP
export async function web_Fdwbcen36v(req) {
return new Response(`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Retro Space Interface</title>
<style>
body {
margin: 0;
web_YhrAkPFife
@dhvanil
An interactive, runnable TypeScript val by dhvanil
HTTP
export async function web_YhrAkPFife(req) {
return new Response(`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello World</title>
<style>
body { font-family: sans-serif; margin: 2rem; }
</style>
val_C41U1hApxX
@dhvanil
An interactive, runnable TypeScript val by dhvanil
HTTP
export async function val_C41U1hApxX(req) {
try {
// Execute the code directly and capture its result
const result = await (async () => {
const calculateFractalDimension = (points) => { const boxCount = (size) => { let count = 0; for (let i = 0; i < points.length; i++) { if (points[i].x < size && points[i].y < size) count++; } return count; }; const sizes = [1, 2, 4, 8, 16]; const counts = sizes.map(size => boxCount(size)); const logCounts = counts.map(count => Math.log(count)); const logSizes = sizes.map(size => Math.log(size)); const slope = (logCounts[1] - logCounts[0]) / (logSizes[1] - logSizes[0]); return -slope; }; const mandelbrotPoints = [/* Add points from the Mandelbrot set */]; const sierpinskiPoints = [/* Add points from the Sierpinski triangle */]; return { mandelbrotDimension: calculateFractalDimension(mandelbrotPoints), sierpinskiDimension: calculateFractalDimension(sierpinskiPoints) };
// Return the result in a properly formatted response
return new Response(JSON.stringify({
result: result,
type: typeof result
headers: { 'Content-Type': 'application/json' }
dateme_browse
@lejlot
@jsxImportSource npm:hono@3/jsx
Script
/** @jsxImportSource npm:hono@3/jsx */
function absoluteURL(url) {
if (url.startsWith("http://") || url.startsWith("https://"))
return url;
else return "https://" + url;
let headers = [
"Name",
"Age",
"Gender",
"InterestedIn",
safeMessageBoard
@jahabeebs
content-checker is designed to be a modern, open-source library for programmatic and AI content moderation. Currently content-checker supports image and text moderation.
Thanks to LLMs in addition to detecting specific profane words, we can detect malicious intent in text.
So, a user who tries to circumvent the AI profanity filter by using a variation of a profane word, or even just a malicious phrase
without a specific word in the profanity list, will still be flagged. Image moderation is also supported, using the Inception V3 model of the NSFW JS library. Future features will include moderation tools (auto-ban, bots), more powerful models, and multimedia support for video and audio moderation. To get an API key for the AI endpoints sign up free at https://www.openmoderator.com
To install content-checker do npm install content-checker and check out the README: https://github.com/utilityfueled/content-checker
HTTP
`content-checker` is designed to be a modern, open-source library for programmatic and AI content moderation. Currently content-checker supports image and text moderation.
Thanks to LLMs in addition to detecting specific profane words, we can detect malicious **intent** in text.
So, a user who tries to circumvent the AI profanity filter by using a variation of a profane word, or even just a malicious phrase
without a specific word in the profanity list, will still be flagged. Image moderation is also supported, using the Inception V3 model of the NSFW JS library.
Future features will include moderation tools (auto-ban, bots), more powerful models, and multimedia support for video and audio moderation.
To get an API key for the AI endpoints sign up free at https://www.openmoderator.com
/** @jsxImportSource npm:hono@3/jsx */
const app = new Hono();
const apiKey = Deno.env.get("OPEN_MODERATOR_API_KEY");
if (!apiKey) {
lucia_middleware
@stevekrouse
Lucia Middleware Import users. Backed by Val Town SQLite. Demo: @stevekrouse/lucia_middleware_demo If you want a version that is safe to import (but not call) on the frontend: import { luciaMiddleware } from "https://esm.town/v/stevekrouse/lucia_middleware_safe"; Usage Wrap your HTTP handler in it, ie export default luciaMiddleware(handler) In your handler, redirect to /auth/signup , /auth/login , /auth/logout to trigger those flows.
Remember Response.redirect is broken in Val Town right now, so either use links or return new Response(null, { 302, headers: { Location: "/place/to/redirect" }}) In your HTTP handler, read the X-Lucia-Username header, ie const username = req.headers.get("X-Lucia-Username") If the user is logged in, you now have a username you can work with. If not, it will be empty Custom Sign Up and Log In pages By default, the middleware has very basic sign in and sign up pages.
The only way to customize those right now is to fork this middleware and customize them to your liking. Todos [ ] Allow users to specify the users & sessions table [ ] Remove Hono from this middleware (attempted in this fork: @stevekrouse/lucia_middleware_vanilla) [ ] Allow users to customize the auth pages without forking the middleware Initially built by @pomdtr
Script
# Lucia Middleware
Import users. Backed by Val Town SQLite.
Demo: @stevekrouse/lucia_middleware_demo
If you want a version that is safe to import (but not call) on the frontend:
```ts
## Usage
/** @jsxImportSource npm:hono/jsx **/
// TODO - make these configurable
const userTable = "lucia_users_1";
const sessionTable = "lucia_sessions_1";
evalUI
@maxm
An interactive, runnable TypeScript val by maxm
HTTP
export default async function(req: Request): Promise<Response> {
if (req.method === "GET") {
return new Response(indexHTML, {
headers: { "Content-Type": "text/html" },
} else if (req.method === "POST") {
const code = await req.text();
console.log([...req.headers.entries()], code);
return Response.json(await evalCode(transform(code)));
} else {
return new Response("Method Not Allowed", { status: 405 });
getWeather
@stevekrouse
Get Weather Simple function to get weather data from the free wttr.in service. import { getWeather } from "https://esm.town/v/stevekrouse/getWeather";
let weather = await getWeather("Brooklyn, NY");
console.log(weather.current_condition[0].FeelsLikeF)
Script
## Get Weather
Simple function to get weather data from the free [wttr.in](https://wttr.in/:help) service.
```ts
let weather = await getWeather("Brooklyn, NY");
console.log(weather.current_condition[0].FeelsLikeF)
export async function getWeather(location: string): Promise<WeatherResponse> {
return fetchJSON(`https://wttr.in/${location}?format=j1`);
export interface WeatherResponse {
current_condition: CurrentCondition[];
nearest_area: NearestArea[];
expressHTMLExample
@prindom
// View at https://prindom-expresshtmlexample.express.val.run/?name=Dominik
Express (deprecated)
// View at https://prindom-expresshtmlexample.express.val.run/?name=Dominik
export async function expressHTMLExample(
req: express.Request,
res: express.Response,
let getButton = (label = "Label", id) => {
let button = `<div class='w-fit p-2'>
<a
class="group relative inline-block focus:outline-none focus:ring"
href="/download"
<span
val_sUC1JuSSBu
@dhvanil
An interactive, runnable TypeScript val by dhvanil
HTTP
export async function val_sUC1JuSSBu(req) {
try {
// Execute the code directly and capture its result
const result = await (async () => {
const calculateFractalDimension = (points) => { const boxCount = (size) => { let count = 0; for (let i = 0; i < points.length; i++) { if (points[i].x < size && points[i].y < size) count++; } return count; }; const sizes = [1, 2, 4, 8, 16]; const counts = sizes.map(size => boxCount(size)); const logCounts = counts.map(count => Math.log(count)); const logSizes = sizes.map(size => Math.log(size)); const slope = (logCounts[1] - logCounts[0]) / (logSizes[1] - logSizes[0]); return -slope; }; const mandelbrotPoints = [/* Add points from the Mandelbrot set */]; const sierpinskiPoints = [/* Add points from the Sierpinski triangle */]; return { mandelbrotDimension: calculateFractalDimension(mandelbrotPoints), sierpinskiDimension: calculateFractalDimension(sierpinskiPoints) };
// Return the result in a properly formatted response
return new Response(JSON.stringify({
result: result,
type: typeof result
headers: { 'Content-Type': 'application/json' }
claude_share_html
@adagradschool
An interactive, runnable TypeScript val by adagradschool
Script
export default function handler(req) {
return new Response(
"\n <!DOCTYPE html>\n <html>\n <head>\n <title>Claude Chat Conversation</title>\n <meta charset=\"UTF-8\">\n <style>\n body {\n font-family: system-ui, -apple-system, sans-serif;\n line-height: 1.5;\n max-width: 800px;\n margin: 0 auto;\n padding: 20px;\n background: #f9fafb;\n }\n .message {\n margin: 20px 0;\n padding: 15px;\n border-radius: 8px;\n }\n .human {\n background: #e5e7eb;\n }\n .assistant {\n background: #dbeafe;\n }\n .role {\n font-weight: bold;\n margin-bottom: 8px;\n }\n </style>\n </head>\n <body>\n \n <div class=\"message human\">\n <div class=\"role\">Human</div>\n <div class=\"content\">so, how was your day</div>\n </div>\n \n <div class=\"message assistant\">\n <div class=\"role\">Claude</div>\n <div class=\"content\">I aim to have authentic conversations while being direct about my nature as an AI. While I appreciate the friendly question, I should note that I don't actually experience days in the way humans do. I'd be happy to hear about your day though, or to help you with any questions or tasks you might have.</div>\n </div>\n \n </body>\n",
headers: {
"Content-Type": "text/html",
valle_tmp_7637538511907467267008900862313
@janpaul123
* Hacker News Clone (HTML frontend)
* This script sets up an HTTP Val to serve a simple HTML page that mimics Hacker News.
* The page contains static, fake example stories for now.
HTTP
* Hacker News Clone (HTML frontend)
* This script sets up an HTTP Val to serve a simple HTML page that mimics Hacker News.
* The page contains static, fake example stories for now.
export default async function(req: Request): Promise<Response> {
const htmlContent = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
firehoseReadMessagesExample
@healeycodes
// Initially forked from @lukas.sampleFirehose
Script
// Initially forked from @lukas.sampleFirehose
export let firehoseReadMessagesExample = (async () => {
const cborx = await import("https://deno.land/x/cbor@v1.5.2/index.js");
const multiformats = await import("npm:multiformats");
const uint8arrays = await import("npm:uint8arrays");
const { z } = await import("https://deno.land/x/zod@v3.21.4/mod.ts");
const xrpc = await import("npm:@atproto/xrpc");
const cborCodec = await import(
"https://cdn.jsdelivr.net/npm/@ipld/dag-cbor/+esm"
const cborEncode = cborCodec.encode;