File size: 8,061 Bytes
7a5aa35 68037ed 33ffc9c 68037ed e4feb9d 33ffc9c 68037ed 7f60362 68037ed 7f60362 68037ed 33ffc9c 68037ed 7f60362 68037ed 7f60362 68037ed 7f60362 68037ed 7f60362 68037ed 7f60362 33ffc9c 68037ed 33ffc9c 68037ed 33ffc9c 68037ed e4feb9d 33ffc9c 68037ed e4feb9d 68037ed 33ffc9c 68037ed 33ffc9c e4feb9d 68037ed e4feb9d 33ffc9c cecb963 68037ed 7a5aa35 68037ed 7a5aa35 33ffc9c 68037ed 7a5aa35 68037ed e4feb9d 7a5aa35 33ffc9c 7a5aa35 e4feb9d 7a5aa35 7f60362 e4feb9d 7a5aa35 7f60362 7a5aa35 33ffc9c 68037ed 7a5aa35 33ffc9c 68037ed cecb963 68037ed cecb963 68037ed 33ffc9c cecb963 68037ed cecb963 68037ed 33ffc9c cecb963 68037ed e4feb9d 7f60362 e4feb9d 68037ed e4feb9d 7f60362 e4feb9d 7f60362 e4feb9d 68037ed e4feb9d 7f60362 33ffc9c cecb963 68037ed e4feb9d 7a5aa35 33ffc9c 68037ed |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 |
import { serve } from "bun";
// --- Interfaces ---
export interface Dependency {
name: string;
source: "relative" | "remote";
location: string;
}
export interface DeepSearchData {
[key: string]: string;
}
export interface Item {
avatar_url: string;
name: string;
full_name: string;
created_at: string;
description?: string | null;
default_branch?: string;
open_issues: number;
stargazers_count: number;
forks_count: number;
watchers_count: number;
contentIsCorrect?: boolean;
tags_url: string;
license: string;
readme_content: string;
specials?: string;
topics?: string[];
size: number;
has_build_zig_zon?: boolean;
has_build_zig?: boolean;
fork: boolean;
updated_at: string;
dependencies?: Dependency[];
berg?: number;
gitlab?: number;
archived?: boolean;
}
// --- Constants ---
const packagesUrls = [
"https://raw.githubusercontent.com/Zigistry/database/refs/heads/main/database/games.json",
"https://raw.githubusercontent.com/Zigistry/database/refs/heads/main/database/gui.json",
"https://raw.githubusercontent.com/Zigistry/database/refs/heads/main/database/packages.json",
"https://raw.githubusercontent.com/Zigistry/database/refs/heads/main/database/web.json",
];
const programsUrl =
"https://raw.githubusercontent.com/Zigistry/database/refs/heads/main/database/programs.json";
// --- Data Loading ---
let packages: Item[] = [];
let programs: Item[] = [];
async function loadData() {
const packagesFile = await Promise.all(packagesUrls.map((url) => fetch(url)));
packages = (await Promise.all(packagesFile.map((file) => file.json())))
.flat() as Item[];
const programsFile = await fetch(programsUrl);
programs = (await programsFile.json()) as Item[];
console.log("Data loaded");
}
await loadData();
// Refresh the data every 10 minutes
setInterval(loadData, 10 * 60 * 100);
// --- CORS Headers ---
const corsHeaders: Record<string, string> = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
};
// --- Sorting Helpers ---
const sortByDate = (a: Item, b: Item) =>
new Date(b.created_at ?? "").getTime() - new Date(a.created_at ?? "").getTime();
const sortByUsage = (a: Item, b: Item) =>
(b.stargazers_count ?? 0) - (a.stargazers_count ?? 0);
// --- Pre-sorted Data ---
function getSorted() {
const packagesArray = packages as Item[];
const programsArray = programs as Item[];
return {
packages: {
latest: [...packagesArray].sort(sortByDate),
mostUsed: [...packagesArray].sort(sortByUsage),
},
programs: {
latest: [...programsArray].sort(sortByDate),
mostUsed: [...programsArray].sort(sortByUsage),
},
};
}
// --- Filtering ---
function filterItems(
items: Item[],
q: string | null,
filter: string | null
): Item[] {
return items.filter(({ name, full_name, description, topics }) => {
if (filter && !topics?.some((t) => t.toLowerCase() === filter)) return false;
if (!q) return true;
const lowerQ = q.toLowerCase();
return [name, full_name, description, ...(topics ?? [])].some((field) =>
field?.toLowerCase().includes(lowerQ)
);
});
}
// --- Pagination ---
function getPaginated(items: Item[], page = 0, size = 10): Item[] {
const start = page * size;
return items.slice(start, start + size);
}
// --- Find by Owner/Repo ---
function findItem(items: Item[], owner: string, repo: string): Item | undefined {
return items.find(
({ full_name }) => full_name?.toLowerCase() === `${owner}/${repo}`
);
}
// --- Parse Range ---
function parseRange(str: string | null, max: number): [number, number] {
const match = str?.match(/^(\d+)\.\.(\d+)$/);
const [start, end] = match
? [parseInt(match[1] ?? "0", 10), parseInt(match[2] ?? "10", 10)]
: [0, 10];
return [Math.max(0, start), Math.min(max, end)];
}
// --- Server ---
serve({
port: 7860,
async fetch(req) {
const url = new URL(req.url);
const { pathname, searchParams } = url;
const q = searchParams.get("q")?.trim().toLowerCase() ?? null;
const filter = searchParams.get("filter")?.trim().toLowerCase() ?? null;
const sorted = getSorted();
// Handle CORS preflight
if (req.method === "OPTIONS") {
return new Response(null, {
status: 204,
headers: {
...corsHeaders,
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
},
});
}
// Search endpoints
if (pathname === "/api/searchPackages") {
const result = filterItems(packages, q, filter).slice(0, 25);
return Response.json(result, { headers: corsHeaders });
}
if (pathname === "/api/searchPrograms") {
const result = filterItems(programs, q, filter).slice(0, 25);
return Response.json(result, { headers: corsHeaders });
}
// Infinite scroll endpoints
if (pathname === "/api/infiniteScrollPackages") {
const page = parseInt(searchParams.get("pageNumber") || "0", 10);
if (isNaN(page) || page < 0)
return Response.json(
{ error: "Invalid page number" },
{ status: 400, headers: corsHeaders }
);
return Response.json(getPaginated(packages, page), {
headers: corsHeaders,
});
}
if (pathname === "/api/infiniteScrollPrograms") {
const page = parseInt(searchParams.get("pageNumber") || "0", 10);
if (isNaN(page) || page < 0)
return Response.json(
{ error: "Invalid page number" },
{ status: 400, headers: corsHeaders }
);
return Response.json(getPaginated(programs, page), {
headers: corsHeaders,
});
}
// Get single program/package by owner/repo
const programMatch = pathname.match(/^\/api\/programs\/([^/]+)\/([^/]+)$/);
if (programMatch) {
const owner = programMatch[1]?.toLowerCase() ?? "";
const repo = programMatch[2]?.toLowerCase() ?? "";
const found = findItem(programs, owner, repo);
return Response.json(found || { error: "Program not found" }, {
status: found ? 200 : 404,
headers: corsHeaders,
});
}
const packageMatch = pathname.match(/^\/api\/packages\/([^/]+)\/([^/]+)$/);
if (packageMatch) {
const owner = packageMatch[1]?.toLowerCase() ?? "";
const repo = packageMatch[2]?.toLowerCase() ?? "";
const found = findItem(packages, owner, repo);
return Response.json(found || { error: "Package not found" }, {
status: found ? 200 : 404,
headers: corsHeaders,
});
}
// Index details endpoints
if (pathname === "/api/indexDetailsPackages") {
const section = searchParams.get("section");
if (section !== "latestRepos" && section !== "mostUsed") {
return Response.json(
{ error: "Invalid section" },
{ status: 400, headers: corsHeaders }
);
}
const sortKey = section === "latestRepos" ? "latest" : "mostUsed";
const data = sorted.packages[sortKey as keyof typeof sorted.packages] ?? packages;
const [start, end] = parseRange(searchParams.get("range"), data.length);
return Response.json(data.slice(start, end), { headers: corsHeaders });
}
if (pathname === "/api/indexDetailsPrograms") {
const section = searchParams.get("section");
if (section !== "latestRepos" && section !== "mostUsed") {
return Response.json(
{ error: "Invalid section" },
{ status: 400, headers: corsHeaders }
);
}
const sortKey = section === "latestRepos" ? "latest" : "mostUsed";
const data = sorted.programs[sortKey as keyof typeof sorted.programs] ?? programs;
const [start, end] = parseRange(searchParams.get("range"), data.length);
return Response.json(data.slice(start, end), { headers: corsHeaders });
}
// Not found
return new Response("Not Found", {
status: 404,
headers: corsHeaders,
});
},
});
console.log("Server running on http://localhost:7860"); |