1import { basicAuthMiddleware } from "./auth.ts";
2import { handleApiRequest } from "./api/index.ts";
3import { getRequests } from "./api/requests.ts";
4import { getUserSummary } from "./api/user-summary.ts";
5import { getInferenceCalls } from "./api/inference-calls.ts";
6import { renderDashboard } from "./views/dashboard.ts";
7import { renderRequests } from "./views/requests.ts";
22const path = url.pathname;
2324// Handle API requests
25if (path.startsWith("/api/")) {
26return handleApiRequest(req);
27}
28
45/**
6* Handle API requests
7*/
8export async function handleApiRequest(req: Request): Promise<Response> {
9const url = new URL(req.url);
10const path = url.pathname.replace("/api/", "");
11
12try {
13// Route to the appropriate API handler
14if (path === "requests") {
15const usageId = url.searchParams.get("usage_id");
59}
60} catch (error) {
61console.error("API error:", error);
62return new Response(JSON.stringify({ error: error.message }), {
63status: 500,
32<ol>
33<li>
34Login with your Val Town API token (with projects:read, projects:write, user:read permissions)
35</li>
36<li>Select a project to work on</li>
70</div>
71<h3>Cost Tracking</h3>
72<p>See estimated API usage costs for each interaction</p>
73</div>
74</section>
79<ul>
80<li>React frontend with TypeScript</li>
81<li>Hono API server backend</li>
82<li>Web Audio API for sound notifications</li>
83<li>AI SDK for Claude integration</li>
84</ul>
85<p>
86The application proxies requests to the Anthropic API and Val Town API, allowing Claude to view and edit your
87project files directly.
88</p>
Townie-09.cursorrules10 matches
13- Generate code in TypeScript or TSX
14- Add appropriate TypeScript types and interfaces for all data structures
15- Prefer official SDKs or libraries than writing API calls directly
16- Ask the user to supply API or library documentation if you are at all unsure about it
17- **Never bake in secrets into the code** - always use environment variables
18- Include comments explaining complex logic (avoid commenting obvious operations)
23### 1. HTTP Trigger
2425- Create web APIs and endpoints
26- Handle HTTP requests and responses
27- Example structure:
173However, it's *extremely importing* to note that `parseProject` and other Standard Library utilities ONLY RUN ON THE SERVER.
174If you need access to this data on the client, run it in the server and pass it to the client by splicing it into the HTML page
175or by making an API request for it.
176177## Val Town Platform Specifics
181- **AI Image:** To inline generate an AI image use: `<img src="https://maxm-imggenurl.web.val.run/the-description-of-your-image" />`
182- **Storage:** DO NOT use the Deno KV module for storage
183- **Browser APIs:** DO NOT use the `alert()`, `prompt()`, or `confirm()` methods
184- **Weather Data:** Use open-meteo for weather data (doesn't require API keys) unless otherwise specified
185- **View Source:** Add a view source link by importing & using `import.meta.url.replace("ems.sh", "val.town)"` (or passing this data to the client) and include `target="_top"` attribute
186- **Error Debugging:** Add `<script src="https://esm.town/v/std/catch"></script>` to HTML to capture client-side errors
187- **Error Handling:** Only use try...catch when there's a clear local resolution; Avoid catches that merely log or return 500s. Let errors bubble up with full context
188- **Environment Variables:** Use `Deno.env.get('keyname')` when you need to, but generally prefer APIs that don't require keys
189- **Imports:** Use `https://esm.sh` for npm and Deno dependencies to ensure compatibility on server and browser
190- **Storage Strategy:** Only use backend storage if explicitly required; prefer simple static client-side sites
224### Backend (Hono) Best Practices
225226- Hono is the recommended API framework
227- Main entry point should be `backend/index.ts`
228- **Static asset serving:** Use the utility functions to read and serve project files:
248});
249```
250- Create RESTful API routes for CRUD operations
251- Always include this snippet at the top-level Hono app to re-throwing errors to see full stack traces:
252```ts
285- For files in the project, use `readFile` helpers
2862875. **API Design:**
288- `fetch` handler is the entry point for HTTP vals
289- Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`
Discord-to-LinearREADME.md2 matches
17- `DISCORD_MONITORED_CHANNELS`: Comma-separated channel IDs to monitor (right-click channel → Copy ID)
18- Example: `1327384540187983926,1327384540187983927`
19- `LINEAR_API_KEY`: Your Linear API key
20- Go to Linear Settings → API → Personal API keys → Create key
21- `LINEAR_TEAM_ID`: Your Linear team UUID, this is NOT the 3 letter `Team Identifier` found in issue IDs
22- On any Linear page, type `CMD+K` to pull up the quick menu + enter `Dev: Copy model UUID` to copy your UUID
Discord-to-Linearmain.tsx3 matches
1import { blob } from "https://esm.town/v/std/blob";
2import { CONFIG } from "./backend/config.tsx";
3import { DiscordAPI } from "./backend/discord.tsx";
4import { LinearSDK } from "./backend/linear.tsx";
52425// Initialize services
26const discord = new DiscordAPI();
27const linear = new LinearSDK();
2845*/
46async function processChannelReactions(
47discord: DiscordAPI,
48linear: LinearSDK,
49serverId: string,
Discord-to-Linearlinear.tsx1 match
67constructor() {
8this.client = new LinearClient({ apiKey: Deno.env.get("LINEAR_API_KEY")! });
9}
10
PlaywrightDemomain.ts3 matches
3import { Browser } from "npm:playwright-core";
4import { valTownChromium } from "./valTownChromium.ts";
5import { STEEL_API_KEY } from "./consts.ts";
6import { hackerNewsDemo } from "./hackerNewsDemo.ts";
78const client = new Steel({
9steelAPIKey: STEEL_API_KEY,
10});
111920browser = await valTownChromium.connectOverCDP(
21`wss://connect.steel.dev?apiKey=${STEEL_API_KEY}&sessionId=${session.id}`,
22{ slowMo: 0 },
23);
PlaywrightDemoconsts.ts1 match
1export const STEEL_API_KEY = Deno.env.get("STEEL_API_KEY");
2
weatherWeatherMap.tsx13 matches
17export default function WeatherMap({ onLocationSelect, selectedLocation }: WeatherMapProps) {
18const mapRef = useRef<HTMLDivElement>(null);
19const mapInstanceRef = useRef<any>(null);
20const markersRef = useRef<any[]>([]);
21const selectedMarkerRef = useRef<any>(null);
29// Create map centered on UK
30const map = window.L.map(mapRef.current).setView([54.5, -2], 3);
31mapInstanceRef.current = map;
3233// Add OpenStreetMap tiles
4647return () => {
48if (mapInstanceRef.current) {
49mapInstanceRef.current.remove();
50mapInstanceRef.current = null;
51}
52if (selectedMarkerRef.current) {
58// Zoom to selected location when it changes
59useEffect(() => {
60if (!mapInstanceRef.current || !selectedLocation) return;
6162const { latitude, longitude } = selectedLocation;
64// Remove previous selected location marker
65if (selectedMarkerRef.current) {
66mapInstanceRef.current.removeLayer(selectedMarkerRef.current);
67selectedMarkerRef.current = null;
68}
6970// Zoom to the selected location with a nice animation
71mapInstanceRef.current.setView([latitude, longitude], 12, {
72animate: true,
73duration: 1.0
102icon: selectedIcon,
103zIndexOffset: 1000 // Ensure it appears above other markers
104}).addTo(mapInstanceRef.current);
105106}, [selectedLocation]);
108// Update markers when weather data changes
109useEffect(() => {
110if (!mapInstanceRef.current || !window.L) return;
111112// Clear existing markers
113markersRef.current.forEach(marker => {
114mapInstanceRef.current.removeLayer(marker);
115});
116markersRef.current = [];
147const marker = window.L.marker([point.latitude, point.longitude], {
148icon: customIcon
149}).addTo(mapInstanceRef.current);
150151// Add popup with detailed info
192try {
193setLoading(true);
194const response = await fetch('/api/weather/map');
195if (response.ok) {
196const data = await response.json();