Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

balena-request

Package Overview
Dependencies
Maintainers
1
Versions
177
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

balena-request - npm Package Compare versions

Comparing version 11.4.2 to 11.5.0-ts-f42aae2871081c6197106a0cbae874b1ae388e7c

build/progress.d.ts

12

build/progress.js

@@ -61,2 +61,9 @@ "use strict";

/**
* This callback is displayed as a global member.
* @callback estimateStreamCallback
* @param {BalenaRequestOptions} options
*
* @returns {Promise<NodeJS.ReadableStream>} request stream
*/
/**
* @summary Make a node request with progress

@@ -66,3 +73,3 @@ * @function

*
* @returns {(options) => Promise<NodeJS.ReadableStream>} request stream
* @returns {estimateStreamCallback} request stream callback
*

@@ -99,3 +106,2 @@ * @example

const output = new stream.PassThrough();
// @ts-expect-error
output.response = response;

@@ -121,3 +127,3 @@ const responseLength = utils.getResponseLength(response);

// Always using Z_SYNC_FLUSH is what cURL does.
var zlibOptions = {
let zlibOptions = {
flush: zlib.constants.Z_SYNC_FLUSH,

@@ -124,0 +130,0 @@ finishFlush: zlib.constants.Z_SYNC_FLUSH,

@@ -20,5 +20,2 @@ "use strict";

const tslib_1 = require("tslib");
/**
* @module request
*/
const urlLib = require("url");

@@ -28,4 +25,9 @@ const errors = require("balena-errors");

/**
* @module request
*/
/**
* @summary Creates a new balena-request instance.
*
* @param {object} options
* @param {import('balena-auth').default} options.auth
* @param {object} options.auth
* @param {boolean} options.debug

@@ -36,3 +38,3 @@ * @param {number} options.retries

*/
function getRequest({ auth, debug = false, retries = 0, isBrowser = false, interceptors = [], }) {
function getRequest({ auth, debug = false, retries = 0, isBrowser = false, interceptors: $interceptors = [], }) {
const requestAsync = utils.getRequestAsync();

@@ -47,3 +49,2 @@ const requestStream = isBrowser

: utils.debugRequest;
const exports = {};
const prepareOptions = function (options) {

@@ -71,3 +72,3 @@ return tslib_1.__awaiter(this, void 0, void 0, function* () {

if (baseUrl && !isAbsoluteUrl) {
yield exports.refreshToken({ baseUrl });
yield refreshToken({ baseUrl });
}

@@ -101,3 +102,3 @@ if (yield auth.isExpired()) {

const interceptResponseError = (responseError) => interceptResponseOrError(Promise.reject(responseError));
var interceptRequestOrError = (initialPromise) => tslib_1.__awaiter(this, void 0, void 0, function* () {
const interceptRequestOrError = (initialPromise) => tslib_1.__awaiter(this, void 0, void 0, function* () {
return exports.interceptors.reduce(function (promise, { request, requestError }) {

@@ -112,6 +113,8 @@ if (request != null || requestError != null) {

});
var interceptResponseOrError = function (initialPromise) {
const interceptResponseOrError = function (initialPromise) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
interceptors = exports.interceptors.slice().reverse();
return interceptors.reduce(function (promise, { response, responseError }) {
return exports.interceptors
.slice()
.reverse()
.reduce(function (promise, { response, responseError }) {
if (response != null || responseError != null) {

@@ -167,3 +170,3 @@ return promise.then(response, responseError);

*/
exports.send = function (options) {
function send(options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {

@@ -204,3 +207,3 @@ // Only set the default timeout when doing a normal HTTP

});
};
}
/**

@@ -244,3 +247,3 @@ * @summary Stream an HTTP response from balena.

*/
exports.stream = function (options) {
function stream(options) {
const progress = require('./progress');

@@ -251,6 +254,4 @@ return prepareOptions(options)

const download = yield progress.estimate(requestStream, isBrowser)(opts);
// @ts-expect-error
if (!utils.isErrorCode(download.response.statusCode)) {
// TODO: Move this to balena-image-manager
// @ts-expect-error
download.mime = download.response.headers.get('Content-Type');

@@ -271,31 +272,9 @@ return download;

const responseError = chunks.join() || 'The request was unsuccessful';
// @ts-expect-error
debugRequest(options, download.response);
// @ts-expect-error
throw new errors.BalenaRequestError(responseError,
// @ts-expect-error
download.response.statusCode);
throw new errors.BalenaRequestError(responseError, download.response.statusCode);
}))
.then(interceptResponse, interceptResponseError);
};
.then((x) => interceptResponse(x), interceptResponseError);
}
/**
* @summary Array of interceptors
* @type {Interceptor[]}
* @public
*
* @description
* The current array of interceptors to use. Interceptors intercept requests made
* by calls to `.stream()` and `.send()` (some of which are made internally) and
* are executed in the order they appear in this array for requests, and in the
* reverse order for responses.
*
* @example
* request.interceptors.push(
* requestError: (error) ->
* console.log(error)
* throw error
* )
*/
exports.interceptors = interceptors;
/**
* @typedef Interceptor

@@ -329,2 +308,22 @@ * @type {object}

/**
* @summary Array of interceptor
* @type {Interceptor[]}
* @public
*
* @description
* The current array of interceptors to use. Interceptors intercept requests made
* by calls to `.stream()` and `.send()` (some of which are made internally) and
* are executed in the order they appear in this array for requests, and in the
* reverse order for responses.
*
* @example
* request.interceptors.push(
* requestError: (error) ->
* console.log(error)
* throw error
* )
*/
// Shortcut to get the correct jsdoc readme generated
const interceptors = $interceptors;
/**
* @summary Refresh token on user request

@@ -346,3 +345,3 @@ * @function

*/
exports.refreshToken = function ({ baseUrl }) {
function refreshToken({ baseUrl, }) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {

@@ -355,3 +354,3 @@ // Only refresh if we have balena-auth

try {
response = yield exports.send({
response = yield send({
url: '/user/v1/refresh-token',

@@ -374,2 +373,8 @@ baseUrl,

});
}
const exports = {
send,
stream,
interceptors,
refreshToken,
};

@@ -376,0 +381,0 @@ return exports;

@@ -29,3 +29,3 @@ "use strict";

*/
exports.TOKEN_REFRESH_INTERVAL = 1 * 1000 * 60 * 60; // 1 hour in milliseconds
exports.TOKEN_REFRESH_INTERVAL = 1 * 60 * 60 * 1000; // 1 hour in milliseconds
/**

@@ -40,3 +40,3 @@ * @summary Determine if the token should be updated

*
* @param {import('balena-auth').default} auth - an instance of `balena-auth`
* @param {object} auth - an instance of `balena-auth`
* @returns {Promise<Boolean>} the token should be updated

@@ -50,2 +50,3 @@ *

function shouldRefreshKey(auth) {
var _a;
return tslib_1.__awaiter(this, void 0, void 0, function* () {

@@ -60,4 +61,3 @@ const hasKey = yield auth.hasKey();

}
const age = yield auth.getAge();
// @ts-expect-error
const age = (_a = (yield auth.getAge())) !== null && _a !== void 0 ? _a : 0;
return age >= exports.TOKEN_REFRESH_INTERVAL;

@@ -75,3 +75,3 @@ });

*
* @param {import('balena-auth').default} auth - an instance of `balena-auth`
* @param {object} auth - an instance of `balena-auth`
* @returns {Promise<string | undefined>} authorization header

@@ -84,3 +84,3 @@ *

*/
exports.getAuthorizationHeader = function (auth) {
function getAuthorizationHeader(auth) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {

@@ -97,3 +97,4 @@ if (auth == null) {

});
};
}
exports.getAuthorizationHeader = getAuthorizationHeader;
/**

@@ -199,6 +200,3 @@ * @summary Get error message from response

function debugRequest(options, response) {
return console.error(Object.assign({
statusCode: response.statusCode,
duration: response.duration,
}, options));
return console.error(Object.assign({ statusCode: response.statusCode, duration: response.duration }, options));
}

@@ -241,6 +239,6 @@ exports.debugRequest = debugRequest;

const processRequestOptions = function (options) {
if (options == null) {
options = {};
let url = options.url || options.uri;
if (url == null) {
throw new Error('url option not provided');
}
let url = options.url || options.uri;
if (options.baseUrl) {

@@ -253,8 +251,2 @@ url = urlLib.resolve(options.baseUrl, url);

}
const opts = {};
opts.timeout = options.timeout;
opts.retries = options.retries;
opts.method = options.method;
opts.compress = options.gzip;
opts.signal = options.signal;
let { body, headers } = options;

@@ -268,3 +260,2 @@ if (headers == null) {

}
opts.body = body;
if (!IS_BROWSER) {

@@ -275,15 +266,12 @@ if (!headers['Accept-Encoding']) {

}
if (options.followRedirect) {
opts.redirect = 'follow';
}
opts.headers = new HeadersPonyfill(headers);
if (options.strictSSL === false) {
throw new Error('`strictSSL` must be true or absent');
}
for (let key of UNSUPPORTED_REQUEST_PARAMS) {
if (options[key] != null) {
throw new Error(`The ${key} param is not supported. Value: ${options[key]}`);
for (const key of UNSUPPORTED_REQUEST_PARAMS) {
const unsupportedOptionValue = options[key];
if (unsupportedOptionValue != null) {
throw new Error(`The ${key} param is not supported. Value: ${unsupportedOptionValue}`);
}
}
opts.mode = 'cors';
const opts = Object.assign({ timeout: options.timeout, retries: options.retries, method: options.method, compress: options.gzip, signal: options.signal, body, headers: new HeadersPonyfill(headers), mode: 'cors' }, (options.followRedirect && { redirect: 'follow' }));
return [url, opts];

@@ -336,3 +324,3 @@ };

// This is the actual implementation that hides the internal `retriesRemaining` parameter
var requestAsync = function (fetch, options, retriesRemaining) {
function requestAsync(fetch, options, retriesRemaining) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {

@@ -364,3 +352,3 @@ const [url, opts] = processRequestOptions(options);

}
const response = yield p;
const response = (yield p);
if (opts.signal) {

@@ -385,4 +373,4 @@ handleAbortIfNotSupported(opts.signal, response);

});
};
var handleAbortIfNotSupported = function (signal, response) {
}
function handleAbortIfNotSupported(signal, response) {
const emulateAbort = (() => {

@@ -415,3 +403,3 @@ var _a, _b;

}
};
}
/**

@@ -432,8 +420,5 @@ * @summary The factory that returns the `requestAsync` function.

*/
function getRequestAsync(fetch) {
if (fetch == null) {
fetch = normalFetch;
}
return (options) => requestAsync(fetch, options);
function getRequestAsync($fetch = normalFetch) {
return (options) => requestAsync($fetch, options);
}
exports.getRequestAsync = getRequestAsync;

@@ -7,2 +7,9 @@ # Change Log

# v11.5.0
## (2021-11-28)
* Convert tests to JavaScript and drop coffeescript [Thodoris Greasidis]
* Fix the jsdoc generation [Thodoris Greasidis]
* Convert to typescript and publish typings [Thodoris Greasidis]
# v11.4.2

@@ -9,0 +16,0 @@ ## (2021-09-20)

{
"name": "balena-request",
"version": "11.4.2",
"version": "11.5.0-ts-f42aae2871081c6197106a0cbae874b1ae388e7c",
"description": "Balena HTTP client",
"main": "build/request.js",
"types": "build/request.d.ts",
"homepage": "https://github.com/balena-io-modules/balena-request",

@@ -20,8 +21,8 @@ "repository": {

"scripts": {
"lint": "balena-lint -e js --typescript lib",
"lint-fix": "balena-lint -e js --typescript --fix lib",
"lint": "balena-lint -e ts --typescript -e js lib tests",
"lint-fix": "balena-lint -e ts --typescript -e js --fix lib tests",
"pretest": "npm run build",
"test": "npm run test-node && npm run test-browser",
"posttest": "npm run lint",
"test-node": "mocha -r coffeescript/register tests/**/*.spec.coffee",
"test-node": "mocha --reporter spec tests/**/*.spec.js",
"test-browser": "mockttp -c karma start",

@@ -31,3 +32,3 @@ "build": "npx tsc",

"prepare": "npm run build",
"readme": "jsdoc2md --template doc/README.hbs lib/request.js lib/progress.js lib/utils.js > README.md"
"readme": "jsdoc2md --template doc/README.hbs build/request.js build/progress.js build/utils.js > README.md"
},

@@ -43,3 +44,2 @@ "author": "Juan Cruz Viotti <juanchiviotti@gmail.com>",

"bluebird": "^3.7.2",
"coffeescript": "~1.12.7",
"jsdoc-to-markdown": "^6.0.1",

@@ -70,4 +70,4 @@ "karma": "^3.1.4",

"versionist": {
"publishedAt": "2021-09-20T16:51:51.717Z"
"publishedAt": "2021-11-28T12:56:27.952Z"
}
}

@@ -56,13 +56,34 @@ balena-request

* [request](#module_request)
* _static_
* [.interceptors](#module_request.interceptors) : <code>Array.&lt;Interceptor&gt;</code>
* [.send(options)](#module_request.send) ⇒ <code>Promise.&lt;Object&gt;</code>
* [.stream(options)](#module_request.stream) ⇒ <code>Promise.&lt;Stream&gt;</code>
* [.refreshToken()](#module_request.refreshToken) ⇒ <code>String</code>
* _inner_
* [~Interceptor](#module_request..Interceptor) : <code>object</code>
* [~getRequest(options)](#module_request..getRequest)
* [~interceptors](#module_request..getRequest..interceptors) : <code>Array.&lt;Interceptor&gt;</code>
* [~send(options)](#module_request..getRequest..send) ⇒ <code>Promise.&lt;Object&gt;</code>
* [~stream(options)](#module_request..getRequest..stream) ⇒ <code>Promise.&lt;NodeJS.ReadableStream&gt;</code>
* [~refreshToken(options)](#module_request..getRequest..refreshToken) ⇒ <code>Promise.&lt;String&gt;</code>
* [~Interceptor](#module_request..Interceptor) : <code>object</code>
<a name="module_request.interceptors"></a>
<a name="module_request..getRequest"></a>
### request.interceptors : <code>Array.&lt;Interceptor&gt;</code>
### request~getRequest(options)
**Kind**: inner method of [<code>request</code>](#module_request)
**Summary**: Creates a new balena-request instance.
| Param | Type |
| --- | --- |
| options | <code>object</code> |
| options.auth | <code>object</code> |
| options.debug | <code>boolean</code> |
| options.retries | <code>number</code> |
| options.isBrowser | <code>boolean</code> |
| options.interceptors | <code>array</code> |
* [~getRequest(options)](#module_request..getRequest)
* [~interceptors](#module_request..getRequest..interceptors) : <code>Array.&lt;Interceptor&gt;</code>
* [~send(options)](#module_request..getRequest..send) ⇒ <code>Promise.&lt;Object&gt;</code>
* [~stream(options)](#module_request..getRequest..stream) ⇒ <code>Promise.&lt;NodeJS.ReadableStream&gt;</code>
* [~refreshToken(options)](#module_request..getRequest..refreshToken) ⇒ <code>Promise.&lt;String&gt;</code>
<a name="module_request..getRequest..interceptors"></a>
#### getRequest~interceptors : <code>Array.&lt;Interceptor&gt;</code>
The current array of interceptors to use. Interceptors intercept requests made

@@ -73,4 +94,4 @@ by calls to `.stream()` and `.send()` (some of which are made internally) and

**Kind**: static property of [<code>request</code>](#module_request)
**Summary**: Array of interceptors
**Kind**: inner constant of [<code>getRequest</code>](#module_request..getRequest)
**Summary**: Array of interceptor
**Access**: public

@@ -85,5 +106,5 @@ **Example**

```
<a name="module_request.send"></a>
<a name="module_request..getRequest..send"></a>
### request.send(options) ⇒ <code>Promise.&lt;Object&gt;</code>
#### getRequest~send(options) ⇒ <code>Promise.&lt;Object&gt;</code>
This function automatically handles authorization with balena.

@@ -96,3 +117,3 @@

**Kind**: static method of [<code>request</code>](#module_request)
**Kind**: inner method of [<code>getRequest</code>](#module_request..getRequest)
**Summary**: Perform an HTTP request to balena

@@ -111,2 +132,3 @@ **Returns**: <code>Promise.&lt;Object&gt;</code> - response

| [options.body] | <code>\*</code> | | body |
| [options.timeout] | <code>number</code> | | body |

@@ -131,5 +153,5 @@ **Example**

```
<a name="module_request.stream"></a>
<a name="module_request..getRequest..stream"></a>
### request.stream(options) ⇒ <code>Promise.&lt;Stream&gt;</code>
#### getRequest~stream(options) ⇒ <code>Promise.&lt;NodeJS.ReadableStream&gt;</code>
This function emits a `progress` event, passing an object with the following properties:

@@ -149,5 +171,5 @@

**Kind**: static method of [<code>request</code>](#module_request)
**Kind**: inner method of [<code>getRequest</code>](#module_request..getRequest)
**Summary**: Stream an HTTP response from balena.
**Returns**: <code>Promise.&lt;Stream&gt;</code> - response
**Returns**: <code>Promise.&lt;NodeJS.ReadableStream&gt;</code> - response
**Access**: public

@@ -174,10 +196,10 @@

```
<a name="module_request.refreshToken"></a>
<a name="module_request..getRequest..refreshToken"></a>
### request.refreshToken() ⇒ <code>String</code>
#### getRequest~refreshToken(options) ⇒ <code>Promise.&lt;String&gt;</code>
This function automatically refreshes the authentication token.
**Kind**: static method of [<code>request</code>](#module_request)
**Kind**: inner method of [<code>getRequest</code>](#module_request..getRequest)
**Summary**: Refresh token on user request
**Returns**: <code>String</code> - token - new token
**Returns**: <code>Promise.&lt;String&gt;</code> - token - new token
**Access**: public

@@ -187,3 +209,4 @@

| --- | --- | --- |
| options.url | <code>String</code> | relative url |
| options | <code>object</code> | |
| options.baseUrl | <code>String</code> | relative url |

@@ -190,0 +213,0 @@ **Example**

{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"declaration": true,
"outDir": "build",
"noImplicitAny": false,
"removeComments": false,
"preserveConstEnums": true,
"strictNullChecks": true,
"strict": true,
"sourceMap": false,

@@ -11,0 +10,0 @@ "target": "es2015",

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc