Commit 660a1b8ac9

660a1b8ac927d891d298cc5ba4a2fc050f7d5a6f

parent: 27e767b85d

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-08-09 09:12 UTC

More performant finding line for each listing in yaml

Layout: unified · split

web/src/components/things/DataActions.svelte +6 −10
@@ -1,13 +1,12 @@
1<script lang="ts"> 1<script lang="ts">
2 import { onMount } from 'svelte';
3 import { 2 import {
4 fetchSrcData,
5 makeRemovalRequest, 3 makeRemovalRequest,
6 makeEditRequest, 4 makeEditRequest,
7 } from '@utils/data-src-delete-n-edit'; 5 } from '@utils/data-src-delete-n-edit';
8 import FontAwesome from '@components/form/FontAwesome.svelte'; 6 import FontAwesome from '@components/form/FontAwesome.svelte';
9 7
10 import type { ChangelogPr } from '../../utils/fetch-changelog'; 8 import type { ChangelogPr } from '../../utils/fetch-changelog';
9 import type { ServiceSource } from '@utils/fetch-line-numbers';
11 10
12 interface HistoryItem { 11 interface HistoryItem {
13 date: string; 12 date: string;
@@ -22,16 +21,18 @@
22 sectionName: string; 21 sectionName: string;
23 serviceName: string; 22 serviceName: string;
24 history?: HistoryItem[]; 23 history?: HistoryItem[];
24 source?: ServiceSource;
25 } 25 }
26 const { 26 const {
27 categoryName, 27 categoryName,
28 sectionName, 28 sectionName,
29 serviceName, 29 serviceName,
30 history = [], 30 history = [],
31 source,
31 }: Props = $props(); 32 }: Props = $props();
32 33
33 let lineNumbers: { start: number; end: number } | null = $state(null); 34 const lineNumbers = source?.lineNumbers;
34 let yamlContent = $state(''); 35 const yamlContent = source?.yaml ?? '';
35 36
36 const getGitHubSrcFile = () => { 37 const getGitHubSrcFile = () => {
37 if (lineNumbers) { 38 if (lineNumbers) {
@@ -49,12 +50,6 @@
49 'style=felipec&type=code&showBorder=on&showLineNumbers=on&showFileMeta=on&showFullPath=on&showCopy=on'; 50 'style=felipec&type=code&showBorder=on&showLineNumbers=on&showFileMeta=on&showFullPath=on&showCopy=on';
50 return `${host}/iframe.html?target=${target}&${opts}`; 51 return `${host}/iframe.html?target=${target}&${opts}`;
51 }; 52 };
52
53 onMount(async () => {
54 const results = await fetchSrcData(categoryName, sectionName, serviceName);
55 lineNumbers = results.lineNumbers;
56 yamlContent = results.yamlContent;
57 });
58</script> 53</script>
59 54
60{#if history.length > 0} 55{#if history.length > 0}
@@ -125,6 +120,7 @@
125 <iframe 120 <iframe
126 frameborder="0" 121 frameborder="0"
127 scrolling="no" 122 scrolling="no"
123 loading="lazy"
128 class="yaml-embed" 124 class="yaml-embed"
129 allow="clipboard-write" 125 allow="clipboard-write"
130 title="awesome-privacy.yml" 126 title="awesome-privacy.yml"
web/src/components/things/DeleteListing.svelte +9 −21
@@ -1,36 +1,24 @@
1<script lang="ts"> 1<script lang="ts">
2 import FontAwesome from '@components/form/FontAwesome.svelte'; 2 import FontAwesome from '@components/form/FontAwesome.svelte';
3 import { 3 import { makeRemovalRequest } from '@utils/data-src-delete-n-edit';
4 fetchSrcData, 4 import type { ServiceSource } from '@utils/fetch-line-numbers';
5 makeRemovalRequest,
6 } from '@utils/data-src-delete-n-edit';
7 import { onMount } from 'svelte';
8 5
9 interface Props { 6 interface Props {
10 categoryName: string; 7 categoryName: string;
11 sectionName: string; 8 sectionName: string;
12 serviceName: string; 9 serviceName: string;
10 source?: ServiceSource;
13 } 11 }
14 const { categoryName, sectionName, serviceName }: Props = $props(); 12 const { categoryName, sectionName, serviceName, source }: Props = $props();
15 13
16 const apYaml = 14 const apYaml =
17 'https://github.com/lissy93/awesome-privacy/blob/main/awesome-privacy.yml'; 15 'https://github.com/lissy93/awesome-privacy/blob/main/awesome-privacy.yml';
18 16
19 let yamlContent = $state(''); 17 const yamlContent = source?.yaml ?? '';
20 let editLink = $state(apYaml); 18 const lineNumbers = source?.lineNumbers;
21 19 const editLink = lineNumbers
22 onMount(async () => { 20 ? `${apYaml}#L${lineNumbers.start}-L${lineNumbers.end}`
23 const results = await fetchSrcData(categoryName, sectionName, serviceName); 21 : apYaml;
24 yamlContent = results.yamlContent;
25
26 const lineNumbers = results.lineNumbers || null;
27 const numberRange = lineNumbers
28 ? `#L${lineNumbers.start}-L${lineNumbers.end}`
29 : '';
30 const yamlLink =
31 'https://github.com/lissy93/awesome-privacy/blob/main/awesome-privacy.yml';
32 editLink = `${yamlLink}${numberRange}`;
33 });
34</script> 22</script>
35 23
36<div class="actions"> 24<div class="actions">
web/src/components/things/GitHubDetailedInfo.astro +6
@@ -282,6 +282,12 @@ const languageChart = `https://quickchart.io/chart?c=${generateChartData(gitHubD
282 } 282 }
283 } 283 }
284 284
285 .list-table {
286 li .val a :global(svg) {
287 width: 1rem;
288 }
289 }
290
285 @include detail-info-base; 291 @include detail-info-base;
286 292
287 .tags { 293 .tags {
web/src/components/things/ServiceList.astro +4 −1
@@ -6,6 +6,7 @@ import FontAwesome from '@components/form/FontAwesome.svelte';
6import DeleteListing from '@components/things/DeleteListing.svelte'; 6import DeleteListing from '@components/things/DeleteListing.svelte';
7import ServiceIcon from '@components/things/ServiceIcon.astro'; 7import ServiceIcon from '@components/things/ServiceIcon.astro';
8import { slugify } from '@utils/fetch-data'; 8import { slugify } from '@utils/fetch-data';
9import { fetchServiceSources } from '@utils/fetch-line-numbers';
9 10
10import GitHubMetrics from '@components/things/ItemGitHubMetrics.astro'; 11import GitHubMetrics from '@components/things/ItemGitHubMetrics.astro';
11import SaveListing from '@components/things/SaveListing.svelte'; 12import SaveListing from '@components/things/SaveListing.svelte';
@@ -31,6 +32,8 @@ const {
31const sortedServices = [...(services || [])].sort((a, b) => 32const sortedServices = [...(services || [])].sort((a, b) =>
32 a.name.localeCompare(b.name), 33 a.name.localeCompare(b.name),
33); 34);
35
36const sources = await fetchServiceSources(categoryName, sectionName);
34--- 37---
35 38
36<section> 39<section>
@@ -40,10 +43,10 @@ const sortedServices = [...(services || [])].sort((a, b) =>
40 {sortedServices.map((service: Service) => ( 43 {sortedServices.map((service: Service) => (
41 <li id={slugify(service.name)}> 44 <li id={slugify(service.name)}>
42 <DeleteListing 45 <DeleteListing
43 client:load
44 categoryName={categoryName} 46 categoryName={categoryName}
45 sectionName={sectionName} 47 sectionName={sectionName}
46 serviceName={service.name} 48 serviceName={service.name}
49 source={sources[service.name]}
47 /> 50 />
48 <div class="save-listing"> 51 <div class="save-listing">
49 <SaveListing 52 <SaveListing
web/src/pages/[...listing].astro +3 −1
@@ -16,6 +16,7 @@ import SocialShare from '@components/form/Social.astro';
16import DataActions from '@components/things/DataActions.svelte'; 16import DataActions from '@components/things/DataActions.svelte';
17import type { AwesomePrivacy, Section, Service } from '../types/Service'; 17import type { AwesomePrivacy, Section, Service } from '../types/Service';
18import { fetchData, slugify } from '@utils/fetch-data'; 18import { fetchData, slugify } from '@utils/fetch-data';
19import { fetchServiceSources } from '@utils/fetch-line-numbers';
19import { codebergUrl } from '@utils/parse-markdown'; 20import { codebergUrl } from '@utils/parse-markdown';
20import { plainText, truncate } from '@utils/meta-tags'; 21import { plainText, truncate } from '@utils/meta-tags';
21import { fetchChangelog } from '@utils/fetch-changelog'; 22import { fetchChangelog } from '@utils/fetch-changelog';
@@ -160,6 +161,7 @@ const discordData = discordInvite
160 : null; 161 : null;
161const redditData = subreddit ? await fetchRedditInfo(subreddit) : null; 162const redditData = subreddit ? await fetchRedditInfo(subreddit) : null;
162const dockerData = await fetchDockerData(name); 163const dockerData = await fetchDockerData(name);
164const sources = await fetchServiceSources(categoryName, parentSection.name);
163const websiteData = 165const websiteData =
164 url && !ignoredSites.some((s) => url.includes(s)) 166 url && !ignoredSites.some((s) => url.includes(s))
165 ? await fetchWebsiteInfo(url) 167 ? await fetchWebsiteInfo(url)
@@ -368,11 +370,11 @@ const makeSoftwareSchema = () => {
368 <section> 370 <section>
369 <h2>About the Data: {name}</h2> 371 <h2>About the Data: {name}</h2>
370 <DataActions 372 <DataActions
371 client:load
372 categoryName={categoryName} 373 categoryName={categoryName}
373 sectionName={parentSection.name} 374 sectionName={parentSection.name}
374 serviceName={name} 375 serviceName={name}
375 history={serviceHistory} 376 history={serviceHistory}
377 source={sources[name]}
376 /> 378 />
377 <h3>API</h3> 379 <h3>API</h3>
378 <p> 380 <p>
web/src/pages/api/line-numbers.json.ts +3 −109
@@ -1,113 +1,7 @@
1import type { APIRoute } from 'astro'; 1import type { APIRoute } from 'astro';
2import yaml from 'js-yaml'; 2import { fetchLineNumbers } from '@utils/fetch-line-numbers';
3 3
4import type { AwesomePrivacy, Service, Category } from '../../types/Service'; 4export const GET: APIRoute = async () =>
5 5 new Response(JSON.stringify(await fetchLineNumbers()), {
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' }, 6 headers: { 'content-type': 'application/json' },
112 }); 7 });
113};
web/src/utils/data-src-delete-n-edit.ts −46
@@ -95,49 +95,3 @@ export const makeAdditionRequest = (
95 'https://github.com/Lissy93/awesome-privacy/issues/new'; 95 'https://github.com/Lissy93/awesome-privacy/issues/new';
96 return `${issueCreateUrl}?${queryParams.toString()}`; 96 return `${issueCreateUrl}?${queryParams.toString()}`;
97}; 97};
98
99export const makeSourceYamlLink = async (
100 categoryName: string,
101 sectionName: string,
102 serviceName: string,
103) => {
104 const sourceData = await fetchSrcData(categoryName, sectionName, serviceName);
105 const lineNumbers = sourceData.lineNumbers || null;
106 const numberRange = lineNumbers
107 ? `L${lineNumbers.start}-L${lineNumbers.end}`
108 : '';
109 const yamlLink =
110 'https://github.com/lissy93/awesome-privacy/blob/main/awesome-privacy.yml';
111 return `${yamlLink}${numberRange}`;
112};
113
114export const fetchSrcData = async (
115 categoryName: string,
116 sectionName: string,
117 serviceName: string,
118) => {
119 const lineNumberData = await fetch('/api/line-numbers.json').then((res) =>
120 res.json(),
121 );
122
123 if (
124 lineNumberData &&
125 lineNumberData[categoryName] &&
126 lineNumberData[categoryName][sectionName] &&
127 lineNumberData[categoryName][sectionName][serviceName]
128 ) {
129 return {
130 lineNumbers:
131 lineNumberData[categoryName][sectionName][serviceName].lineNumbers,
132 yamlContent: lineNumberData[categoryName][sectionName][serviceName].yaml,
133 };
134 } else {
135 console.error(
136 'No line number data found for',
137 categoryName,
138 sectionName,
139 serviceName,
140 );
141 return { lineNumbers: [], yamlContent: '' };
142 }
143};
web/src/utils/fetch-line-numbers.ts added +98
@@ -0,0 +1,98 @@
1import yaml from 'js-yaml';
2import { error } from './logger';
3import { safeFetch } from './safe-fetch';
4
5import type { AwesomePrivacy } from '../types/Service';
6
7export interface LineNumberRange {
8 start: number;
9 end: number;
10}
11
12export interface ServiceSource {
13 lineNumbers: LineNumberRange | null;
14 yaml: string;
15}
16
17export type LineNumberData = Record<
18 string,
19 Record<string, Record<string, ServiceSource>>
20>;
21
22const awesomePrivacyYamlPath =
23 'https://raw.githubusercontent.com/Lissy93/awesome-privacy/main/awesome-privacy.yml';
24
25const isServiceEnd = (line: string) =>
26 line.trim().length === 0 ||
27 line.startsWith(' - ') ||
28 line.includes('- name:') ||
29 line.includes('notableMentions:') ||
30 line.includes('furtherInfo:') ||
31 line.includes('wordOfWarning:');
32
33const findServiceRange = (
34 serviceName: string,
35 yamlLines: string[],
36 from: number,
37): LineNumberRange | null => {
38 const offset = yamlLines
39 .slice(from)
40 .findIndex((line) => line.trim() === `- name: ${serviceName}`);
41 if (offset === -1) return null;
42
43 const start = from + offset + 1;
44 const endOffset = yamlLines.slice(start).findIndex(isServiceEnd);
45 return {
46 start,
47 end: endOffset === -1 ? yamlLines.length : start + endOffset,
48 };
49};
50
51const makeResults = (
52 yamlObject: AwesomePrivacy,
53 yamlLines: string[],
54): LineNumberData => {
55 const results: LineNumberData = {};
56 let cursor = 0;
57 (yamlObject.categories || []).forEach((category) => {
58 results[category.name] = {};
59 (category.sections || []).forEach((section) => {
60 results[category.name][section.name] = {};
61 (section.services || []).forEach((service) => {
62 const lineNumbers = findServiceRange(service.name, yamlLines, cursor);
63 if (lineNumbers) cursor = lineNumbers.start;
64 results[category.name][section.name][service.name] = {
65 lineNumbers,
66 yaml: yaml.dump(service),
67 };
68 });
69 });
70 });
71 return results;
72};
73
74const buildLineNumbers = async (): Promise<LineNumberData> => {
75 try {
76 const res = await safeFetch(awesomePrivacyYamlPath, {}, 15000);
77 if (!res.ok) {
78 error('Data', `HTTP ${res.status} fetching awesome-privacy.yml`);
79 return {};
80 }
81 const text = await res.text();
82 return makeResults(yaml.load(text) as AwesomePrivacy, text.split('\n'));
83 } catch (err) {
84 error('Data', `Failed to build line numbers: ${err}`);
85 return {};
86 }
87};
88
89let cached: Promise<LineNumberData> | null = null;
90
91export const fetchLineNumbers = (): Promise<LineNumberData> =>
92 (cached ??= buildLineNumbers());
93
94export const fetchServiceSources = async (
95 categoryName: string,
96 sectionName: string,
97): Promise<Record<string, ServiceSource>> =>
98 (await fetchLineNumbers())[categoryName]?.[sectionName] ?? {};