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;
HHGtoMyDaygenerateFunFacts.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
196* @returns Array of parsed facts
197*/
198function parseFallbackFacts(responseText, expectedDates) {
199// Try to extract facts using regex
200const factPattern = /(\d{4}-\d{2}-\d{2})["']?[,:]?\s*["']?(.*?)["']?[,}]/gs;
259260/**
261* Main function to generate and store fun facts for the next 7 days
262*/
263export async function generateAndStoreFunFacts() {
264try {
265// Get previous fun facts
300* Intended to be used as a Val Town cron job
301*/
302export default async function() {
303console.log("Running fun facts generation cron job...");
304return await generateAndStoreFunFacts();
HHGtoMyDaygetWeather.ts5 matches
5const TABLE_NAME = `memories`;
67function summarizeWeather(weather: WeatherResponse) {
8const summarizeDay = (day: WeatherResponse["weather"][number]) => ({
9date: day.date,
21}
2223async function generateConciseWeatherSummary(weatherDay) {
24try {
25// Get API key from environment
79}
8081async function deleteExistingForecast(date: string) {
82await sqlite.execute(
83`
89}
9091async function insertForecast(date: string, forecast: string) {
92const { nanoid } = await import("https://esm.sh/nanoid@5.0.5");
93108}
109110export default async function getWeatherForecast(interval: number) {
111const weather = await getWeather("Boston, MA");
112console.log({ weather });
1// Map Vote Tallying Function with Rate Limit Service Integration
2// This function counts emoji reactions and announces winners in a Hell Let Loose map vote
3import seedrandom from "https://esm.sh/seedrandom";
4import { DiscordRateLimitService } from "https://esm.town/v/ktodaz/Discord_Bot_Services/discord-rate-limit-service.tsx";
4849// Enhanced Discord API request with rate limiting
50async function discordRequest(endpoint: string, options: RequestInit = {}) {
51const token = Deno.env.get("DISCORD_BOT_TOKEN");
52if (!token) {
104105// Get emoji mapping to decode emoji reactions
106function getEmojiMapping() {
107return {
108"๐": "Dawn",
119120// Get color from string
121function getColorFromString(colorName: string): number {
122const colorMap: Record<string, number> = {
123"Red": 0xED4245,
139140// Load configuration
141async function getConfiguration(): Promise<CurrentConfig> {
142try {
143const { success, config, error } = getCurrentConfig();
160161// Load placeholder embed data
162export function getPlaceholderEmbedData(): Promise<PlaceholderEmbedData> {
163return Promise.resolve({
164Title: "The votes are in!",
171172// Load top winners embed data
173export function getTopWinnersEmbedData(): Promise<TopWinnersEmbedData> {
174return Promise.resolve({
175Title: "Announcing The Top {0} Winners!",
182183// Get all messages in a channel with rate limiting
184async function getChannelMessages(channelId: string) {
185try {
186let allMessages = [];
220221// Get reactions for a specific message with rate limiting
222async function getMessageReactions(channelId: string, messageId: string, emoji: string) {
223try {
224const encodedEmoji = encodeURIComponent(emoji);
237238// Get user info from Discord API with rate limiting
239async function getUserInfo(guildId: string, userId: string) {
240try {
241const routeKey = `/guilds/${guildId}/members`;
252253// Send placeholder embed while counting votes
254async function sendPlaceholderEmbed(channelId: string) {
255try {
256const placeholderData = await getPlaceholderEmbedData();
284285// Send winners announcement embed with rate limiting
286async function sendWinnersEmbed(
287channelId: string,
288winners: MapVote[],
339340// Create a thread for full results with rate limiting
341async function createFullResultsThread(channelId: string, allVotes: MapVote[], userVotes: UserVote[]) {
342try {
343const channelRoutKey = `/channels/${channelId}/threads`;
474475// Format processing time
476function formatProcessingTime(startTime: number): string {
477const totalSeconds = Math.floor((Date.now() - startTime) / 1000);
478const minutes = Math.floor(totalSeconds / 60);
487488// Setup required database tables
489async function setupDatabase() {
490// Create vote_sessions table if it doesn't exist
491await sqlite.execute(`
528}
529530// Main voting tallying function
531export default async function(channelId: string) {
532console.log(`๐ข Starting vote tallying for channel ${channelId}`);
533const startTime = Date.now();
594console.log(`Processing: Embed: ${mapName} (${variant}), Reactions: ${reaction.count}`);
595596// Get users who reacted with this emoji - using rate limited function
597const reactedUsers = await getMessageReactions(channelId, msg.id, emoji);
598console.log(`Emote key ${variant}: ${reactedUsers.length} users`);
799}
800801// Function to get previous vote results
802export async function getPreviousVoteResults(limit: number = 5) {
803try {
804await setupDatabase();
synced_reducermain.tsx1 match
1export default async function(req: Request): Promise<Response> {
2const url = new URL(req.url);
3if (url.pathname === "/v1") {
8const CREATION_LOCK_KEY = "map_vote_creation_first_half";
910// Basic Discord request function with rate limiting
11async function safeDiscordRequest(endpoint: string, options: RequestInit = {}) {
12const token = Deno.env.get("DISCORD_BOT_TOKEN");
1343}
4445// Simplified test function that just checks channel access
46async function testChannelAccess(channelId: string) {
47try {
48console.log(`Testing access to channel ${channelId}`);
73}
7475// Main function
76export default async function() {
77console.log("๐งช SIMPLE TEST: Map Vote Tally Channel Access Test");
78
untitled-4783main.js10 matches
1516// --- INITIALIZATION ---
17function init() {
18// Scene
19scene = new THREE.Scene();
77}
7879function addBuilding(x, y, z, width, height, depth, color) {
80const geometry = new THREE.BoxGeometry(width, height, depth);
81const material = new THREE.MeshStandardMaterial({ color: color });
8687// --- GAME LOOP & UPDATES ---
88function animate(currentTime) {
89if (gameOver) {
90scoreElement.innerText = `GAME OVER! Survived: ${Math.floor(gameTime / 1000)}s\nPress R to Restart`;
114let lastFrameTime = 0;
115116function handlePlayerMovement() {
117const moveDirection = new THREE.Vector3();
118const rotationSpeed = playerTurnSpeed;
143}
144145function updateCamera() {
146const offset = new THREE.Vector3(0, 3, -6); // Camera offset from player
147offset.applyQuaternion(player.quaternion); // Apply player's rotation to offset
150}
151152function spawnCars(currentTime) {
153if (currentTime - lastCarSpawnTime > CAR_SPAWN_INTERVAL) {
154lastCarSpawnTime = currentTime;
179}
180181function updateCars() {
182cars.forEach((car, index) => {
183car.position.z += car.userData.directionZ * car.userData.speed;
191}
192193function checkCollisions() {
194const playerBox = new THREE.Box3().setFromObject(player);
195cars.forEach(car => {
204}
205206function restartGame() {
207gameOver = false;
208gameTime = 0;
220221// --- UTILITIES ---
222function onWindowResize() {
223camera.aspect = window.innerWidth / window.innerHeight;
224camera.updateProjectionMatrix();
luciaMagicLinkStartermagic-links.ts3 matches
56// Create a magic link token for the given email
7export async function createMagicLinkToken(userEmail: string): Promise<string> {
8const token = generateSessionToken();
9const now = Math.floor(Date.now() / 1000);
1920// Send a magic link email
21export async function sendMagicLinkEmail(url: string, userEmail: string, token: string): Promise<boolean> {
22try {
23const magicLink = `${url}/auth/magic-link/${token}`;
4748// Validate a magic link token and create a session
49export async function validateMagicLinkToken(token: string): Promise<{ valid: boolean; userId?: number }> {
50const now = Math.floor(Date.now() / 1000);
51