Skip to content

Commit

Permalink
fix: Omit CORS errors - replace fetch with importScripts
Browse files Browse the repository at this point in the history
  • Loading branch information
3y3 committed Sep 27, 2024
1 parent b899548 commit 5201148
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 20 deletions.
4 changes: 2 additions & 2 deletions src/indexer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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};
}
Expand Down
33 changes: 15 additions & 18 deletions src/worker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ declare const self: ServiceWorkerGlobalScope & {
config?: WorkerConfig;
api?: ISearchWorkerApi;
language?: (lunr: unknown) => Builder.Plugin;
index: object;
registry: Registry;
};

const NOT_INITIALIZED = {
Expand Down Expand Up @@ -70,22 +72,23 @@ async function load(): Promise<[Index, Registry]> {
}

const promise: Promise<[Index, Registry]> = (async () => {
const [indexData, registry] = await Promise.all([
request<Index>(`${config.base}/${config.resources.index}`),
request<Registry>(`${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) => {
Expand All @@ -97,9 +100,3 @@ async function load(): Promise<[Index, Registry]> {

return [index, registry];
}

async function request<T>(url: string): Promise<T> {
const request = await fetch(url);

return request.json();
}

0 comments on commit 5201148

Please sign in to comment.