tinycanvasmain.ts2 matches
1314*/
15const handler = async function(req) {
16const req_url = new URL(req.url);
17if (req_url.pathname == "/") {
79`, { status: 404, statusText: "Not found.", headers: { "Content-Type": "text/html", }})
80}
81export default async function (req: Request): Promise<Response> {
82try {
83return await handler(req);
1export default function () {
2const body = `<!doctype html>
3<html lang="en">
9697/************************************************************************
98* State: raw variables & functions, and evaluated variables
99************************************************************************/
100const rawVars = new Map(); // name -> rhs string (raw)
101const functions = new Map(); // name -> { params: [], body: "..." }
102const computedVars = new Map(); // name -> evaluated value (primitive, array, string, etc)
103105* Helpers
106************************************************************************/
107function isQuotedString(s) {
108return (s.length >= 2) && ((s[0] === '"' && s[s.length-1] === '"') || (s[0] === "'" && s[s.length-1] === "'"));
109}
110111function toObj(map) {
112const o = Object.create(null);
113for (const [k,v] of map.entries()) o[k] = v;
117// Evaluate an expression string in a sandbox that includes:
118// - current computedVars
119// - user functions (as JS functions that evaluate their bodies with the same sandbox + parameters)
120// - builtins
121function evalWithScope(expr) {
122// Build base scope
123const scope = Object.assign({}, builtins, toObj(computedVars));
124// attach user functions into scope as callables
125for (const [name, def] of functions.entries()) {
126scope[name] = (...args) => {
127// local scope that includes current computedVars and builtins, plus params
130try {
131// Use with(scope) { return (body) } to allow body to reference names
132return Function('scope', 'with(scope){ return (' + def.body + ') }')(local);
133} catch (e) {
134// propagate error
140// Now evaluate expression in the scope
141try {
142return Function('scope', 'with(scope){ return (' + expr + ') }')(scope);
143} catch (e) {
144throw e;
148/************************************************************************
149* Parse the document top-down:
150* - function defs f(a,b)=...
151* - variable defs name = rhs (rhs may be quoted string OR an expression)
152*
153* We evaluate variables in document order so earlier defs are available to later ones.
154************************************************************************/
155function parseDocument(doc) {
156rawVars.clear();
157functions.clear();
158computedVars.clear();
159163if (!line) continue;
164165// function: name(arg1, arg2) = body
166const fm = line.match(/^([A-Za-z_][\\w]*)\\s*\\(([^)]*)\\)\\s*=\\s*(.+)$/);
167if (fm) {
169const params = fm[2].split(',').map(s=>s.trim()).filter(Boolean);
170const body = fm[3].trim();
171functions.set(name, { params, body });
172continue;
173}
180rawVars.set(name, rhs);
181182// attempt to evaluate using current environment (earlier vars + functions)
183try {
184let value;
275}, { decorations: v => v.decorations });
276277function stringifyValue(v) {
278if (v === null || v === undefined) return String(v);
279if (typeof v === 'number') {
location-feed-generatorcheckins.ts10 matches
19* Convert API PlaceInput to proper Place object
20*/
21function _sanitizePlaceInput(input: PlaceInput): Place {
22const latitude = typeof input.latitude === "string"
23? parseFloat(input.latitude)
52}
5354async function _getEnhancedAddressRecord(
55place: Place,
56): Promise<CommunityAddressRecord> {
139}
140141// Helper function to authenticate user with Iron Session (both web and mobile)
142async function authenticateUser(
143c: Context,
144): Promise<{ did: string; oauthSession: any } | null> {
207208// Create a checkin with address using StrongRef architecture
209export async function createCheckin(c: Context): Promise<Response> {
210try {
211// Authenticate user with Iron Session
289}
290291// Helper function to extract rkey from AT Protocol URI
292function extractRkey(uri: string): string {
293const parts = uri.split("/");
294return parts[parts.length - 1];
296297// Create address and checkin records via AT Protocol using clean OAuth API
298async function createAddressAndCheckin(
299sessions: OAuthSessionsInterface,
300did: string,
466}
467468// Simple function to get a checkin by ID for frontend routes
469export async function getCheckinById(checkinId: string) {
470try {
471const results = await db.select().from(checkinsTable)
279let timerInterval;
280281function startTimer() {
282startTime = Date.now();
283timerInterval = setInterval(updateTimer, 10);
284}
285286function stopTimer() {
287clearInterval(timerInterval);
288const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(2);
291}
292293function updateTimer() {
294const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(2);
295timerDisplay.textContent = elapsedTime + 's';
296}
297298function updateStats(text) {
299const encoder = new TextEncoder();
300const utf8 = new Uint8Array(text.length * 3);
339}
340341function adjustInputTextareaHeight() {
342inputText.style.height = 'auto';
343inputText.style.height = inputText.scrollHeight + 10 + 'px';
350351352async function updateHistoryList() {
353const history = await db.history.reverse().limit(50).toArray();
354historyList.innerHTML = history.map(item =>
386});
387388// Accordion functionality
389document.querySelectorAll('[id^="accordion-"]').forEach(button => {
390button.addEventListener('click', () => {
zoomtest.cursorrules12 matches
45- Ask clarifying questions when requirements are ambiguous
6- Provide complete, functional solutions rather than skeleton implementations
7- Test your logic against edge cases before presenting the final solution
8- Ensure all code follows Val Town's specific platform requirements
17- **Never bake in secrets into the code** - always use environment variables
18- Include comments explaining complex logic (avoid commenting obvious operations)
19- Follow modern ES6+ conventions and functional programming practices if possible
2021## Types of triggers
2829```ts
30export default async function (req: Request) {
31return new Response("Hello World");
32}
4243```ts
44export default async function () {
45// Scheduled task code
46}
5657```ts
58export default async function (email: Email) {
59// Process email
60}
66## Val Town Standard Libraries
6768Val Town provides several hosted services and utility functions.
6970### Blob Storage
120```
121122## Val Town Utility Functions
123124Val Town provides several utility functions to help with common project tasks.
125126### Importing Utilities
200โ โโโ database/
201โ โ โโโ migrations.ts # Schema definitions
202โ โ โโโ queries.ts # DB query functions
203โ โ โโโ README.md
204โ โโโ routes/ # Route modules
219โโโ shared/
220โโโ README.md
221โโโ utils.ts # Shared types and functions
222```
223226- 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:
229```ts
230import { readFile, serveFile } from "https://esm.town/v/std/utils@85-main/index.ts";
260- Run migrations on startup or comment out for performance
261- Change table names when modifying schemas rather than altering
262- Export clear query functions with proper TypeScript typing
263264## Common Gotchas and Solutions
flowxo-http-bot-samplebot.ts1 match
51});
5253function sendToWorkvivo(message: any, channel: string) {
54const payload = {
55bot_userid: BOT_USER_ID,
chatterchatStream.js3 matches
5import { serverApiKey } from "../config.js";
67function collectToolTextFromArray(toolArray) {
8if (!Array.isArray(toolArray)) return '';
9const parts = [];
10for (const t of toolArray) {
11try {
12const name = t?.name || t?.tool || t?.function?.name || t?.id || '';
13const args = t?.arguments || t?.input || t?.params || null;
14const output = t?.output || t?.result || t?.content || null;
23}
2425export function registerChatStreamRoute(app) {
26app.post('/api/chatStream', async (c) => {
27try {
25let jobCounter = 0;
2627function now() { return Date.now(); }
2829function newJobId() {
30jobCounter += 1;
31return String(now()) + "-" + String(jobCounter);
32}
3334function createJob(type, input) {
35const id = newJobId();
36const job = {
52}
5354function getJob(id) { return jobs.get(String(id)); }
5556function publish(job, eventName, payload) {
57const encoder = new TextEncoder();
58const data = (payload === undefined) ? "" : JSON.stringify(payload);
63}
6465function completeJob(job, result) {
66job.status = "completed";
67job.updatedAt = now();
73}
7475function failJob(job, message) {
76job.status = "error";
77job.updatedAt = now();
82}
8384function cancelJob(job) {
85try { job.abortController && job.abortController.abort(); } catch (_) { /* ignore */ }
86job.status = "cancelled";
91}
9293async function runChatJob(job) {
94const input = job.input || {};
95const {
282}
283284function tryParseJson(s) {
285try { return JSON.parse(s); } catch (_) { return { raw: s }; }
286}
287288function collectToolTextFromArray(toolArray) {
289if (!Array.isArray(toolArray)) return '';
290const parts = [];
291for (const t of toolArray) {
292try {
293const name = t?.name || t?.tool || t?.function?.name || t?.id || '';
294const args = t?.arguments || t?.input || t?.params || null;
295const output = t?.output || t?.result || t?.content || null;
304}
305306export function registerJobsRoutes(app) {
307// Create job
308app.post('/api/jobs', async (c) => {
chatterchatCompletion.js6 matches
1// Minimal Groq Chat Completions client using fetch
2import { extractOrRepairJsonResults, extractStructuredSummary, renderStructuredSummaryToHtml } from "./jsonUtils.js";
3export async function groqChatCompletion(apiKey, payload) {
4console.log('>>> [groqChatCompletion] Payload:', payload);
5const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
22// extractOrRepairJsonResults moved to ./jsonUtils.js
2324export function buildSearchPrompt(query, source, dateRange, language, offset) {
25// Always search in English; present in the selected language
26const presentationLanguage = (typeof language === 'string' && language.trim()) ? language : 'english';
5051// Lightweight router: decide between 'links' (JSON list) and 'text' (short answer)
52export async function routeQueryMode(apiKey, query) {
53// Routing disabled: force plain chat mode
54return 'text';
77}
7879export async function performSearch({ apiKey, query, dateRange, source, language, offset = 0, model, stream, reasoningEffort, forceLinksRoute = false }) {
80// const prompt = buildSearchPrompt(query, source, dateRange, language, offset);
81// const start = Date.now();
128import { marked } from "npm:marked";
129130function buildSummaryPrompt(url, title, language) {
131const languageInstruction = language && language !== 'english'
132? `Please provide the summary in ${language}. `
167}
168169export async function summarizeUrl({ apiKey, url, title, language, model, stream, reasoningEffort }) {
170const summaryPrompt = buildSummaryPrompt(url, title, language);
171const start = Date.now();
chatterchatStreamSSE.js3 matches
4import { serverApiKey } from "../config.js";
56function collectToolTextFromArray(toolArray) {
7if (!Array.isArray(toolArray)) return '';
8const parts = [];
9for (const t of toolArray) {
10try {
11const name = t?.name || t?.tool || t?.function?.name || t?.id || '';
12const args = t?.arguments || t?.input || t?.params || null;
13const output = t?.output || t?.result || t?.content || null;
22}
2324export function registerChatStreamSSERoute(app) {
25app.post('/api/chatStreamSSE', async (c) => {
26try {