stevensDemo.cursorrules10 matches
20### 2. HTTP Vals
2122- Create web APIs and endpoints
23- Handle HTTP requests and responses
24- Example structure:
66- Generate code in TypeScript
67- Add appropriate TypeScript types and interfaces for all data structures
68- Prefer official SDKs or libraries than writing API calls directly
69- Ask the user to supply API or library documentation if you are at all unsure about it
70- **Never bake in secrets into the code** - always use environment variables
71- Include comments explaining complex logic (avoid commenting obvious operations)
190- For AI-generated images, use: `https://maxm-imggenurl.web.val.run/the-description-of-your-image`
191- **Storage:** DO NOT use the Deno KV module for storage
192- **Browser APIs:** DO NOT use the `alert()`, `prompt()`, or `confirm()` methods
193- **Weather Data:** Use open-meteo for weather data (doesn't require API keys) unless otherwise specified
194- **View Source:** Add a view source link with `import.meta.url.replace("esm.town", "val.town")` and include `target="_top"` attribute
195- **Error Debugging:** Add `<script src="https://esm.town/v/std/catch"></script>` to HTML to capture client-side errors
196- **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
197- **Environment Variables:** Use `Deno.env.get('keyname')` and minimize their use - prefer APIs without keys
198- **Imports:** Use `https://esm.sh` for npm and Deno dependencies to ensure compatibility on server and browser
199- **Storage Strategy:** Only use backend storage if explicitly required; prefer simple static client-side sites
230231### Backend (Hono) Best Practices
232- Hono is the recommended API framework (similar to Express, Flask, or Sinatra)
233- Main entry point should be `backend/index.ts`
234- **Static asset serving:** Use the utility functions to read and serve project files:
251});
252```
253- Create RESTful API routes for CRUD operations
254- Be careful with error handling as Hono tends to swallow errors
255- Always include this snippet at the top-level Hono app to re-throwing errors to see full stack traces:
268- Use React 18.2.0 consistently in all imports and the `@jsxImportSource` pragma
269- Follow the React component pattern from the example project
270- Handle API calls properly with proper error catching
271272### Database Patterns
299- For files in the project, use `readFile` helpers
3003015. **API Design:**
302- `fetch` handler is the entry point for HTTP vals
303- Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`
stevensDemoApp.tsx8 matches
10import { NotebookView } from "./NotebookView.tsx";
1112const API_BASE = "/api/memories";
13const MEMORIES_PER_PAGE = 20; // Increased from 7 to 20 memories per page
149091// Fetch avatar image
92fetch("/api/images/stevens.jpg")
93.then((response) => {
94if (response.ok) return response.blob();
104105// Fetch wood background
106fetch("/api/images/wood.jpg")
107.then((response) => {
108if (response.ok) return response.blob();
133setError(null);
134try {
135const response = await fetch(API_BASE);
136if (!response.ok) {
137throw new Error(`HTTP error! status: ${response.status}`);
176177try {
178const response = await fetch(API_BASE, {
179method: "POST",
180headers: { "Content-Type": "application/json" },
199200try {
201const response = await fetch(`${API_BASE}/${id}`, {
202method: "DELETE",
203});
231232try {
233const response = await fetch(`${API_BASE}/${editingMemory.id}`, {
234method: "PUT",
235headers: { "Content-Type": "application/json" },
606<div className="font-pixel text-[#f8f1e0]">
607<style jsx>{`
608@import url("https://fonts.googleapis.com/css2?family=Pixelify+Sans&display=swap");
609610@tailwind base;
3738// Auth routes (no JWT required)
39app.route("/api/auth", authRoutes);
4041// JWT middleware for protected routes
42app.use("/api/*", async (c, next) => {
43// Skip JWT check for auth routes and OPTIONS requests
44if (c.req.path.startsWith("/api/auth") || c.req.method === "OPTIONS") {
45return next();
46}
53});
5455// API routes
56app.route("/api/users", userRoutes);
57app.route("/api/aircraft", aircraftRoutes);
58app.route("/api/maintenance", maintenanceRoutes);
59app.route("/api/flights", flightRoutes);
60app.route("/api/billing", billingRoutes);
61app.route("/api/weather", weatherRoutes);
6263// Serve frontend files
73// Get initial data for bootstrapping the app
74const initialData = {
75apiUrl: "/api",
76projectInfo: {
77name: "Glider Tow Operation Management",
30โโโ backend/
31โ โโโ database/ # SQLite database setup and queries
32โ โโโ routes/ # API endpoints
33โ โโโ index.ts # Main entry point
34โโโ frontend/
pageexplainerREADME.md7 matches
9- Uses OpenAI to analyze the page and answer questions about it
10- Provides a simple, user-friendly web interface
11- Also supports JSON API for programmatic usage
1213## Usage
20- Click "Analyze Webpage" to get your answer
2122### API Usage
2324You can also use this Val programmatically by sending a POST request with JSON:
3435```bash
36curl -X POST https://api.val.town/v1/run/yourusername/webpage-analyzer \
37-H "Content-Type: application/json" \
38-d '{"url": "https://example.com", "question": "What is the main heading on this page?"}'
4243```javascript
44const response = await fetch('https://api.val.town/v1/run/yourusername/webpage-analyzer', {
45method: 'POST',
46headers: {
57```
5859## Response Format (API)
6061The API returns a JSON response with the following structure:
6263```json
78## Requirements
7980This Val requires an OpenAI API key to be set as an environment variable in your Val Town account.
pageexplainerwebpage-analyzer.ts3 matches
164if (req.method === "POST") {
165try {
166// Check content type to determine if it's a form submission or JSON API request
167const contentType = req.headers.get('content-type') || '';
168
172// Parse input based on content type
173if (contentType.includes('application/json')) {
174// Handle JSON API request
175const body = await req.json();
176url = body.url;
284// Return response based on content type
285if (contentType.includes('application/json')) {
286// Return JSON for API requests
287return new Response(JSON.stringify(result), {
288headers: {
MullbotgenerateFunFacts.tsx7 matches
7172/**
73* Generates fun facts for the next 7 days using OpenAI API
74* @param previousFacts Previous fun facts to avoid duplication
75* @returns Array of generated fun facts
77async function generateFunFacts(previousFacts) {
78try {
79// Get API key from environment
80const apiKey = Deno.env.get("OPENAI_API_KEY");
81if (!apiKey) {
82console.error("OpenAI API key is not configured.");
83return null;
84}
8586// Initialize OpenAI client
87const openai = new OpenAI({ apiKey });
8889// Format previous facts for the prompt
139console.log({ message });
140141// Call OpenAI API
142const response = await openai.chat.completions.create({
143model: "gpt-4-turbo-preview", // You can adjust the model as needed
1import ok from "https://npllm.val.run/api/npm-package/left-pad-robust";
23console.log(ok);
5## Structure
67- `index.ts` - Main entry point for the HTTP API
8- `cron.ts` - Scheduled job to check for floods and send alerts
9- `database/` - Database schema and queries
10- `routes/` - API route handlers
11- `services/` - Business logic services
1213## API Endpoints
1415### Authentication
1617- `POST /api/auth/signup` - Create a new user account
18- `POST /api/auth/login` - Log in to an existing account
19- `GET /api/auth/me` - Get current user information
2021### Locations
2223- `GET /api/locations` - Get all locations for the current user
24- `POST /api/locations` - Add a new location
25- `GET /api/locations/:id` - Get a specific location
26- `DELETE /api/locations/:id` - Delete a location
2728### Flood Checking
2930- `POST /api/check-floods` - Check for potential floods for a user's locations
3132## Cron Job
11};
1213// API base URL
14const API_BASE_URL = '';
1516// DOM Elements
150
151try {
152const response = await fetch(`${API_BASE_URL}/api/auth/login`, {
153method: 'POST',
154headers: {
191
192try {
193const response = await fetch(`${API_BASE_URL}/api/auth/signup`, {
194method: 'POST',
195headers: {
247async function loadLocations() {
248try {
249const response = await fetch(`${API_BASE_URL}/api/locations`, {
250headers: {
251'Authorization': `Bearer ${state.token}`
304
305try {
306const response = await fetch(`${API_BASE_URL}/api/locations/${locationId}`, {
307method: 'DELETE',
308headers: {
326// Load alerts
327async function loadAlerts() {
328// This would be an API call to get alerts
329// For now, we'll just use a placeholder
330state.alerts = [];
455
456try {
457const response = await fetch(`${API_BASE_URL}/api/locations`, {
458method: 'POST',
459headers: {
500elements.checkFloodsBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Checking...';
501
502const response = await fetch(`${API_BASE_URL}/api/check-floods`, {
503method: 'POST',
504headers: {