From 0ff54bfcd3f947f34cd26bf9b8b2ea120f34d3a2 Mon Sep 17 00:00:00 2001 From: Ian Walter Date: Sun, 16 Jun 2019 20:34:22 -0400 Subject: [PATCH] Fixing externalDep logic --- dist/dist.js | 24 +- index.js | 46 +- tests/snapshots/cli.tests.snap | 91 +--- tests/snapshots/dist.tests.snap | 795 +------------------------------- 4 files changed, 57 insertions(+), 899 deletions(-) diff --git a/dist/dist.js b/dist/dist.js index ace899e..6925104 100644 --- a/dist/dist.js +++ b/dist/dist.js @@ -2,7 +2,7 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var path = require('path'); +var path = _interopDefault(require('path')); var readPkgUp = _interopDefault(require('read-pkg-up')); var rollup = require('rollup'); var cjsPlugin = _interopDefault(require('rollup-plugin-commonjs')); @@ -16,7 +16,7 @@ var hashbang = _interopDefault(require('@ianwalter/rollup-plugin-hashbang')); async function dist (options) { // Read modules package.json. - const { package: pkg, path: path$1 } = await readPkgUp(); + const { package: pkg, path: projectPath } = await readPkgUp(); // TODO: comment const hasFormat = options.cjs || options.esm || options.browser; @@ -25,8 +25,9 @@ async function dist (options) { // Deconstruct options and set defaults if necessary. let { name = options.name || npmShortName(pkg.name), - input = options.input || path.resolve(path.join(path.dirname(path$1), 'index.js')), - output = options.output || path.join(path.dirname(path$1), 'dist'), + input = options.input || + path.resolve(path.join(path.dirname(projectPath), 'index.js')), + output = options.output || path.join(path.dirname(projectPath), 'dist'), cjs = getFormat(options.cjs, pkg.main), esm = getFormat(options.esm, pkg.module), browser = getFormat(options.browser, pkg.browser) @@ -61,9 +62,18 @@ async function dist (options) { } const byIsNotInlineDep = dep => inlineDeps.indexOf(dep) === -1; const externalDeps = [...builtinModules, ...deps.filter(byIsNotInlineDep)]; - const external = id => ( - externalDeps.includes(id) || externalDeps.some(n => id.includes(n + '/')) - ); + const isInExternal = id => { + try { + const modulePath = require.resolve(id); + if (id !== modulePath) { + return externalDeps.some(external => modulePath.includes(external)) + } + } catch (err) { + // Nothing needs to be done with this error. + } + return false + }; + const external = id => externalDeps.includes(id) || isInExternal(id); // Set the default babel config. const babelConfig = { diff --git a/index.js b/index.js index bc5a666..bda67a4 100644 --- a/index.js +++ b/index.js @@ -1,4 +1,4 @@ -import { dirname, join, resolve, extname } from 'path' +import path from 'path' import readPkgUp from 'read-pkg-up' import { rollup } from 'rollup' import cjsPlugin from 'rollup-plugin-commonjs' @@ -12,7 +12,7 @@ import hashbang from '@ianwalter/rollup-plugin-hashbang' export default async function dist (options) { // Read modules package.json. - const { package: pkg, path } = await readPkgUp() + const { package: pkg, path: projectPath } = await readPkgUp() // TODO: comment const hasFormat = options.cjs || options.esm || options.browser @@ -21,8 +21,9 @@ export default async function dist (options) { // Deconstruct options and set defaults if necessary. let { name = options.name || npmShortName(pkg.name), - input = options.input || resolve(join(dirname(path), 'index.js')), - output = options.output || join(dirname(path), 'dist'), + input = options.input || + path.resolve(path.join(path.dirname(projectPath), 'index.js')), + output = options.output || path.join(path.dirname(projectPath), 'dist'), cjs = getFormat(options.cjs, pkg.main), esm = getFormat(options.esm, pkg.module), browser = getFormat(options.browser, pkg.browser) @@ -36,7 +37,7 @@ export default async function dist (options) { // Import plugins file if specified. let plugins = [] if (typeof options.plugins === 'string') { - const input = resolve(options.plugins) + const input = path.resolve(options.plugins) const external = Object.keys(pkg.devDependencies || {}) const { generate } = await rollup({ input, external }) const { output: [{ code }] } = await generate({ format: 'cjs' }) @@ -57,9 +58,18 @@ export default async function dist (options) { } const byIsNotInlineDep = dep => inlineDeps.indexOf(dep) === -1 const externalDeps = [...builtinModules, ...deps.filter(byIsNotInlineDep)] - const external = id => ( - externalDeps.includes(id) || externalDeps.some(n => id.includes(n + '/')) - ) + const isInExternal = id => { + try { + const modulePath = require.resolve(id) + if (id !== modulePath) { + return externalDeps.some(external => modulePath.includes(external)) + } + } catch (err) { + // Nothing needs to be done with this error. + } + return false + } + const external = id => externalDeps.includes(id) || isInExternal(id) // Set the default babel config. const babelConfig = { @@ -104,16 +114,16 @@ export default async function dist (options) { let esmCode = (esm || browser) ? esmBundle.output[0].code : undefined // Determine the output file paths. - const dir = extname(output) ? dirname(output) : output - const cjsPath = typeof cjs === 'string' && extname(cjs) - ? resolve(cjs) - : join(dir, `${name}.js`) - const esmPath = typeof esm === 'string' && extname(esm) - ? resolve(esm) - : join(dir, `${name}.m.js`) - const browserPath = typeof browser === 'string' && extname(browser) - ? resolve(browser) - : join(dir, `${name}.browser.js`) + const dir = path.extname(output) ? path.dirname(output) : output + const cjsPath = typeof cjs === 'string' && path.extname(cjs) + ? path.resolve(cjs) + : path.join(dir, `${name}.js`) + const esmPath = typeof esm === 'string' && path.extname(esm) + ? path.resolve(esm) + : path.join(dir, `${name}.m.js`) + const browserPath = typeof browser === 'string' && path.extname(browser) + ? path.resolve(browser) + : path.join(dir, `${name}.browser.js`) // Return an object with the properties that use the file path as the key and // the source code as the value. diff --git a/tests/snapshots/cli.tests.snap b/tests/snapshots/cli.tests.snap index 5e822db..773824f 100644 --- a/tests/snapshots/cli.tests.snap +++ b/tests/snapshots/cli.tests.snap @@ -18,6 +18,10 @@ exports[`dist file generated using custom plugins 2`] = ` Object.defineProperty(exports, '__esModule', { value: true }); +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var __vue_normalize__ = _interopDefault(require('vue-runtime-helpers/dist/normalize-component.js')); + // // // @@ -30,91 +34,6 @@ var script = { data: () => ({ name: 'World' }) }; -function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier -/* server only */ -, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) { - if (typeof shadowMode !== 'boolean') { - createInjectorSSR = createInjector; - createInjector = shadowMode; - shadowMode = false; - } // Vue.extend constructor export interop. - - - var options = typeof script === 'function' ? script.options : script; // render functions - - if (template && template.render) { - options.render = template.render; - options.staticRenderFns = template.staticRenderFns; - options._compiled = true; // functional template - - if (isFunctionalTemplate) { - options.functional = true; - } - } // scopedId - - - if (scopeId) { - options._scopeId = scopeId; - } - - var hook; - - if (moduleIdentifier) { - // server build - hook = function hook(context) { - // 2.3 injection - context = context || // cached call - this.$vnode && this.$vnode.ssrContext || // stateful - this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext; // functional - // 2.2 with runInNewContext: true - - if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { - context = __VUE_SSR_CONTEXT__; - } // inject component styles - - - if (style) { - style.call(this, createInjectorSSR(context)); - } // register component module identifier for async chunk inference - - - if (context && context._registeredComponents) { - context._registeredComponents.add(moduleIdentifier); - } - }; // used by ssr in case component is cached and beforeCreate - // never gets called - - - options._ssrRegister = hook; - } else if (style) { - hook = shadowMode ? function () { - style.call(this, createInjectorShadow(this.$root.$options.shadowRoot)); - } : function (context) { - style.call(this, createInjector(context)); - }; - } - - if (hook) { - if (options.functional) { - // register for functional component in vue file - var originalRender = options.render; - - options.render = function renderWithStyleInjection(h, context) { - hook.call(context); - return originalRender(h, context); - }; - } else { - // inject component registration as beforeCreate hook - var existing = options.beforeCreate; - options.beforeCreate = existing ? [].concat(existing, hook) : [hook]; - } - } - - return script; -} - -var normalizeComponent_1 = normalizeComponent; - /* script */ const __vue_script__ = script; @@ -136,7 +55,7 @@ var __vue_staticRenderFns__ = []; - var Greeting = normalizeComponent_1( + var Greeting = __vue_normalize__( { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ }, __vue_inject_styles__, __vue_script__, diff --git a/tests/snapshots/dist.tests.snap b/tests/snapshots/dist.tests.snap index 0bae9d5..57c5775 100644 --- a/tests/snapshots/dist.tests.snap +++ b/tests/snapshots/dist.tests.snap @@ -6,397 +6,10 @@ Object { "/fakePath/exportDefaultFunctionWithImports.js", "'use strict'; -const preserveCamelCase = input => { - let isLastCharLower = false; - let isLastCharUpper = false; - let isLastLastCharUpper = false; - - for (let i = 0; i < input.length; i++) { - const c = input[i]; - - if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) { - input = input.slice(0, i) + '-' + input.slice(i); - isLastCharLower = false; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = true; - i++; - } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(c) && c.toLowerCase() === c) { - input = input.slice(0, i - 1) + '-' + input.slice(i - 1); - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = false; - isLastCharLower = true; - } else { - isLastCharLower = c.toLowerCase() === c; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = c.toUpperCase() === c; - } - } - - return input; -}; - -var camelcase = (input, options) => { - options = Object.assign({ - pascalCase: false - }, options); - - const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x; - - if (Array.isArray(input)) { - input = input.map(x => x.trim()) - .filter(x => x.length) - .join('-'); - } else { - input = input.trim(); - } - - if (input.length === 0) { - return ''; - } - - if (input.length === 1) { - return options.pascalCase ? input.toUpperCase() : input.toLowerCase(); - } - - if (/^[a-z\\\\d]+$/.test(input)) { - return postProcess(input); - } - - const hasUpperCase = input !== input.toLowerCase(); - - if (hasUpperCase) { - input = preserveCamelCase(input); - } - - input = input - .replace(/^[_.\\\\- ]+/, '') - .toLowerCase() - .replace(/[_.\\\\- ]+(\\\\w|$)/g, (m, p1) => p1.toUpperCase()); - - return postProcess(input); -}; - -function npmShortName (name = '') { - const parts = name.split('/'); - return parts.length ? camelcase(parts[parts.length - 1]) : '' -} - -/*! MIT License © Sindre Sorhus */ - -const getGlobal = property => { - /* istanbul ignore next */ - if (typeof self !== 'undefined' && self && property in self) { - return self[property]; - } - - /* istanbul ignore next */ - if (typeof window !== 'undefined' && window && property in window) { - return window[property]; - } - - if (typeof global !== 'undefined' && global && property in global) { - return global[property]; - } - - /* istanbul ignore next */ - if (typeof globalThis !== 'undefined' && globalThis) { - return globalThis[property]; - } -}; - -const document = getGlobal('document'); -const Headers = getGlobal('Headers'); -const Response = getGlobal('Response'); -const fetch = getGlobal('fetch'); -const AbortController = getGlobal('AbortController'); - -const isObject = value => value !== null && typeof value === 'object'; -const supportsAbortController = typeof getGlobal('AbortController') === 'function'; - -const deepMerge = (...sources) => { - let returnValue = {}; - - for (const source of sources) { - if (Array.isArray(source)) { - if (!(Array.isArray(returnValue))) { - returnValue = []; - } - - returnValue = [...returnValue, ...source]; - } else if (isObject(source)) { - for (let [key, value] of Object.entries(source)) { - if (isObject(value) && Reflect.has(returnValue, key)) { - value = deepMerge(returnValue[key], value); - } - - returnValue = {...returnValue, [key]: value}; - } - } - } - - return returnValue; -}; - -const requestMethods = [ - 'get', - 'post', - 'put', - 'patch', - 'head', - 'delete' -]; - -const responseTypes = { - json: 'application/json', - text: 'text/*', - formData: 'multipart/form-data', - arrayBuffer: '*/*', - blob: '*/*' -}; - -const retryMethods = new Set([ - 'get', - 'put', - 'head', - 'delete', - 'options', - 'trace' -]); - -const retryStatusCodes = new Set([ - 408, - 413, - 429, - 500, - 502, - 503, - 504 -]); - -const retryAfterStatusCodes = new Set([ - 413, - 429, - 503 -]); - -class HTTPError extends Error { - constructor(response) { - super(response.statusText); - this.name = 'HTTPError'; - this.response = response; - } -} - -class TimeoutError extends Error { - constructor() { - super('Request timed out'); - this.name = 'TimeoutError'; - } -} - -const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); - -// \`Promise.race()\` workaround (#91) -const timeout = (promise, ms, abortController) => new Promise((resolve, reject) => { - /* eslint-disable promise/prefer-await-to-then */ - promise.then(resolve).catch(reject); - delay(ms).then(() => { - if (supportsAbortController) { - abortController.abort(); - } - - reject(new TimeoutError()); - }); - /* eslint-enable promise/prefer-await-to-then */ -}); - -const normalizeRequestMethod = input => requestMethods.includes(input) ? input.toUpperCase() : input; - -class Ky { - constructor(input, { - timeout = 10000, - hooks, - throwHttpErrors = true, - searchParams, - json, - ...otherOptions - }) { - this._retryCount = 0; - - this._options = { - method: 'get', - credentials: 'same-origin', // TODO: This can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208 - retry: 2, - ...otherOptions - }; - - if (supportsAbortController) { - this.abortController = new AbortController(); - if (this._options.signal) { - this._options.signal.addEventListener('abort', () => { - this.abortController.abort(); - }); - } - - this._options.signal = this.abortController.signal; - } - - this._options.method = normalizeRequestMethod(this._options.method); - this._options.prefixUrl = String(this._options.prefixUrl || ''); - this._input = String(input || ''); - - if (this._options.prefixUrl && this._input.startsWith('/')) { - throw new Error('\`input\` must not begin with a slash when using \`prefixUrl\`'); - } - - if (this._options.prefixUrl && !this._options.prefixUrl.endsWith('/')) { - this._options.prefixUrl += '/'; - } - - this._input = this._options.prefixUrl + this._input; - - if (searchParams) { - const url = new URL(this._input, document && document.baseURI); - if (typeof searchParams === 'string' || (URLSearchParams && searchParams instanceof URLSearchParams)) { - url.search = searchParams; - } else if (Object.values(searchParams).every(param => typeof param === 'number' || typeof param === 'string')) { - url.search = new URLSearchParams(searchParams).toString(); - } else { - throw new Error('The \`searchParams\` option must be either a string, \`URLSearchParams\` instance or an object with string and number values'); - } - - this._input = url.toString(); - } - - this._timeout = timeout; - this._hooks = deepMerge({ - beforeRequest: [], - afterResponse: [] - }, hooks); - this._throwHttpErrors = throwHttpErrors; - - const headers = new Headers(this._options.headers || {}); - - if (json) { - if (this._options.body) { - throw new Error('The \`json\` option cannot be used with the \`body\` option'); - } - - headers.set('content-type', 'application/json'); - this._options.body = JSON.stringify(json); - } - - this._options.headers = headers; - - const fn = async () => { - await delay(1); - let response = await this._fetch(); - - for (const hook of this._hooks.afterResponse) { - // eslint-disable-next-line no-await-in-loop - const modifiedResponse = await hook(response.clone()); - - if (modifiedResponse instanceof Response) { - response = modifiedResponse; - } - } - - if (!response.ok && this._throwHttpErrors) { - throw new HTTPError(response); - } - - return response; - }; - - const isRetriableMethod = retryMethods.has(this._options.method.toLowerCase()); - const result = isRetriableMethod ? this._retry(fn) : fn(); - - for (const [type, mimeType] of Object.entries(responseTypes)) { - result[type] = async () => { - headers.set('accept', mimeType); - return (await result).clone()[type](); - }; - } - - return result; - } - - _calculateRetryDelay(error) { - this._retryCount++; - - if (this._retryCount < this._options.retry && !(error instanceof TimeoutError)) { - if (error instanceof HTTPError) { - if (!retryStatusCodes.has(error.response.status)) { - return 0; - } - - const retryAfter = error.response.headers.get('Retry-After'); - if (retryAfter && retryAfterStatusCodes.has(error.response.status)) { - let after = Number(retryAfter); - if (Number.isNaN(after)) { - after = Date.parse(retryAfter) - Date.now(); - } else { - after *= 1000; - } - - return after; - } - - if (error.response.status === 413) { - return 0; - } - } - - const BACKOFF_FACTOR = 0.3; - return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000; - } - - return 0; - } - - async _retry(fn) { - try { - return await fn(); - } catch (error) { - const ms = this._calculateRetryDelay(error); - if (ms !== 0 && this._retryCount > 0) { - await delay(ms); - return this._retry(fn); - } - - if (this._throwHttpErrors) { - throw error; - } - } - } - - async _fetch() { - for (const hook of this._hooks.beforeRequest) { - // eslint-disable-next-line no-await-in-loop - await hook(this._options); - } - - return timeout(fetch(this._input, this._options), this._timeout, this.abortController); - } -} - -const createInstance = (defaults = {}) => { - if (!isObject(defaults) || Array.isArray(defaults)) { - throw new TypeError('The \`defaultOptions\` argument must be an object'); - } - - const ky = (input, options) => new Ky(input, deepMerge({}, defaults, options)); - - for (const method of requestMethods) { - ky[method] = (input, options) => new Ky(input, deepMerge({}, defaults, options, {method})); - } - - ky.extend = defaults => createInstance(defaults); - - return ky; -}; +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var ky = createInstance(); +var npmShortName = _interopDefault(require('@ianwalter/npm-short-name')); +var ky = _interopDefault(require('ky')); var url = 'Hello World'; @@ -409,397 +22,8 @@ module.exports = greeting; ], "esm": Array [ "/fakePath/exportDefaultFunctionWithImports.m.js", - "const preserveCamelCase = input => { - let isLastCharLower = false; - let isLastCharUpper = false; - let isLastLastCharUpper = false; - - for (let i = 0; i < input.length; i++) { - const c = input[i]; - - if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) { - input = input.slice(0, i) + '-' + input.slice(i); - isLastCharLower = false; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = true; - i++; - } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(c) && c.toLowerCase() === c) { - input = input.slice(0, i - 1) + '-' + input.slice(i - 1); - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = false; - isLastCharLower = true; - } else { - isLastCharLower = c.toLowerCase() === c; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = c.toUpperCase() === c; - } - } - - return input; -}; - -var camelcase = (input, options) => { - options = Object.assign({ - pascalCase: false - }, options); - - const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x; - - if (Array.isArray(input)) { - input = input.map(x => x.trim()) - .filter(x => x.length) - .join('-'); - } else { - input = input.trim(); - } - - if (input.length === 0) { - return ''; - } - - if (input.length === 1) { - return options.pascalCase ? input.toUpperCase() : input.toLowerCase(); - } - - if (/^[a-z\\\\d]+$/.test(input)) { - return postProcess(input); - } - - const hasUpperCase = input !== input.toLowerCase(); - - if (hasUpperCase) { - input = preserveCamelCase(input); - } - - input = input - .replace(/^[_.\\\\- ]+/, '') - .toLowerCase() - .replace(/[_.\\\\- ]+(\\\\w|$)/g, (m, p1) => p1.toUpperCase()); - - return postProcess(input); -}; - -function npmShortName (name = '') { - const parts = name.split('/'); - return parts.length ? camelcase(parts[parts.length - 1]) : '' -} - -/*! MIT License © Sindre Sorhus */ - -const getGlobal = property => { - /* istanbul ignore next */ - if (typeof self !== 'undefined' && self && property in self) { - return self[property]; - } - - /* istanbul ignore next */ - if (typeof window !== 'undefined' && window && property in window) { - return window[property]; - } - - if (typeof global !== 'undefined' && global && property in global) { - return global[property]; - } - - /* istanbul ignore next */ - if (typeof globalThis !== 'undefined' && globalThis) { - return globalThis[property]; - } -}; - -const document = getGlobal('document'); -const Headers = getGlobal('Headers'); -const Response = getGlobal('Response'); -const fetch = getGlobal('fetch'); -const AbortController = getGlobal('AbortController'); - -const isObject = value => value !== null && typeof value === 'object'; -const supportsAbortController = typeof getGlobal('AbortController') === 'function'; - -const deepMerge = (...sources) => { - let returnValue = {}; - - for (const source of sources) { - if (Array.isArray(source)) { - if (!(Array.isArray(returnValue))) { - returnValue = []; - } - - returnValue = [...returnValue, ...source]; - } else if (isObject(source)) { - for (let [key, value] of Object.entries(source)) { - if (isObject(value) && Reflect.has(returnValue, key)) { - value = deepMerge(returnValue[key], value); - } - - returnValue = {...returnValue, [key]: value}; - } - } - } - - return returnValue; -}; - -const requestMethods = [ - 'get', - 'post', - 'put', - 'patch', - 'head', - 'delete' -]; - -const responseTypes = { - json: 'application/json', - text: 'text/*', - formData: 'multipart/form-data', - arrayBuffer: '*/*', - blob: '*/*' -}; - -const retryMethods = new Set([ - 'get', - 'put', - 'head', - 'delete', - 'options', - 'trace' -]); - -const retryStatusCodes = new Set([ - 408, - 413, - 429, - 500, - 502, - 503, - 504 -]); - -const retryAfterStatusCodes = new Set([ - 413, - 429, - 503 -]); - -class HTTPError extends Error { - constructor(response) { - super(response.statusText); - this.name = 'HTTPError'; - this.response = response; - } -} - -class TimeoutError extends Error { - constructor() { - super('Request timed out'); - this.name = 'TimeoutError'; - } -} - -const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); - -// \`Promise.race()\` workaround (#91) -const timeout = (promise, ms, abortController) => new Promise((resolve, reject) => { - /* eslint-disable promise/prefer-await-to-then */ - promise.then(resolve).catch(reject); - delay(ms).then(() => { - if (supportsAbortController) { - abortController.abort(); - } - - reject(new TimeoutError()); - }); - /* eslint-enable promise/prefer-await-to-then */ -}); - -const normalizeRequestMethod = input => requestMethods.includes(input) ? input.toUpperCase() : input; - -class Ky { - constructor(input, { - timeout = 10000, - hooks, - throwHttpErrors = true, - searchParams, - json, - ...otherOptions - }) { - this._retryCount = 0; - - this._options = { - method: 'get', - credentials: 'same-origin', // TODO: This can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208 - retry: 2, - ...otherOptions - }; - - if (supportsAbortController) { - this.abortController = new AbortController(); - if (this._options.signal) { - this._options.signal.addEventListener('abort', () => { - this.abortController.abort(); - }); - } - - this._options.signal = this.abortController.signal; - } - - this._options.method = normalizeRequestMethod(this._options.method); - this._options.prefixUrl = String(this._options.prefixUrl || ''); - this._input = String(input || ''); - - if (this._options.prefixUrl && this._input.startsWith('/')) { - throw new Error('\`input\` must not begin with a slash when using \`prefixUrl\`'); - } - - if (this._options.prefixUrl && !this._options.prefixUrl.endsWith('/')) { - this._options.prefixUrl += '/'; - } - - this._input = this._options.prefixUrl + this._input; - - if (searchParams) { - const url = new URL(this._input, document && document.baseURI); - if (typeof searchParams === 'string' || (URLSearchParams && searchParams instanceof URLSearchParams)) { - url.search = searchParams; - } else if (Object.values(searchParams).every(param => typeof param === 'number' || typeof param === 'string')) { - url.search = new URLSearchParams(searchParams).toString(); - } else { - throw new Error('The \`searchParams\` option must be either a string, \`URLSearchParams\` instance or an object with string and number values'); - } - - this._input = url.toString(); - } - - this._timeout = timeout; - this._hooks = deepMerge({ - beforeRequest: [], - afterResponse: [] - }, hooks); - this._throwHttpErrors = throwHttpErrors; - - const headers = new Headers(this._options.headers || {}); - - if (json) { - if (this._options.body) { - throw new Error('The \`json\` option cannot be used with the \`body\` option'); - } - - headers.set('content-type', 'application/json'); - this._options.body = JSON.stringify(json); - } - - this._options.headers = headers; - - const fn = async () => { - await delay(1); - let response = await this._fetch(); - - for (const hook of this._hooks.afterResponse) { - // eslint-disable-next-line no-await-in-loop - const modifiedResponse = await hook(response.clone()); - - if (modifiedResponse instanceof Response) { - response = modifiedResponse; - } - } - - if (!response.ok && this._throwHttpErrors) { - throw new HTTPError(response); - } - - return response; - }; - - const isRetriableMethod = retryMethods.has(this._options.method.toLowerCase()); - const result = isRetriableMethod ? this._retry(fn) : fn(); - - for (const [type, mimeType] of Object.entries(responseTypes)) { - result[type] = async () => { - headers.set('accept', mimeType); - return (await result).clone()[type](); - }; - } - - return result; - } - - _calculateRetryDelay(error) { - this._retryCount++; - - if (this._retryCount < this._options.retry && !(error instanceof TimeoutError)) { - if (error instanceof HTTPError) { - if (!retryStatusCodes.has(error.response.status)) { - return 0; - } - - const retryAfter = error.response.headers.get('Retry-After'); - if (retryAfter && retryAfterStatusCodes.has(error.response.status)) { - let after = Number(retryAfter); - if (Number.isNaN(after)) { - after = Date.parse(retryAfter) - Date.now(); - } else { - after *= 1000; - } - - return after; - } - - if (error.response.status === 413) { - return 0; - } - } - - const BACKOFF_FACTOR = 0.3; - return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000; - } - - return 0; - } - - async _retry(fn) { - try { - return await fn(); - } catch (error) { - const ms = this._calculateRetryDelay(error); - if (ms !== 0 && this._retryCount > 0) { - await delay(ms); - return this._retry(fn); - } - - if (this._throwHttpErrors) { - throw error; - } - } - } - - async _fetch() { - for (const hook of this._hooks.beforeRequest) { - // eslint-disable-next-line no-await-in-loop - await hook(this._options); - } - - return timeout(fetch(this._input, this._options), this._timeout, this.abortController); - } -} - -const createInstance = (defaults = {}) => { - if (!isObject(defaults) || Array.isArray(defaults)) { - throw new TypeError('The \`defaultOptions\` argument must be an object'); - } - - const ky = (input, options) => new Ky(input, deepMerge({}, defaults, options)); - - for (const method of requestMethods) { - ky[method] = (input, options) => new Ky(input, deepMerge({}, defaults, options, {method})); - } - - ky.extend = defaults => createInstance(defaults); - - return ky; -}; - -var ky = createInstance(); + "import npmShortName from '@ianwalter/npm-short-name'; +import ky from 'ky'; var url = 'Hello World'; @@ -889,21 +113,16 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var camelCase = _interopDefault(require('camelcase')); +var npmShortName = _interopDefault(require('@ianwalter/npm-short-name')); var pSettle = _interopDefault(require('p-settle')); -function npmShortName(name = '') { - const parts = name.split('/'); - return parts.length ? camelCase(parts[parts.length - 1]) : ''; -} - function greeting() { return 'Hello World'; } +exports.npmShortName = npmShortName; exports.pSettle = pSettle; exports.greeting = greeting; -exports.npmShortName = npmShortName; ", ], }