From 5201148f9a963f52837307245178d88be96a09eb Mon Sep 17 00:00:00 2001 From: 3y3 <3y3@ya.ru> Date: Fri, 27 Sep 2024 03:13:31 +0300 Subject: [PATCH] fix: Omit CORS errors - replace fetch with importScripts --- src/indexer/index.ts | 4 ++-- src/worker/index.ts | 33 +++++++++++++++------------------ 2 files changed, 17 insertions(+), 20 deletions(-) diff --git a/src/indexer/index.ts b/src/indexer/index.ts index 78aabaf..7fd81f0 100644 --- a/src/indexer/index.ts +++ b/src/indexer/index.ts @@ -65,8 +65,8 @@ export class Indexer { * @returns {{index: Index, registry: Registry}} */ release(lang: string) { - const index = JSON.stringify(this.indices[lang].build()); - const registry = JSON.stringify(this.docs[lang]); + const index = 'self.indexData=' + JSON.stringify(this.indices[lang].build()); + const registry = 'self.registry=' + JSON.stringify(this.docs[lang]); return {index, registry}; } diff --git a/src/worker/index.ts b/src/worker/index.ts index fb72261..a510a09 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -17,6 +17,8 @@ declare const self: ServiceWorkerGlobalScope & { config?: WorkerConfig; api?: ISearchWorkerApi; language?: (lunr: unknown) => Builder.Plugin; + index: object; + registry: Registry; }; const NOT_INITIALIZED = { @@ -70,22 +72,23 @@ async function load(): Promise<[Index, Registry]> { } const promise: Promise<[Index, Registry]> = (async () => { - const [indexData, registry] = await Promise.all([ - request(`${config.base}/${config.resources.index}`), - request(`${config.base}/${config.resources.registry}`), - ]); + const scripts = [ + `${config.base}/${config.resources.index}`, + `${config.base}/${config.resources.registry}`, + config.resources.language && `${config.base}/${config.resources.language}`, + ].filter(Boolean) as string[]; - if (config.resources.language) { - importScripts(`${config.base}/${config.resources.language}`); - } + // Load resources using importScripts instead of fetch + // because fetch will produce CORS errors on file:// protocol + importScripts(...scripts); - if (self.language) { - self.language(lunr); - } + const {index, registry, language} = self; - const index = Index.load(indexData); + if (language) { + language(lunr); + } - return [index, registry]; + return [Index.load(index), registry]; })(); promise.catch((error) => { @@ -97,9 +100,3 @@ async function load(): Promise<[Index, Registry]> { return [index, registry]; } - -async function request(url: string): Promise { - const request = await fetch(url); - - return request.json(); -}