Requests

Useful library for sending requests.

目前為 2020-06-27 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/405822/820811/Requests.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name Requests
// @namespace https://rafaelgssa.gitlab.io/monkey-scripts
// @version 2.0.2
// @author rafaelgssa
// @description Useful library for sending requests.
// @match *://*/*
// @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
// @require https://greasyfork.org/scripts/405813-monkey-utils/code/Monkey%20Utils.js
// @require https://greasyfork.org/scripts/405802-monkey-dom/code/Monkey%20DOM.js
// @grant GM.xmlHttpRequest
// @grant GM_xmlhttpRequest
// ==/UserScript==

/* global DOM, Utils */

/**
 * @typedef {'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'} RequestMethod
 */

/**
 * @template T
 * @typedef {Object} ExtendedResponse
 * @property {string} url
 * @property {string} text
 * @property {T} [json]
 * @property {Document} [dom]
 */

// eslint-disable-next-line
const Requests = (() => {
	/**
	 * Sends a request to a URL with a specific method.
	 * @template T
	 * @param {RequestMethod} method The method to use.
	 * @param {string} url The URL where to send the request.
	 * @param {RequestInit | GM.Request} [options] The options for the request.
	 * @returns {Promise<ExtendedResponse<T>>} The response of the request.
	 */
	const _sendWithMethod = (method, url, options = {}) => {
		return send(url, { ...options, method });
	};

	/**
	 * Sends a request to a URL.
	 * @template T
	 * @param {string} url The URL where to send the request.
	 * @param {RequestInit | GM.Request} [options] The options for the request.
	 * @returns {Promise<ExtendedResponse<T>>} The response of the request.
	 */
	const send = (url, options = {}) => {
		if (_isInternal(url, options)) {
			return _sendInternal(url, options);
		}
		return _sendExternal(url, options);
	};

	/**
	 * Checks if the request is internal (uses window.fetch) or external (uses GM.xmlHttpRequest to bypass CORS).
	 * @param {string} url
	 * @param {RequestInit | GM.Request} options
	 * @returns {options is RequestInit}
	 */
	// eslint-disable-next-line
	const _isInternal = (url, options) => {
		return url.includes(window.location.host);
	};

	/**
	 * Sends an internal request (uses window.fetch).
	 * @template T
	 * @param {string} url
	 * @param {RequestInit} options
	 * @returns {Promise<ExtendedResponse<T>>}
	 */
	const _sendInternal = async (url, options) => {
		const [internalFetch, internalOptions] = _getInternalObjects(options);
		const response = await internalFetch(url, internalOptions);
		/** @type {ExtendedResponse<T>} */
		const extendedResponse = {
			url: response.url,
			text: await response.text(),
		};
		return _processResponse(extendedResponse);
	};

	/**
	 * Allows the request to be made in the current Firefox container.
	 * @param {RequestInit} options
	 * @returns {[Function, RequestInit]}
	 */
	const _getInternalObjects = (options) => {
		if ('wrappedJSObject' in window) {
			window.wrappedJSObject.options = cloneInto(options, window);
			return [window.wrappedJSObject.fetch, window.wrappedJSObject.options];
		}
		return [window.fetch, options];
	};

	/**
	 * Sends an external request (uses GM.xmlHttpRequest to bypass CORS).
	 * @template T
	 * @param {string} url
	 * @param {Partial<GM.Request>} options
	 * @returns {Promise<ExtendedResponse<T>>}
	 */
	const _sendExternal = (url, options) => {
		return new Promise((resolve) => {
			GM.xmlHttpRequest({
				url,
				method: 'GET',
				...options,
				onload: (response) => {
					/** @type {ExtendedResponse<T>} */
					const extendedResponse = {
						url: response.finalUrl,
						text: response.responseText,
					};
					resolve(_processResponse(extendedResponse));
				},
			});
		});
	};

	/**
	 * Processes a response to return DOMs and JSONs already parsed.
	 * @template T
	 * @param {ExtendedResponse<T>} response
	 * @returns {ExtendedResponse<T>}
	 */
	const _processResponse = (response) => {
		const processedResponse = { ...response };
		try {
			processedResponse.dom = DOM.parse(response.text);
		} catch (err) {
			// Response is not a DOM, just ignore.
		}
		try {
			processedResponse.json = JSON.parse(response.text);
		} catch (err) {
			// Response is not a JSON, just ignore.
		}
		return processedResponse;
	};

	/**
	 * Parses a query string into an object.
	 * @param {string} query The query to parse.
	 * @returns {Record<string, string>} The parsed object.
	 */
	const parseQuery = (query) => {
		/** @type {Record<string, string>} */
		const params = {};
		const rawQuery = query.startsWith('?') ? query.slice(1) : query;
		const parts = rawQuery.split('&').filter(Utils.isSet);
		for (const part of parts) {
			const [key, value] = part.split('=').filter(Utils.isSet);
			params[key] = value;
		}
		return params;
	};

	/**
	 * Converts an object to a query string.
	 * @param {Record<string, unknown>} obj The object to convert.
	 * @returns {string} The converted query string, without '?'.
	 */
	const convertToQuery = (obj) => {
		return Object.entries(obj)
			.map((entry) => entry.join('='))
			.join('&');
	};

	return {
		CONNECT: /** @template T */ (
			/** @type [string] | [string, RequestInit | GM.Request] */ ...args
		) => /** @type Promise<ExtendedResponse<T>> */ (_sendWithMethod('CONNECT', args[0], args[1])),
		DELETE: /** @template T */ (
			/** @type [string] | [string, RequestInit | GM.Request] */ ...args
		) => /** @type Promise<ExtendedResponse<T>> */ (_sendWithMethod('DELETE', args[0], args[1])),
		GET: /** @template T */ (/** @type [string] | [string, RequestInit | GM.Request] */ ...args) =>
			/** @type Promise<ExtendedResponse<T>> */ (_sendWithMethod('GET', args[0], args[1])),
		HEAD: /** @template T */ (/** @type [string] | [string, RequestInit | GM.Request] */ ...args) =>
			/** @type Promise<ExtendedResponse<T>> */ (_sendWithMethod('HEAD', args[0], args[1])),
		OPTIONS: /** @template T */ (
			/** @type [string] | [string, RequestInit | GM.Request] */ ...args
		) => /** @type Promise<ExtendedResponse<T>> */ (_sendWithMethod('OPTIONS', args[0], args[1])),
		PATCH: /** @template T */ (
			/** @type [string] | [string, RequestInit | GM.Request] */ ...args
		) => /** @type Promise<ExtendedResponse<T>> */ (_sendWithMethod('PATCH', args[0], args[1])),
		POST: /** @template T */ (/** @type [string] | [string, RequestInit | GM.Request] */ ...args) =>
			/** @type Promise<ExtendedResponse<T>> */ (_sendWithMethod('POST', args[0], args[1])),
		PUT: /** @template T */ (/** @type [string] | [string, RequestInit | GM.Request] */ ...args) =>
			/** @type Promise<ExtendedResponse<T>> */ (_sendWithMethod('PUT', args[0], args[1])),
		TRACE: /** @template T */ (
			/** @type [string] | [string, RequestInit | GM.Request] */ ...args
		) => /** @type Promise<ExtendedResponse<T>> */ (_sendWithMethod('TRACE', args[0], args[1])),
		send,
		parseQuery,
		convertToQuery,
	};
})();