stevensDemogetWeather.ts5 matches
8const TABLE_NAME = `memories`;
910function summarizeWeather(weather: WeatherResponse) {
11const summarizeDay = (day: WeatherResponse["weather"][number]) => ({
12date: day.date,
25}
2627async function generateConciseWeatherSummary(weatherDay) {
28try {
29// Get API key from environment
83}
8485async function deleteExistingForecast(date: string) {
86await sqlite.execute(
87`
93}
9495async function insertForecast(date: string, forecast: string) {
96const { nanoid } = await import("https://esm.sh/nanoid@5.0.5");
97112}
113114export default async function getWeatherForecast(interval: number) {
115const weather = await getWeather("Washington, DC");
116console.log({ weather });
stevensDemogetCalendarEvents.ts6 matches
6const LOCAL_TIMEZONE = "America/New_York";
78async function deleteExistingCalendarEvents() {
9await sqlite.execute(
10`
15}
1617// Helper function to extract time from ISO string without timezone conversion
18function extractTimeFromISO(isoString) {
19// Match the time portion of the ISO string
20const timeMatch = isoString.match(/T(\d{2}):(\d{2}):/);
31}
3233function formatEventToNaturalLanguage(event) {
34const summary = event.summary || "Untitled event";
3583}
8485async function insertCalendarEvent(date, eventText) {
86const { nanoid } = await import("https://esm.sh/nanoid@5.0.5");
8797}
9899export default async function getCalendarEvents() {
100try {
101const events = await getEvents(
stevensDemogenerateFunFacts.ts8 matches
11* @returns Array of previous fun facts
12*/
13async function getPreviousFunFacts() {
14try {
15const result = await sqlite.execute(
32* @param dates Array of date strings in ISO format
33*/
34async function deleteExistingFunFacts(dates) {
35try {
36for (const date of dates) {
51* @param factText The fun fact text
52*/
53async function insertFunFact(date, factText) {
54try {
55await sqlite.execute(
75* @returns Array of generated fun facts
76*/
77async function generateFunFacts(previousFacts) {
78try {
79// Get API key from environment
197* @returns Array of parsed facts
198*/
199function parseFallbackFacts(responseText, expectedDates) {
200// Try to extract facts using regex
201const factPattern = /(\d{4}-\d{2}-\d{2})["']?[,:]?\s*["']?(.*?)["']?[,}]/gs;
260261/**
262* Main function to generate and store fun facts for the next 7 days
263*/
264export async function generateAndStoreFunFacts() {
265try {
266// Get previous fun facts
301* Intended to be used as a Val Town cron job
302*/
303export default async function() {
304console.log("Running fun facts generation cron job...");
305return await generateAndStoreFunFacts();
stevensDemo.cursorrules15 matches
8### 1. Script Vals
910- Basic JavaScript/TypeScript functions
11- Can be imported by other vals
12- Example structure:
1314```typescript
15export function myFunction() {
16// Your code here
17}
2526```typescript
27export default async function (req: Request) {
28return new Response("Hello World");
29}
3738```typescript
39export default async function () {
40// Scheduled task code
41}
4950```typescript
51export default async function (email: Email) {
52// Process email
53}
5758- Ask clarifying questions when requirements are ambiguous
59- Provide complete, functional solutions rather than skeleton implementations
60- Test your logic against edge cases before presenting the final solution
61- Ensure all code follows Val Town's specific platform requirements
70- **Never bake in secrets into the code** - always use environment variables
71- Include comments explaining complex logic (avoid commenting obvious operations)
72- Follow modern ES6+ conventions and functional programming practices if possible
7374## Val Town Standard Libraries
7576Val Town provides several hosted services and utility functions.
7778### Blob Storage
124```
125126## Val Town Utility Functions
127128Val Town provides several utility functions to help with common project tasks.
129130### Importing Utilities
176{
177name: "should add numbers correctly",
178function: () => {
179expect(1 + 1).toBe(2);
180},
210│ ├── database/
211│ │ ├── migrations.ts # Schema definitions
212│ │ ├── queries.ts # DB query functions
213│ │ └── README.md
214│ ├── index.ts # Main entry point
226└── shared/
227├── README.md
228└── utils.ts # Shared types and functions
229```
230232- 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:
235```ts
236// Use the serveFile utility to handle content types automatically
273- Run migrations on startup or comment out for performance
274- Change table names when modifying schemas rather than altering
275- Export clear query functions with proper TypeScript typing
276- Follow the queries and migrations pattern from the example
277
stevensDemocronDailyBrief.ts1 match
1import { sendDailyBriefing } from "./sendDailyBrief.ts";
23export async function cronDailyBrief() {
4try {
5const chatId = Deno.env.get("TELEGRAM_CHAT_ID");
stevensDemoApp.tsx2 matches
62};
6364export function App() {
65const [memories, setMemories] = useState<Memory[]>([]);
66const [loading, setLoading] = useState(true);
139const data = await response.json();
140141// Change the sorting function to show memories in chronological order
142const sortedMemories = [...data].sort((a, b) => {
143const dateA = a.createdDate || 0;
TodoistTesttoday_and_overdue.tsx3 matches
3import React, { useEffect, useState } from "https://esm.sh/react@18.2.0";
45function App() {
6const [tasks, setTasks] = useState<any[]>([]);
7const [loading, setLoading] = useState(false);
114}
115116function client() {
117createRoot(document.getElementById("root")).render(<App />);
118}
119if (typeof document !== "undefined") { client(); }
120121export default async function server(request: Request): Promise<Response> {
122// Todoist API endpoint
123const TODOIST_API_BASE = "https://api.todoist.com/rest/v2";
untitled-2512new-file-9861.tsx13 matches
7475// --- HTML Generation for UI (with Glassmorphic Styling and Upload Form) ---
76function generateViewerHtml(tagsData: StoredTag[], dbError?: string): string {
77const tagsJson = JSON.stringify(tagsData);
78const sourceUrl = import.meta.url.replace("esm.town", "val.town");
373const sourceApiUrl = "${sourceUrl}"; // For form submission
374375Â Â Â Â function escapeHtml(unsafe) {
376Â Â Â Â Â Â if (unsafe === null || typeof unsafe === 'undefined') return '';
377Â Â Â Â Â Â return unsafe
384Â Â Â Â }
385386Â Â Â Â function renderTable(filteredData) {
387Â Â Â Â Â Â const container = document.getElementById('tagsTableContainer');
388Â Â Â Â Â Â if (!container) return;
406Â Â Â Â }
407408Â Â Â Â function renderTagsByDocument(data) {
409Â Â Â Â Â Â const container = document.getElementById('tagsByDocumentContainer');
410Â Â Â Â Â Â if (!container) return;
474475Â Â Â Â Â Â if (uploadForm && uploadStatusDiv) {
476Â Â Â Â Â Â Â uploadForm.addEventListener('submit', async function(event) {
477Â Â Â Â Â Â Â Â Â event.preventDefault();
478Â Â Â Â Â Â Â Â Â uploadStatusDiv.style.display = 'block';
552}
553554// --- SQLite Helper Functions (Refactored) ---
555// ... (ensureTableExists and storeTags remain the same)
556async function ensureTableExists(log: LogEntry[]) {
557const agent = "SQLite Agent";
558try {
575}
576577async function storeTags(documentIdentifier: string, tags: string[], log: LogEntry[]) {
578const agent = "SQLite Agent";
579if (!tags || tags.length === 0) {
623624// --- Main Val Export ---
625export default async function(req: Request) {
626// --- Dynamic Imports (Inside Handler for Val Town) ---
627const { OpenAI } = await import("https://esm.town/v/std/openai");
631632// ---Extract Text using pdf.js-extract ---
633async function extractPdfTextNative(data: ArrayBuffer, fileName: string, log: LogEntry[]): Promise<string | null> {
634const agent = "PDF Extraction Agent";
635log.push({ agent, type: "step", message: `Processing PDF: ${fileName}...` });
653}
654655// --- Helper Function: Call OpenAI API ---
656async function callOpenAI(
657openai: OpenAI,
658systemPrompt: string,
690691// --- Main Agent Flow Logic ---
692async function runExtractionWorkflow(
693input: { documentUrl?: string; documentText?: string; documentFile?: File },
694log: LogEntry[],
Townieschema.tsx2 matches
21}
2223async function createTables() {
24// archive a table
25// await sqlite.execute(
51}
5253async function deleteTables() {
54await sqlite.execute(`DROP TABLE IF EXISTS ${USAGE_TABLE}`);
55}
EEPMOnitoringnewsArticle.tsx5 matches
428429// Main Component for the News Article Tab - Adapted to use inline styles and MediaMonitoringTab patterns
430export function NewsArticleTab({ user }) {
431const [articles, setArticles] = useState([]);
432const [title, setTitle] = useState("");
601};
602603// Function to open the edit modal - Similar pattern to MediaMonitoringTab
604const handleEditClick = (article) => {
605// Assuming article properties match backend column names (e.g., main_idea)
617};
618619// Function to close the edit modal - Similar pattern to MediaMonitoringTab
620const handleCloseEditModal = () => {
621setIsEditModalOpen(false);
631};
632633// Function to handle changes in the edit modal form - Similar pattern to MediaMonitoringTab
634const handleEditFormChange = (e) => {
635const { name, value } = e.target;
640};
641642// Function to save the edited entry - Similar pattern to MediaMonitoringTab
643const handleSaveEdit = async () => {
644// Validate required fields from editFormData