Function bodies 22 total
car function · typescript · L31-L50 (20 LOC)src/endpoints/car.ts
async function car(
request: Request,
params: Record<string, string>,
): Promise<Response> {
const serverResponse = await fetch("https://island.is/api/graphql", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
operationName: "publicVehicleSearch",
variables: { input: { search: params.number } },
query: VEHICLE_SEARCH_QUERY,
}),
});
const json = await serverResponse.json();
const url = new URL(request.url);
return response(
json.data.publicVehicleSearch,
url.searchParams.get("pretty") === "true",
);
}gengi function · typescript · L27-L64 (38 LOC)src/endpoints/gengi.ts
async function gengi(
_request: Request,
params: Record<string, string>,
): Promise<Response> {
const response = await fetch(
"https://www.borgun.is/currency/Default.aspx?function=all",
);
const text = await response.text();
const json = xml2js(text, { compact: true }) as unknown as BorgunRates;
const currencies: Record<string, Currency> = {};
for (const rate of json["Rates"]["Rate"]) {
const code = rate["CurrencyCode"]["_text"];
const description = rate["CurrencyDescription"]?.["_text"]?.split(",")
?.reverse()?.join(" ").trim();
currencies[code] = {
rate: parseFloat(rate["CurrencyRate"]["_text"]),
};
if (description) {
currencies[code].description = capitalizeFirstLetter(description);
}
}
let data = currencies;
if (params.code) {
const codes = params.code.split(",");
const filteredCodes = Object.entries(currencies).filter(([code]) =>
codes.includes(code)
);
data = Object.fromEntries(filteredCodmeetups function · typescript · L5-L23 (19 LOC)src/endpoints/meetups.ts
function meetups(
request: Request,
): Response {
const url = new URL(request.url);
const format = url.searchParams.get("format");
// Return RSS feed if format=rss
if (format === "rss") {
return new Response(generateRSS(meetupData), {
headers: {
"Content-Type": "application/rss+xml; charset=utf-8",
"Access-Control-Allow-Origin": "*",
},
});
}
// Default JSON response
return response(meetupData, url.searchParams.get("pretty") === "true");
}meta function · typescript · L4-L13 (10 LOC)src/endpoints/meta.ts
export default function meta(router: Router) {
return function (
request: Request,
_params: Record<string, string>,
): Response {
const endpoints = router.getEndpoints();
const url = new URL(request.url);
return response({ endpoints }, url.searchParams.get("pretty") === "true");
};
}isGreyColor function · typescript · L17-L24 (8 LOC)src/endpoints/nova-2f1.ts
function isGreyColor(hex: string): boolean {
const m = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
if (!m) return false;
const r = parseInt(m[1], 16);
const g = parseInt(m[2], 16);
const b = parseInt(m[3], 16);
return Math.max(r, g, b) - Math.min(r, g, b) < 30;
}findInactiveDayClasses function · typescript · L35-L96 (62 LOC)src/endpoints/nova-2f1.ts
async function findInactiveDayClasses(
doc: ReturnType<InstanceType<typeof DOMParser>["parseFromString"]>,
): Promise<Set<string>> {
const classCounts = new Map<string, number>();
let total = 0;
for (const span of doc!.querySelectorAll("span")) {
if (!DAY_NAMES.includes(span.textContent!.trim())) continue;
const parent = span.parentElement;
if (!parent) continue;
total++;
for (
const cls of (parent.getAttribute("class") || "").split(/\s+/).filter(
Boolean,
)
) {
classCounts.set(cls, (classCounts.get(cls) || 0) + 1);
}
}
if (total === 0) return new Set();
// Variant classes appear on some but not all day parent elements
const variantClasses = new Set<string>();
for (const [cls, count] of classCounts) {
if (count < total) variantClasses.add(cls);
}
// Need at least two variants (active + inactive) to distinguish
if (variantClasses.size < 2) return new Set();
// Fetch CSS stylesheets to determine whicnova2f1 function · typescript · L98-L170 (73 LOC)src/endpoints/nova-2f1.ts
async function nova2f1(request: Request): Promise<Response> {
const res = await fetch("https://www.nova.is/dansgolfid/fyrir-thig/2f1");
const html = await res.text();
const doc = new DOMParser().parseFromString(html, "text/html")!;
const inactiveDayClasses = await findInactiveDayClasses(doc);
const offers: Offer[] = [];
const links = doc.querySelectorAll('a[href^="/dansgolfid/fyrir-thig/2f1/"]');
for (const link of links) {
const href = link.getAttribute("href")!;
// Walk up to find the card container that holds both h4 and img
let card = link.parentElement;
while (card && !(card.querySelector("h4") && card.querySelector("img"))) {
card = card.parentElement;
}
if (!card) continue;
const name = card.querySelector("h4")!.textContent!.trim();
const image = card.querySelector("img")!.getAttribute("src") || "";
// Description is in the div following the h4
const h4 = card.querySelector("h4")!;
const descriptionDiv = h4.parAll rows above produced by Repobility · https://repobility.com
raceCalendar function · typescript · L7-L31 (25 LOC)src/endpoints/race-calendar.ts
async function raceCalendar(
request: Request,
): Promise<Response> {
const serverResponse = await fetch(
"https://www.hlaupadagskra.is/_api/cloud-data/v2/items/query?.r=eyJkYXRhQ29sbGVjdGlvbklkIjoiSXRlbXMiLCJxdWVyeSI6eyJmaWx0ZXIiOnsic2hvdyI6eyIkZXEiOiIxIn19LCJzb3J0IjpbeyJmaWVsZE5hbWUiOiJkYWdzZXRuaW5nIiwib3JkZXIiOiJBU0MifV0sInBhZ2luZyI6eyJvZmZzZXQiOjAsImxpbWl0IjoxMDB9LCJmaWVsZHMiOltdfSwicmVmZXJlbmNlZEl0ZW1PcHRpb25zIjpbXSwicmV0dXJuVG90YWxDb3VudCI6dHJ1ZSwiZW52aXJvbm1lbnQiOiJMSVZFIiwiYXBwSWQiOiI5YTM0OGM5Yy0yNTE3LTRlMmEtOWRkYS03ZGJkNDA1OGYwMTAifQ",
{
headers: {
Cookie:
"server-session-bind=2a88933c-44c4-4e54-a400-fc1e7444fce1; XSRF-TOKEN=1762804542|PA5PBhJYXDjy; hs=1446915969; svSession=a1daa7a12468a978c01c5464eb4885e4edb70c26663d32cdff69c903a73196d9ab2f9e95379580c3123ed36135b11eb81e60994d53964e647acf431e4f798bcd568a3f5c8eec855bc95fb3ed5e1592b6a2b505858be77d2eab3eea5c9388d7346beea4c8eedcfb2353a9084512333211e6d4adc95067e47e2b8a15c65525daeaab36407bcb9854f4generateErrorFingerprint function · typescript · L20-L34 (15 LOC)src/error-monitor.ts
function generateErrorFingerprint(error: Error, _url?: string): string {
// Create a fingerprint from error message and first few lines of stack
const stackLines = error.stack?.split("\n").slice(0, 3).join("\n") || "";
const fingerprint = `${error.name}:${error.message}:${stackLines}`;
// Create a simple hash
let hash = 0;
for (let i = 0; i < fingerprint.length; i++) {
const char = fingerprint.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
}
return `error-${Math.abs(hash).toString(16)}`;
}createGitHubIssue function · typescript · L39-L145 (107 LOC)src/error-monitor.ts
async function createGitHubIssue(
report: ErrorReport,
fingerprint: string,
): Promise<void> {
const githubToken = Deno.env.get("GITHUB_TOKEN");
const githubRepo = Deno.env.get("GITHUB_REPOSITORY");
// Only report in production and when GitHub token is available
if (
!githubToken || !githubRepo ||
Deno.env.get("DENO_DEPLOYMENT_ID") === undefined
) {
console.error(
"Error monitoring: Not in production or missing configuration",
{
hasToken: !!githubToken,
hasRepo: !!githubRepo,
hasDeploymentId: Deno.env.get("DENO_DEPLOYMENT_ID") !== undefined,
},
);
return;
}
const [owner, repo] = githubRepo.split("/");
const apiUrl = `https://api.github.com/repos/${owner}/${repo}`;
try {
// Check if there's already an open issue with this fingerprint
const issuesResponse = await fetch(
`${apiUrl}/issues?state=open&labels=uncaught-error&per_page=100`,
{
headers: {
"Authorization": reportError function · typescript · L150-L168 (19 LOC)src/error-monitor.ts
export async function reportError(
error: Error,
request?: Request,
): Promise<void> {
const report: ErrorReport = {
message: error.message,
stack: error.stack,
timestamp: new Date().toISOString(),
url: request?.url,
method: request?.method,
};
// Log the error
console.error("Uncaught error:", report);
// Generate fingerprint and create issue
const fingerprint = generateErrorFingerprint(error, request?.url);
await createGitHubIssue(report, fingerprint);
}formatLogEntry function · typescript · L3-L46 (44 LOC)src/middleware.ts
function formatLogEntry(
req: Request,
status: number,
responseSize: number,
): string {
// Common Log Format: host - - [date] "method path protocol" status size
const url = new URL(req.url);
const date = new Date();
// Format: [10/Oct/2000:13:55:36 -0700]
const day = String(date.getDate()).padStart(2, "0");
const month = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
][date.getMonth()];
const year = date.getFullYear();
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
const offset = -date.getTimezoneOffset();
const offsetHours = String(Math.floor(Math.abs(offset) / 60)).padStart(
2,
"0",
);
const offsetMinutes = String(Math.abs(offset) % 60).padStart(2, "0");
const offsetSign = offset >= 0 ? "+" : "-";
const formattedDate =
Router class · typescript · L19-L113 (95 LOC)src/router.ts
export class Router {
#routes: Record<
string,
Array<{ pattern: URLPattern; handler: CallbackHandler }>
> = {
"GET": [],
"POST": [],
"PUT": [],
};
#middleware: Middleware[] = [];
use(middleware: Middleware) {
this.#middleware.push(middleware);
}
add(method: string, pathname: string, handler: CallbackHandler) {
this.#routes[method].push({
pattern: new URLPattern({ pathname }),
handler,
});
}
async route(req: Request): Promise<Response> {
// Find matching route
for (const route of this.#routes[req.method]) {
if (route.pattern.test(req.url)) {
const match = route.pattern.exec(req.url);
if (match) {
const params = (match.pathname.groups || {}) as Record<
string,
string
>;
// Create the handler function that will be called at the end of middleware chain
const handler = async () => {
try {
return await route[use method · typescript · L30-L32 (3 LOC)src/router.ts
use(middleware: Middleware) {
this.#middleware.push(middleware);
}add method · typescript · L34-L39 (6 LOC)src/router.ts
add(method: string, pathname: string, handler: CallbackHandler) {
this.#routes[method].push({
pattern: new URLPattern({ pathname }),
handler,
});
}Repobility · code-quality intelligence · https://repobility.com
route method · typescript · L41-L84 (44 LOC)src/router.ts
async route(req: Request): Promise<Response> {
// Find matching route
for (const route of this.#routes[req.method]) {
if (route.pattern.test(req.url)) {
const match = route.pattern.exec(req.url);
if (match) {
const params = (match.pathname.groups || {}) as Record<
string,
string
>;
// Create the handler function that will be called at the end of middleware chain
const handler = async () => {
try {
return await route["handler"](req, params);
} catch (error) {
// Report the error to monitoring system
await reportError(error as Error, req);
// Return a 500 error response
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{
status: 500,
headers: {
"Content-Type": "application/json",
#executeMiddleware method · typescript · L86-L101 (16 LOC)src/router.ts
async #executeMiddleware(
req: Request,
handler: () => Promise<Response>,
): Promise<Response> {
let index = 0;
const next = async (): Promise<Response> => {
if (index < this.#middleware.length) {
const middleware = this.#middleware[index++];
return await middleware(req, next);
}
return await handler();
};
return await next();
}getEndpoints method · typescript · L102-L112 (11 LOC)src/router.ts
getEndpoints() {
const endpoints: Array<{ endpoint: string; description: string }> = [];
for (const method in this.#routes) {
for (const route of this.#routes[method]) {
if (route.handler.meta) {
endpoints.push(route.handler.meta);
}
}
}
return endpoints;
}generateRSS function · typescript · L4-L42 (39 LOC)src/rss.ts
export function generateRSS(
items: Array<{
title: string;
description: string | null;
url: string;
data: {
start: string;
end: string | null;
};
}>,
): string {
const now = new Date().toUTCString();
const rssItems = items.map((item) => {
const startDate = new Date(item.data.start);
const description = item.description || "No description available.";
return ` <item>
<title>${escapeXml(item.title)}</title>
<description>${escapeXml(description)}</description>
<link>${escapeXml(item.url)}</link>
<guid isPermaLink="true">${escapeXml(item.url)}</guid>
<pubDate>${startDate.toUTCString()}</pubDate>
</item>`;
}).join("\n");
return `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Icelandic Tech Meetups</title>
<description>List of Icelandic tech meetups and community groups from apis.is</description>
<link>https://apisescapeXml function · typescript · L47-L54 (8 LOC)src/rss.ts
function escapeXml(text: string): string {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}capitalizeFirstLetter function · typescript · L1-L3 (3 LOC)src/utils.ts
export function capitalizeFirstLetter(val: string) {
return String(val).charAt(0).toUpperCase() + String(val).slice(1);
}response function · typescript · L5-L14 (10 LOC)src/utils.ts
export function response(
data: unknown[] | Record<string, unknown>,
pretty = false,
) {
return new Response(JSON.stringify(data, null, pretty ? 2 : 0), {
headers: {
"Access-Control-Allow-Origin": "*",
},
});
}