107export type FirecrawlMapInput = z.infer<typeof FirecrawlMapInputSchema>;
108109function getApiKey(): string {
110const key = Deno.env.get("FIRECRAWL_API_KEY") || "";
111if (!key) {
115}
116117function getFirecrawlClient(): FirecrawlApp {
118const apiKey = getApiKey();
119return new FirecrawlApp({ apiKey });
124* Handles single page scraping with all supported options.
125*/
126export async function fetchFromFirecrawlAPI(
127input: ScraperInput,
128): Promise<unknown> {
173* Maps all URLs from a website using Firecrawl's dedicated map endpoint.
174*/
175export async function performFirecrawlMap(
176input: FirecrawlMapInput,
177): Promise<unknown> {
184185// Check if FirecrawlApp has a map method
186if ("mapUrl" in firecrawl && typeof firecrawl.mapUrl === "function") {
187// Use the SDK's map method if available
188return await firecrawl.mapUrl(input.url, {
12import { exchangeToken, getCsrfToken, getCurrentUser, logout } from "../handlers/authService.ts";
1314// Documentation services - Updated to use handler functions
15import { getOpenAPIJSON, getOpenAPIYAML } from "../handlers/openapiService.ts";
16import { getSwaggerUI } from "../handlers/swaggerService.ts";
49// import { hashData } from '@/handlers/hash.service.ts';
5051// // --- Helper function to get error messages ---
52// function getErrorMessage(error: unknown): string {
53// if (error instanceof Error) return error.message;
54// if (typeof error === 'string') return error;
6768// --- Service Router Creation ---
69export function createServiceRouter(): ServiceRouter {
70const router: ServiceRouter = {
71// === Core Auth Handlers ===
83handleSpotifyCallback,
8485// === Documentation Handlers - Now using imported functions ===
86getOpenAPIJSON,
87getOpenAPIYAML,
226}
227228// --- Utility functions for the router ---
229export function getServiceHandler(
230operationId: string,
231router: ServiceRouter,
234}
235236export function listOperations(router: ServiceRouter): string[] {
237return Object.keys(router);
238}
api_ianmenethil_comsecurityConfig.ts5 matches
175176// ============================================================================
177// HELPER FUNCTIONS
178// ============================================================================
179181* Check if IP is whitelisted
182*/
183export function isIpWhitelisted(ip: string): boolean {
184return IP_WHITELIST.includes(ip);
185}
188* Get rate limit for specific endpoint
189*/
190export function getEndpointRateLimit(path: string) {
191const endpoints = RATE_LIMIT_CONFIG.endpoints as Record<
192string,
202* Check if country is allowed
203*/
204export function isCountryAllowed(country: string): boolean {
205if (!GEOFENCING_CONFIG.enabled) return true;
206219* Check if scheme is blocked
220*/
221export function isSchemeBlocked(url: string): boolean {
222return PATH_SECURITY_CONFIG.blockedSchemes.some((scheme) => url.toLowerCase().startsWith(scheme));
223}
api_ianmenethil_comheaderConfig.ts6 matches
9394// ============================================================================
95// HELPER FUNCTIONS
96// ============================================================================
9799* Build CSP header string from config
100*/
101export function buildCSPHeader(config: CSPConfig = CSP_CONFIG): string {
102if (!config.enabled) return "";
103130* Get CSP header value for current environment
131*/
132export function getCSPHeaderValue(): string {
133return buildCSPHeader(CSP_CONFIG);
134}
214215// ============================================================================
216// ADDITIONAL HELPER FUNCTIONS
217// ============================================================================
218220* Get all security headers
221*/
222export function getSecurityHeaders(): Record<string, string> {
223return { ...SECURITY_HEADERS_CONFIG };
224}
227* Update security header dynamically
228*/
229export function updateSecurityHeader(header: string, value: string): void {
230SECURITY_HEADERS_CONFIG[header] = value;
231if (
api_ianmenethil_comcontrollerRegistry.ts11 matches
78/**
9* Handler function signature for all API endpoints
10*/
11export type HandlerFunction = (c: Context) => Promise<Response> | Response;
1213/**
89/**
90* Dynamic handler resolver
91* Resolves x-controller and x-method to actual handler functions
92*/
93export class HandlerResolver {
94private static handlerCache = new Map<string, HandlerFunction>();
9596/**
101method: string,
102operationId: string,
103): Promise<HandlerFunction> {
104const cacheKey = `${controller}.${method}`;
105129const module = await import(controllerConfig.module);
130131// Get the handler function
132const handlerFunction = module[handlerName];
133if (!handlerFunction || typeof handlerFunction !== "function") {
134throw new Error(
135`Handler function '${handlerName}' not found or not a function in module '${controllerConfig.module}'`,
136);
137}
138139// Cache the resolved handler
140this.handlerCache.set(cacheKey, handlerFunction);
141142return handlerFunction;
143} catch (error) {
144throw new Error(
api_ianmenethil_comauthConfig.ts5 matches
259260// ============================================================================
261// HELPER FUNCTIONS
262// ============================================================================
263265* Check if a specific auth method is enabled
266*/
267export function isAuthMethodEnabled(method: keyof typeof AUTH_METHODS_CONFIG): boolean {
268return AUTH_METHODS_CONFIG[method]?.enabled ?? false;
269}
272* Get OAuth provider configuration
273*/
274export function getOAuthProvider(provider: keyof typeof OAUTH_PROVIDERS_CONFIG.providers) {
275const config = OAUTH_PROVIDERS_CONFIG.providers[provider];
276if (!config?.ENABLED) {
283* Check if user has required permission
284*/
285export function userHasPermission(userPermissions: string[], requiredPermission: string): boolean {
286return userPermissions.includes(requiredPermission) ||
287userPermissions.includes(AUTHORIZATION_CONFIG.adminPermission);
291* Get CSRF exempt paths
292*/
293export function isCsrfExempt(path: string): boolean {
294return CSRF_CONFIG.exempt.some((exempt) => {
295if (exempt.endsWith("*")) {
18export type Permission = BasePermission | string;
1920export function isBasePermission(permission: string): permission is BasePermission {
21return ["read", "write", "delete", "admin"].includes(permission);
22}
171export const SERVER = APP_CONFIG.server;
172173export function getConfig<T = unknown>(path: string): T {
174const keys = path.split(".");
175let current: any = APP_CONFIG;
Studybeaststudybeast.tsx6 matches
136];
137138function LoginTimer({ loginTime, onExpire }: { loginTime: number; onExpire: () => void }) {
139const [timeLeft, setTimeLeft] = useState(0);
140const [progressPercent, setProgressPercent] = useState(100);
187}
188189function LoginPage({ onLogin }: { onLogin: (username: string) => void }) {
190const [username, setUsername] = useState("");
191const [password, setPassword] = useState("");
277}
278279function CourseCard({ course }: { course: Course }) {
280return (
281<div className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow">
319}
320321function App() {
322const [searchTerm, setSearchTerm] = useState("");
323const [isLoggedIn, setIsLoggedIn] = useState(false);
478}
479480function client() {
481createRoot(document.getElementById("root")).render(<App />);
482}
483if (typeof document !== "undefined") { client(); }
484485export default async function server(request: Request): Promise<Response> {
486return new Response(
487`
hm-invoicesv1val-town.mdc17 matches
910- Ask clarifying questions when requirements are ambiguous
11- Provide complete, functional solutions rather than skeleton implementations
12- Test your logic against edge cases before presenting the final solution
13- Ensure all code follows Val Town's specific platform requirements
22- **Never bake in secrets into the code** - always use environment variables
23- Include comments explaining complex logic (avoid commenting obvious operations)
24- Follow modern ES6+ conventions and functional programming practices if possible
2526## Types of triggers
3334```ts
35export default async function (req: Request) {
36return new Response("Hello World");
37}
43## Val Town Standard Libraries
4445Val Town provides several hosted services and utility functions.
4647### Blob Storage
85```
8687## Val Town Utility Functions
8889Val Town provides several utility functions to help with common project tasks.
9091### Importing Utilities
168โโโ backend/
169โ โโโ database/
170โ โ โโโ queries.ts # DB query functions (CRUD operations)
171โ โ โโโ README.md
172โ โโโ routes/ # Route modules
188โโโ README.md
189โโโ config.ts # Database table names and shared config
190โโโ utils.ts # Shared types and functions
191```
192267268<script>
269function showResult(data, isError = false) {
270const resultDiv = document.getElementById('result');
271resultDiv.className = \`mt-6 p-4 rounded-lg \${isError ? 'bg-red-100 border border-red-300 text-red-800' : 'bg-green-100 border border-green-300 text-green-800'}\`;
274}
275276async function makeRequest(action) {
277try {
278const response = await fetch(\`?action=\${action}\`, { method: 'POST' });
284}
285286function getStatus() {
287makeRequest('status');
288}
289290function seedDatabase() {
291makeRequest('seed');
292}
293294function forceSeed() {
295makeRequest('force-seed');
296}
297298function clearDatabase() {
299if (confirm('Are you sure you want to clear all data from the database?')) {
300makeRequest('clear');
379- Main entry point should be `main.tsx`
380- **Database Setup:** Use the admin utilities to handle table creation and seeding. Backend should focus on CRUD operations only
381- **Database Queries:** Keep all query functions in `backend/database/queries.ts` with proper TypeScript typing
382- **Static asset serving:** Use the utility functions to read and serve project files:
383```ts
384import { readFile, serveFile } from "https://esm.town/v/std/utils@85-main/index.ts";
417- **Backend Focus:** Backend database queries should only handle CRUD operations, not table creation
418- Change table names when modifying schemas rather than altering (update in `shared/config.ts`)
419- Export clear query functions with proper TypeScript typing
420421## Common Gotchas and Solutions