1import { fetch } from "https://esm.town/v/std/fetch";
2import { OpenAI } from "https://esm.town/v/std/openai"; // Assuming OpenAI library is available
3import { z } from "npm:zod"; // Using Zod for input validation
173174try {
175const response = await fetch('/generate', {
176method: 'POST',
177headers: { 'Content-Type': 'application/json' },
287288try {
289const response = await fetch('/test', {
290method: 'POST',
291headers: { 'Content-Type': 'application/json' },
1import { fetch } from "https://esm.town/v/std/fetch";
2import { OpenAI } from "https://esm.town/v/std/openai";
3import { z } from "npm:zod";
87const setupInForQ = (q) => { clrInArea(); currentQ = q; let inp; const commonEnter = (ev) => { if (ev.key === 'Enter' && !ev.shiftKey) { ev.preventDefault(); sendHandler(); } }; switch (q.type) { case 'select': inp = document.createElement('select'); inp.id = 'user-input'; inp.className = 'form-control'; (q.opts || []).forEach(opt => { const o = document.createElement('option'); o.value = opt.value; o.textContent = opt.label; inp.appendChild(o); }); break; case 'textarea': inp = document.createElement('textarea'); inp.id = 'user-input'; inp.rows = 3; inp.placeholder = "Enter details..."; inp.className = 'form-control'; inp.addEventListener('keypress', commonEnter); break; case 'number': inp = document.createElement('input'); inp.type = 'number'; inp.id = 'user-input'; inp.placeholder = "Enter number..."; if (q.min != null) inp.min = q.min; if (q.max != null) inp.max = q.max; inp.className = 'form-control'; inp.addEventListener('keypress', commonEnter); break; default: inp = document.createElement('input'); inp.type = 'text'; inp.id = 'user-input'; inp.placeholder = "Your answer..."; inp.className = 'form-control'; inp.addEventListener('keypress', commonEnter); break; } const btn = document.createElement('button'); btn.id = 'send-button'; btn.textContent = 'Send'; btn.onclick = sendHandler; inputArea.append(inp, btn); enableInput(true); inp.focus(); };
88const sendHandler = async () => { const inp = document.getElementById('user-input'); if (!inp || !currentQ) return; let answer = inp.value; if (currentQ.type === 'number') { const num = parseFloat(answer); answer = !isNaN(num) ? num : (answer.trim() === '' ? '' : answer); } clrErr(); let displayAnswer = typeof answer === 'number' ? answer.toString() : answer; if (currentQ.type === 'select') { const opt = Array.from(inp.options).find(o => o.value === answer); displayAnswer = opt ? opt.text : answer; if (answer === "") displayAnswer = "(Skipped)"; } else if (typeof answer === 'string' && !answer.trim() && currentQ.type !== 'textarea') { displayAnswer = "(No input)"; } if (displayAnswer && !["(Skipped)", "(No input)"].includes(displayAnswer)) addUser(displayAnswer); else if (typeof answer === 'string' && !answer.trim() && currentQ.type === 'textarea') addUser("(Empty details)"); const lastAns = { field: currentQ.fld, value: answer }; clrInArea(); enableInput(false); setLoad(true); await sendToSrv({ task: task, sessionId: sid, lastAnswer: lastAns, state: srvState }); };
89const sendToSrv = async (pld) => { try { console.log("-> /questionnaire:", pld); const resp = await fetch('/questionnaire', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(pld) }); setLoad(false); clrErr(); if (!resp.ok) { let msg = \`Server error: \${resp.status} \${resp.statusText}\`; try { msg += \` - \${(await resp.json()).error || 'Details unavailable'}\` } catch(e){} throw new Error(msg); } const data = await resp.json(); console.log("<- /questionnaire:", data); sid = data.sid; srvState = data.state; if (data.error) { showErr(data.error); if (currentQ) { addBot(\`Issue: \${data.error}. Try again.\`); setupInForQ(currentQ); } else { addBot(\`Error: \${data.error}. Select task again.\`); showTasks(); } return; } if (data.isDone) { addBot("Info gathered. Processing..."); enableInput(false); clrInArea(); setLoad(true); await execWf(data.data); } else if (data.nextQ) { addBot(data.nextQ.txt); setupInForQ(data.nextQ); } else { showErr("Unexpected server response."); enableInput(false); addBot("Something went wrong. Refresh and try again."); } } catch (err) { console.error("Comm error:", err); setLoad(false); showErr(\`Comm error: \${err.message}\`); enableInput(false); addBot("Connection issue. Refresh to start over."); } };
90const execWf = async (finalPld) => { enableInput(false); try { console.log("-> /execute:", finalPld); if (!finalPld?.task || !finalPld.data) throw new Error("Invalid execution payload."); const resp = await fetch('/execute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(finalPld) }); setLoad(false); const resData = await resp.json(); console.log("<- /execute:", resData); resDisp.style.display = 'block'; setTimeout(() => resDisp.classList.add('visible'), 10); resCont.innerHTML = ''; logCont.innerHTML = ''; if (!resp.ok || resData.error) { const msg = resData.error || \`Exec failed: Status \${resp.status}\`; resCont.innerHTML = \`<div class="error-message">\${esc(msg)}</div>\`; if(resData.dtls) resCont.innerHTML += \`<p>Details: \${esc(typeof resData.dtls === 'string' ? resData.dtls : JSON.stringify(resData.dtls))}</p>\`; addBot(\`Error processing request: \${esc(msg)}\`); } else { resCont.innerHTML = fmtRes(resData.result, finalPld.task); addBot("Request complete! See results."); } logCont.innerHTML = fmtLogs(resData.logs); clrInArea(); showTasks(); } catch (err) { console.error("Exec error:", err); setLoad(false); resDisp.style.display = 'block'; setTimeout(() => resDisp.classList.add('visible'), 10); resCont.innerHTML = \`<div class="error-message">Execution failed: \${esc(err.message)}</div>\`; logCont.innerHTML = fmtLogs(null); addBot("Critical error during execution. Check logs or retry."); clrInArea(); showTasks(); } };
91const fmtList = (items, tag='li') => items && items.length > 0 ? \`<ul>\${items.map(i => \`<$\{tag\}>\${esc(i)}</\$\{tag\}>\`).join('')}</ul>\` : '';
92const fmtDictList = (items) => items && items.length > 0 ? \`<ul>\${items.map(d => \`<li><strong>\${esc(d.dx || d.diagnosis)}</strong>\${(d.rationale) ? \`: \${esc(d.rationale)}\` : ''}</li>\`).join('')}</ul>\` : '';
pondiversefetchCreations0 matches
1import { blob } from "https://esm.town/v/std/blob";
2import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";
3import { TABLE_NAME } from "./updateTable";
45export default async function(req: Request): Promise<Response> {
41const [strategyError, setStrategyError] = useState<string | null>(null);
4243// --- Fetch Profile ---
44const fetchProfile = useCallback(async () => {
45setIsLoadingProfile(true);
46setProfileError(null);
47try {
48const response = await fetch("/api/profile");
49if (response.status === 404) {
50setProfile(null);
59} else if (!response.ok) {
60const data = await response.json();
61throw new Error(data.error || "Failed to fetch profile");
62} else {
63const data = await response.json();
64setProfile(data);
65setFormData({ // Pre-fill form with fetched data or defaults
66business_type: data.business_type || "",
67service_area: data.service_area || "",
74} catch (err: any) {
75setProfileError(err.message);
76console.error("Fetch profile error:", err);
77} finally {
78setIsLoadingProfile(false);
8182useEffect(() => {
83fetchProfile();
84}, [fetchProfile]);
8586// --- Input Handlers ---
98setStrategyError(null);
99try {
100const response = await fetch("/api/profile", {
101method: "POST",
102headers: { "Content-Type": "application/json" },
127setStrategy(null);
128try {
129// Use POST to trigger generation, profile is fetched server-side
130const response = await fetch("/api/generate-strategy", { method: "POST" });
131const data = await response.json();
132if (!response.ok) {
441} catch (e: any) {
442/* ... error handling ... */
443console.error("Error fetching profile:", e.message);
444return new Response(JSON.stringify({ error: "Database error fetching profile" }), {
445status: 500,
446headers: { "Content-Type": "application/json" },
477if (url.pathname === "/api/generate-strategy" && request.method === "POST") {
478let profile: any = null;
479// 1. Fetch the enhanced profile
480try {
481const { rows } = await sqlite.execute({
495}
496} catch (e: any) {
497/* ... error handling ... */ return new Response(JSON.stringify({ error: "DB error fetching profile" }), {
498status: 500,
499});
955
956// Simulação de geocodificação reversa
957fetch(\`https://nominatim.openstreetmap.org/reverse?format=json&lat=\${lat}&lon=\${lng}&accept-language=pt-BR\`)
958.then(response => response.json())
959.then(data => {
avidAzureKiwimain.tsx3 matches
45try {
6const initialResponse = await fetch(baseUrl);
7const initialHtml = await initialResponse.text();
823links.map(async (pageUrl) => {
24try {
25const response = await fetch(pageUrl);
26const html = await response.text();
27const content = extractPureContent(html);
28return content ? `## ${pageUrl}\n\n${content}` : '';
29} catch (error) {
30console.error(`Failed to fetch ${pageUrl}:`, error);
31return '';
32}
mohitkingsprojectmain.tsx17 matches
88];
8990// Fetch currency rates
91useEffect(() => {
92async function fetchCurrencyRates() {
93try {
94const response = await fetch("https://open.exchangerate-api.com/v6/latest");
95const data = await response.json();
96setCurrencyRates(data.rates);
97} catch (error) {
98console.error("Failed to fetch currency rates:", error);
99}
100}
101fetchCurrencyRates();
102}, []);
103104// Cryptocurrency data fetching
105useEffect(() => {
106async function fetchCoinData() {
107try {
108setLoading(true);
109const response = await fetch(
110"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false",
111);
114setLoading(false);
115} catch (error) {
116console.error("Failed to fetch coin data:", error);
117setLoading(false);
118}
119}
120121fetchCoinData();
122123const refreshInterval = autoRefresh
124? setInterval(() => {
125fetchCoinData();
126setRefreshCount(prev => prev + 1);
127}, 60000)
148);
149150// Price history fetching
151const fetchPriceHistory = async (coinId: string, days: string) => {
152try {
153const response = await fetch(
154`https://api.coingecko.com/api/v3/coins/${coinId}/market_chart?vs_currency=usd&days=${days}`,
155);
166setChartError(null);
167} catch (error) {
168console.error(`Failed to fetch ${days} price history:`, error);
169setChartError(`Unable to load ${days} price history`);
170}
279onClick={() => {
280setSelectedCoin(coin);
281fetchPriceHistory(coin.id, "24h");
282}}
283className={`p-4 rounded-lg cursor-pointer ${
313<button
314key={range}
315onClick={() => fetchPriceHistory(selectedCoin.id, range)}
316className={`p-2 rounded ${
317selectedTimeRange === range
valProfilePageREADME.md1 match
64- Hono (server-side)
65- Tailwind CSS (styling)
66- Uses the Charlie's User Search API for fetching user val data
67- Uses Val Town's profile picture proxy for user avatars
68
valProfilePageindex.ts7 matches
4const app = new Hono();
56// API endpoint to fetch user profile data
7app.get("/api/profile/:username", async (c) => {
8const username = c.req.param("username");
10try {
11// Call the user search API
12const response = await fetch(
13`https://charliesusersearch.val.run/?user=${username}`
14);
15
16if (!response.ok) {
17return c.json({ error: "Failed to fetch user data" }, 500);
18}
19
21return c.json(data);
22} catch (error) {
23console.error("Error fetching user data:", error);
24return c.json({ error: "Failed to fetch user data" }, 500);
25}
26});
52});
5354// HTTP vals expect an exported "fetch handler"
55// This is how you "run the server" in Val Town with Hono
56export default app.fetch;
valProfilePageValGridItem.tsx7 matches
1/** @jsxImportSource https://esm.sh/react@18.2.0 */
2import React, { useState, useEffect } from "https://esm.sh/react@18.2.0";
3import { fetchMoiConfig } from "../utils/moiConfig.tsx";
45interface Val {
45};
46
47// Attempt to fetch moi.md for this val if it doesn't have an image
48useEffect(() => {
49const fetchMoiData = async () => {
50// Only try to fetch moi.md if there's no image_url
51if (!val.image_url) {
52try {
59// Construct the base URL for the val/project
60const baseUrl = urlParts.slice(0, xIndex + 3).join('/');
61const config = await fetchMoiConfig(baseUrl);
62setMoiConfig(config);
63}
64} catch (error) {
65console.error("Error fetching moi.md for val:", error);
66}
67}
68};
69
70fetchMoiData();
71}, [val.url, val.image_url]);
72