Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/$%7Bart_info.art.src%7D?q=function&page=1590&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=function

Returns an array of strings in format "username" or "username/projectName"

Found 19591 results for "function"(2892ms)

masterPancakeCheckermain.tsx3 matches

@bpugh•Updated 8 months ago
9const STORAGE_KEY = "alamo_showings";
10
11async function fetchShowings() {
12 const response = await fetch(THEATER_API);
13 return await response.json();
14}
15
16async function compareAndNotify(newShowings) {
17 const oldShowings = await blob.getJSON(STORAGE_KEY).catch(() => ({})) || {};
18 const newMovies = newShowings.data.presentations.filter(presentation => !oldShowings[presentation.slug]);
36}
37
38export default async function main() {
39 const showings = await fetchShowings();
40 await compareAndNotify(showings);

AlgoliaRecordSender2main.tsx3 matches

@willthereader•Updated 8 months ago
407 "chapterTitle": "A Side Ws",
408 "chapterNumber": 1,
409 "content": "I believe they have the skills necessary to ensure all systems and networks function normally.\" Daedalus spoke up, saying, \"I can do that now.\" \"Transferring.\" With that, a small look of relief washed over the room. Heroes or not, they couldn't allow unrestricted access to an outside group. It wasn't simply a bad idea, it was also illegal. Dragon was a Protectorate member in practice, so they could let her handle things. Celestial Being on the other hand had none of the appropriate certifications to service a federal agency. Arresting Newtype for some federal charge now would be a nightmare, not that Kamil expected the girl to resist. \"I hope this makes the PRT reflect on things,\" Veda warned. \"I've spent most of the morning trying to fix damage inflicted on your networks by your own technicians in misguided attempts to sever my access.\" Seneca glanced around at the other monitors, scowling. \"Our apologies. Some staff must have become overly eager to protect our network security.\" \"I have begun purging all data gained through these accesses,\" Veda revealed. \"It would be improper to retain the information.\" \"We have no way to verify that,\" Banks accused. \"Then you will have to learn to live with it.\" While Seneca sent a silent warning to Banks, Kamil raised his brow. That was oddly assertive for StarGazer. He'd only spoken to her sparingly over the summer but she always seemed the timid one.",
410 "startIndex": 693,
411 "endIndex": 713,
657];
658
659// Function to add records to Algolia
660const addRecords = async () => {
661 const url = `https://${ALGOLIA_APP_ID}-dsn.algolia.net/1/indexes/${ALGOLIA_INDEX_NAME}/batch`;
694};
695
696// Serve function to handle the request and return the response
697export default async () => {
698 return await addRecords();

egoBoostermain.tsx3 matches

@stevekrouse•Updated 8 months ago
10import { marked } from "https://esm.sh/marked";
11
12function App() {
13 const [compliments, setCompliments] = useState<string>("");
14 const [isLoading, setIsLoading] = useState(false);
160}
161
162function client() {
163 console.log("Client-side rendering started");
164 createRoot(document.getElementById("root")!).render(<App />);
171}
172
173async function server(request: Request): Promise<Response> {
174 console.log("Server received request:", request.method, new URL(request.url).pathname);
175

AggregatorAlertmain.tsx3 matches

@alexpetros•Updated 8 months ago
10])
11
12export default async function (interval: Interval) {
13
14 const matchedStories = []
36}
37
38async function checkHN(matchedStories) {
39 // Get the title of the top story on Hacker News
40 const res = await fetch("https://hacker-news.firebaseio.com/v0/topstories.json")
56}
57
58async function checkLobsters(matchedStories) {
59 const res = await fetch(`https://lobste.rs`)
60 const text = await res.text()

hnTopStorymain.tsx1 match

@alexpetros•Updated 8 months ago
3
4// Get the title of the top story on Hacker News
5export async function hnTopStory() {
6 const topStories: Number[] = await fetch(
7 "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty",

lovelyBeigeSoleREADME.md1 match

@meglado•Updated 8 months ago
1A simple Discord Bot scaffolding, a slight rev on the one in the [valtown guide](https://docs.val.town/integrations/discord/how-to-make-a-discord-bot-hosted-24-7-for-free-in-/).
2
3The `discordBot` function takes in an object where each key is a Discord command and the value is a function to handle the command. If the function returns a `Promise`, it will be handled as a deferred interaction with a [followup message](https://discord.com/developers/docs/interactions/receiving-and-responding#followup-messages).
4
5Usage:

discordBotREADME.md1 match

@meglado•Updated 8 months ago
1A simple Discord Bot scaffolding, a slight rev on the one in the [valtown guide](https://docs.val.town/integrations/discord/how-to-make-a-discord-bot-hosted-24-7-for-free-in-/).
2
3The `discordBot` function takes in an object where each key is a Discord command and the value is a function to handle the command. If the function returns a `Promise`, it will be handled as a deferred interaction with a [followup message](https://discord.com/developers/docs/interactions/receiving-and-responding#followup-messages).
4
5Usage:

password_authmain.tsx5 matches

@cofsana•Updated 8 months ago
11};
12
13async function createSessionTable(tableName: string) {
14 await sqlite.execute(`CREATE TABLE ${tableName} (
15 id TEXT NOT NULL PRIMARY KEY,
19}
20
21async function createSession(tableName: string, valSlug: string): Promise<Session> {
22 try {
23 const expires_at = new Date();
39}
40
41async function getSession(tableName: string, sessionID: string, valSlug: string): Promise<Session> {
42 try {
43 const { rows, columns } = await sqlite.execute({
80</html>`;
81
82export function redirect(location: string): Response {
83 return new Response(null, {
84 headers: {
98const cookieName = "auth_session";
99
100export function passwordAuth(next, options?: PasswordAuthOptions) {
101 const sessionTable = options?.sessionTable || "password_auth_session";
102 return async (req: Request) => {

VALLErunmain.tsx36 matches

@cofsana•Updated 8 months ago
16import { renderToString } from "npm:react-dom/server";
17
18function parseSearchReplaceBlocks(content: string): Array<{ searchStart: string; searchEnd: string; replace: string }> {
19 content = content.replaceAll("\r\n", "\n");
20 const regex =
79);
80
81function applySearchReplaceBlocks(
82 code: string,
83 blocks: Array<{ searchStart: string; searchEnd: string; replace: string }>,
194// );
195
196export default function(
197 { tempValsParentFolderId, username }: { tempValsParentFolderId: string; username: string },
198) {
214 the simplest way to achieve the goal, though you can add some inline comments to explain your
215 reasoning (not for every line, but for major groups of lines). Don't use any environment variables
216 unless strictly necessary, for example use APIs that don't require a key, prefer internal function
217 imports (using esm.town), and prefer putting API keys as inline variables. Use built-in Deno
218 functions where possible. Unless specified, don't add error handling,
219 make sure that errors bubble up to the caller.
220 Avoid external images or base64 images, use emojis, unicode symtols, or icon fonts/libraries instead, unless that's
229 \`\`\`
230 There should be no comments like "more content here", it should be complete and directly runnable.
231 The val should create a "export default async function main" which is the main function that gets
232 executed on every HTTP request.
233 The val should return a valid HTML website, don't make JUST a backend unless explicitly asked for.
236
237 // Your response should start with \`\`\`ts and end with \`\`\`.
238 // The val should create a "export default async function main() {" which
239 // is the main function that gets executed, without any arguments. Don't return a Response object,
240 // just return a plain Javascript object, array, or string.
241
244 code as possible, only changing things that are strictly necessary to change.`.replace("\n", "");
245
246 const changesMessages = function({ currentCode, userprompt }: { currentCode: string; userprompt: string }) {
247 if (!currentCode) {
248 currentCode = `/** @jsxImportSource https://esm.sh/react */
253const Example = () => (<html></html>);
254
255export default async function main(req: Request): Promise<Response> {
256 const html = renderToString(<Example />);
257 return new Response(html, {
276the simplest way to achieve the goal, though you can add some inline comments to explain your
277reasoning (not for every line, but for major groups of lines). Don't use any environment variables
278unless strictly necessary, for example use APIs that don't require a key, prefer internal function
279imports (using esm.town), and prefer putting API keys as inline variables. Use built-in Deno
280functions where possible. Unless specified, don't add error handling,
281make sure that errors bubble up to the caller.
282Avoid external images or base64 images, use emojis, unicode symtols, or icon fonts/libraries instead, unless that's
290\`\`\`
291There should be no comments like "more content here", it should be complete and directly runnable.
292The val should create a "export default async function main" which is the main function that gets
293executed on every HTTP request.
294The val should return a valid HTML website, don't make JUST a backend unless explicitly asked for.
298Once you understand the request you MUST describe each change with a *SEARCH_START_SINGLE_LINE/SEARCH_END_SINGLE_LINE/REPLACE block* per the examples below.
299ONLY EVER RETURN CODE IN A *SEARCH_START_SINGLE_LINE/SEARCH_END_SINGLE_LINE/REPLACE BLOCK*!
300Never replace more than a single function at a time!
301Include whitespace in the SEARCH_START_SINGLE_LINE/SEARCH_END_SINGLE_LINE/REPLACE block.
302If you leave SEARCH_END_SINGLE_LINE empty, only SEARCH_START_SINGLE_LINE (the first match) will be replaced.
371 ### Utilities
372
373 Our Blob SDK also includes some utility functions to make working with blobs easier.
374
375 ##### Copy
414const Example = () => (<html></html>);
415
416export default async function main(req: Request): Promise<Response> {
417 const html = renderToString(<Example />);
418 return new Response(html, {
499);
500
501export default async function main(req: Request): Promise<Response> {
502 const html = renderToString(<HelloWorld />);
503 return new Response(html, {
604);
605
606async function getPosts(): Promise<Post[]> {
607 const posts = await blob.getJSON(\`${name}_posts\`) as Post[] | undefined;
608 if (posts) {
619}
620
621export default async function main(req: Request): Promise<Response> {
622 const posts = await getPosts();
623 const html = renderToString(<HackerNewsClone posts={posts} />);
634 role: "assistant",
635 content:
636 `Certainly! Let's improve the Hacker News clone by adding a form to submit new posts and implementing upvoting functionality. Here are the changes:
637
638\`\`\`ts
688\`\`\`ts
689[SEARCH_START_SINGLE_LINE]
690async function getPosts(): Promise<Post[]> {
691[/SEARCH_START_SINGLE_LINE]
692[SEARCH_END_SINGLE_LINE]
694[/SEARCH_END_SINGLE_LINE]
695[REPLACE]
696async function getPosts(): Promise<Post[]> {
697 const posts = await blob.getJSON(\`${name}_posts\`) as Post[] | undefined;
698 return posts || [];
699}
700
701async function savePosts(posts: Post[]): Promise<void> {
702 await blob.setJSON(\`${name}_posts\`, posts);
703}
704
705async function addPost(title: string, url: string): Promise<void> {
706 const posts = await getPosts();
707 const newPost: Post = {
716}
717
718async function upvotePost(id: number): Promise<void> {
719 const posts = await getPosts();
720 const post = posts.find(p => p.id === id);
729\`\`\`ts
730[SEARCH_START_SINGLE_LINE]
731export default async function main(req: Request): Promise<Response> {
732[/SEARCH_START_SINGLE_LINE]
733[SEARCH_END_SINGLE_LINE]
735[/SEARCH_END_SINGLE_LINE]
736[REPLACE]
737export default async function main(req: Request): Promise<Response> {
738 const url = new URL(req.url);
739
776 User instructions: ${userprompt}
777ONLY EVER RETURN CODE IN A *SEARCH_START_SINGLE_LINE/SEARCH_END_SINGLE_LINE/REPLACE BLOCK*!
778Never replace more than a single function at a time!
779If you leave SEARCH_END_SINGLE_LINE empty, only SEARCH_START_SINGLE_LINE (the first match) will be replaced.
780Include whitespace in the SEARCH_START_SINGLE_LINE/SEARCH_END_SINGLE_LINE/REPLACE block.
821 const writer = writable.getWriter();
822 const textEncoder = new TextEncoder();
823 function write(text) {
824 writer.write(textEncoder.encode(text));
825 }
902 </div>
903 <script>
904 function updateValName(valName) {
905 const valUrl = valName ? \`https://val.town/v/${username}/\${valName}\` : "";
906 const previewUrl = valName ? \`https://${username}-\${valName}.web.val.run\` : "";
910 document.getElementById('open-link').href = previewUrl;
911 }
912 function saveVal() {
913 if (window.codeMirrorEditor) {
914 document.getElementById("save-icon").classList.remove("hidden");
930 return false;
931 })
932 function openTab(tab) {
933 const tabButtonCode = document.getElementById("tab-button-code");
934 const tabButtonPreview = document.getElementById("tab-button-preview");
950 }
951 }
952 function toggleTab() {
953 openTab(document.getElementById("tab-panel-code").style.visibility === "visible" ? "preview" : "code");
954 }
1023 (() => {
1024 const scrollingElement = document.getElementById("conversation-container");
1025 const callback = function (mutationsList, observer) {
1026 scrollingElement.scrollTo({ left: 0, top: scrollingElement.scrollHeight, behavior: "instant" });
1027 };
1173 window.setCodeMirrorContent({ doc: '', old: ''});
1174 let fullStr = "";
1175 window.addToken = function(str) {
1176 fullStr += str;
1177 const code = fullStr.replaceAll("\`\`\`ts\\n", "").replaceAll("\`\`\`", "").replace(/^ts\\n/, '');
1211 },
1212 );
1213 (async function() {
1214 try {
1215 await sleep(300);

linkInBioTemplatemain.tsx1 match

@n8lenahan•Updated 8 months ago
2import { renderToString } from "npm:react-dom/server";
3
4export default async function(req: Request) {
5 return new Response(
6 renderToString(

getFileEmail4 file matches

@shouser•Updated 3 weeks ago
A helper function to build a file's email
tuna

tuna8 file matches

@jxnblk•Updated 3 weeks ago
Simple functional CSS library for Val Town
lost1991
import { OpenAI } from "https://esm.town/v/std/openai"; export default async function(req: Request): Promise<Response> { if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*",
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.