web/src/pages/api/line-numbers.json.ts

113 lines · 3228 bytes

  1import type { APIRoute } from 'astro';
  2import yaml from 'js-yaml';
  3
  4import type { AwesomePrivacy, Service, Category } from '../../types/Service';
  5
  6interface LineNumberRange {
  7  start: number;
  8  end: number;
  9}
 10
 11interface LineNumberData {
 12  [category: string]: {
 13    [section: string]: {
 14      [service: string]: {
 15        lineNumbers: LineNumberRange | null;
 16        yaml: string;
 17      };
 18    };
 19  };
 20}
 21
 22const awesomePrivacyYamlPath =
 23  'https://raw.githubusercontent.com/Lissy93/awesome-privacy/main/awesome-privacy.yml';
 24
 25/**
 26 * Given a service object and an array of string lines from the raw YAML
 27 * Find the starting and ending line number for that service
 28 */
 29const calculateServiceRange = (
 30  service: Service,
 31  category: Category,
 32  yamlLines: string[],
 33): LineNumberRange | null => {
 34  const lookFor = `- name: ${service.name}`;
 35  const categoryStart = yamlLines.findIndex((line) =>
 36    line.includes(category.name),
 37  );
 38  const start =
 39    yamlLines.slice(categoryStart).findIndex((line) => line.includes(lookFor)) +
 40    categoryStart +
 41    1;
 42  if (start === -1) return null;
 43  const detectEnd = (line: string) => {
 44    return (
 45      line.trim().length === 0 ||
 46      line.startsWith('  - ') ||
 47      line.includes('- name:') ||
 48      line.includes('notableMentions:') ||
 49      line.includes('furtherInfo:') ||
 50      line.includes('wordOfWarning:')
 51    );
 52  };
 53  const remainingLines = yamlLines.slice(start);
 54  const end = start + remainingLines.findIndex(detectEnd);
 55
 56  return { start, end };
 57};
 58
 59/**
 60 * Given a service object, convert it into a correctly formatted YAML string
 61 */
 62const convertJsonIntoYaml = (service: Service): string => {
 63  return yaml.dump(service);
 64};
 65
 66/**
 67 * Given the object representation of the YAML and the array of lines from the raw YAML
 68 * Organize the data into a format that can be returned as JSON
 69 */
 70const makeResults = (
 71  yamlObject: AwesomePrivacy,
 72  yamlLines: string[],
 73): LineNumberData => {
 74  const organizedData: LineNumberData = {};
 75  (yamlObject.categories || []).forEach((category) => {
 76    organizedData[category.name] = {};
 77    (category.sections || []).forEach((section) => {
 78      organizedData[category.name][section.name] = {};
 79      (section.services || []).forEach((service) => {
 80        organizedData[category.name][section.name][service.name] = {
 81          lineNumbers: calculateServiceRange(service, category, yamlLines),
 82          yaml: convertJsonIntoYaml(service),
 83        };
 84      });
 85    });
 86  });
 87  return organizedData;
 88};
 89
 90export const GET: APIRoute = async () => {
 91  // Fetch the raw YAML from the awesome-privacy repository
 92  const yamlContent = await fetch(awesomePrivacyYamlPath)
 93    .then((response) => response.text())
 94    .catch((error) => {
 95      return JSON.stringify({
 96        error: 'Failed to fetch YAML file',
 97        details: error,
 98      });
 99    });
100
101  // Array of lines from the raw YAML
102  const yamlLines: string[] = yamlContent.split('\n');
103
104  // Object representation of the YAML
105  const yamlObject = yaml.load(yamlContent) as AwesomePrivacy;
106
107  // Make results
108  const results = makeResults(yamlObject, yamlLines);
109
110  return new Response(JSON.stringify(results), {
111    headers: { 'content-type': 'application/json' },
112  });
113};