refactor: remove logger

This commit is contained in:
Ayo Ayco 2024-11-10 21:01:35 +01:00
parent a567a88540
commit 249caabd67
4 changed files with 99 additions and 120 deletions

View file

@ -1,79 +1,95 @@
---
export interface Props {
skipSave?: boolean
skipSave?: boolean;
}
---
<div id="library" data-preferences={JSON.stringify(Astro.props)}>
<span id="heading"></span>
<ul id="post-list"></ul>
</div>
<script>
import { getPostCard, renderPost } from '../utils/library'
import { cozify } from '../utils/sanitizer';
import { logError, logInfo } from '../utils/logger';
const cache = await caches.open('cozy-reader');
import { getPostCard, renderPost } from "../utils/library";
import { cozify } from "../utils/sanitizer";
const cache = await caches.open("cozy-reader");
const baseUrl = window.location.origin;
let url = new URL(window.location.href);
// only cached unencoded url param
const urlParam = url.searchParams.get('url')
const urlParam = url.searchParams.get("url");
if (urlParam) {
url = new URL(`${url.origin}/?url=${urlParam}`);
}
const preferencesEl = document.querySelector('[data-preferences]') as HTMLElement;
const preferencesStr = preferencesEl?.dataset.preferences ?? '';
const preferencesEl = document.querySelector(
"[data-preferences]"
) as HTMLElement;
const preferencesStr = preferencesEl?.dataset.preferences ?? "";
const { skipSave } = JSON.parse(preferencesStr);
const routerOutlet = 'router-outlet';
const routerOutlet = "router-outlet";
const includesAppURL = urlParam?.includes(baseUrl) ?? false;
try {
if (url.href.slice(0, url.href.length - 1) !== baseUrl && !skipSave && !includesAppURL) {
logInfo('adding one to cache', {context: 'cozy-reader', data: url})
if (
url.href.slice(0, url.href.length - 1) !== baseUrl &&
!skipSave &&
!includesAppURL
) {
console.info("adding one to cache", {
context: "cozy-reader",
data: url,
});
await cache.add(url);
}
} catch (error) {
logError('ERR', {context: 'cozy-reader', data: error})
console.error("ERR", { context: "cozy-reader", data: error });
}
const cachedRequests = (await cache.keys())
.filter(request => {
const cachedRequests = (await cache.keys()).filter((request) => {
const urlObj = new URL(request.url);
const urlParam = urlObj.searchParams.get('url');
const urlParam = urlObj.searchParams.get("url");
return urlObj.search !== ''
&& !urlParam?.startsWith(baseUrl)
&& urlParam !== ''
&& urlParam !== 'null';
return (
urlObj.search !== "" &&
!urlParam?.startsWith(baseUrl) &&
urlParam !== "" &&
urlParam !== "null"
);
});
if (cachedRequests?.length && routerOutlet !== null) {
const list = document.querySelector('#post-list');
const heading = document.querySelector('#library span#heading') as HTMLHeadingElement;
heading.innerHTML = 'History';
const list = document.querySelector("#post-list");
const heading = document.querySelector(
"#library span#heading"
) as HTMLHeadingElement;
heading.innerHTML = "History";
cachedRequests
.reverse()
.forEach(async (request) => {
cachedRequests.reverse().forEach(async (request) => {
const { url } = request;
const link = document.createElement('a');
const link = document.createElement("a");
let responseText;
const fullResponse = await cache.match(url)
if (!fullResponse && url.slice(0, url.length - 1) !== baseUrl && !skipSave && !includesAppURL) {
logInfo('updating cached', {context: 'cozy-reader', data: url})
const fullResponse = await cache.match(url);
if (
!fullResponse &&
url.slice(0, url.length - 1) !== baseUrl &&
!skipSave &&
!includesAppURL
) {
console.info("updating cached", { context: "cozy-reader", data: url });
await cache.add(url);
}
fullResponse?.text().then(async data => {
fullResponse?.text().then(async (data) => {
responseText = data;
const cleanedResponse = await cozify(responseText, baseUrl)
const html = document.createElement('html');
const cleanedResponse = await cozify(responseText, baseUrl);
const html = document.createElement("html");
html.innerHTML = cleanedResponse;
const title = html.querySelector('meta[property="cozy:title"]')?.getAttribute('content');
if (title === 'Something is not right') {
const title = html
.querySelector('meta[property="cozy:title"]')
?.getAttribute("content");
if (title === "Something is not right") {
cache.delete(url);
return; // temporary fix for deleting cached errors
}
@ -83,18 +99,21 @@ export interface Props {
link.href = url;
link.onclick = async (e) => {
e.preventDefault();
localStorage.setItem('scrollPosition', window.scrollY.toString());
localStorage.setItem("scrollPosition", window.scrollY.toString());
scrollTo(0, 0);
logInfo('using cached response', {context: 'cozy-reader', data: url})
renderPost(cleanedResponse, url, routerOutlet)
}
const item = document.createElement('li');
console.info("using cached response", {
context: "cozy-reader",
data: url,
});
renderPost(cleanedResponse, url, routerOutlet);
};
const item = document.createElement("li");
item.appendChild(link);
list?.appendChild(item);
});
});
window.addEventListener('popstate', async (data) => {
window.addEventListener("popstate", async (data) => {
let url = data.state?.url;
let isHome = false;
@ -103,17 +122,20 @@ export interface Props {
isHome = true;
} else {
// replace scrollPosition
localStorage.setItem('scrollPosition', window.scrollY.toString());
localStorage.setItem("scrollPosition", window.scrollY.toString());
}
const fullResponse = await cache.match(url)
const fullResponse = await cache.match(url);
fullResponse?.text().then(async (data) => {
const responseText = data;
const cleanedResponse = await cozify(responseText, baseUrl);
logInfo('using cached response', {context: 'cozy-reader', data: url})
console.info("using cached response", {
context: "cozy-reader",
data: url,
});
renderPost(cleanedResponse, url, routerOutlet, true);
if (isHome) {
const scrollPosition = localStorage.getItem('scrollPosition');
const scrollPosition = localStorage.getItem("scrollPosition");
scrollTo(0, scrollPosition ? parseInt(scrollPosition) : 0);
}
});
@ -122,7 +144,6 @@ export interface Props {
</script>
<style>
#library {
span#heading {
color: #555;
@ -137,7 +158,6 @@ export interface Props {
gap: 1em;
li {
a {
text-decoration: none;
color: #000;
@ -151,7 +171,8 @@ export interface Props {
grid-template-columns: calc(70px + 0.5em) auto;
.post-card__image {
img, svg {
img,
svg {
width: 70px;
height: 70px;
object-fit: cover;
@ -173,14 +194,16 @@ export interface Props {
min-height: calc(70px + 0.5rem);
}
.post-card__title, .post-card__description {
.post-card__title,
.post-card__description {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.post-card__meta, .post-card__description {
.post-card__meta,
.post-card__description {
font-size: smaller;
color: #555;
}
@ -202,7 +225,6 @@ export interface Props {
text-align: right;
}
}
}
}
}

View file

@ -1,18 +1,16 @@
import { logError, logInfo } from './utils/logger'
/**
* Note: @ayco/astro-sw integration injects variables `__prefix`, `__version`, & `__assets`
* -- find usage in `astro.config.mjs` integrations
* @see https://ayco.io/n/@ayco/astro-sw
*/
const cacheName = `${__prefix ?? 'app'}-v${__version ?? '000'}`
const forceLogging = true;
const cleanOldCaches = async () => {
const allowCacheNames = ['cozy-reader', cacheName];
const allCaches = await caches.keys();
allCaches.forEach(key => {
if (!allowCacheNames.includes(key)) {
logInfo('Deleting old cache', {force: !!forceLogging, data: key, context: 'cozy-sw'});
console.info('Deleting old cache', key);
caches.delete(key);
}
});
@ -20,14 +18,14 @@ const cleanOldCaches = async () => {
const addResourcesToCache = async (resources) => {
const cache = await caches.open(cacheName);
logInfo('adding resources to cache...', { force: !!forceLogging, context: 'cozy-sw', data: resources })
console.info('adding resources to cache...', resources)
try {
await cache.addAll(resources);
} catch(error) {
logError('failed to add resources to cache; make sure requests exists and that there are no duplicates', {force: !!forceLogging, context: 'cozy-sw', data: {
console.error('failed to add resources to cache; make sure requests exists and that there are no duplicates', {
resources,
error
}})
})
}
};
@ -35,7 +33,7 @@ const putInCache = async (request, response) => {
const cache = await caches.open(cacheName);
if (response.ok) {
logInfo('adding one response to cache...', { force: forceLogging, context: 'cozy-sw', data: request.url })
console.info('adding one response to cache...', request.url)
// if exists, replace
cache.keys().then( keys => {
@ -56,15 +54,15 @@ const cacheAndRevalidate = async ({ request, fallbackUrl }) => {
// Try get the resource from the cache
const responseFromCache = await cache.match(request);
if (responseFromCache) {
logInfo('using cached response...', { force: forceLogging, context: 'cozy-sw', data: responseFromCache.url })
console.info('using cached response...', responseFromCache.url);
// get network response for revalidation of cached assets
fetch(request.clone()).then((responseFromNetwork) => {
if (responseFromNetwork) {
logInfo('fetched updated resource...', { force: forceLogging, context: 'cozy-sw', data: responseFromNetwork.url })
console.info('fetched updated resource...', { force: forceLogging, context: 'cozy-sw', data: responseFromNetwork.url })
putInCache(request, responseFromNetwork.clone());
}
}).catch((error) => {
logInfo('failed to fetch updated resource', { force: forceLogging, context: 'cozy-sw', data: error })
console.info('failed to fetch updated resource', { force: forceLogging, context: 'cozy-sw', data: error })
});
return responseFromCache;
@ -77,7 +75,7 @@ const cacheAndRevalidate = async ({ request, fallbackUrl }) => {
// we need to save clone to put one copy in cache
// and serve second one
putInCache(request, responseFromNetwork.clone());
logInfo('using network response', { force: forceLogging, context: 'cozy-sw', data: responseFromNetwork.url })
console.info('using network response', { force: forceLogging, context: 'cozy-sw', data: responseFromNetwork.url })
return responseFromNetwork;
} catch (error) {
@ -85,7 +83,7 @@ const cacheAndRevalidate = async ({ request, fallbackUrl }) => {
// Try the fallback
const fallbackResponse = await cache.match(fallbackUrl);
if (fallbackResponse) {
logInfo('using fallback cached response...', { force: forceLogging, context: 'cozy-sw', data: fallbackResponse.url })
console.info('using fallback cached response...', { force: forceLogging, context: 'cozy-sw', data: fallbackResponse.url })
return fallbackResponse;
}
@ -100,13 +98,13 @@ const cacheAndRevalidate = async ({ request, fallbackUrl }) => {
};
self.addEventListener('activate', (event) => {
logInfo('activating service worker...', { force: forceLogging, context: 'cozy-sw' })
console.info('activating service worker...', { force: forceLogging, context: 'cozy-sw' })
cleanOldCaches();
});
self.addEventListener('install', (event) => {
logInfo('installing service worker...', { force: forceLogging, context: 'cozy-sw' })
console.info('installing service worker...', { force: forceLogging, context: 'cozy-sw' })
self.skipWaiting(); // go straight to activate
event.waitUntil(
@ -115,7 +113,7 @@ self.addEventListener('install', (event) => {
});
self.addEventListener('fetch', (event) => {
logInfo('fetch happened', {data: event});
console.info('fetch happened', {data: event});
event.respondWith(
cacheAndRevalidate({

View file

@ -1,6 +0,0 @@
export type Feature = 'Send to Email' | 'Hide Images';
export const featureFlags: Record<Feature, boolean> = {
'Send to Email': false,
'Hide Images': false,
};

View file

@ -1,35 +0,0 @@
// @ts-check
/**
* This is just a temporary placeholder for a logger singleton
*/
export type LogOptions = {
force?: boolean
context?: string,
data?: any
}
function log(message, method: 'log' | 'info' | 'error' = 'log', options?: LogOptions) {
let {context, force, data} = options ?? {};
context = context && context !== ''
? `[${context}]: `
: ''
if (force) {
console[method](`${context}${message}`, data ?? '');
}
}
export function logMessage(message: string, options: LogOptions) {
log(message, 'log', options);
}
export function logInfo(message: string, options: LogOptions) {
log(message, 'info', options);
}
export function logError(message: string, options: LogOptions) {
log(message, 'error', options);
}