Skip to content

Commit

Permalink
Merge branch 'fetch-utilities' into language-select
Browse files Browse the repository at this point in the history
  • Loading branch information
StefanVukovic99 committed Feb 3, 2024
2 parents 0142a91 + c3b594d commit cd560a2
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 67 deletions.
3 changes: 2 additions & 1 deletion ext/js/background/backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ import {ClipboardReader} from '../comm/clipboard-reader.js';
import {Mecab} from '../comm/mecab.js';
import {createApiMap, invokeApiMapHandler} from '../core/api-map.js';
import {ExtensionError} from '../core/extension-error.js';
import {fetchJson, fetchText} from '../core/fetch-utilities.js';
import {log} from '../core/logger.js';
import {clone, deferPromise, fetchJson, fetchText, isObject, promiseTimeout} from '../core/utilities.js';
import {clone, deferPromise, isObject, promiseTimeout} from '../core/utilities.js';
import {isNoteDataValid} from '../data/anki-util.js';
import {OptionsUtil} from '../data/options-util.js';
import {getAllPermissions, hasPermissions, hasRequiredPermissionsForOptions} from '../data/permissions-util.js';
Expand Down
57 changes: 57 additions & 0 deletions ext/js/core/fetch-utilities.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright (C) 2024 Yomitan Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import {readResponseJson} from './json.js';

/**
* @param {string} url
* @returns {Promise<Response>}
*/
async function fetchAsset(url) {
const response = await fetch(chrome.runtime.getURL(url), {
method: 'GET',
mode: 'no-cors',
cache: 'default',
credentials: 'omit',
redirect: 'follow',
referrerPolicy: 'no-referrer'
});
if (!response.ok) {
throw new Error(`Failed to fetch ${url}: ${response.status}`);
}
return response;
}


/**
* @param {string} url
* @returns {Promise<string>}
*/
export async function fetchText(url) {
const response = await fetchAsset(url);
return await response.text();
}

/**
* @template [T=unknown]
* @param {string} url
* @returns {Promise<T>}
*/
export async function fetchJson(url) {
const response = await fetchAsset(url);
return await readResponseJson(response);
}
46 changes: 4 additions & 42 deletions ext/js/data/options-util.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import {parseJson, readResponseJson} from '../core/json.js';
import {fetchJson, fetchText} from '../core/fetch-utilities.js';
import {parseJson} from '../core/json.js';
import {escapeRegExp, isObject} from '../core/utilities.js';
import {TemplatePatcher} from '../templates/template-patcher.js';
import {JsonSchema} from './json-schema.js';
Expand All @@ -32,7 +33,7 @@ export class OptionsUtil {
/** */
async prepare() {
/** @type {import('ext/json-schema').Schema} */
const schema = await this._fetchJson('/data/schemas/options-schema.json');
const schema = await fetchJson('/data/schemas/options-schema.json');
this._optionsSchema = new JsonSchema(schema);
}

Expand Down Expand Up @@ -438,7 +439,7 @@ export class OptionsUtil {
if (fieldTemplates === null) { continue; }

if (patch === null) {
const content = await this._fetchText(modificationsUrl);
const content = await fetchText(modificationsUrl);
if (this._templatePatcher === null) {
this._templatePatcher = new TemplatePatcher();
}
Expand All @@ -449,45 +450,6 @@ export class OptionsUtil {
}
}

/**
* @param {string} url
* @returns {Promise<Response>}
*/
async _fetchGeneric(url) {
url = chrome.runtime.getURL(url);
const response = await fetch(url, {
method: 'GET',
mode: 'no-cors',
cache: 'default',
credentials: 'omit',
redirect: 'follow',
referrerPolicy: 'no-referrer'
});
if (!response.ok) {
throw new Error(`Failed to fetch ${url}: ${response.status}`);
}
return response;
}

/**
* @param {string} url
* @returns {Promise<string>}
*/
async _fetchText(url) {
const response = await this._fetchGeneric(url);
return await response.text();
}

/**
* @template [T=unknown]
* @param {string} url
* @returns {Promise<T>}
*/
async _fetchJson(url) {
const response = await this._fetchGeneric(url);
return await readResponseJson(response);
}

/**
* @param {string} string
* @returns {number}
Expand Down
26 changes: 2 additions & 24 deletions ext/js/dom/sandbox/css-style-applier.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import {readResponseJson} from '../../core/json.js';
import {fetchJson} from '../../core/fetch-utilities.js';

/**
* This class is used to apply CSS styles to elements using a consistent method
Expand Down Expand Up @@ -48,7 +48,7 @@ export class CssStyleApplier {
/** @type {import('css-style-applier').RawStyleData} */
let rawData = [];
try {
rawData = await this._fetchJsonAsset(this._styleDataUrl);
rawData = await fetchJson(this._styleDataUrl);
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
Expand Down Expand Up @@ -98,28 +98,6 @@ export class CssStyleApplier {

// Private

/**
* Fetches and parses a JSON file.
* @template [T=unknown]
* @param {string} url The URL to the file.
* @returns {Promise<T>} A JSON object.
* @throws {Error} An error is thrown if the fetch fails.
*/
async _fetchJsonAsset(url) {
const response = await fetch(url, {
method: 'GET',
mode: 'no-cors',
cache: 'default',
credentials: 'omit',
redirect: 'follow',
referrerPolicy: 'no-referrer'
});
if (!response.ok) {
throw new Error(`Failed to fetch ${url}: ${response.status}`);
}
return await readResponseJson(response);
}

/**
* Gets an array of candidate CSS rules which might match a specific class.
* @param {string} className A whitespace-separated list of classes.
Expand Down

0 comments on commit cd560a2

Please sign in to comment.