1import {Config} from "./types.ts"
2
3export async function callValTownApi(
4 config: Config,
5 path: string,
7): Promise<any> {
8 // Path conversion for endpoints that have changed in v2
9 let apiPath = path
10
11 // If any old v1 paths are accidentally used, convert them to v2
12 if (path.startsWith("/v1/projects")) {
13 apiPath = path.replace("/v1/projects", "/v2/vals")
14 console.warn(`Converting deprecated v1 path to v2: ${path} → ${apiPath}`)
15 } else if (path.startsWith("/v1/alias/projects")) {
16 apiPath = path.replace("/v1/alias/projects", "/v2/alias/vals")
17 console.warn(`Converting deprecated v1 path to v2: ${path} → ${apiPath}`)
18 }
19
20 const url = `${config.apiBase}${apiPath}`
21
22 if (!config.apiToken) {
23 throw new Error("API token is required for ValTown API calls");
24 }
25
26 const headers: HeadersInit = {
27 'Authorization': `Bearer ${config.apiToken}`,
28 'Content-Type': 'application/json',
29 }
39 if (!response.ok) {
40 const errorText = await response.text()
41 throw new Error(`API error (${response.status}): ${errorText}`)
42 }
43
52 });
53
54 // Send the SMS via Twilio API
55 const twilioResponse = await fetch(
56 `https://api.twilio.com/2010-04-01/Accounts/${sid}/Messages.json`,
57 {
58 method: "POST",
67 if (!twilioResponse.ok) {
68 const errorText = await twilioResponse.text();
69 console.error("Twilio API error:", twilioResponse.status, errorText);
70 return new Response(`Twilio error: ${errorText}`, { status: 500 });
71 }
27 <head>
28 <title>SQLite Explorer</title>
29 <link rel="preconnect" href="https://fonts.googleapis.com" />
30
31 <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
32 <link
33 href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@300..700&family=Source+Sans+3:ital,wght@0,200..900;1,200..900&display=swap"
34 rel="stylesheet"
35 />
13## Authentication
14
15Login to your SQLite Explorer with [password authentication](https://www.val.town/v/pomdtr/password_auth) with your [Val Town API Token](https://www.val.town/settings/api) as the password.
16
17## Todos / Plans
9To use it on your own Val Town SQLite database, [fork it](https://www.val.town/v/stevekrouse/sqlite_admin/fork) to your account.
10
11It uses [basic authentication](https://www.val.town/v/pomdtr/basicAuth) with your [Val Town API Token](https://www.val.town/settings/api) as the password (leave the username field blank).
12
13Migrated from folder: utils/sqlite_admin/sqlite_admin
18app.get("/shared/**/*", (c) => serveFile(c.req.path, import.meta.url));
19
20// API endpoints
21app.get("/api/messages", async (c) => {
22 const messages = await getMessages();
23 return c.json(messages);
24});
25
26app.post("/api/messages", async (c) => {
27 const { content } = await c.req.json();
28
38```
39
40## API Endpoints
41
42- `GET /` - Serves the React application with initial data
43- `GET /api/messages` - Fetch all messages (JSON)
44- `POST /api/messages` - Create a new message
45- `GET /public/**` - Static assets (CSS, JS, etc.)
46- `/*` - All other routes handled by TanStack Router
8## Hono
9
10This app uses [Hono](https://hono.dev/) as the API framework. You can think of Hono as a replacement for [ExpressJS](https://expressjs.com/) that works in serverless environments like Val Town or Cloudflare Workers. If you come from Python or Ruby, Hono is also a lot like [Flask](https://github.com/pallets/flask) or [Sinatra](https://github.com/sinatra/sinatra), respectively.
11
12## Serving assets to the frontend
20### `index.html`
21
22The most complicated part of this backend API is serving index.html. In this app (like most apps) we serve it at the root, ie `GET /`.
23
24We *bootstrap* `index.html` with some initial data from the server, so that it gets dynamically injected JSON data without having to make another round-trip request to the server to get that data on the frontend. This is a common pattern for client-side rendered apps.
25
26## CRUD API Routes
27
28This app has two CRUD API routes: for reading and inserting into the messages table. They both speak JSON, which is standard. They import their functions from `/backend/database/queries.ts`. These routes are called from the React app to refresh and update data.
29
30## Errors
31
32Hono and other API frameworks have a habit of swallowing up Errors. We turn off this default behavior by re-throwing errors, because we think most of the time you'll want to see the full stack trace instead of merely "Internal Server Error". You can customize how you want errors to appear.
7 queryKey: ["messages"],
8 queryFn: async () => {
9 const response = await fetch("/api/messages");
10 if (!response.ok) {
11 throw new Error("Failed to fetch messages");
25 return useMutation({
26 mutationFn: async (content: string) => {
27 const response = await fetch("/api/messages", {
28 method: "POST",
29 headers: { "Content-Type": "application/json" },
73<script>
74(function() {
75 const API_URL = '${sourceUrl}';
76 const STORE_KEYS = { projects: 'aura_projects_v1', tasks: 'aura_tasks_v1' };
77 const ACTIVE_TASK_WARNING_THRESHOLD = 50;
253 addMessageToChat('ai', 'Aura is thinking...');
254 try {
255 const res = await fetch(\`\${API_URL}?action=chat\`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: userMessage, tasks, projects, history: conversationHistory.slice(-4) }) });
256 if (!res.ok) {
257 const err = await res.json();
284 toggleLoading(btn, true);
285 try {
286 const res = await fetch(\`\${API_URL}?action=synthesizeProject\`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ goal }) });
287 if (!res.ok) {
288 const err = await res.json();
317 toggleLoading(btn, true);
318 try {
319 const res = await fetch(\`\${API_URL}?action=getDailyReschedule\`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ tasks: todayTasks }) });
320 if (!res.ok) {
321 const err = await res.json();