Search
reactiveStateBlob
@postpostscript
reactiveStateBlob: wrap blob state in a proxy to autosave it on changes Examples (full example at @postpostscript/reactiveStateBlobExample ) import { reactiveStateBlob } from "https://esm.town/v/postpostscript/reactiveStateBlob"
using state = await reactiveStateBlob({
viewCount: 0,
rows: [] as {
x: number;
y: number;
}[],
});
state.viewCount += 1;
state.rows.push({
x: Math.random(),
y: Math.random(),
}); This infers the key from the name of the val that uses it. To specify it, pass the key option: using state = await reactiveStateBlob({
viewCount: 0,
rows: [] as {
x: number;
y: number;
}[],
}, {
key: 'reactiveStateBlobExample.state',
}); Updating Schema If you want to update the schema, or always verify the state that is pulled from the job, pass a function as the first argument: using state = await reactiveStateBlob((existingState) => {
return {
viewCount: (existingState.viewCount ?? 0) as number,
rows: (existingState.rows ?? []) as {
x: number;
y: number;
}[],
someNewField: (existingState.someNewField ?? "") as string,
}
}) Options using state = await reactiveStateBlob<{
value: number;
}>({
value: 0,
}, {
log: true, // log when saving
key: "blobKey", // blob key to fetch/save to
timeout: 100, // ms, defaults to 10
lock: true, // or LockOptions (see https://www.val.town/v/postpostscript/lock#options)
}) See Also @postpostscript/counter (example at @postpostscript/counterExample )
Script
# reactiveStateBlob: wrap blob state in a proxy to autosave it on changes
## Examples (full example at [@postpostscript/reactiveStateBlobExample](reactiveStateBlobExample))
import { reactiveStateBlob } from "https://esm.town/v/postpostscript/reactiveStateBlob"
using state = await reactiveStateBlob({
persistentStateReactive,
export async function reactiveStateBlob<T extends Record<string, unknown>>(
return `reactiveStateBlob:${handle}/${name}`;
const cache = persistentStateBlobReactive({
export function persistentStateBlobReactive<T extends Record<string, unknown>>(
return persistentStateReactive(persistentStateBlob(opts));
getEventsForAnalyser
@nmsilva
// Team Performance Analysis
Script
touramentsActive,
date,
{ client } = {}
const tournamentsInfo = getTournaments(tournaments, touramentsActive);
const tournamentsIds = tournamentsInfo.map((t) => t.id);
for (const tournamentId of tournamentsIds) {
const { dataByTeam: dataByTeamForTournament, totals: tournamentTotals } =
await getTournamentTeamsStats(tournamentId, date, { client });
dataByTeam = {
...dataByTeam,
reminder_cron
@kajgod
An interactive, runnable TypeScript val by kajgod
Cron
import { sqlite } from "https://esm.town/v/std/sqlite?v=4";
import { Row } from "npm:@libsql/client";
import axios from "npm:axios";
const fromAddress = "reminder@plk-bjelowbar.hr";
generativeNoise
@wking
Generative Noise Demo This is based on a post I wrote on Craft Lab The article breaks down the basic building blocks that go into most generative projects.
HTTP
/** @jsxImportSource npm:react **/
import Alea from "npm:alea";
import { renderToString } from "npm:react-dom@18/server";
import { createNoise2D } from "npm:simplex-noise";
export default (req: Request) => {
fresh
@yawnxyz
// Add QR code generation endpoint
HTTP
<meta name="twitter:title" content="Fresh Invoices">
<meta name="description" content="Deliver free invoices instantly to your client's door, with our free browser-based invoice generator. No signup required!">
<meta property="og:description" content="Deliver free invoices instantly to your client's door, with our free browser-based invoice generator. No signup required!">
<meta name="twitter:description" content="Deliver free invoices instantly to your client's door, with our free browser-based invoice generator. No signup required!">
<meta property="og:image" content="https://f2.phage.directory/capsid/nfi8lRWJ/fresh-invoices.png">
<p class="mb-1">It's your responsibility to invoice your customer in line with their local laws, taxes, and regulations.</p>
<p class="mb-1">All data stays inside the browser, with IndexedDB. No data leaves the browser/client.</p>
A micro-project built by <a class="hover:text-gray-800 underline" href="https://labspace.ai">labspace.ai</a>. Open Source on <a class="hover:text-gray-800 underline" href="https://www.val.town/v/yawnxyz/fresh">val.town</a>.
oceanTheme
@paswan
๐ ๐ An under the sea resume theme ๐ ๐
Script
li {
margin-bottom: 10px;
aside {
margin-top: 8px;
margin-bottom: 8px;
.fish {
position: absolute;
right: -50px; /* Start outside the viewport */
animation: swim linear infinite;
@keyframes swim {
googleGenerativeAIStreamingExample
@tr3ntg
Google Generative AI Streaming Example Example Val showing how to set up an authenticated Google GoogleGenerativeAI client. Prerequisite: Follow Google's Getting Started guide to get an API key and view some example methods.
HTTP
# Google Generative AI Streaming Example
Example Val showing how to set up an authenticated Google `GoogleGenerativeAI` client.
**Prerequisite:**
socialImage
@tylergaw
Simple image generator A bit of a toy image creator that can be used anywhere images can be, but is intended for social share images in og:image or twitter:image meta tags. Usage examples In a live web page Live example https://tylergaw-socialimageusage.web.val.run/ Live example Val https://www.val.town/v/tylergaw.socialImageUsage Code examples Default This will set the og:image of a web page to a png image of an orange 1200x600 pixel rectangle <meta property="og:image" content="https://tylergaw-socialimage.web.val.run/"> Works the same way as an embedded image <img src="https://tylergaw-socialimage.web.val.run/"> Customize with query parameters General note, some clients are more permissive with unencoded query params than others. It's best to encodeURIComponent for all params. Available params: bg : Sets the background color. Default orange . See Color format examples below for details color : Sets the background color. Default black . See Color format examples below for details w : Sets the width of the image. Default 1200 h : Sets the height of the image. Default 600 text : Sets the text displayed. Default Wellow horld <meta property="og:image" content="https://tylergaw-socialimage.web.val.run/?bg=pink&w=1000&h=400"> Color format examples bg and color parameters can any valid color that works with canvas fillStyle in hex, rgb(a), hsl(a), rrggbbaa, etc format. Note # must be encoded. Hex ?bg=%235f0ac7 rgb(a) ?bg=rgba(100,200,85,0.5) rrggbbaa ?bg=%23ff0095d1 hsl(a) ?bg=hsla(100,100%25,50%25,0.5)
HTTP
**Customize with query parameters**
General note, some clients are more permissive with unencoded query params than others. It's best to `encodeURIComponent` for all params.
Available params:
GDI_AIChatCompletionService
@rozek
This val is part of a series of examples to introduce "val.town" in my computer science course at
Stuttgart University of Applied Sciences . The idea is to motivate even first-semester students not to wait but to put their
ideas into practice from the very beginning and implement web apps with
frontend and backend. It contains a simple HTTP end point which expects a POST request with a JSON
structure containing the properties "SystemMessage" and "UserMessage". These
message are then used to run an OpenAI chat completion and produce an "assistant
message" which is sent back to the client as plain text. This val is the companion of https://rozek-gdi_aichatcompletion.web.val.run/ which contains the browser part (aka "frontend") for this example. The code was created using Townie - with only a few small manual corrections. This val is licensed under the MIT License.
HTTP
message are then used to run an OpenAI chat completion and produce an "assistant
message" which is sent back to the client as plain text.
This val is the companion of
add_to_notion_w_ai
@nerdymomocat
Uses instructor and open ai (with gpt-4-turbo) to process any content into a notion database entry. Use addToNotion with any database id and content. await addToNotion(
"DB_ID_GOES_HERE",
"CONTENT_GOES HERE"//"for example: $43.28 ordered malai kofta and kadhi (doordash) [me and mom] jan 3 2024"
); Prompts are created based on your database name, database description, property name, property type, property description, and if applicable, property options (and their descriptions). Supports: checkbox, date, multi_select, number, rich_text, select, status, title, url, email Uses NOTION_API_KEY , OPENAI_API_KEY stored in env variables and uses Valtown blob storage to store information about the database. Use get_notion_db_info to use the stored blob if exists or create one, use get_and_save_notion_db_info to create a new blob (and replace an existing one if exists).
Script
import Instructor from "npm:@instructor-ai/instructor";
import { Client } from "npm:@notionhq/client";
import OpenAI from "npm:openai";
const NOTION_API_KEY = process.env.NOTION_API_KEY;
const notion = new Client({
auth: NOTION_API_KEY,
apiKey: process.env.OPENAI_API_KEY ?? undefined,
const client = Instructor({
client: oai,
mode: "TOOLS",
const db_info = await get_notion_db_info(dbid);
const processed_message = await client.chat.completions.create({
messages: [{ role: "system", content: db_info["system_message"] }, { role: "user", content: text }],
savePDF
@iamseeley
๐๏ธ save your html as a pdf using html2pdf // Adjust the options
html2pdf(element, {
margin: 0.2,
filename: 'resume.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
}) usage <!-- Add the button to your html -->
<body>
<button id="saveAsPDFButton">Save as PDF</button>
<!-- Import the module -->
<script type="module" src="https://esm.town/v/iamseeley/savePDF"></script>
</body>
Script
page-break-before: auto !important;
page-break-inside: auto !important;
margin-bottom: 20px !important; /* Add space between sections */
section > ul {
page-break-inside: auto !important;
margin-bottom: 15px !important;
section > ul > li {
page-break-inside: avoid !important;
margin-bottom: 15px !important;
#certificates > ul > li {
page-break-inside: auto !important;
margin-bottom: 20px !important;
.title-period {
page-break-inside: avoid !important;
margin-bottom: 5px !important;
.highlights {
page-break-inside: auto !important;
.highlight-item {
page-break-inside: avoid !important;
margin-bottom: 8px !important;
valtownOpenAPI
@pomdtr
Val Town Typescript Spec This val return an up-to-date typescript version of the val.town openapi spec for usage with a feTS client. Usage Deno script import { createClient, type NormalizeOAS } from "npm:fets";
import openapi from "https://pomdtr-valtownOpenAPI.web.val.run/openapi.ts";
export const client = createClient<NormalizeOAS<typeof openapi>>({
endpoint: openapi.servers[0].url,
});
HTTP
# [Val Town Typescript Spec](https://pomdtr-valtownOpenAPI.web.val.run)
This val return an up-to-date typescript version of the val.town openapi spec for usage with a [feTS](https://github.com/ardatan/feTS) client.
## Usage
```typecript
import { createClient, type NormalizeOAS } from "npm:fets";
import openapi from "https://pomdtr-valtownOpenAPI.web.val.run/openapi.ts";
export const client = createClient<NormalizeOAS<typeof openapi>>({
endpoint: openapi.servers[0].url,
clone_my_vals_to_sqlite
@stevekrouse
I'm not particularly proud of this code
Script
import createClient from "https://esm.town/v/stevekrouse/val_town_client";
const client = createClient();
// from https://www.val.town/v/pomdtr/valTownToSQLite
while ((page === 0 || vals.length) && page < 100 && !error) {
const response = await client.GET("/v1/users/{user_id}/vals", {
params: {
tangibleIvoryCanidae
@alexwein
Find a Big Word - Bogglelike This endpoint displays an randomly generated SVG of a 4x4 grid of letters.
The Grid is guaranteed to have word that uses every letter using standard Boggle-style word-finding rules. Thanks to Fil for the example using Observable Plot. | | |
|-----|-----|
| Web page | https://alexwein-fabwbogglelike.web.val.run |
| Observable Plotย for image | https://observablehq.com/plot/ |
| wordnik from words | https://github.com/wordnik/wordlist |
HTTP
import d3 from "https://esm.sh/d3@7";
export async function fabw(board) {
// Import d3 and Plot with a server-side compatible approach
const { document } = await import("https://esm.sh/linkedom@0.16.1").then((m) =>
m.parseHTML(`<html><body></body></html>`)
// Ensure global is defined for server-side rendering
globalThis.document = document;
globalThis.window = { document } as any;
wideLib
@maxm
// const rows = parseRows([
Script
import { createClient, InsertResult } from "npm:@clickhouse/client";
import { z } from "npm:zod";
const schemaVersion = 3;
function _client() {
return createClient({
url: Deno.env.get("WIDE_CLICKHOUSE_URL"),
try {
await _client().command({
query: migration,
"boolean.values": Object.values(row.boolean),
return await _client().insert({
table: `logs_${schemaVersion}`,
console.log(queryString, { field_name, userId });
const query = await _client().query({
query: queryString,
export async function fields(userId: string, search: string = "") {
return (await (await _client().query({
query: `
: filter.value;
const query = await _client().query({
query: queryString,