UNPKG

propr

Version:

A proper way to interface with prepr.io

284 lines (282 loc) 10.1 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __accessCheck = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet = (obj, member, getter) => { __accessCheck(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet = (obj, member, value, setter) => { __accessCheck(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // src/index.ts var src_exports = {}; __export(src_exports, { createPreprClient: () => createPreprClient, default: () => PreprClient }); module.exports = __toCommonJS(src_exports); var import_ofetch = require("ofetch"); var import_murmurhash = __toESM(require("murmurhash")); var HASH_MULTIPLIER = 2 ** 32 / 1e4; var _headers, _baseUrl, _timeout, _userId, _path, _graphqlQuery, _graphqlVariables; var PreprClient = class { /** * Creates a new PreprClient instance with the specified options. * @param options - The options used to configure the PreprClient instance. */ constructor(options) { /** * The headers used for all requests made by this PreprClient instance. * @private */ __privateAdd(this, _headers, new import_ofetch.Headers()); /** * The base URL of the Prepr API used for all requests made by this PreprClient instance. * @default https://cdn.prepr.io * @private */ __privateAdd(this, _baseUrl, new URL("https://cdn.prepr.io")); /** * The timeout in milliseconds for requests made by this PreprClient instance. * @default 4000 * @private */ __privateAdd(this, _timeout, 4e3); /** * The ID of the user associated with this PreprClient instance. * @private */ __privateAdd(this, _userId, void 0); /** * The path used for the request. * @private */ __privateAdd(this, _path, ""); /** * The GraphQL query used for the request. * @private */ __privateAdd(this, _graphqlQuery, void 0); /** * The GraphQL variables used for the request. * @private */ __privateAdd(this, _graphqlVariables, {}); /** * The query parameters used for the request. * @public */ this.query = new URLSearchParams(); this.token(options.token); if (options.baseUrl) __privateSet(this, _baseUrl, new URL(options.baseUrl)); if (typeof options.timeout === "number") __privateSet(this, _timeout, options.timeout); if (options.userId) __privateSet(this, _userId, this.calculateUserId(options.userId)); } /** * Calculates the numeric user ID from a string. * @private */ calculateUserId(userId) { return (0, import_murmurhash.default)(userId, 1) * HASH_MULTIPLIER; } /** * Sets the user ID for the Prepr-ABTesting header used in requests made by this PreprClient instance. * @param userId - The user ID to set. If `undefined`, the header will be removed from requests. * @returns This PreprClient instance. */ userId(userId) { __privateSet(this, _userId, typeof userId === "string" ? this.calculateUserId(userId) : userId); return this; } /** * Sets the timeout for requests made by this PreprClient instance. * @param milliseconds - The timeout in milliseconds. * @returns This PreprClient instance. */ timeout(milliseconds) { __privateSet(this, _timeout, milliseconds); return this; } /** * Sets the timeout in milliseconds for requests made by this PreprClient instance. * @param milliseconds - The timeout in milliseconds. * @returns This PreprClient instance. */ sort(field) { this.query.set("sort", field); return this; } /** * Sets the maximum number of results to return for requests made by this PreprClient instance. * @param limit - The maximum number of results to return. * @returns This PreprClient instance. */ limit(limit) { this.query.set("limit", `${limit}`); return this; } /** * Sets the number of results to skip for requests made by this PreprClient instance. * @param skip - The number of results to skip. * @returns This PreprClient instance. */ skip(skip) { this.query.set("skip", `${skip}`); return this; } /** * Sets the path for requests made by this PreprClient instance. * @param path - The path to set. * @returns This PreprClient instance. */ path(path) { __privateSet(this, _path, path); return this; } /** * Sets the Prepr API token for requests made by this PreprClient instance. * @param token - The Prepr API token to set. * @returns This PreprClient instance. */ token(token) { __privateGet(this, _headers).set("Authorization", `Bearer ${token}`); return this; } /** * Sets the GraphQL query to include in requests made by this PreprClient instance. * @param graphqlQuery - The GraphQL query to set. * @returns This PreprClient instance. */ graphqlQuery(graphqlQuery) { __privateSet(this, _graphqlQuery, graphqlQuery); return this; } /** * Sets the GraphQL variables to include in requests made by this PreprClient instance. * @param graphqlVariables - The GraphQL variables to set. * @returns This PreprClient instance. */ graphqlVariables(graphqlVariables) { __privateSet(this, _graphqlVariables, graphqlVariables); return this; } /** * Makes a request to the Prepr API. * @param request - The request to make. This can be a URL, a Request object, or a string representing a path to append to the base URL. * @param options - The options for the request. These will be merged with the options set on this PreprClient instance. * @returns A Promise that resolves to the response from the Prepr API. */ fetch() { return __async(this, arguments, function* (request = __privateGet(this, _path), options) { const controller = new AbortController(); const fetchTimeout = setTimeout(controller.abort, __privateGet(this, _timeout)); if (__privateGet(this, _userId)) __privateGet(this, _headers).set("Prepr-ABTesting", `${__privateGet(this, _userId)}`); const gqlOptions = __privateGet(this, _graphqlQuery) ? { method: "POST", body: { query: __privateGet(this, _graphqlQuery), variables: __privateGet(this, _graphqlVariables) } } : {}; const fetcher = import_ofetch.ofetch.create(__spreadValues({ baseURL: __privateGet(this, _baseUrl).toString(), headers: __privateGet(this, _headers), query: this.query, signal: controller.signal, onResponse: () => { clearTimeout(fetchTimeout); this.query = new URLSearchParams(); __privateSet(this, _graphqlQuery, ""); __privateSet(this, _graphqlVariables, {}); } }, gqlOptions)); return fetcher(request, options); }); } }; _headers = new WeakMap(); _baseUrl = new WeakMap(); _timeout = new WeakMap(); _userId = new WeakMap(); _path = new WeakMap(); _graphqlQuery = new WeakMap(); _graphqlVariables = new WeakMap(); var createPreprClient = (options) => new PreprClient(options); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { createPreprClient });