Skip to content

Commit

Permalink
refactor: pull filter into module
Browse files Browse the repository at this point in the history
  • Loading branch information
meatcar committed Aug 21, 2023
1 parent bbc2e06 commit 2f33fef
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 13 deletions.
16 changes: 16 additions & 0 deletions src/filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {
getUserAgentRegExp,
getBrowsersList,
} from "browserslist-useragent-regexp";

export function buildUARegex(constraint: string): [RegExp, string[]] {
const query = { browsers: [constraint] };

const browsers = getBrowsersList(query);
const set: Set<string> = new Set();
for (let { family, version } of browsers) {
set.add(`${family} v${version.join(".")}`);
}

return [getUserAgentRegExp(query), Array.from(set)];
}
20 changes: 7 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,24 @@
import Koa from "koa";
import Router from "koa-router";
import logger from "koa-logger";
import { buildUARegex } from "./filter";

import {
getUserAgentRegExp,
getBrowsersList,
} from "browserslist-useragent-regexp";

const app = new Koa();
const router = new Router();

const query = { browsers: ["< 0.01%"] };
const regexp = getUserAgentRegExp(query);

const permittedBrowsers = getBrowsersList(query)
.map(({ family, version }) => `- ${family} v${version.join(".")}`)
.reduce((acc, v) => acc.add(v), new Set());

const list = [...permittedBrowsers].join("\n");
/*
* We clamp each browser to 0.01% market share, so collectively they add up to 1%-ish world-wide share.
*/
const [regexp, browsers] = buildUARegex("< 0.01%");
const prettyList = browsers.map((s) => `- ${s}`).join("\n");

router.get("/", async (ctx, next) => {
const ua = ctx.headers["user-agent"] || "";
if (regexp.test(ua)) {
ctx.body = "πŸ₯‡πŸ₯ˆπŸ… Welcome to the secret 1% club. πŸ₯‡πŸ₯ˆπŸ…";
} else {
ctx.body = `You don't belong here! Only one of the following browsers is allowed:\n\n${list}`;
ctx.body = `You don't belong here! Only one of the following browsers is allowed:\n\n${prettyList}`;
}
await next();
});
Expand Down

0 comments on commit 2f33fef

Please sign in to comment.