User:Thundercraft5/sw.js

// Add any test code here. // DO NOT SUBMIT TO JSRT! /* global self, Request */ /* jshint undef:true, esversion: 6 */ const map = { "test": "User:Thundercraft5/sw.js/module.js", "test2": "User:Thundercraft5/sw.js/module2.js", };

const providers = { "unpkg": "https://unpkg.com/${PACKAGE}@${VERSION|latest}/${PATH}", "esm-sh": "https://esm.sh/${PACKAGE}@${VERSION|latest}/${PATH}", "jsdelivr": "https://cdn.jsdelivr.com/npm/${PACKAGE}@${VERSION|latest}/${PATH}", };

function formatString(s, replacements) { return s.replace(/\${(? \w+?)(?:\|(?.+?)?})/g, (...args) => {		const { name, defaultValue } = args.shift;		return replacements[name] || defaultValue || "";	}); }

self.addEventListener('fetch', event => { // ignore:line	let { request: { url }, request } = event;	url = new URL(url);	console.log(event.clientId, url, Object.fromEntries(request.headers));	if (url.pathname.match(/^\/@(?!.*\/wiki\/).*(\.[mc]?js$)?/)) {		let normalized = url.pathname.replace(/^\/@/g, "");		console.log(normalized);		const isSpecifier = ![".", "/"].some(s => normalized.includes(s));		const { groups: providerMatch } = normalized.match(/^(? [\w\-]+):(? [a-z\-0-9]+)(?:@(? [\d\.]{1,3}\d+|latest))?(? [^\&\?\#]+)?/) || {};		if (isSpecifier && !providerMatch) {			normalized = map[normalized];			if (!normalized) {				console.warn(`Module specifier "${normalized}" not found!`);				return event.respondWith(Promise.reject(new Error(`Module specifier "${normalized}" could not be resolved`)));			}		} else if (providerMatch) {			const { provider, path, version = "latest", package: packageName } = providerMatch;			normalized = formatString(providers[provider], { PACKAGE: packageName, PATH: path, VERSION: version, });		}		normalized = new URL(normalized, url);		url.searchParams.append("action", "raw");		url.searchParams.append("ctype", "text/javascript");		url.searchParams.set("title", normalized);		url.pathname = "/index.php";		event.respondWith(fetch(new Request(url, { ...request })) .then(async response => {				const headers = Object.fromEntries(response.headers);				if (headers?.["content-type"]?.split(";").shift !== "text/javascript") 					throw new Error(`Server responded with a MIME type of "${headers["content-type"].split(";").shift}", expected "text/javascript" instead`);				return [					{ ...response, url }, 					headers,					await response.text,				];			}) .then(([response, headers, text]) => new Response(new Blob([text], { type: headers["content-type"] }), { ...response }))); 	} });

self.addEventListener('activate', event => {	console.log(event); });

self.addEventListener('install', event => {	console.log(event);	});