Auto-commit 2026-04-29 16:31

This commit is contained in:
2026-04-29 16:31:27 -04:00
parent e8687bb6b2
commit 0495ee5bd2
19691 changed files with 3272886 additions and 138 deletions

202
node_modules/gcp-metadata/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

235
node_modules/gcp-metadata/README.md generated vendored Normal file
View File

@@ -0,0 +1,235 @@
[//]: # "This README.md file is auto-generated, all changes to this file will be lost."
[//]: # "To regenerate it, use `python -m synthtool`."
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>
# [GCP Metadata: Node.js Client](https://github.com/googleapis/gcp-metadata)
[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages)
[![npm version](https://img.shields.io/npm/v/gcp-metadata.svg)](https://www.npmjs.com/package/gcp-metadata)
Get the metadata from a Google Cloud Platform environment
A comprehensive list of changes in each version may be found in
[the CHANGELOG](https://github.com/googleapis/gcp-metadata/blob/main/CHANGELOG.md).
* [GCP Metadata Node.js Client API Reference][client-docs]
* [GCP Metadata Documentation][product-docs]
* [github.com/googleapis/gcp-metadata](https://github.com/googleapis/gcp-metadata)
Read more about the client libraries for Cloud APIs, including the older
Google APIs Client Libraries, in [Client Libraries Explained][explained].
[explained]: https://cloud.google.com/apis/docs/client-libraries-explained
**Table of contents:**
* [Quickstart](#quickstart)
* [Installing the client library](#installing-the-client-library)
* [Using the client library](#using-the-client-library)
* [Samples](#samples)
* [Versioning](#versioning)
* [Contributing](#contributing)
* [License](#license)
## Quickstart
### Installing the client library
```bash
npm install gcp-metadata
```
### Using the client library
```javascript
const gcpMetadata = require('gcp-metadata');
async function quickstart() {
// check to see if this code can access a metadata server
const isAvailable = await gcpMetadata.isAvailable();
console.log(`Is available: ${isAvailable}`);
// Instance and Project level metadata will only be available if
// running inside of a Google Cloud compute environment such as
// Cloud Functions, App Engine, Kubernetes Engine, or Compute Engine.
// To learn more about the differences between instance and project
// level metadata, see:
// https://cloud.google.com/compute/docs/storing-retrieving-metadata#project-instance-metadata
if (isAvailable) {
// grab all top level metadata from the service
const instanceMetadata = await gcpMetadata.instance();
console.log('Instance metadata:');
console.log(instanceMetadata);
// get all project level metadata
const projectMetadata = await gcpMetadata.project();
console.log('Project metadata:');
console.log(projectMetadata);
}
}
quickstart();
```
#### Check to see if the metadata server is available
```js
const isAvailable = await gcpMetadata.isAvailable();
```
#### Access all metadata
```js
const data = await gcpMetadata.instance();
console.log(data); // ... All metadata properties
```
#### Access specific properties
```js
const data = await gcpMetadata.instance('hostname');
console.log(data); // ...Instance hostname
const projectId = await gcpMetadata.project('project-id');
console.log(projectId); // ...Project ID of the running instance
```
#### Access nested properties with the relative path
```js
const data = await gcpMetadata.instance('service-accounts/default/email');
console.log(data); // ...Email address of the Compute identity service account
```
#### Access specific properties with query parameters
```js
const data = await gcpMetadata.instance({
property: 'tags',
params: { alt: 'text' }
});
console.log(data) // ...Tags as newline-delimited list
```
#### Access with custom headers
```js
await gcpMetadata.instance({
headers: { 'no-trace': '1' }
}); // ...Request is untraced
```
### Take care with large number valued properties
In some cases number valued properties returned by the Metadata Service may be
too large to be representable as JavaScript numbers. In such cases we return
those values as `BigNumber` objects (from the [bignumber.js](https://github.com/MikeMcl/bignumber.js) library). Numbers
that fit within the JavaScript number range will be returned as normal number
values.
```js
const id = await gcpMetadata.instance('id');
console.log(id) // ... BigNumber { s: 1, e: 18, c: [ 45200, 31799277581759 ] }
console.log(id.toString()) // ... 4520031799277581759
```
### Environment variables
* `GCE_METADATA_HOST`: provide an alternate host or IP to perform lookup against (useful, for example, you're connecting through a custom proxy server).
For example:
```
export GCE_METADATA_HOST='169.254.169.254'
```
* `DETECT_GCP_RETRIES`: number representing number of retries that should be attempted on metadata lookup.
* `DEBUG_AUTH`: emit debugging logs
* `METADATA_SERVER_DETECTION`: configure desired metadata server availability check behavior.
* `assume-present`: don't try to ping the metadata server, but assume it's present
* `none`: don't try to ping the metadata server, but don't try to use it either
* `bios-only`: treat the result of a BIOS probe as canonical (don't fall back to pinging)
* `ping-only`: skip the BIOS probe, and go straight to pinging
## Samples
Samples are in the [`samples/`](https://github.com/googleapis/gcp-metadata/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample.
| Sample | Source Code | Try it |
| --------------------------- | --------------------------------- | ------ |
| Quickstart | [source code](https://github.com/googleapis/gcp-metadata/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/gcp-metadata&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) |
The [GCP Metadata Node.js Client API Reference][client-docs] documentation
also contains samples.
## Supported Node.js Versions
Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule).
Libraries are compatible with all current _active_ and _maintenance_ versions of
Node.js.
If you are using an end-of-life version of Node.js, we recommend that you update
as soon as possible to an actively supported LTS version.
Google's client libraries support legacy versions of Node.js runtimes on a
best-efforts basis with the following warnings:
* Legacy versions are not tested in continuous integration.
* Some security patches and features cannot be backported.
* Dependencies cannot be kept up-to-date.
Client libraries targeting some end-of-life versions of Node.js are available, and
can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag).
The dist-tags follow the naming convention `legacy-(version)`.
For example, `npm install gcp-metadata@legacy-8` installs client libraries
for versions compatible with Node.js 8.
## Versioning
This library follows [Semantic Versioning](http://semver.org/).
This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways
unless absolutely necessary (e.g. because of critical security issues) or with
an extensive deprecation period. Issues and requests against **stable** libraries
are addressed with the highest priority.
More Information: [Google Cloud Platform Launch Stages][launch_stages]
[launch_stages]: https://cloud.google.com/terms/launch-stages
## Contributing
Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/gcp-metadata/blob/main/CONTRIBUTING.md).
Please note that this `README.md`, the `samples/README.md`,
and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`)
are generated from a central template. To edit one of these files, make an edit
to its templates in
[directory](https://github.com/googleapis/synthtool).
## License
Apache Version 2.0
See [LICENSE](https://github.com/googleapis/gcp-metadata/blob/main/LICENSE)
[client-docs]: https://cloud.google.com/nodejs/docs/reference/gcp-metadata/latest
[product-docs]: https://cloud.google.com/compute/docs/storing-retrieving-metadata
[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png
[projects]: https://console.cloud.google.com/project
[billing]: https://support.google.com/cloud/answer/6293499#enable-billing
[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local

57
node_modules/gcp-metadata/build/src/gcp-residency.d.ts generated vendored Normal file
View File

@@ -0,0 +1,57 @@
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Known paths unique to Google Compute Engine Linux instances
*/
export declare const GCE_LINUX_BIOS_PATHS: {
BIOS_DATE: string;
BIOS_VENDOR: string;
};
/**
* Determines if the process is running on a Google Cloud Serverless environment (Cloud Run or Cloud Functions instance).
*
* Uses the:
* - {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}.
* - {@link https://cloud.google.com/functions/docs/env-var Cloud Functions environment variables}.
*
* @returns {boolean} `true` if the process is running on GCP serverless, `false` otherwise.
*/
export declare function isGoogleCloudServerless(): boolean;
/**
* Determines if the process is running on a Linux Google Compute Engine instance.
*
* @returns {boolean} `true` if the process is running on Linux GCE, `false` otherwise.
*/
export declare function isGoogleComputeEngineLinux(): boolean;
/**
* Determines if the process is running on a Google Compute Engine instance with a known
* MAC address.
*
* @returns {boolean} `true` if the process is running on GCE (as determined by MAC address), `false` otherwise.
*/
export declare function isGoogleComputeEngineMACAddress(): boolean;
/**
* Determines if the process is running on a Google Compute Engine instance.
*
* @returns {boolean} `true` if the process is running on GCE, `false` otherwise.
*/
export declare function isGoogleComputeEngine(): boolean;
/**
* Determines if the process is running on Google Cloud Platform.
*
* @returns {boolean} `true` if the process is running on GCP, `false` otherwise.
*/
export declare function detectGCPResidency(): boolean;

114
node_modules/gcp-metadata/build/src/gcp-residency.js generated vendored Normal file
View File

@@ -0,0 +1,114 @@
"use strict";
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.GCE_LINUX_BIOS_PATHS = void 0;
exports.isGoogleCloudServerless = isGoogleCloudServerless;
exports.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux;
exports.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress;
exports.isGoogleComputeEngine = isGoogleComputeEngine;
exports.detectGCPResidency = detectGCPResidency;
const fs_1 = require("fs");
const os_1 = require("os");
/**
* Known paths unique to Google Compute Engine Linux instances
*/
exports.GCE_LINUX_BIOS_PATHS = {
BIOS_DATE: '/sys/class/dmi/id/bios_date',
BIOS_VENDOR: '/sys/class/dmi/id/bios_vendor',
};
const GCE_MAC_ADDRESS_REGEX = /^42:01/;
/**
* Determines if the process is running on a Google Cloud Serverless environment (Cloud Run or Cloud Functions instance).
*
* Uses the:
* - {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}.
* - {@link https://cloud.google.com/functions/docs/env-var Cloud Functions environment variables}.
*
* @returns {boolean} `true` if the process is running on GCP serverless, `false` otherwise.
*/
function isGoogleCloudServerless() {
/**
* `CLOUD_RUN_JOB` is used for Cloud Run Jobs
* - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}.
*
* `FUNCTION_NAME` is used in older Cloud Functions environments:
* - See {@link https://cloud.google.com/functions/docs/env-var Python 3.7 and Go 1.11}.
*
* `K_SERVICE` is used in Cloud Run and newer Cloud Functions environments:
* - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}.
* - See {@link https://cloud.google.com/functions/docs/env-var Cloud Functions newer runtimes}.
*/
const isGFEnvironment = process.env.CLOUD_RUN_JOB ||
process.env.FUNCTION_NAME ||
process.env.K_SERVICE;
return !!isGFEnvironment;
}
/**
* Determines if the process is running on a Linux Google Compute Engine instance.
*
* @returns {boolean} `true` if the process is running on Linux GCE, `false` otherwise.
*/
function isGoogleComputeEngineLinux() {
if ((0, os_1.platform)() !== 'linux')
return false;
try {
// ensure this file exist
(0, fs_1.statSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_DATE);
// ensure this file exist and matches
const biosVendor = (0, fs_1.readFileSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR, 'utf8');
return /Google/.test(biosVendor);
}
catch {
return false;
}
}
/**
* Determines if the process is running on a Google Compute Engine instance with a known
* MAC address.
*
* @returns {boolean} `true` if the process is running on GCE (as determined by MAC address), `false` otherwise.
*/
function isGoogleComputeEngineMACAddress() {
const interfaces = (0, os_1.networkInterfaces)();
for (const item of Object.values(interfaces)) {
if (!item)
continue;
for (const { mac } of item) {
if (GCE_MAC_ADDRESS_REGEX.test(mac)) {
return true;
}
}
}
return false;
}
/**
* Determines if the process is running on a Google Compute Engine instance.
*
* @returns {boolean} `true` if the process is running on GCE, `false` otherwise.
*/
function isGoogleComputeEngine() {
return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress();
}
/**
* Determines if the process is running on Google Cloud Platform.
*
* @returns {boolean} `true` if the process is running on GCP, `false` otherwise.
*/
function detectGCPResidency() {
return isGoogleCloudServerless() || isGoogleComputeEngine();
}
//# sourceMappingURL=gcp-residency.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"gcp-residency.js","sourceRoot":"","sources":["../../src/gcp-residency.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAwBH,0DAkBC;AAOD,gEAcC;AAQD,0EAcC;AAOD,sDAEC;AAOD,gDAEC;AArGD,2BAA0C;AAC1C,2BAA+C;AAE/C;;GAEG;AACU,QAAA,oBAAoB,GAAG;IAClC,SAAS,EAAE,6BAA6B;IACxC,WAAW,EAAE,+BAA+B;CAC7C,CAAC;AAEF,MAAM,qBAAqB,GAAG,QAAQ,CAAC;AAEvC;;;;;;;;GAQG;AACH,SAAgB,uBAAuB;IACrC;;;;;;;;;;OAUG;IACH,MAAM,eAAe,GACnB,OAAO,CAAC,GAAG,CAAC,aAAa;QACzB,OAAO,CAAC,GAAG,CAAC,aAAa;QACzB,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC;IAExB,OAAO,CAAC,CAAC,eAAe,CAAC;AAC3B,CAAC;AAED;;;;GAIG;AACH,SAAgB,0BAA0B;IACxC,IAAI,IAAA,aAAQ,GAAE,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IAEzC,IAAI,CAAC;QACH,yBAAyB;QACzB,IAAA,aAAQ,EAAC,4BAAoB,CAAC,SAAS,CAAC,CAAC;QAEzC,qCAAqC;QACrC,MAAM,UAAU,GAAG,IAAA,iBAAY,EAAC,4BAAoB,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;QAE1E,OAAO,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACnC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,SAAgB,+BAA+B;IAC7C,MAAM,UAAU,GAAG,IAAA,sBAAiB,GAAE,CAAC;IAEvC,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC;QAC7C,IAAI,CAAC,IAAI;YAAE,SAAS;QAEpB,KAAK,MAAM,EAAC,GAAG,EAAC,IAAI,IAAI,EAAE,CAAC;YACzB,IAAI,qBAAqB,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;gBACpC,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,SAAgB,qBAAqB;IACnC,OAAO,0BAA0B,EAAE,IAAI,+BAA+B,EAAE,CAAC;AAC3E,CAAC;AAED;;;;GAIG;AACH,SAAgB,kBAAkB;IAChC,OAAO,uBAAuB,EAAE,IAAI,qBAAqB,EAAE,CAAC;AAC9D,CAAC"}

141
node_modules/gcp-metadata/build/src/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,141 @@
export declare const BASE_PATH = "/computeMetadata/v1";
export declare const HOST_ADDRESS = "http://169.254.169.254";
export declare const SECONDARY_HOST_ADDRESS = "http://metadata.google.internal.";
export declare const HEADER_NAME = "Metadata-Flavor";
export declare const HEADER_VALUE = "Google";
export declare const HEADERS: Readonly<{
"Metadata-Flavor": "Google";
}>;
/**
* Metadata server detection override options.
*
* Available via `process.env.METADATA_SERVER_DETECTION`.
*/
export declare const METADATA_SERVER_DETECTION: Readonly<{
'assume-present': "don't try to ping the metadata server, but assume it's present";
none: "don't try to ping the metadata server, but don't try to use it either";
'bios-only': "treat the result of a BIOS probe as canonical (don't fall back to pinging)";
'ping-only': "skip the BIOS probe, and go straight to pinging";
}>;
type HeadersInit = ConstructorParameters<typeof Headers>[0];
export interface Options {
params?: {
[index: string]: string;
};
property?: string;
headers?: HeadersInit;
}
export interface MetadataAccessor {
/**
*
* @example
*
* // equivalent to `project('project-id')`;
* const metadataKey = 'project/project-id';
*/
metadataKey: string;
params?: Options['params'];
headers?: Options['headers'];
noResponseRetries?: number;
fastFail?: boolean;
}
export type BulkResults<T extends readonly MetadataAccessor[]> = {
[key in T[number]['metadataKey']]: ReturnType<JSON['parse']>;
};
/**
* Obtain metadata for the current GCE instance.
*
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
*
* @example
* ```
* const serviceAccount: {} = await instance('service-accounts/');
* const serviceAccountEmail: string = await instance('service-accounts/default/email');
* ```
*/
export declare function instance<T = any>(options?: string | Options): Promise<T>;
/**
* Obtain metadata for the current GCP project.
*
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
*
* @example
* ```
* const projectId: string = await project('project-id');
* const numericProjectId: number = await project('numeric-project-id');
* ```
*/
export declare function project<T = any>(options?: string | Options): Promise<T>;
/**
* Obtain metadata for the current universe.
*
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
*
* @example
* ```
* const universeDomain: string = await universe('universe-domain');
* ```
*/
export declare function universe<T>(options?: string | Options): Promise<T>;
/**
* Retrieve metadata items in parallel.
*
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
*
* @example
* ```
* const data = await bulk([
* {
* metadataKey: 'instance',
* },
* {
* metadataKey: 'project/project-id',
* },
* ] as const);
*
* // data.instance;
* // data['project/project-id'];
* ```
*
* @param properties The metadata properties to retrieve
* @returns The metadata in `metadatakey:value` format
*/
export declare function bulk<T extends readonly Readonly<MetadataAccessor>[], R extends BulkResults<T> = BulkResults<T>>(properties: T): Promise<R>;
/**
* Determine if the metadata server is currently available.
*/
export declare function isAvailable(): Promise<boolean>;
/**
* reset the memoized isAvailable() lookup.
*/
export declare function resetIsAvailableCache(): void;
/**
* A cache for the detected GCP Residency.
*/
export declare let gcpResidencyCache: boolean | null;
/**
* Detects GCP Residency.
* Caches results to reduce costs for subsequent calls.
*
* @see setGCPResidency for setting
*/
export declare function getGCPResidency(): boolean;
/**
* Sets the detected GCP Residency.
* Useful for forcing metadata server detection behavior.
*
* Set `null` to autodetect the environment (default behavior).
* @see getGCPResidency for getting
*/
export declare function setGCPResidency(value?: boolean | null): void;
/**
* Obtain the timeout for requests to the metadata server.
*
* In certain environments and conditions requests can take longer than
* the default timeout to complete. This function will determine the
* appropriate timeout based on the environment.
*
* @returns {number} a request timeout duration in milliseconds.
*/
export declare function requestTimeout(): number;
export * from './gcp-residency';

402
node_modules/gcp-metadata/build/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,402 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.gcpResidencyCache = exports.METADATA_SERVER_DETECTION = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = void 0;
exports.instance = instance;
exports.project = project;
exports.universe = universe;
exports.bulk = bulk;
exports.isAvailable = isAvailable;
exports.resetIsAvailableCache = resetIsAvailableCache;
exports.getGCPResidency = getGCPResidency;
exports.setGCPResidency = setGCPResidency;
exports.requestTimeout = requestTimeout;
/**
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const gaxios_1 = require("gaxios");
const jsonBigint = require("json-bigint");
const gcp_residency_1 = require("./gcp-residency");
const logger = __importStar(require("google-logging-utils"));
exports.BASE_PATH = '/computeMetadata/v1';
exports.HOST_ADDRESS = 'http://169.254.169.254';
exports.SECONDARY_HOST_ADDRESS = 'http://metadata.google.internal.';
exports.HEADER_NAME = 'Metadata-Flavor';
exports.HEADER_VALUE = 'Google';
exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE });
const log = logger.log('gcp-metadata');
/**
* Metadata server detection override options.
*
* Available via `process.env.METADATA_SERVER_DETECTION`.
*/
exports.METADATA_SERVER_DETECTION = Object.freeze({
'assume-present': "don't try to ping the metadata server, but assume it's present",
none: "don't try to ping the metadata server, but don't try to use it either",
'bios-only': "treat the result of a BIOS probe as canonical (don't fall back to pinging)",
'ping-only': 'skip the BIOS probe, and go straight to pinging',
});
/**
* Returns the base URL while taking into account the GCE_METADATA_HOST
* environment variable if it exists.
*
* @returns The base URL, e.g., http://169.254.169.254/computeMetadata/v1.
*/
function getBaseUrl(baseUrl) {
if (!baseUrl) {
baseUrl =
process.env.GCE_METADATA_IP ||
process.env.GCE_METADATA_HOST ||
exports.HOST_ADDRESS;
}
// If no scheme is provided default to HTTP:
if (!/^https?:\/\//.test(baseUrl)) {
baseUrl = `http://${baseUrl}`;
}
return new URL(exports.BASE_PATH, baseUrl).href;
}
// Accepts an options object passed from the user to the API. In previous
// versions of the API, it referred to a `Request` or an `Axios` request
// options object. Now it refers to an object with very limited property
// names. This is here to help ensure users don't pass invalid options when
// they upgrade from 0.4 to 0.5 to 0.8.
function validate(options) {
Object.keys(options).forEach(key => {
switch (key) {
case 'params':
case 'property':
case 'headers':
break;
case 'qs':
throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");
default:
throw new Error(`'${key}' is not a valid configuration option.`);
}
});
}
async function metadataAccessor(type, options = {}, noResponseRetries = 3, fastFail = false) {
const headers = new Headers(exports.HEADERS);
let metadataKey = '';
let params = {};
if (typeof type === 'object') {
const metadataAccessor = type;
new Headers(metadataAccessor.headers).forEach((value, key) => headers.set(key, value));
metadataKey = metadataAccessor.metadataKey;
params = metadataAccessor.params || params;
noResponseRetries = metadataAccessor.noResponseRetries || noResponseRetries;
fastFail = metadataAccessor.fastFail || fastFail;
}
else {
metadataKey = type;
}
if (typeof options === 'string') {
metadataKey += `/${options}`;
}
else {
validate(options);
if (options.property) {
metadataKey += `/${options.property}`;
}
new Headers(options.headers).forEach((value, key) => headers.set(key, value));
params = options.params || params;
}
const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request;
const req = {
url: `${getBaseUrl()}/${metadataKey}`,
headers,
retryConfig: { noResponseRetries },
params,
responseType: 'text',
timeout: requestTimeout(),
};
log.info('instance request %j', req);
const res = await requestMethod(req);
log.info('instance metadata is %s', res.data);
const metadataFlavor = res.headers.get(exports.HEADER_NAME);
if (metadataFlavor !== exports.HEADER_VALUE) {
throw new RangeError(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${metadataFlavor ? `'${metadataFlavor}'` : 'no header'}`);
}
if (typeof res.data === 'string') {
try {
return jsonBigint.parse(res.data);
}
catch {
/* ignore */
}
}
return res.data;
}
async function fastFailMetadataRequest(options) {
const secondaryOptions = {
...options,
url: options.url
?.toString()
.replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)),
};
// We race a connection between DNS/IP to metadata server. There are a couple
// reasons for this:
//
// 1. the DNS is slow in some GCP environments; by checking both, we might
// detect the runtime environment significantly faster.
// 2. we can't just check the IP, which is tarpitted and slow to respond
// on a user's local machine.
//
// Returns first resolved promise or if all promises get rejected we return an AggregateError.
//
// Note, however, if a failure happens prior to a success, a rejection should
// occur, this is for folks running locally.
//
const r1 = (0, gaxios_1.request)(options);
const r2 = (0, gaxios_1.request)(secondaryOptions);
return Promise.any([r1, r2]);
}
/**
* Obtain metadata for the current GCE instance.
*
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
*
* @example
* ```
* const serviceAccount: {} = await instance('service-accounts/');
* const serviceAccountEmail: string = await instance('service-accounts/default/email');
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function instance(options) {
return metadataAccessor('instance', options);
}
/**
* Obtain metadata for the current GCP project.
*
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
*
* @example
* ```
* const projectId: string = await project('project-id');
* const numericProjectId: number = await project('numeric-project-id');
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function project(options) {
return metadataAccessor('project', options);
}
/**
* Obtain metadata for the current universe.
*
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
*
* @example
* ```
* const universeDomain: string = await universe('universe-domain');
* ```
*/
function universe(options) {
return metadataAccessor('universe', options);
}
/**
* Retrieve metadata items in parallel.
*
* @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys}
*
* @example
* ```
* const data = await bulk([
* {
* metadataKey: 'instance',
* },
* {
* metadataKey: 'project/project-id',
* },
* ] as const);
*
* // data.instance;
* // data['project/project-id'];
* ```
*
* @param properties The metadata properties to retrieve
* @returns The metadata in `metadatakey:value` format
*/
async function bulk(properties) {
const r = {};
await Promise.all(properties.map(item => {
return (async () => {
const res = await metadataAccessor(item);
const key = item.metadataKey;
r[key] = res;
})();
}));
return r;
}
/*
* How many times should we retry detecting GCP environment.
*/
function detectGCPAvailableRetries() {
return process.env.DETECT_GCP_RETRIES
? Number(process.env.DETECT_GCP_RETRIES)
: 0;
}
let cachedIsAvailableResponse;
/**
* Determine if the metadata server is currently available.
*/
async function isAvailable() {
if (process.env.METADATA_SERVER_DETECTION) {
const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();
if (!(value in exports.METADATA_SERVER_DETECTION)) {
throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join('`, `')}\`, or unset`);
}
switch (value) {
case 'assume-present':
return true;
case 'none':
return false;
case 'bios-only':
return getGCPResidency();
case 'ping-only':
// continue, we want to ping the server
}
}
try {
// If a user is instantiating several GCP libraries at the same time,
// this may result in multiple calls to isAvailable(), to detect the
// runtime environment. We use the same promise for each of these calls
// to reduce the network load.
if (cachedIsAvailableResponse === undefined) {
cachedIsAvailableResponse = metadataAccessor('instance', undefined, detectGCPAvailableRetries(),
// If the default HOST_ADDRESS has been overridden, we should not
// make an effort to try SECONDARY_HOST_ADDRESS (as we are likely in
// a non-GCP environment):
!(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST));
}
await cachedIsAvailableResponse;
return true;
}
catch (e) {
const err = e;
if (process.env.DEBUG_AUTH) {
console.info(err);
}
if (err.type === 'request-timeout') {
// If running in a GCP environment, metadata endpoint should return
// within ms.
return false;
}
if (err.response && err.response.status === 404) {
return false;
}
else {
if (!(err.response && err.response.status === 404) &&
// A warning is emitted if we see an unexpected err.code, or err.code
// is not populated:
(!err.code ||
![
'EHOSTDOWN',
'EHOSTUNREACH',
'ENETUNREACH',
'ENOENT',
'ENOTFOUND',
'ECONNREFUSED',
].includes(err.code.toString()))) {
let code = 'UNKNOWN';
if (err.code)
code = err.code.toString();
process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, 'MetadataLookupWarning');
}
// Failure to resolve the metadata service means that it is not available.
return false;
}
}
}
/**
* reset the memoized isAvailable() lookup.
*/
function resetIsAvailableCache() {
cachedIsAvailableResponse = undefined;
}
/**
* A cache for the detected GCP Residency.
*/
exports.gcpResidencyCache = null;
/**
* Detects GCP Residency.
* Caches results to reduce costs for subsequent calls.
*
* @see setGCPResidency for setting
*/
function getGCPResidency() {
if (exports.gcpResidencyCache === null) {
setGCPResidency();
}
return exports.gcpResidencyCache;
}
/**
* Sets the detected GCP Residency.
* Useful for forcing metadata server detection behavior.
*
* Set `null` to autodetect the environment (default behavior).
* @see getGCPResidency for getting
*/
function setGCPResidency(value = null) {
exports.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)();
}
/**
* Obtain the timeout for requests to the metadata server.
*
* In certain environments and conditions requests can take longer than
* the default timeout to complete. This function will determine the
* appropriate timeout based on the environment.
*
* @returns {number} a request timeout duration in milliseconds.
*/
function requestTimeout() {
return getGCPResidency() ? 0 : 3000;
}
__exportStar(require("./gcp-residency"), exports);
//# sourceMappingURL=index.js.map

1
node_modules/gcp-metadata/build/src/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,88 @@
data-uri-to-buffer
==================
### Generate a Buffer instance from a [Data URI][rfc] string
[![Build Status](https://travis-ci.org/TooTallNate/node-data-uri-to-buffer.svg?branch=master)](https://travis-ci.org/TooTallNate/node-data-uri-to-buffer)
This module accepts a ["data" URI][rfc] String of data, and returns a
node.js `Buffer` instance with the decoded data.
Installation
------------
Install with `npm`:
``` bash
$ npm install data-uri-to-buffer
```
Example
-------
``` js
import dataUriToBuffer from 'data-uri-to-buffer';
// plain-text data is supported
let uri = 'data:,Hello%2C%20World!';
let decoded = dataUriToBuffer(uri);
console.log(decoded.toString());
// 'Hello, World!'
// base64-encoded data is supported
uri = 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D';
decoded = dataUriToBuffer(uri);
console.log(decoded.toString());
// 'Hello, World!'
```
API
---
### dataUriToBuffer(String uri) → Buffer
The `type` property on the Buffer instance gets set to the main type portion of
the "mediatype" portion of the "data" URI, or defaults to `"text/plain"` if not
specified.
The `typeFull` property on the Buffer instance gets set to the entire
"mediatype" portion of the "data" URI (including all parameters), or defaults
to `"text/plain;charset=US-ASCII"` if not specified.
The `charset` property on the Buffer instance gets set to the Charset portion of
the "mediatype" portion of the "data" URI, or defaults to `"US-ASCII"` if the
entire type is not specified, or defaults to `""` otherwise.
*Note*: If the only the main type is specified but not the charset, e.g.
`"data:text/plain,abc"`, the charset is set to the empty string. The spec only
defaults to US-ASCII as charset if the entire type is not specified.
License
-------
(The MIT License)
Copyright (c) 2014 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[rfc]: http://tools.ietf.org/html/rfc2397

View File

@@ -0,0 +1,15 @@
/// <reference types="node" />
export interface MimeBuffer extends Buffer {
type: string;
typeFull: string;
charset: string;
}
/**
* Returns a `Buffer` instance from the given data URI `uri`.
*
* @param {String} uri Data URI to turn into a Buffer instance
* @returns {Buffer} Buffer instance from Data URI
* @api public
*/
export declare function dataUriToBuffer(uri: string): MimeBuffer;
export default dataUriToBuffer;

View File

@@ -0,0 +1,53 @@
/**
* Returns a `Buffer` instance from the given data URI `uri`.
*
* @param {String} uri Data URI to turn into a Buffer instance
* @returns {Buffer} Buffer instance from Data URI
* @api public
*/
export function dataUriToBuffer(uri) {
if (!/^data:/i.test(uri)) {
throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
}
// strip newlines
uri = uri.replace(/\r?\n/g, '');
// split the URI up into the "metadata" and the "data" portions
const firstComma = uri.indexOf(',');
if (firstComma === -1 || firstComma <= 4) {
throw new TypeError('malformed data: URI');
}
// remove the "data:" scheme and parse the metadata
const meta = uri.substring(5, firstComma).split(';');
let charset = '';
let base64 = false;
const type = meta[0] || 'text/plain';
let typeFull = type;
for (let i = 1; i < meta.length; i++) {
if (meta[i] === 'base64') {
base64 = true;
}
else if (meta[i]) {
typeFull += `;${meta[i]}`;
if (meta[i].indexOf('charset=') === 0) {
charset = meta[i].substring(8);
}
}
}
// defaults to US-ASCII only if type is not provided
if (!meta[0] && !charset.length) {
typeFull += ';charset=US-ASCII';
charset = 'US-ASCII';
}
// get the encoded data portion and decode URI-encoded chars
const encoding = base64 ? 'base64' : 'ascii';
const data = unescape(uri.substring(firstComma + 1));
const buffer = Buffer.from(data, encoding);
// set `.type` and `.typeFull` properties to MIME type
buffer.type = type;
buffer.typeFull = typeFull;
// set the `.charset` property
buffer.charset = charset;
return buffer;
}
export default dataUriToBuffer;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file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SAAS,CAAC,CAAC,CAAC,CAAC;aAC/B;SACD;KACD;IACD,oDAAoD;IACpD,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;QAChC,QAAQ,IAAI,mBAAmB,CAAC;QAChC,OAAO,GAAG,UAAU,CAAC;KACrB;IAED,4DAA4D;IAC5D,MAAM,QAAQ,GAAG,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7C,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;IACrD,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAe,CAAC;IAEzD,sDAAsD;IACtD,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAE3B,8BAA8B;IAC9B,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC;IAEzB,OAAO,MAAM,CAAC;AACf,CAAC;AAED,eAAe,eAAe,CAAC"}

View File

@@ -0,0 +1,62 @@
{
"name": "data-uri-to-buffer",
"version": "4.0.1",
"description": "Generate a Buffer instance from a Data URI string",
"type": "module",
"exports": "./dist/index.js",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist",
"src"
],
"scripts": {
"build": "tsc",
"test": "jest",
"prepublishOnly": "npm run build"
},
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/node-data-uri-to-buffer.git"
},
"engines": {
"node": ">= 12"
},
"keywords": [
"data",
"uri",
"datauri",
"data-uri",
"buffer",
"convert",
"rfc2397",
"2397"
],
"author": "Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/TooTallNate/node-data-uri-to-buffer/issues"
},
"homepage": "https://github.com/TooTallNate/node-data-uri-to-buffer",
"devDependencies": {
"@types/jest": "^27.0.2",
"@types/node": "^12.20.36",
"jest": "^27.3.1",
"ts-jest": "^27.0.7",
"typescript": "^4.4.4"
},
"jest": {
"preset": "ts-jest",
"globals": {
"ts-jest": {
"diagnostics": false,
"isolatedModules": true
}
},
"verbose": false,
"testEnvironment": "node",
"testMatch": [
"<rootDir>/test/**/*.test.ts"
]
}
}

View File

@@ -0,0 +1,68 @@
export interface MimeBuffer extends Buffer {
type: string;
typeFull: string;
charset: string;
}
/**
* Returns a `Buffer` instance from the given data URI `uri`.
*
* @param {String} uri Data URI to turn into a Buffer instance
* @returns {Buffer} Buffer instance from Data URI
* @api public
*/
export function dataUriToBuffer(uri: string): MimeBuffer {
if (!/^data:/i.test(uri)) {
throw new TypeError(
'`uri` does not appear to be a Data URI (must begin with "data:")'
);
}
// strip newlines
uri = uri.replace(/\r?\n/g, '');
// split the URI up into the "metadata" and the "data" portions
const firstComma = uri.indexOf(',');
if (firstComma === -1 || firstComma <= 4) {
throw new TypeError('malformed data: URI');
}
// remove the "data:" scheme and parse the metadata
const meta = uri.substring(5, firstComma).split(';');
let charset = '';
let base64 = false;
const type = meta[0] || 'text/plain';
let typeFull = type;
for (let i = 1; i < meta.length; i++) {
if (meta[i] === 'base64') {
base64 = true;
} else if(meta[i]) {
typeFull += `;${ meta[i]}`;
if (meta[i].indexOf('charset=') === 0) {
charset = meta[i].substring(8);
}
}
}
// defaults to US-ASCII only if type is not provided
if (!meta[0] && !charset.length) {
typeFull += ';charset=US-ASCII';
charset = 'US-ASCII';
}
// get the encoded data portion and decode URI-encoded chars
const encoding = base64 ? 'base64' : 'ascii';
const data = unescape(uri.substring(firstComma + 1));
const buffer = Buffer.from(data, encoding) as MimeBuffer;
// set `.type` and `.typeFull` properties to MIME type
buffer.type = type;
buffer.typeFull = typeFull;
// set the `.charset` property
buffer.charset = charset;
return buffer;
}
export default dataUriToBuffer;

202
node_modules/gcp-metadata/node_modules/gaxios/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

240
node_modules/gcp-metadata/node_modules/gaxios/README.md generated vendored Normal file
View File

@@ -0,0 +1,240 @@
# gaxios
[![npm version](https://img.shields.io/npm/v/gaxios.svg)](https://www.npmjs.org/package/gaxios)
[![codecov](https://codecov.io/gh/googleapis/gaxios/branch/master/graph/badge.svg)](https://codecov.io/gh/googleapis/gaxios)
[![Code Style: Google](https://img.shields.io/badge/code%20style-google-blueviolet.svg)](https://github.com/google/gts)
> An HTTP request client that provides an `axios` like interface over top of `node-fetch`.
## Install
```sh
$ npm install gaxios
```
## Example
```js
import {request} from 'gaxios';
const res = await request({url: 'https://google.com/'});
```
## `fetch`-Compatible API Example
We offer a drop-in `fetch`-compatible API as well.
```js
import {instance} from 'gaxios';
const res = await instance.fetch('https://google.com/');
```
To disable the auto-processing of the request body in `res.data`, set `{responseType: 'stream'}` or `.adapter` on a Gaxios instance's defaults or per-request.
## Setting Defaults
Gaxios supports setting default properties both on the default instance, and on additional instances. This is often useful when making many requests to the same domain with the same base settings. For example:
```js
import {Gaxios} from 'gaxios';
const gaxios = new Gaxios();
gaxios.defaults = {
baseURL: 'https://example.com'
headers: new Headers({
Authorization: 'SOME_TOKEN'
})
}
await gaxios.request({url: '/data'});
```
Note that setting default values will take precedence
over other authentication methods, i.e., application default credentials.
## `GaxiosResponse`
The `GaxiosResponse` object extends the `fetch` API's [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object, with the addition of:
- `config`: the configuration used for the request.
- `data`: the transformed `.body`, such as JSON, text, arrayBuffer, or more.
## Request Options
```ts
interface GaxiosOptions = {
// The url to which the request should be sent. Required.
url: string | URL,
// The HTTP method to use for the request. Defaults to `GET`.
method: 'GET',
// The base Url to use for the request.
// Resolved as `new URL(url, baseURL)`
baseURL: 'https://example.com/v1/' | URL;
// The HTTP methods to be sent with the request.
headers: new Headers(),
// The data to send in the body of the request. Objects will be serialized as JSON
// except for:
// - `ArrayBuffer`
// - `Blob`
// - `Buffer` (Node.js)
// - `DataView`
// - `File`
// - `FormData`
// - `ReadableStream`
// - `stream.Readable` (Node.js)
// - strings
// - `TypedArray` (e.g. `Uint8Array`, `BigInt64Array`)
// - `URLSearchParams`
// - all other objects where:
// - headers.get('Content-Type') === 'application/x-www-form-urlencoded' (as they will be serialized as `URLSearchParams`)
//
// Here are a few examples that would prevent setting `Content-Type: application/json` by default:
// - data: JSON.stringify({some: 'data'}) // a `string`
// - data: fs.readFile('./some-data.jpeg') // a `stream.Readable`
data: {
some: 'data'
},
// The max size of the http response content in bytes allowed.
// Defaults to `0`, which is the same as unset.
maxContentLength: 2000,
// The query parameters that will be encoded using `URLSearchParams` and
// appended to the url
params: {
querystring: 'parameters'
},
// The timeout for the HTTP request in milliseconds. No timeout by default.
timeout: 60000,
// Optional method to override making the actual HTTP request. Useful
// for writing tests and instrumentation
adapter?: async (options, defaultAdapter) => {
const res = await defaultAdapter(options);
res.data = {
...res.data,
extraProperty: 'your extra property',
};
return res;
};
// The expected return type of the request. Options are:
// 'json' | 'stream' | 'blob' | 'arraybuffer' | 'text' | 'unknown'
// Defaults to `unknown`.
//
// If the `fetchImplementation` is native `fetch`, the
// stream is a `ReadableStream`, otherwise `readable.Stream`.
//
// Note: Setting 'stream' does not consume the `Response#body` - this can
// be useful for passthrough requests, where a consumer would like to
// transform the `Response#body`, or for using Gaxios as a drop-in `fetch`
// replacement.
responseType: 'unknown',
// The node.js http agent to use for the request.
agent: someHttpsAgent,
// Custom function to determine if the response is valid based on the
// status code. Defaults to (>= 200 && < 300)
validateStatus: (status: number) => true,
/**
* Implementation of `fetch` to use when making the API call. Will use
* `node-fetch` by default.
*/
fetchImplementation?: typeof fetch;
// Configuration for retrying of requests.
retryConfig: {
// The number of times to retry the request. Defaults to 3.
retry?: number;
// The number of retries already attempted.
currentRetryAttempt?: number;
// The HTTP Methods that will be automatically retried.
// Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE']
httpMethodsToRetry?: string[];
// The HTTP response status codes that will automatically be retried.
// Defaults to: [[100, 199], [408, 408], [429, 429], [500, 599]]
statusCodesToRetry?: number[][];
// Function to invoke when a retry attempt is made.
onRetryAttempt?: (err: GaxiosError) => Promise<void> | void;
// Function to invoke which determines if you should retry
shouldRetry?: (err: GaxiosError) => Promise<boolean> | boolean;
// When there is no response, the number of retries to attempt. Defaults to 2.
noResponseRetries?: number;
// The amount of time to initially delay the retry, in ms. Defaults to 100ms.
retryDelay?: number;
},
// Enables default configuration for retries.
retry: boolean,
// Enables aborting via AbortController
signal?: AbortSignal
/**
* A collection of parts to send as a `Content-Type: multipart/related` request.
*/
multipart?: GaxiosMultipartOptions;
/**
* An optional proxy to use for requests.
* Available via `process.env.HTTP_PROXY` and `process.env.HTTPS_PROXY` as well - with a preference for the this config option when multiple are available.
* The `agent` option overrides this.
*
* @see {@link GaxiosOptions.noProxy}
* @see {@link GaxiosOptions.agent}
*/
proxy?: string | URL;
/**
* A list for excluding traffic for proxies.
* Available via `process.env.NO_PROXY` as well as a common-separated list of strings - merged with any local `noProxy` rules.
*
* - When provided a string, it is matched by
* - Wildcard `*.` and `.` matching are available. (e.g. `.example.com` or `*.example.com`)
* - When provided a URL, it is matched by the `.origin` property.
* - For example, requesting `https://example.com` with the following `noProxy`s would result in a no proxy use:
* - new URL('https://example.com')
* - new URL('https://example.com:443')
* - The following would be used with a proxy:
* - new URL('http://example.com:80')
* - new URL('https://example.com:8443')
* - When provided a regular expression it is used to match the stringified URL
*
* @see {@link GaxiosOptions.proxy}
*/
noProxy?: (string | URL | RegExp)[];
/**
* An experimental, customizable error redactor.
*
* Set `false` to disable.
*
* @remarks
*
* This does not replace the requirement for an active Data Loss Prevention (DLP) provider. For DLP suggestions, see:
* - https://cloud.google.com/sensitive-data-protection/docs/redacting-sensitive-data#dlp_deidentify_replace_infotype-nodejs
* - https://cloud.google.com/sensitive-data-protection/docs/infotypes-reference#credentials_and_secrets
*
* @experimental
*/
errorRedactor?: typeof defaultErrorRedactor | false;
}
```
## License
[Apache-2.0](https://github.com/googleapis/gaxios/blob/main/LICENSE)

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,109 @@
"use strict";
// Copyright 2019 Google, LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const child_process_1 = require("child_process");
const multiparty = __importStar(require("multiparty"));
const cors_1 = __importDefault(require("cors"));
const util_1 = require("util");
const port = 7172;
const exec = (0, util_1.promisify)(child_process_1.execFile);
async function listen(app, port) {
return new Promise((resolve, reject) => {
const server = app.listen(port, (err) => {
if (err) {
reject(err);
}
resolve(server);
});
});
}
// Starts a web server that browser tests will use, then runs actual browser
// tests.
async function main() {
const app = (0, express_1.default)();
app.use((0, cors_1.default)());
app.post('/path', (req, res) => {
if (req.header('origin')) {
res.set('Access-Control-Allow-Origin', req.header('origin'));
}
const form = new multiparty.Form({ autoFields: true });
form.parse(req, (err, fields) => {
if (err) {
res.status(500).send({ message: err.message });
}
else {
res.status(200).send(fields.null);
}
});
});
app.get('/path', (req, res) => {
if (req.header('origin')) {
res.set('Access-Control-Allow-Origin', req.header('origin'));
}
res.send('response');
});
app.get('/querystring', (req, res) => {
if (req.header('origin')) {
res.set('Access-Control-Allow-Origin', req.header('origin'));
}
const query = req.query.query;
res.send(query || '');
});
const server = await listen(app, port);
console.log(`[http server] I'm listening on port ${port}! Starting karma.`);
await exec('karma', ['start']);
server.close();
console.log(`[http server] Karma has finished! I'm no longer listening on port ${port}!`);
}
main().catch(err => {
console.log('Error:', err);
});
//# sourceMappingURL=browser-test-runner.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"browser-test-runner.js","sourceRoot":"","sources":["../../../browser-test/browser-test-runner.ts"],"names":[],"mappings":";AAAA,6BAA6B;AAC7B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCA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O,CAAC,GAAG,CACT,qEAAqE,IAAI,GAAG,CAC7E,CAAC;AACJ,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;IACjB,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;AAC7B,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,81 @@
"use strict";
// Copyright 2019 Google, LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const assert_1 = __importDefault(require("assert"));
const mocha_1 = require("mocha");
const index_1 = require("../src/index");
const port = 7172; // should match the port defined in `webserver.ts`
(0, mocha_1.describe)('💻 browser tests', () => {
(0, mocha_1.it)('should just work from browser', async () => {
const result = await (0, index_1.request)({ url: `http://localhost:${port}/path` });
assert_1.default.strictEqual(result.status, 200);
assert_1.default.strictEqual(result.data, 'response');
});
(0, mocha_1.it)('should pass querystring parameters from browser', async () => {
const result = await (0, index_1.request)({
url: `http://localhost:${port}/querystring`,
params: { query: 'value' },
});
assert_1.default.strictEqual(result.status, 200);
assert_1.default.strictEqual(result.data, 'value');
});
(0, mocha_1.it)('should allow passing browser fetch explicitly', async () => {
const result = await (0, index_1.request)({
url: `http://localhost:${port}/path`,
fetchImplementation: window.fetch,
});
assert_1.default.strictEqual(result.status, 200);
});
(0, mocha_1.it)('should support multipart post from the browser', async () => {
const headers = new Headers();
const multipart = [
{
'Content-Type': 'application/json',
body: JSON.stringify({ hello: 'world' }),
},
{
'Content-Type': 'text/plain',
body: 'hello world!',
},
];
const boundary = globalThis?.crypto.randomUUID() || (await import('crypto')).randomUUID();
const finale = `--${boundary}--`;
headers.set('Content-Type', `multipart/related; boundary=${boundary}`);
let content = '';
for (const part of multipart) {
const preamble = `--${boundary}\r\nContent-Type: ${part['Content-Type']}\r\n\r\n`;
// rStream.push(preamble);
content += preamble;
if (typeof part.body === 'string') {
content += part.body;
content += '\r\n';
}
}
content += finale;
const result = await (0, index_1.request)({
headers,
data: content,
method: 'POST',
url: `http://localhost:${port}/path`,
});
assert_1.default.strictEqual(result.status, 200);
const parts = result.data;
assert_1.default.strictEqual(parts[0], '{"hello":"world"}');
assert_1.default.strictEqual(parts[1], 'hello world!');
});
});
//# sourceMappingURL=test.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"test.browser.js","sourceRoot":"","sources":["../../../browser-test/test.browser.ts"],"names":[],"mappings":";AAAA,6BAA6B;AAC7B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;AAEjC,oDAA4B;AAC5B,iCAAmC;AACnC,wCAAqC;AACrC,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,kDAAkD;AAErE,IAAA,gBAAQ,EAAC,kBAAkB,EAAE,GAAG,EAAE;IAChC,IAAA,UAAE,EAAC,+BAA+B,EAAE,KAAK,IAAI,EAAE;QAC7C,MAAM,MAAM,GAAG,MAAM,IAAA,eAAO,EAAC,EAAC,GAAG,EAAE,oBAAoB,IAAI,OAAO,EAAC,CAAC,CAAC;QACrE,gBAAM,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QACvC,gBAAM,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IAC9C,CAAC,CAAC,CAAC;IAEH,IAAA,UAAE,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,CAAC,CAAC;QAEvE,IAAI,OAAO,GAAG,EAAE,CAAC;QACjB,KAAK,MAAM,IAAI,IAAI,SAAS,EAAE,CAAC;YAC7B,MAAM,QAAQ,GAAG,KAAK,QAAQ,qBAAqB,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC;YAClF,0BAA0B;YAC1B,OAAO,IAAI,QAAQ,CAAC;YACpB,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAClC,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC;gBACrB,OAAO,IAAI,MAAM,CAAC;YACpB,CAAC;QACH,CAAC;QACD,OAAO,IAAI,MAAM,CAAC;QAClB,MAAM,MAAM,GAAG,MAAM,IAAA,eAAO,EAAC;YAC3B,OAAO;YACP,IAAI,EAAE,OAAO;YACb,MAAM,EAAE,MAAM;YACd,GAAG,EAAE,oBAAoB,IAAI,OAAO;SACrC,CAAC,CAAC;QACH,gBAAM,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QACvC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAgB,CAAC;QACtC,gBAAM,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,mBAAmB,CAAC,CAAC;QAClD,gBAAM,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,cAAc,CAAC,CAAC;IAC/C,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,329 @@
import { Agent } from 'http';
import { Readable } from 'stream';
/**
* TypeScript does not have this type available globally - however `@types/node` includes `undici-types`, which has it:
* - https://www.npmjs.com/package/@types/node/v/18.19.59?activeTab=dependencies
*
* Additionally, this is the TypeScript pattern for type sniffing and `import("undici-types")` is pretty common:
* - https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/globals.d.ts
*/
type _BodyInit = typeof globalThis extends {
BodyInit: infer T;
} ? T : import('undici-types').BodyInit;
/**
* An AIP-193 conforming error interface.
*
* @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
*
* @param res the response object
* @returns the extracted error information
*/
export interface AIPErrorInterface {
error: {
code: number;
message: string;
status: string;
details?: {}[];
};
}
/**
* Support `instanceof` operator for `GaxiosError`s in different versions of this library.
*
* @see {@link GaxiosError[Symbol.hasInstance]}
*/
export declare const GAXIOS_ERROR_SYMBOL: unique symbol;
export declare class GaxiosError<T = ReturnType<JSON['parse']>> extends Error {
config: GaxiosOptionsPrepared;
response?: GaxiosResponse<T> | undefined;
/**
* An error code.
* Can be a system error code, DOMException error name, or any error's 'code' property where it is a `string`.
*
* It is only a `number` when the cause is sourced from an API-level error (AIP-193).
*
* @see {@link https://nodejs.org/api/errors.html#errorcode error.code}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names DOMException#error_names}
* @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
*
* @example
* 'ECONNRESET'
*
* @example
* 'TimeoutError'
*
* @example
* 500
*/
code?: string | number;
/**
* An HTTP Status code.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status Response#status}
*
* @example
* 500
*/
status?: number;
/**
* @deprecated use {@link GaxiosError.cause} instead.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause Error#cause}
*
* @privateRemarks
*
* We will want to remove this property later as the modern `cause` property is better suited
* for displaying and relaying nested errors. Keeping this here makes the resulting
* error log larger than it needs to be.
*
*/
error?: Error | NodeJS.ErrnoException;
/**
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
*
* @see {@link GAXIOS_ERROR_SYMBOL}
* @see {@link GaxiosError[Symbol.hasInstance]}
* @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200}
* @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior}
*/
[GAXIOS_ERROR_SYMBOL]: string;
/**
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
*
* @see {@link GAXIOS_ERROR_SYMBOL}
* @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]}
*/
static [Symbol.hasInstance](instance: unknown): boolean;
constructor(message: string, config: GaxiosOptionsPrepared, response?: GaxiosResponse<T> | undefined, cause?: unknown);
}
type GaxiosResponseData = ReturnType<JSON['parse']> | GaxiosOptionsPrepared['data'];
export type GaxiosPromise<T = GaxiosResponseData> = Promise<GaxiosResponse<T>>;
export interface GaxiosResponse<T = GaxiosResponseData> extends Response {
config: GaxiosOptionsPrepared;
data: T;
}
export interface GaxiosMultipartOptions {
headers: Headers;
content: string | Readable;
}
/**
* Request options that are used to form the request.
*/
export interface GaxiosOptions extends RequestInit {
/**
* Optional method to override making the actual HTTP request. Useful
* for writing tests.
*/
adapter?: <T = GaxiosResponseData>(options: GaxiosOptionsPrepared, defaultAdapter: (options: GaxiosOptionsPrepared) => GaxiosPromise<T>) => GaxiosPromise<T>;
url?: string | URL;
baseURL?: string | URL;
/**
* The data to send in the {@link RequestInit.body} of the request. Objects will be
* serialized as JSON, except for:
* - `ArrayBuffer`
* - `Blob`
* - `Buffer` (Node.js)
* - `DataView`
* - `File`
* - `FormData`
* - `ReadableStream`
* - `stream.Readable` (Node.js)
* - strings
* - `TypedArray` (e.g. `Uint8Array`, `BigInt64Array`)
* - `URLSearchParams`
* - all other objects where:
* - headers['Content-Type'] === 'application/x-www-form-urlencoded' (serialized as `URLSearchParams`)
*
* In all other cases, if you would like to prevent `application/json` as the
* default `Content-Type` header you must provide a string or readable stream
* rather than an object, e.g.:
*
* ```ts
* {data: JSON.stringify({some: 'data'})}
* {data: fs.readFile('./some-data.jpeg')}
* ```
*/
data?: _BodyInit | ArrayBuffer | Blob | Buffer | DataView | File | FormData | ReadableStream | Readable | string | ArrayBufferView | URLSearchParams | {};
/**
* The maximum size of the http response `Content-Length` in bytes allowed.
*/
maxContentLength?: number;
/**
* The maximum number of redirects to follow. Defaults to 20.
*
* @deprecated non-spec. Should use `20` if enabled per-spec: https://fetch.spec.whatwg.org/#http-redirect-fetch
*/
maxRedirects?: number;
/**
* @deprecated non-spec. Should use `20` if enabled per-spec: https://fetch.spec.whatwg.org/#http-redirect-fetch
*/
follow?: number;
/**
* A collection of parts to send as a `Content-Type: multipart/related` request.
*
* This is passed to {@link RequestInit.body}.
*/
multipart?: GaxiosMultipartOptions[];
params?: GaxiosResponseData;
/**
* @deprecated Use {@link URLSearchParams} instead and pass this directly to {@link GaxiosOptions.data `data`}.
*/
paramsSerializer?: (params: {
[index: string]: string | number;
}) => string;
/**
* A timeout for the request, in milliseconds. No timeout by default.
*/
timeout?: number;
/**
* @deprecated ignored
*/
onUploadProgress?: (progressEvent: GaxiosResponseData) => void;
/**
* If the `fetchImplementation` is native `fetch`, the
* stream is a `ReadableStream`, otherwise `readable.Stream`
*/
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream' | 'unknown';
agent?: Agent | ((parsedUrl: URL) => Agent);
validateStatus?: (status: number) => boolean;
retryConfig?: RetryConfig;
retry?: boolean;
/**
* @deprecated non-spec. https://github.com/node-fetch/node-fetch/issues/1438
*/
size?: number;
/**
* Implementation of `fetch` to use when making the API call. Will use `fetch` by default.
*
* @example
*
* let customFetchCalled = false;
* const myFetch = (...args: Parameters<typeof fetch>) => {
* customFetchCalled = true;
* return fetch(...args);
* };
*
* {fetchImplementation: myFetch};
*/
fetchImplementation?: typeof fetch;
cert?: string;
key?: string;
/**
* An optional proxy to use for requests.
* Available via `process.env.HTTP_PROXY` and `process.env.HTTPS_PROXY` as well - with a preference for the this config option when multiple are available.
* The {@link GaxiosOptions.agent `agent`} option overrides this.
*
* @see {@link GaxiosOptions.noProxy}
* @see {@link GaxiosOptions.agent}
*/
proxy?: string | URL;
/**
* A list for excluding traffic for proxies.
* Available via `process.env.NO_PROXY` as well as a common-separated list of strings - merged with any local `noProxy` rules.
*
* - When provided a string, it is matched by
* - Wildcard `*.` and `.` matching are available. (e.g. `.example.com` or `*.example.com`)
* - When provided a URL, it is matched by the `.origin` property.
* - For example, requesting `https://example.com` with the following `noProxy`s would result in a no proxy use:
* - new URL('https://example.com')
* - new URL('https://example.com:443')
* - The following would be used with a proxy:
* - new URL('http://example.com:80')
* - new URL('https://example.com:8443')
* - When provided a regular expression it is used to match the stringified URL
*
* @see {@link GaxiosOptions.proxy}
*/
noProxy?: (string | URL | RegExp)[];
/**
* An experimental error redactor.
*
* @remarks
*
* This does not replace the requirement for an active Data Loss Prevention (DLP) provider. For DLP suggestions, see:
* - https://cloud.google.com/sensitive-data-protection/docs/redacting-sensitive-data#dlp_deidentify_replace_infotype-nodejs
* - https://cloud.google.com/sensitive-data-protection/docs/infotypes-reference#credentials_and_secrets
*
* @experimental
*/
errorRedactor?: typeof defaultErrorRedactor | false;
}
export interface GaxiosOptionsPrepared extends GaxiosOptions {
headers: Headers;
url: URL;
}
/**
* Gaxios retry configuration.
*/
export interface RetryConfig {
/**
* The number of times to retry the request. Defaults to 3.
*/
retry?: number;
/**
* The number of retries already attempted.
*/
currentRetryAttempt?: number;
/**
* The amount of time to initially delay the retry, in ms. Defaults to 100ms.
*/
retryDelay?: number;
/**
* The HTTP Methods that will be automatically retried.
* Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE']
*/
httpMethodsToRetry?: string[];
/**
* The HTTP response status codes that will automatically be retried.
* Defaults to: [[100, 199], [408, 408], [429, 429], [500, 599]]
*/
statusCodesToRetry?: number[][];
/**
* Function to invoke when a retry attempt is made.
*/
onRetryAttempt?: (err: GaxiosError) => Promise<void> | void;
/**
* Function to invoke which determines if you should retry
*/
shouldRetry?: (err: GaxiosError) => Promise<boolean> | boolean;
/**
* When there is no response, the number of retries to attempt. Defaults to 2.
*/
noResponseRetries?: number;
/**
* Function to invoke which returns a promise. After the promise resolves,
* the retry will be triggered. If provided, this will be used in-place of
* the `retryDelay`
*/
retryBackoff?: (err: GaxiosError, defaultBackoffMs: number) => Promise<void>;
/**
* Time that the initial request was made. Users should not set this directly.
*/
timeOfFirstRequest?: number;
/**
* The length of time to keep retrying in ms. The last sleep period will
* be shortened as necessary, so that the last retry runs at deadline (and not
* considerably beyond it). The total time starting from when the initial
* request is sent, after which an error will be returned, regardless of the
* retrying attempts made meanwhile. Defaults to Number.MAX_SAFE_INTEGER indicating to effectively
* ignore totalTimeout.
*/
totalTimeout?: number;
maxRetryDelay?: number;
retryDelayMultiplier?: number;
}
/**
* An experimental error redactor.
*
* @param config Config to potentially redact properties of
* @param response Config to potentially redact properties of
*
* @experimental
*/
export declare function defaultErrorRedactor<O extends GaxiosOptionsPrepared, R extends GaxiosResponse<GaxiosResponseData>>(data: {
config?: O;
response?: R;
}): {
config?: O;
response?: R;
};
export {};

View File

@@ -0,0 +1,311 @@
"use strict";
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GaxiosError = exports.GAXIOS_ERROR_SYMBOL = void 0;
exports.defaultErrorRedactor = defaultErrorRedactor;
const extend_1 = __importDefault(require("extend"));
const util_cjs_1 = __importDefault(require("./util.cjs"));
const pkg = util_cjs_1.default.pkg;
/**
* Support `instanceof` operator for `GaxiosError`s in different versions of this library.
*
* @see {@link GaxiosError[Symbol.hasInstance]}
*/
exports.GAXIOS_ERROR_SYMBOL = Symbol.for(`${pkg.name}-gaxios-error`);
class GaxiosError extends Error {
config;
response;
/**
* An error code.
* Can be a system error code, DOMException error name, or any error's 'code' property where it is a `string`.
*
* It is only a `number` when the cause is sourced from an API-level error (AIP-193).
*
* @see {@link https://nodejs.org/api/errors.html#errorcode error.code}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names DOMException#error_names}
* @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
*
* @example
* 'ECONNRESET'
*
* @example
* 'TimeoutError'
*
* @example
* 500
*/
code;
/**
* An HTTP Status code.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status Response#status}
*
* @example
* 500
*/
status;
/**
* @deprecated use {@link GaxiosError.cause} instead.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause Error#cause}
*
* @privateRemarks
*
* We will want to remove this property later as the modern `cause` property is better suited
* for displaying and relaying nested errors. Keeping this here makes the resulting
* error log larger than it needs to be.
*
*/
error;
/**
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
*
* @see {@link GAXIOS_ERROR_SYMBOL}
* @see {@link GaxiosError[Symbol.hasInstance]}
* @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200}
* @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior}
*/
[exports.GAXIOS_ERROR_SYMBOL] = pkg.version;
/**
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
*
* @see {@link GAXIOS_ERROR_SYMBOL}
* @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]}
*/
static [Symbol.hasInstance](instance) {
if (instance &&
typeof instance === 'object' &&
exports.GAXIOS_ERROR_SYMBOL in instance &&
instance[exports.GAXIOS_ERROR_SYMBOL] === pkg.version) {
return true;
}
// fallback to native
return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance);
}
constructor(message, config, response, cause) {
super(message, { cause });
this.config = config;
this.response = response;
this.error = cause instanceof Error ? cause : undefined;
// deep-copy config as we do not want to mutate
// the existing config for future retries/use
this.config = (0, extend_1.default)(true, {}, config);
if (this.response) {
this.response.config = (0, extend_1.default)(true, {}, this.response.config);
}
if (this.response) {
try {
this.response.data = translateData(this.config.responseType,
// workaround for `node-fetch`'s `.data` deprecation...
this.response?.bodyUsed ? this.response?.data : undefined);
}
catch {
// best effort - don't throw an error within an error
// we could set `this.response.config.responseType = 'unknown'`, but
// that would mutate future calls with this config object.
}
this.status = this.response.status;
}
if (cause instanceof DOMException) {
// The DOMException's equivalent to code is its name
// E.g.: name = `TimeoutError`, code = number
// https://developer.mozilla.org/en-US/docs/Web/API/DOMException/name
this.code = cause.name;
}
else if (cause &&
typeof cause === 'object' &&
'code' in cause &&
(typeof cause.code === 'string' || typeof cause.code === 'number')) {
this.code = cause.code;
}
}
/**
* An AIP-193 conforming error extractor.
*
* @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
*
* @internal
* @expiremental
*
* @param res the response object
* @returns the extracted error information
*/
static extractAPIErrorFromResponse(res, defaultErrorMessage = 'The request failed') {
let message = defaultErrorMessage;
// Use res.data as the error message
if (typeof res.data === 'string') {
message = res.data;
}
if (res.data &&
typeof res.data === 'object' &&
'error' in res.data &&
res.data.error &&
!res.ok) {
if (typeof res.data.error === 'string') {
return {
message: res.data.error,
code: res.status,
status: res.statusText,
};
}
if (typeof res.data.error === 'object') {
// extract status from data.message
message =
'message' in res.data.error &&
typeof res.data.error.message === 'string'
? res.data.error.message
: message;
// extract status from data.error
const status = 'status' in res.data.error &&
typeof res.data.error.status === 'string'
? res.data.error.status
: res.statusText;
// extract code from data.error
const code = 'code' in res.data.error && typeof res.data.error.code === 'number'
? res.data.error.code
: res.status;
if ('errors' in res.data.error &&
Array.isArray(res.data.error.errors)) {
const errorMessages = [];
for (const e of res.data.error.errors) {
if (typeof e === 'object' &&
'message' in e &&
typeof e.message === 'string') {
errorMessages.push(e.message);
}
}
return Object.assign({
message: errorMessages.join('\n') || message,
code,
status,
}, res.data.error);
}
return Object.assign({
message,
code,
status,
}, res.data.error);
}
}
return {
message,
code: res.status,
status: res.statusText,
};
}
}
exports.GaxiosError = GaxiosError;
function translateData(responseType, data) {
switch (responseType) {
case 'stream':
return data;
case 'json':
return JSON.parse(JSON.stringify(data));
case 'arraybuffer':
return JSON.parse(Buffer.from(data).toString('utf8'));
case 'blob':
return JSON.parse(data.text());
default:
return data;
}
}
/**
* An experimental error redactor.
*
* @param config Config to potentially redact properties of
* @param response Config to potentially redact properties of
*
* @experimental
*/
function defaultErrorRedactor(data) {
const REDACT = '<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.';
function redactHeaders(headers) {
if (!headers)
return;
headers.forEach((_, key) => {
// any casing of `Authentication`
// any casing of `Authorization`
// anything containing secret, such as 'client secret'
if (/^authentication$/i.test(key) ||
/^authorization$/i.test(key) ||
/secret/i.test(key))
headers.set(key, REDACT);
});
}
function redactString(obj, key) {
if (typeof obj === 'object' &&
obj !== null &&
typeof obj[key] === 'string') {
const text = obj[key];
if (/grant_type=/i.test(text) ||
/assertion=/i.test(text) ||
/secret/i.test(text)) {
obj[key] = REDACT;
}
}
}
function redactObject(obj) {
if (!obj || typeof obj !== 'object') {
return;
}
else if (obj instanceof FormData ||
obj instanceof URLSearchParams ||
// support `node-fetch` FormData/URLSearchParams
('forEach' in obj && 'set' in obj)) {
obj.forEach((_, key) => {
if (['grant_type', 'assertion'].includes(key) || /secret/.test(key)) {
obj.set(key, REDACT);
}
});
}
else {
if ('grant_type' in obj) {
obj['grant_type'] = REDACT;
}
if ('assertion' in obj) {
obj['assertion'] = REDACT;
}
if ('client_secret' in obj) {
obj['client_secret'] = REDACT;
}
}
}
if (data.config) {
redactHeaders(data.config.headers);
redactString(data.config, 'data');
redactObject(data.config.data);
redactString(data.config, 'body');
redactObject(data.config.body);
if (data.config.url.searchParams.has('token')) {
data.config.url.searchParams.set('token', REDACT);
}
if (data.config.url.searchParams.has('client_secret')) {
data.config.url.searchParams.set('client_secret', REDACT);
}
}
if (data.response) {
defaultErrorRedactor({ config: data.response.config });
redactHeaders(data.response.headers);
// workaround for `node-fetch`'s `.data` deprecation...
if (data.response.bodyUsed) {
redactString(data.response, 'data');
redactObject(data.response.data);
}
}
return data;
}
//# sourceMappingURL=common.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,104 @@
import { Agent } from 'http';
import { GaxiosOptions, GaxiosOptionsPrepared, GaxiosPromise, GaxiosResponse } from './common.js';
import { GaxiosInterceptorManager } from './interceptor.js';
/**
* An interface for enforcing `fetch`-type compliance.
*
* @remarks
*
* This provides type guarantees during build-time, ensuring the `fetch` method is 1:1
* compatible with the `fetch` API.
*/
interface FetchCompliance {
fetch: typeof fetch;
}
export declare class Gaxios implements FetchCompliance {
#private;
protected agentCache: Map<string | URL, Agent | ((parsedUrl: URL) => Agent)>;
/**
* Default HTTP options that will be used for every HTTP request.
*/
defaults: GaxiosOptions;
/**
* Interceptors
*/
interceptors: {
request: GaxiosInterceptorManager<GaxiosOptionsPrepared>;
response: GaxiosInterceptorManager<GaxiosResponse>;
};
/**
* The Gaxios class is responsible for making HTTP requests.
* @param defaults The default set of options to be used for this instance.
*/
constructor(defaults?: GaxiosOptions);
/**
* A {@link fetch `fetch`} compliant API for {@link Gaxios}.
*
* @remarks
*
* This is useful as a drop-in replacement for `fetch` API usage.
*
* @example
*
* ```ts
* const gaxios = new Gaxios();
* const myFetch: typeof fetch = (...args) => gaxios.fetch(...args);
* await myFetch('https://example.com');
* ```
*
* @param args `fetch` API or `Gaxios#request` parameters
* @returns the {@link Response} with Gaxios-added properties
*/
fetch<T = unknown>(...args: Parameters<typeof fetch> | Parameters<Gaxios['request']>): GaxiosPromise<T>;
/**
* Perform an HTTP request with the given options.
* @param opts Set of HTTP options that will be used for this HTTP request.
*/
request<T = ReturnType<JSON['parse']>>(opts?: GaxiosOptions): GaxiosPromise<T>;
private _defaultAdapter;
/**
* Internal, retryable version of the `request` method.
* @param opts Set of HTTP options that will be used for this HTTP request.
*/
protected _request<T = ReturnType<JSON['parse']>>(opts: GaxiosOptionsPrepared): GaxiosPromise<T>;
private getResponseData;
/**
* By default, throw for any non-2xx status code
* @param status status code from the HTTP response
*/
private validateStatus;
/**
* Attempts to parse a response by looking at the Content-Type header.
* @param {Response} response the HTTP response.
* @returns a promise that resolves to the response data.
*/
private getResponseDataFromContentType;
/**
* Creates an async generator that yields the pieces of a multipart/related request body.
* This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive
* multipart/related requests are not currently supported.
*
* @param {GaxiosMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body.
* @param {string} boundary the boundary string to be placed between each part.
*/
private getMultipartRequest;
/**
* Merges headers.
* If the base headers do not exist a new `Headers` object will be returned.
*
* @remarks
*
* Using this utility can be helpful when the headers are not known to exist:
* - if they exist as `Headers`, that instance will be used
* - it improves performance and allows users to use their existing references to their `Headers`
* - if they exist in another form (`HeadersInit`), they will be used to create a new `Headers` object
* - if the base headers do not exist a new `Headers` object will be created
*
* @param base headers to append/overwrite to
* @param append headers to append/overwrite with
* @returns the base headers instance with merged `Headers`
*/
static mergeHeaders(base?: HeadersInit, ...append: HeadersInit[]): Headers;
}
type HeadersInit = ConstructorParameters<typeof Headers>[0];
export {};

View File

@@ -0,0 +1,564 @@
"use strict";
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Gaxios = void 0;
const extend_1 = __importDefault(require("extend"));
const https_1 = require("https");
const common_js_1 = require("./common.js");
const retry_js_1 = require("./retry.js");
const stream_1 = require("stream");
const interceptor_js_1 = require("./interceptor.js");
const randomUUID = async () => globalThis.crypto?.randomUUID() || (await import('crypto')).randomUUID();
const HTTP_STATUS_NO_CONTENT = 204;
class Gaxios {
agentCache = new Map();
/**
* Default HTTP options that will be used for every HTTP request.
*/
defaults;
/**
* Interceptors
*/
interceptors;
/**
* The Gaxios class is responsible for making HTTP requests.
* @param defaults The default set of options to be used for this instance.
*/
constructor(defaults) {
this.defaults = defaults || {};
this.interceptors = {
request: new interceptor_js_1.GaxiosInterceptorManager(),
response: new interceptor_js_1.GaxiosInterceptorManager(),
};
}
/**
* A {@link fetch `fetch`} compliant API for {@link Gaxios}.
*
* @remarks
*
* This is useful as a drop-in replacement for `fetch` API usage.
*
* @example
*
* ```ts
* const gaxios = new Gaxios();
* const myFetch: typeof fetch = (...args) => gaxios.fetch(...args);
* await myFetch('https://example.com');
* ```
*
* @param args `fetch` API or `Gaxios#request` parameters
* @returns the {@link Response} with Gaxios-added properties
*/
fetch(...args) {
// Up to 2 parameters in either overload
const input = args[0];
const init = args[1];
let url = undefined;
const headers = new Headers();
// prepare URL
if (typeof input === 'string') {
url = new URL(input);
}
else if (input instanceof URL) {
url = input;
}
else if (input && input.url) {
url = new URL(input.url);
}
// prepare headers
if (input && typeof input === 'object' && 'headers' in input) {
_a.mergeHeaders(headers, input.headers);
}
if (init) {
_a.mergeHeaders(headers, new Headers(init.headers));
}
// prepare request
if (typeof input === 'object' && !(input instanceof URL)) {
// input must have been a non-URL object
return this.request({ ...init, ...input, headers, url });
}
else {
// input must have been a string or URL
return this.request({ ...init, headers, url });
}
}
/**
* Perform an HTTP request with the given options.
* @param opts Set of HTTP options that will be used for this HTTP request.
*/
async request(opts = {}) {
let prepared = await this.#prepareRequest(opts);
prepared = await this.#applyRequestInterceptors(prepared);
return this.#applyResponseInterceptors(this._request(prepared));
}
async _defaultAdapter(config) {
const fetchImpl = config.fetchImplementation ||
this.defaults.fetchImplementation ||
(await _a.#getFetch());
// node-fetch v3 warns when `data` is present
// https://github.com/node-fetch/node-fetch/issues/1000
const preparedOpts = { ...config };
delete preparedOpts.data;
const res = (await fetchImpl(config.url, preparedOpts));
const data = await this.getResponseData(config, res);
if (!Object.getOwnPropertyDescriptor(res, 'data')?.configurable) {
// Work-around for `node-fetch` v3 as accessing `data` would otherwise throw
Object.defineProperties(res, {
data: {
configurable: true,
writable: true,
enumerable: true,
value: data,
},
});
}
// Keep object as an instance of `Response`
return Object.assign(res, { config, data });
}
/**
* Internal, retryable version of the `request` method.
* @param opts Set of HTTP options that will be used for this HTTP request.
*/
async _request(opts) {
try {
let translatedResponse;
if (opts.adapter) {
translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this));
}
else {
translatedResponse = await this._defaultAdapter(opts);
}
if (!opts.validateStatus(translatedResponse.status)) {
if (opts.responseType === 'stream') {
const response = [];
for await (const chunk of translatedResponse.data) {
response.push(chunk);
}
translatedResponse.data = response.toString();
}
const errorInfo = common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse, `Request failed with status code ${translatedResponse.status}`);
throw new common_js_1.GaxiosError(errorInfo?.message, opts, translatedResponse, errorInfo);
}
return translatedResponse;
}
catch (e) {
let err;
if (e instanceof common_js_1.GaxiosError) {
err = e;
}
else if (e instanceof Error) {
err = new common_js_1.GaxiosError(e.message, opts, undefined, e);
}
else {
err = new common_js_1.GaxiosError('Unexpected Gaxios Error', opts, undefined, e);
}
const { shouldRetry, config } = await (0, retry_js_1.getRetryConfig)(err);
if (shouldRetry && config) {
err.config.retryConfig.currentRetryAttempt =
config.retryConfig.currentRetryAttempt;
// The error's config could be redacted - therefore we only want to
// copy the retry state over to the existing config
opts.retryConfig = err.config?.retryConfig;
// re-prepare timeout for the next request
this.#appendTimeoutToSignal(opts);
return this._request(opts);
}
if (opts.errorRedactor) {
opts.errorRedactor(err);
}
throw err;
}
}
async getResponseData(opts, res) {
if (res.status === HTTP_STATUS_NO_CONTENT) {
return '';
}
if (opts.maxContentLength &&
res.headers.has('content-length') &&
opts.maxContentLength <
Number.parseInt(res.headers?.get('content-length') || '')) {
throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.", opts, Object.assign(res, { config: opts }));
}
switch (opts.responseType) {
case 'stream':
return res.body;
case 'json': {
const data = await res.text();
try {
return JSON.parse(data);
}
catch {
return data;
}
}
case 'arraybuffer':
return res.arrayBuffer();
case 'blob':
return res.blob();
case 'text':
return res.text();
default:
return this.getResponseDataFromContentType(res);
}
}
#urlMayUseProxy(url, noProxy = []) {
const candidate = new URL(url);
const noProxyList = [...noProxy];
const noProxyEnvList = (process.env.NO_PROXY ?? process.env.no_proxy)?.split(',') || [];
for (const rule of noProxyEnvList) {
noProxyList.push(rule.trim());
}
for (const rule of noProxyList) {
// Match regex
if (rule instanceof RegExp) {
if (rule.test(candidate.toString())) {
return false;
}
}
// Match URL
else if (rule instanceof URL) {
if (rule.origin === candidate.origin) {
return false;
}
}
// Match string regex
else if (rule.startsWith('*.') || rule.startsWith('.')) {
const cleanedRule = rule.replace(/^\*\./, '.');
if (candidate.hostname.endsWith(cleanedRule)) {
return false;
}
}
// Basic string match
else if (rule === candidate.origin ||
rule === candidate.hostname ||
rule === candidate.href) {
return false;
}
}
return true;
}
/**
* Applies the request interceptors. The request interceptors are applied after the
* call to prepareRequest is completed.
*
* @param {GaxiosOptionsPrepared} options The current set of options.
*
* @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
*/
async #applyRequestInterceptors(options) {
let promiseChain = Promise.resolve(options);
for (const interceptor of this.interceptors.request.values()) {
if (interceptor) {
promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
}
}
return promiseChain;
}
/**
* Applies the response interceptors. The response interceptors are applied after the
* call to request is made.
*
* @param {GaxiosOptionsPrepared} options The current set of options.
*
* @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
*/
async #applyResponseInterceptors(response) {
let promiseChain = Promise.resolve(response);
for (const interceptor of this.interceptors.response.values()) {
if (interceptor) {
promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
}
}
return promiseChain;
}
/**
* Validates the options, merges them with defaults, and prepare request.
*
* @param options The original options passed from the client.
* @returns Prepared options, ready to make a request
*/
async #prepareRequest(options) {
// Prepare Headers - copy in order to not mutate the original objects
const preparedHeaders = new Headers(this.defaults.headers);
_a.mergeHeaders(preparedHeaders, options.headers);
// Merge options
const opts = (0, extend_1.default)(true, {}, this.defaults, options);
if (!opts.url) {
throw new Error('URL is required.');
}
if (opts.baseURL) {
opts.url = new URL(opts.url, opts.baseURL);
}
// don't modify the properties of a default or provided URL
opts.url = new URL(opts.url);
if (opts.params) {
if (opts.paramsSerializer) {
let additionalQueryParams = opts.paramsSerializer(opts.params);
if (additionalQueryParams.startsWith('?')) {
additionalQueryParams = additionalQueryParams.slice(1);
}
const prefix = opts.url.toString().includes('?') ? '&' : '?';
opts.url = opts.url + prefix + additionalQueryParams;
}
else {
const url = opts.url instanceof URL ? opts.url : new URL(opts.url);
for (const [key, value] of new URLSearchParams(opts.params)) {
url.searchParams.append(key, value);
}
opts.url = url;
}
}
if (typeof options.maxContentLength === 'number') {
opts.size = options.maxContentLength;
}
if (typeof options.maxRedirects === 'number') {
opts.follow = options.maxRedirects;
}
const shouldDirectlyPassData = typeof opts.data === 'string' ||
opts.data instanceof ArrayBuffer ||
opts.data instanceof Blob ||
// Node 18 does not have a global `File` object
(globalThis.File && opts.data instanceof File) ||
opts.data instanceof FormData ||
opts.data instanceof stream_1.Readable ||
opts.data instanceof ReadableStream ||
opts.data instanceof String ||
opts.data instanceof URLSearchParams ||
ArrayBuffer.isView(opts.data) || // `Buffer` (Node.js), `DataView`, `TypedArray`
/**
* @deprecated `node-fetch` or another third-party's request types
*/
['Blob', 'File', 'FormData'].includes(opts.data?.constructor?.name || '');
if (opts.multipart?.length) {
const boundary = await randomUUID();
preparedHeaders.set('content-type', `multipart/related; boundary=${boundary}`);
opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
}
else if (shouldDirectlyPassData) {
opts.body = opts.data;
}
else if (typeof opts.data === 'object') {
if (preparedHeaders.get('Content-Type') ===
'application/x-www-form-urlencoded') {
// If www-form-urlencoded content type has been set, but data is
// provided as an object, serialize the content
opts.body = opts.paramsSerializer
? opts.paramsSerializer(opts.data)
: new URLSearchParams(opts.data);
}
else {
if (!preparedHeaders.has('content-type')) {
preparedHeaders.set('content-type', 'application/json');
}
opts.body = JSON.stringify(opts.data);
}
}
else if (opts.data) {
opts.body = opts.data;
}
opts.validateStatus = opts.validateStatus || this.validateStatus;
opts.responseType = opts.responseType || 'unknown';
if (!preparedHeaders.has('accept') && opts.responseType === 'json') {
preparedHeaders.set('accept', 'application/json');
}
const proxy = opts.proxy ||
process?.env?.HTTPS_PROXY ||
process?.env?.https_proxy ||
process?.env?.HTTP_PROXY ||
process?.env?.http_proxy;
if (opts.agent) {
// don't do any of the following options - use the user-provided agent.
}
else if (proxy && this.#urlMayUseProxy(opts.url, opts.noProxy)) {
const HttpsProxyAgent = await _a.#getProxyAgent();
if (this.agentCache.has(proxy)) {
opts.agent = this.agentCache.get(proxy);
}
else {
opts.agent = new HttpsProxyAgent(proxy, {
cert: opts.cert,
key: opts.key,
});
this.agentCache.set(proxy, opts.agent);
}
}
else if (opts.cert && opts.key) {
// Configure client for mTLS
if (this.agentCache.has(opts.key)) {
opts.agent = this.agentCache.get(opts.key);
}
else {
opts.agent = new https_1.Agent({
cert: opts.cert,
key: opts.key,
});
this.agentCache.set(opts.key, opts.agent);
}
}
if (typeof opts.errorRedactor !== 'function' &&
opts.errorRedactor !== false) {
opts.errorRedactor = common_js_1.defaultErrorRedactor;
}
if (opts.body && !('duplex' in opts)) {
/**
* required for Node.js and the type isn't available today
* @link https://github.com/nodejs/node/issues/46221
* @link https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1483
*/
opts.duplex = 'half';
}
this.#appendTimeoutToSignal(opts);
return Object.assign(opts, {
headers: preparedHeaders,
url: opts.url instanceof URL ? opts.url : new URL(opts.url),
});
}
#appendTimeoutToSignal(opts) {
if (opts.timeout) {
const timeoutSignal = AbortSignal.timeout(opts.timeout);
if (opts.signal && !opts.signal.aborted) {
opts.signal = AbortSignal.any([opts.signal, timeoutSignal]);
}
else {
opts.signal = timeoutSignal;
}
}
}
/**
* By default, throw for any non-2xx status code
* @param status status code from the HTTP response
*/
validateStatus(status) {
return status >= 200 && status < 300;
}
/**
* Attempts to parse a response by looking at the Content-Type header.
* @param {Response} response the HTTP response.
* @returns a promise that resolves to the response data.
*/
async getResponseDataFromContentType(response) {
let contentType = response.headers.get('Content-Type');
if (contentType === null) {
// Maintain existing functionality by calling text()
return response.text();
}
contentType = contentType.toLowerCase();
if (contentType.includes('application/json')) {
let data = await response.text();
try {
data = JSON.parse(data);
}
catch {
// continue
}
return data;
}
else if (contentType.match(/^text\//)) {
return response.text();
}
else {
// If the content type is something not easily handled, just return the raw data (blob)
return response.blob();
}
}
/**
* Creates an async generator that yields the pieces of a multipart/related request body.
* This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive
* multipart/related requests are not currently supported.
*
* @param {GaxiosMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body.
* @param {string} boundary the boundary string to be placed between each part.
*/
async *getMultipartRequest(multipartOptions, boundary) {
const finale = `--${boundary}--`;
for (const currentPart of multipartOptions) {
const partContentType = currentPart.headers.get('Content-Type') || 'application/octet-stream';
const preamble = `--${boundary}\r\nContent-Type: ${partContentType}\r\n\r\n`;
yield preamble;
if (typeof currentPart.content === 'string') {
yield currentPart.content;
}
else {
yield* currentPart.content;
}
yield '\r\n';
}
yield finale;
}
/**
* A cache for the lazily-loaded proxy agent.
*
* Should use {@link Gaxios[#getProxyAgent]} to retrieve.
*/
// using `import` to dynamically import the types here
static #proxyAgent;
/**
* A cache for the lazily-loaded fetch library.
*
* Should use {@link Gaxios[#getFetch]} to retrieve.
*/
//
static #fetch;
/**
* Imports, caches, and returns a proxy agent - if not already imported
*
* @returns A proxy agent
*/
static async #getProxyAgent() {
this.#proxyAgent ||= (await import('https-proxy-agent')).HttpsProxyAgent;
return this.#proxyAgent;
}
static async #getFetch() {
const hasWindow = typeof window !== 'undefined' && !!window;
this.#fetch ||= hasWindow
? window.fetch
: (await import('node-fetch')).default;
return this.#fetch;
}
/**
* Merges headers.
* If the base headers do not exist a new `Headers` object will be returned.
*
* @remarks
*
* Using this utility can be helpful when the headers are not known to exist:
* - if they exist as `Headers`, that instance will be used
* - it improves performance and allows users to use their existing references to their `Headers`
* - if they exist in another form (`HeadersInit`), they will be used to create a new `Headers` object
* - if the base headers do not exist a new `Headers` object will be created
*
* @param base headers to append/overwrite to
* @param append headers to append/overwrite with
* @returns the base headers instance with merged `Headers`
*/
static mergeHeaders(base, ...append) {
base = base instanceof Headers ? base : new Headers(base);
for (const headers of append) {
const add = headers instanceof Headers ? headers : new Headers(headers);
add.forEach((value, key) => {
// set-cookie is the only header that would repeat.
// A bit of background: https://developer.mozilla.org/en-US/docs/Web/API/Headers/getSetCookie
key === 'set-cookie' ? base.append(key, value) : base.set(key, value);
});
}
return base;
}
}
exports.Gaxios = Gaxios;
_a = Gaxios;
//# sourceMappingURL=gaxios.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
import { GaxiosOptions } from './common.js';
import { Gaxios } from './gaxios.js';
export { GaxiosError, GaxiosPromise, GaxiosResponse, GaxiosOptionsPrepared, RetryConfig, } from './common.js';
export { Gaxios, GaxiosOptions };
export * from './interceptor.js';
/**
* The default instance used when the `request` method is directly
* invoked.
*/
export declare const instance: Gaxios;
/**
* Make an HTTP request using the given options.
* @param opts Options for the request
*/
export declare function request<T>(opts: GaxiosOptions): Promise<import("./common.js").GaxiosResponse<T>>;

View File

@@ -0,0 +1,48 @@
"use strict";
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.instance = exports.Gaxios = exports.GaxiosError = void 0;
exports.request = request;
const gaxios_js_1 = require("./gaxios.js");
Object.defineProperty(exports, "Gaxios", { enumerable: true, get: function () { return gaxios_js_1.Gaxios; } });
var common_js_1 = require("./common.js");
Object.defineProperty(exports, "GaxiosError", { enumerable: true, get: function () { return common_js_1.GaxiosError; } });
__exportStar(require("./interceptor.js"), exports);
/**
* The default instance used when the `request` method is directly
* invoked.
*/
exports.instance = new gaxios_js_1.Gaxios();
/**
* Make an HTTP request using the given options.
* @param opts Options for the request
*/
async function request(opts) {
return exports.instance.request(opts);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;;;;;;;;;;;AAyBjC,0BAEC;AAxBD,2CAAmC;AAS3B,uFATA,kBAAM,OASA;AAPd,yCAMqB;AALnB,wGAAA,WAAW,OAAA;AAOb,mDAAiC;AAEjC;;;GAGG;AACU,QAAA,QAAQ,GAAG,IAAI,kBAAM,EAAE,CAAC;AAErC;;;GAGG;AACI,KAAK,UAAU,OAAO,CAAI,IAAmB;IAClD,OAAO,gBAAQ,CAAC,OAAO,CAAI,IAAI,CAAC,CAAC;AACnC,CAAC"}

View File

@@ -0,0 +1,25 @@
import { GaxiosError, GaxiosOptionsPrepared, GaxiosResponse } from './common.js';
/**
* Interceptors that can be run for requests or responses. These interceptors run asynchronously.
*/
export interface GaxiosInterceptor<T extends GaxiosOptionsPrepared | GaxiosResponse> {
/**
* Function to be run when applying an interceptor.
*
* @param {T} configOrResponse The current configuration or response.
* @returns {Promise<T>} Promise that resolves to the modified set of options or response.
*/
resolved?: (configOrResponse: T) => Promise<T>;
/**
* Function to be run if the previous call to resolved throws / rejects or the request results in an invalid status
* as determined by the call to validateStatus.
*
* @param {GaxiosError} err The error thrown from the previously called resolved function.
*/
rejected?: (err: GaxiosError) => void;
}
/**
* Class to manage collections of GaxiosInterceptors for both requests and responses.
*/
export declare class GaxiosInterceptorManager<T extends GaxiosOptionsPrepared | GaxiosResponse> extends Set<GaxiosInterceptor<T> | null> {
}

View File

@@ -0,0 +1,22 @@
"use strict";
// Copyright 2024 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.GaxiosInterceptorManager = void 0;
/**
* Class to manage collections of GaxiosInterceptors for both requests and responses.
*/
class GaxiosInterceptorManager extends Set {
}
exports.GaxiosInterceptorManager = GaxiosInterceptorManager;
//# sourceMappingURL=interceptor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"interceptor.js","sourceRoot":"","sources":["../../../src/interceptor.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AA0BjC;;GAEG;AACH,MAAa,wBAEX,SAAQ,GAAgC;CAAG;AAF7C,4DAE6C"}

View File

@@ -0,0 +1,8 @@
import { GaxiosError } from './common.js';
export declare function getRetryConfig(err: GaxiosError): Promise<{
shouldRetry: boolean;
config?: undefined;
} | {
shouldRetry: boolean;
config: import("./common.js").GaxiosOptionsPrepared;
}>;

View File

@@ -0,0 +1,165 @@
"use strict";
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRetryConfig = getRetryConfig;
async function getRetryConfig(err) {
let config = getConfig(err);
if (!err || !err.config || (!config && !err.config.retry)) {
return { shouldRetry: false };
}
config = config || {};
config.currentRetryAttempt = config.currentRetryAttempt || 0;
config.retry =
config.retry === undefined || config.retry === null ? 3 : config.retry;
config.httpMethodsToRetry = config.httpMethodsToRetry || [
'GET',
'HEAD',
'PUT',
'OPTIONS',
'DELETE',
];
config.noResponseRetries =
config.noResponseRetries === undefined || config.noResponseRetries === null
? 2
: config.noResponseRetries;
config.retryDelayMultiplier = config.retryDelayMultiplier
? config.retryDelayMultiplier
: 2;
config.timeOfFirstRequest = config.timeOfFirstRequest
? config.timeOfFirstRequest
: Date.now();
config.totalTimeout = config.totalTimeout
? config.totalTimeout
: Number.MAX_SAFE_INTEGER;
config.maxRetryDelay = config.maxRetryDelay
? config.maxRetryDelay
: Number.MAX_SAFE_INTEGER;
// If this wasn't in the list of status codes where we want
// to automatically retry, return.
const retryRanges = [
// https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
// 1xx - Retry (Informational, request still processing)
// 2xx - Do not retry (Success)
// 3xx - Do not retry (Redirect)
// 4xx - Do not retry (Client errors)
// 408 - Retry ("Request Timeout")
// 429 - Retry ("Too Many Requests")
// 5xx - Retry (Server errors)
[100, 199],
[408, 408],
[429, 429],
[500, 599],
];
config.statusCodesToRetry = config.statusCodesToRetry || retryRanges;
// Put the config back into the err
err.config.retryConfig = config;
// Determine if we should retry the request
const shouldRetryFn = config.shouldRetry || shouldRetryRequest;
if (!(await shouldRetryFn(err))) {
return { shouldRetry: false, config: err.config };
}
const delay = getNextRetryDelay(config);
// We're going to retry! Increment the counter.
err.config.retryConfig.currentRetryAttempt += 1;
// Create a promise that invokes the retry after the backOffDelay
const backoff = config.retryBackoff
? config.retryBackoff(err, delay)
: new Promise(resolve => {
setTimeout(resolve, delay);
});
// Notify the user if they added an `onRetryAttempt` handler
if (config.onRetryAttempt) {
await config.onRetryAttempt(err);
}
// Return the promise in which recalls Gaxios to retry the request
await backoff;
return { shouldRetry: true, config: err.config };
}
/**
* Determine based on config if we should retry the request.
* @param err The GaxiosError passed to the interceptor.
*/
function shouldRetryRequest(err) {
const config = getConfig(err);
if ((err.config.signal?.aborted && err.code !== 'TimeoutError') ||
err.code === 'AbortError') {
return false;
}
// If there's no config, or retries are disabled, return.
if (!config || config.retry === 0) {
return false;
}
// Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc)
if (!err.response &&
(config.currentRetryAttempt || 0) >= config.noResponseRetries) {
return false;
}
// Only retry with configured HttpMethods.
if (!config.httpMethodsToRetry ||
!config.httpMethodsToRetry.includes(err.config.method?.toUpperCase() || 'GET')) {
return false;
}
// If this wasn't in the list of status codes where we want
// to automatically retry, return.
if (err.response && err.response.status) {
let isInRange = false;
for (const [min, max] of config.statusCodesToRetry) {
const status = err.response.status;
if (status >= min && status <= max) {
isInRange = true;
break;
}
}
if (!isInRange) {
return false;
}
}
// If we are out of retry attempts, return
config.currentRetryAttempt = config.currentRetryAttempt || 0;
if (config.currentRetryAttempt >= config.retry) {
return false;
}
return true;
}
/**
* Acquire the raxConfig object from an GaxiosError if available.
* @param err The Gaxios error with a config object.
*/
function getConfig(err) {
if (err && err.config && err.config.retryConfig) {
return err.config.retryConfig;
}
return;
}
/**
* Gets the delay to wait before the next retry.
*
* @param {RetryConfig} config The current set of retry options
* @returns {number} the amount of ms to wait before the next retry attempt.
*/
function getNextRetryDelay(config) {
// Calculate time to wait with exponential backoff.
// If this is the first retry, look for a configured retryDelay.
const retryDelay = config.currentRetryAttempt
? 0
: (config.retryDelay ?? 100);
// Formula: retryDelay + ((retryDelayMultiplier^currentRetryAttempt - 1 / 2) * 1000)
const calculatedDelay = retryDelay +
((Math.pow(config.retryDelayMultiplier, config.currentRetryAttempt) - 1) /
2) *
1000;
const maxAllowableDelay = config.totalTimeout - (Date.now() - config.timeOfFirstRequest);
return Math.min(calculatedDelay, maxAllowableDelay, config.maxRetryDelay);
}
//# sourceMappingURL=retry.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../../src/retry.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAIjC,wCAgFC;AAhFM,KAAK,UAAU,cAAc,CAAC,GAAgB;IACnD,IAAI,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;IAC5B,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC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AC,CAAC;AAC7E,CAAC"}

View File

@@ -0,0 +1,16 @@
"use strict";
// Copyright 2023 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const pkg = require('../../../package.json');
module.exports = { pkg };
//# sourceMappingURL=util.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"util.cjs","sourceRoot":"","sources":["../../../src/util.cts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,MAAM,GAAG,GAGL,OAAO,CAAC,uBAAuB,CAAC,CAAC;AAErC,iBAAS,EAAC,GAAG,EAAC,CAAC"}

View File

@@ -0,0 +1,7 @@
declare const _default: {
pkg: {
name: string;
version: string;
};
};
export = _default;

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,128 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const assert_1 = __importDefault(require("assert"));
const child_process_1 = require("child_process");
const fs_1 = __importDefault(require("fs"));
const mv_1 = __importDefault(require("mv"));
const ncp_1 = __importDefault(require("ncp"));
const path_1 = __importDefault(require("path"));
const tmp_1 = __importDefault(require("tmp"));
const util_1 = require("util");
const mocha_1 = require("mocha");
const pack_n_play_1 = require("pack-n-play");
const node_http_1 = require("node:http");
const util_cjs_1 = __importDefault(require("../src/util.cjs"));
/**
* Optionally keep the staging directory between tests.
*/
const KEEP_STAGING_DIRECTORY = false;
const mvp = (0, util_1.promisify)(mv_1.default);
const ncpp = (0, util_1.promisify)(ncp_1.default);
const pkg = util_cjs_1.default.pkg;
const exec = (0, util_1.promisify)(child_process_1.execFile);
(0, mocha_1.describe)('📦 pack and install', () => {
let stagingDir;
let stagingPath;
(0, mocha_1.before)(() => {
stagingDir = tmp_1.default.dirSync({
keep: KEEP_STAGING_DIRECTORY,
unsafeCleanup: true,
});
stagingPath = stagingDir.name;
});
(0, mocha_1.after)('cleanup staging', () => {
if (!KEEP_STAGING_DIRECTORY) {
stagingDir.removeCallback();
}
});
(0, mocha_1.describe)('pack-n-play', () => {
let server;
let url;
(0, mocha_1.before)(async () => {
server = (0, node_http_1.createServer)((req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' });
res.end(`Hello, ${req.headers['user-agent'] || 'World'}`);
});
await new Promise((resolve, reject) => {
server.on('error', reject);
server.listen(0, resolve);
});
const address = server.address();
if (typeof address === 'string') {
url = address;
}
else {
const base = new URL('http://localhost');
base.host = address.address;
base.port = address.port.toString();
url = base.toString();
}
});
(0, mocha_1.after)(() => {
server.close();
});
(0, mocha_1.it)('supports ESM', async () => {
await (0, pack_n_play_1.packNTest)({
sample: {
description: 'import as ESM',
esm: `
import {Gaxios} from 'gaxios';
const gaxios = new Gaxios();
await gaxios.request({url: '${url}'});
`,
},
});
});
(0, mocha_1.it)('supports CJS', async () => {
await (0, pack_n_play_1.packNTest)({
sample: {
description: 'require as CJS',
cjs: `
const {Gaxios} = require('gaxios');
const gaxios = new Gaxios();
gaxios.request({url: '${url}'}).then(console.log);
`,
},
});
});
});
(0, mocha_1.describe)('webpack', () => {
/**
* Create a staging directory with temp fixtures used to test on a fresh
* application.
*/
(0, mocha_1.before)('pack and install', async () => {
await exec('npm', ['pack']);
const tarball = `${pkg.name}-${pkg.version}.tgz`;
await mvp(tarball, `${stagingPath}/gaxios.tgz`);
await ncpp('system-test/fixtures/sample', `${stagingPath}/`);
await exec('npm', ['install'], { cwd: `${stagingPath}/` });
});
(0, mocha_1.it)('should be able to webpack the library', async () => {
// we expect npm install is executed in the before hook
await exec('npx', ['webpack'], { cwd: `${stagingPath}/` });
const bundle = path_1.default.join(stagingPath, 'dist', 'bundle.min.js');
const stat = fs_1.default.statSync(bundle);
(0, assert_1.default)(stat.size < 256 * 1024);
}).timeout(20000);
});
});
//# sourceMappingURL=test.install.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"test.install.js","sourceRoot":"","sources":["../../../system-test/test.install.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;AAEjC,oDAA4B;AAC5B,iDAAuC;AACvC,4CAAoB;AACpB,4CAAoB;AACpB,8CAAsB;AACtB,gDAAwB;AACxB,8CAAsB;AACtB,+BAA+B;AAC/B,iCAAkD;AAClD,6CAAsC;AAEtC,yCAA+C;AAE/C,+DAAmC;AAEnC;;GAEG;AACH,MAAM,sBAAsB,GAAG,KAAK,CAAC;AAErC,MAAM,GAAG,GAAG,IAAA,gBAAS,EAAC,YAAE,CAA+C,CAAC;AACxE,MAAM,IAAI,GAAG,IAAA,gBAAS,EAAC,aAAG,CAAC,CAAC;AAE5B,MAAM,GAAG,GAAG,kBAAI,CAAC,GAAG,CAAC;AAErB,MAAM,IAAI,GAAG,IAAA,gBAAS,EAAC,wBAAQ,CAAC,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,CAAC;YAChD,MAAM,IAAI,CAAC,6BAA6B,EAAE,GAAG,WAAW,GAAG,CAAC,CAAC;YAC7D,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC,SAAS,CAAC,EAAE,EAAC,GAAG,EAAE,GAAG,WAAW,GAAG,EAAC,CAAC,CAAC;QAC3D,CAAC,CAAC,CAAC;QAEH,IAAA,UAAE,EAAC,uCAAuC,EAAE,KAAK,IAAI,EAAE;YACrD,uDAAuD;YACvD,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC,SAAS,CAAC,EAAE,EAAC,GAAG,EAAE,GAAG,WAAW,GAAG,EAAC,CAAC,CAAC;YACzD,MAAM,MAAM,GAAG,cAAI,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,eAAe,CAAC,CAAC;YAC/D,MAAM,IAAI,GAAG,YAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;YACjC,IAAA,gBAAM,EAAC,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC;QACjC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,61 @@
"use strict";
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const assert_1 = __importDefault(require("assert"));
const mocha_1 = require("mocha");
const main = __importStar(require("../src/index.js"));
(0, mocha_1.describe)('📝 main exports', () => {
(0, mocha_1.it)('should export all the types', () => {
(0, assert_1.default)(main.Gaxios);
(0, assert_1.default)(main.GaxiosError);
(0, assert_1.default)(main.GaxiosInterceptorManager);
});
});
//# sourceMappingURL=test.index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"test.index.js","sourceRoot":"","sources":["../../../test/test.index.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEjC,oDAA4B;AAC5B,iCAAmC;AACnC,sDAAwC;AAExC,IAAA,gBAAQ,EAAC,iBAAiB,EAAE,GAAG,EAAE;IAC/B,IAAA,UAAE,EAAC,6BAA6B,EAAE,GAAG,EAAE;QACrC,IAAA,gBAAM,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACpB,IAAA,gBAAM,EAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACzB,IAAA,gBAAM,EAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;IACxC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,367 @@
"use strict";
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const assert_1 = __importDefault(require("assert"));
const nock_1 = __importDefault(require("nock"));
const mocha_1 = require("mocha");
const index_js_1 = require("../src/index.js");
nock_1.default.disableNetConnect();
const url = 'https://example.com';
function getConfig(err) {
const e = err;
if (e && e.config && e.config.retryConfig) {
return e.config.retryConfig;
}
return;
}
(0, mocha_1.afterEach)(() => {
nock_1.default.cleanAll();
});
(0, mocha_1.describe)('🛸 retry & exponential backoff', () => {
(0, mocha_1.it)('should provide an expected set of defaults', async () => {
const scope = (0, nock_1.default)(url).get('/').times(4).reply(500);
await assert_1.default.rejects((0, index_js_1.request)({ url, retry: true }), (e) => {
scope.done();
const config = getConfig(e);
if (!config) {
assert_1.default.fail('no config available');
}
assert_1.default.strictEqual(config.currentRetryAttempt, 3);
assert_1.default.strictEqual(config.retry, 3);
assert_1.default.strictEqual(config.noResponseRetries, 2);
const expectedMethods = ['GET', 'HEAD', 'PUT', 'OPTIONS', 'DELETE'];
for (const method of config.httpMethodsToRetry) {
(0, assert_1.default)(expectedMethods.indexOf(method) > -1);
}
const expectedStatusCodes = [
[100, 199],
[408, 408],
[429, 429],
[500, 599],
];
const statusCodesToRetry = config.statusCodesToRetry;
for (let i = 0; i < statusCodesToRetry.length; i++) {
const [min, max] = statusCodesToRetry[i];
const [expMin, expMax] = expectedStatusCodes[i];
assert_1.default.strictEqual(min, expMin);
assert_1.default.strictEqual(max, expMax);
}
return true;
});
});
(0, mocha_1.it)('should retry on 500 on the main export', async () => {
const body = { buttered: '🥖' };
const scopes = [
(0, nock_1.default)(url).get('/').reply(500),
(0, nock_1.default)(url).get('/').reply(200, body),
];
const res = await (0, index_js_1.request)({
url,
retry: true,
});
assert_1.default.deepStrictEqual(res.data, body);
scopes.forEach(s => s.done());
});
(0, mocha_1.it)('should not retry on a post', async () => {
const scope = (0, nock_1.default)(url).post('/').reply(500);
await assert_1.default.rejects((0, index_js_1.request)({ url, method: 'POST', retry: true }), (e) => {
const config = getConfig(e);
return config.currentRetryAttempt === 0;
});
scope.done();
});
(0, mocha_1.it)('should not retry if user aborted request', async () => {
const ac = new AbortController();
const config = {
method: 'GET',
url: 'https://google.com',
signal: ac.signal,
retryConfig: { retry: 10, noResponseRetries: 10 },
};
const req = (0, index_js_1.request)(config);
ac.abort();
try {
await req;
throw Error('unreachable');
}
catch (err) {
(0, assert_1.default)(err instanceof index_js_1.GaxiosError);
(0, assert_1.default)(err.config);
assert_1.default.strictEqual(err.config.retryConfig?.currentRetryAttempt, 0);
}
});
(0, mocha_1.it)('should retry at least the configured number of times', async () => {
const body = { dippy: '🥚' };
const scopes = [
(0, nock_1.default)(url).get('/').times(3).reply(500),
(0, nock_1.default)(url).get('/').reply(200, body),
];
const cfg = { url, retryConfig: { retry: 4 } };
const res = await (0, index_js_1.request)(cfg);
assert_1.default.deepStrictEqual(res.data, body);
scopes.forEach(s => s.done());
});
(0, mocha_1.it)('should not retry more than configured', async () => {
const scope = (0, nock_1.default)(url).get('/').twice().reply(500);
const cfg = { url, retryConfig: { retry: 1 } };
await assert_1.default.rejects((0, index_js_1.request)(cfg), (e) => {
return getConfig(e).currentRetryAttempt === 1;
});
scope.done();
});
(0, mocha_1.it)('should not retry on 4xx errors', async () => {
const scope = (0, nock_1.default)(url).get('/').reply(404);
await assert_1.default.rejects((0, index_js_1.request)({ url, retry: true }), (e) => {
const cfg = getConfig(e);
return cfg.currentRetryAttempt === 0;
});
scope.done();
});
(0, mocha_1.it)('should retain the baseURL on retry', async () => {
const body = { pumpkin: '🥧' };
const url = '/path';
const baseURL = 'http://example.com';
const scope = (0, nock_1.default)(baseURL).get(url).reply(500).get(url).reply(200, body);
const gaxios = new index_js_1.Gaxios({ baseURL });
const res = await gaxios.request({
url,
retry: true,
});
assert_1.default.deepStrictEqual(res.data, body);
scope.done();
});
(0, mocha_1.it)('should not retry if retries set to 0', async () => {
const scope = (0, nock_1.default)(url).get('/').reply(500);
const cfg = { url, retryConfig: { retry: 0 } };
await assert_1.default.rejects((0, index_js_1.request)(cfg), (e) => {
const cfg = getConfig(e);
return cfg.currentRetryAttempt === 0;
});
scope.done();
});
(0, mocha_1.it)('should notify on retry attempts', async () => {
const body = { buttered: '🥖' };
const scopes = [
(0, nock_1.default)(url).get('/').reply(500),
(0, nock_1.default)(url).get('/').reply(200, body),
];
let flipped = false;
const config = {
url,
retryConfig: {
onRetryAttempt: err => {
const cfg = getConfig(err);
assert_1.default.strictEqual(cfg.currentRetryAttempt, 1);
flipped = true;
},
},
};
await (0, index_js_1.request)(config);
assert_1.default.strictEqual(flipped, true);
scopes.forEach(s => s.done());
});
(0, mocha_1.it)('accepts async onRetryAttempt handler', async () => {
const body = { buttered: '🥖' };
const scopes = [
(0, nock_1.default)(url).get('/').reply(500),
(0, nock_1.default)(url).get('/').reply(200, body),
];
let flipped = false;
const config = {
url,
retryConfig: {
onRetryAttempt: async (err) => {
const cfg = getConfig(err);
assert_1.default.strictEqual(cfg.currentRetryAttempt, 1);
flipped = true;
},
},
};
await (0, index_js_1.request)(config);
assert_1.default.strictEqual(flipped, true);
scopes.forEach(s => s.done());
});
(0, mocha_1.it)('should support overriding the shouldRetry method', async () => {
const scope = (0, nock_1.default)(url).get('/').reply(500);
const config = {
url,
retryConfig: {
shouldRetry: () => {
return false;
},
},
};
await assert_1.default.rejects((0, index_js_1.request)(config), (e) => {
const cfg = getConfig(e);
return cfg.currentRetryAttempt === 0;
});
scope.done();
});
(0, mocha_1.it)('should support overriding the shouldRetry method with a promise', async () => {
const scope = (0, nock_1.default)(url).get('/').reply(500);
const config = {
url,
retryConfig: {
shouldRetry: async () => {
return false;
},
},
};
await assert_1.default.rejects((0, index_js_1.request)(config), (e) => {
const cfg = getConfig(e);
return cfg.currentRetryAttempt === 0;
});
scope.done();
});
(0, mocha_1.it)('should retry on ENOTFOUND', async () => {
const body = { spicy: '🌮' };
const scopes = [
(0, nock_1.default)(url).get('/').reply(500, { code: 'ENOTFOUND' }),
(0, nock_1.default)(url).get('/').reply(200, body),
];
const res = await (0, index_js_1.request)({ url, retry: true });
assert_1.default.deepStrictEqual(res.data, body);
scopes.forEach(s => s.done());
});
(0, mocha_1.it)('should retry on ETIMEDOUT', async () => {
const body = { sizzling: '🥓' };
const scopes = [
(0, nock_1.default)(url).get('/').reply(500, { code: 'ETIMEDOUT' }),
(0, nock_1.default)(url).get('/').reply(200, body),
];
const res = await (0, index_js_1.request)({ url, retry: true });
assert_1.default.deepStrictEqual(res.data, body);
scopes.forEach(s => s.done());
});
(0, mocha_1.it)('should allow configuring noResponseRetries', async () => {
// `nock` is not listening, therefore it should fail
const config = { url, retryConfig: { noResponseRetries: 0 } };
await assert_1.default.rejects((0, index_js_1.request)(config), (e) => {
return (e.code === 'ENETUNREACH' &&
e.config.retryConfig?.currentRetryAttempt === 0);
});
});
(0, mocha_1.it)('should delay the initial retry by 100ms by default', async () => {
const scope = (0, nock_1.default)(url).get('/').reply(500).get('/').reply(200, {});
const start = Date.now();
await (0, index_js_1.request)({
url,
retry: true,
});
const delay = Date.now() - start;
assert_1.default.ok(delay > 100 && delay < 199);
scope.done();
});
(0, mocha_1.it)('should respect the retryDelay if configured', async () => {
const scope = (0, nock_1.default)(url).get('/').reply(500).get('/').reply(200, {});
const start = Date.now();
await (0, index_js_1.request)({
url,
retryConfig: {
retryDelay: 500,
},
});
const delay = Date.now() - start;
assert_1.default.ok(delay > 500 && delay < 599);
scope.done();
});
(0, mocha_1.it)('should respect retryDelayMultiplier if configured', async () => {
const scope = (0, nock_1.default)(url)
.get('/')
.reply(500)
.get('/')
.reply(500)
.get('/')
.reply(200, {});
const start = Date.now();
await (0, index_js_1.request)({
url,
retryConfig: {
retryDelayMultiplier: 3,
},
});
const delay = Date.now() - start;
assert_1.default.ok(delay > 1000 && delay < 1999);
scope.done();
});
(0, mocha_1.it)('should respect totalTimeout if configured', async () => {
const scope = (0, nock_1.default)(url)
.get('/')
.reply(500)
.get('/')
.reply(500)
.get('/')
.reply(200, {});
const start = Date.now();
await (0, index_js_1.request)({
url,
retryConfig: {
retryDelayMultiplier: 100,
totalTimeout: 3000,
},
});
const delay = Date.now() - start;
assert_1.default.ok(delay > 3000 && delay < 3999);
scope.done();
});
(0, mocha_1.it)('should respect maxRetryDelay if configured', async () => {
const scope = (0, nock_1.default)(url)
.get('/')
.reply(500)
.get('/')
.reply(500)
.get('/')
.reply(200, {});
const start = Date.now();
await (0, index_js_1.request)({
url,
retryConfig: {
retryDelayMultiplier: 100,
maxRetryDelay: 4000,
},
});
const delay = Date.now() - start;
assert_1.default.ok(delay > 4000 && delay < 4999);
scope.done();
});
(0, mocha_1.it)('should retry on `timeout`', async () => {
const scope = (0, nock_1.default)(url).get('/').delay(500).reply(400).get('/').reply(204);
const gaxios = new index_js_1.Gaxios();
const timeout = 100;
async function onRetryAttempt({ config, message }) {
(0, assert_1.default)(config.signal?.reason instanceof DOMException);
assert_1.default.equal(config.signal.reason.name, 'TimeoutError');
assert_1.default.match(message, /timeout/i);
// increase timeout to something higher to avoid time-sensitive flaky tests
// note: the second `nock` GET is not delayed like the first one
config.timeout = 10000;
}
const res = await gaxios.request({
url,
timeout,
// NOTE: `node-fetch` does not yet support `TimeoutError` - testing with native `fetch` for now.
fetchImplementation: fetch,
retryConfig: {
onRetryAttempt,
},
});
assert_1.default.equal(res.status, 204);
assert_1.default.equal(res.config?.retryConfig?.currentRetryAttempt, 1);
scope.done();
});
});
//# sourceMappingURL=test.retry.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,71 @@
// Copyright 2019 Google, LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import express from 'express';
import { execFile } from 'child_process';
import * as multiparty from 'multiparty';
import cors from 'cors';
import { promisify } from 'util';
const port = 7172;
const exec = promisify(execFile);
async function listen(app, port) {
return new Promise((resolve, reject) => {
const server = app.listen(port, (err) => {
if (err) {
reject(err);
}
resolve(server);
});
});
}
// Starts a web server that browser tests will use, then runs actual browser
// tests.
async function main() {
const app = express();
app.use(cors());
app.post('/path', (req, res) => {
if (req.header('origin')) {
res.set('Access-Control-Allow-Origin', req.header('origin'));
}
const form = new multiparty.Form({ autoFields: true });
form.parse(req, (err, fields) => {
if (err) {
res.status(500).send({ message: err.message });
}
else {
res.status(200).send(fields.null);
}
});
});
app.get('/path', (req, res) => {
if (req.header('origin')) {
res.set('Access-Control-Allow-Origin', req.header('origin'));
}
res.send('response');
});
app.get('/querystring', (req, res) => {
if (req.header('origin')) {
res.set('Access-Control-Allow-Origin', req.header('origin'));
}
const query = req.query.query;
res.send(query || '');
});
const server = await listen(app, port);
console.log(`[http server] I'm listening on port ${port}! Starting karma.`);
await exec('karma', ['start']);
server.close();
console.log(`[http server] Karma has finished! I'm no longer listening on port ${port}!`);
}
main().catch(err => {
console.log('Error:', err);
});
//# sourceMappingURL=browser-test-runner.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"browser-test-runner.js","sourceRoot":"","sources":["../../../browser-test/browser-test-runner.ts"],"names":[],"mappings":"AAAA,6BAA6B;AAC7B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAC,QAAQ,EAAC,MAAM,eAAe,CAAC;AACvC,OAAO,KAAK,UAAU,MAAM,YAAY,CAAC;AACzC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAC,SAAS,EAAC,MAAM,MAAM,CAAC;AAE/B,MAAM,IAAI,GAAG,IAAI,CAAC;AAElB,MAAM,IAAI,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AAEjC,KAAK,UAAU,MAAM,CACnB,GAAoB,EACpB,IAAY;IAEZ,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,GAAW,EAAE,EAAE;YAC9C,IAAI,GAAG,EAAE,CAAC;gBACR,MAAM,CAAC,GAAG,CAAC,CAAC;YACd,CAAC;YACD,OAAO,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,4EAA4E;AAC5E,SAAS;AACT,KAAK,UAAU,IAAI;IACjB,MAAM,GAAG,GAAG,OAAO,EAAE,CAAC;IAEtB,GAAG,C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,EAAE,CAAC;YACzB,GAAG,CAAC,GAAG,CAAC,6BAA6B,EAAE,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;QAC/D,CAAC;QACD,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC;QAC9B,GAAG,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC;IACxB,CAAC,CAAC,CAAC;IAEH,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,uCAAuC,IAAI,mBAAmB,CAAC,CAAC;IAC5E,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IAC/B,MAAM,CAAC,KAAK,EAAE,CAAC;IACf,OAAO,CAAC,GAAG,CACT,qEAAqE,IAAI,GAAG,CAC7E,CAAC;AACJ,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;IACjB,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;AAC7B,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,76 @@
// Copyright 2019 Google, LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import assert from 'assert';
import { describe, it } from 'mocha';
import { request } from '../src/index';
const port = 7172; // should match the port defined in `webserver.ts`
describe('💻 browser tests', () => {
it('should just work from browser', async () => {
const result = await request({ url: `http://localhost:${port}/path` });
assert.strictEqual(result.status, 200);
assert.strictEqual(result.data, 'response');
});
it('should pass querystring parameters from browser', async () => {
const result = await request({
url: `http://localhost:${port}/querystring`,
params: { query: 'value' },
});
assert.strictEqual(result.status, 200);
assert.strictEqual(result.data, 'value');
});
it('should allow passing browser fetch explicitly', async () => {
const result = await request({
url: `http://localhost:${port}/path`,
fetchImplementation: window.fetch,
});
assert.strictEqual(result.status, 200);
});
it('should support multipart post from the browser', async () => {
const headers = new Headers();
const multipart = [
{
'Content-Type': 'application/json',
body: JSON.stringify({ hello: 'world' }),
},
{
'Content-Type': 'text/plain',
body: 'hello world!',
},
];
const boundary = globalThis?.crypto.randomUUID() || (await import('crypto')).randomUUID();
const finale = `--${boundary}--`;
headers.set('Content-Type', `multipart/related; boundary=${boundary}`);
let content = '';
for (const part of multipart) {
const preamble = `--${boundary}\r\nContent-Type: ${part['Content-Type']}\r\n\r\n`;
// rStream.push(preamble);
content += preamble;
if (typeof part.body === 'string') {
content += part.body;
content += '\r\n';
}
}
content += finale;
const result = await request({
headers,
data: content,
method: 'POST',
url: `http://localhost:${port}/path`,
});
assert.strictEqual(result.status, 200);
const parts = result.data;
assert.strictEqual(parts[0], '{"hello":"world"}');
assert.strictEqual(parts[1], 'hello world!');
});
});
//# sourceMappingURL=test.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"test.browser.js","sourceRoot":"","sources":["../../../browser-test/test.browser.ts"],"names":[],"mappings":"AAAA,6BAA6B;AAC7B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAC,QAAQ,EAAE,EAAE,EAAC,MAAM,OAAO,CAAC;AACnC,OAAO,EAAC,OAAO,EAAC,MAAM,cAAc,CAAC;AACrC,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,kDAAkD;AAErE,QAAQ,CAAC,kBAAkB,EAAE,GAAG,EAAE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type": "module"}

View File

@@ -0,0 +1,329 @@
import { Agent } from 'http';
import { Readable } from 'stream';
/**
* TypeScript does not have this type available globally - however `@types/node` includes `undici-types`, which has it:
* - https://www.npmjs.com/package/@types/node/v/18.19.59?activeTab=dependencies
*
* Additionally, this is the TypeScript pattern for type sniffing and `import("undici-types")` is pretty common:
* - https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/globals.d.ts
*/
type _BodyInit = typeof globalThis extends {
BodyInit: infer T;
} ? T : import('undici-types').BodyInit;
/**
* An AIP-193 conforming error interface.
*
* @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
*
* @param res the response object
* @returns the extracted error information
*/
export interface AIPErrorInterface {
error: {
code: number;
message: string;
status: string;
details?: {}[];
};
}
/**
* Support `instanceof` operator for `GaxiosError`s in different versions of this library.
*
* @see {@link GaxiosError[Symbol.hasInstance]}
*/
export declare const GAXIOS_ERROR_SYMBOL: unique symbol;
export declare class GaxiosError<T = ReturnType<JSON['parse']>> extends Error {
config: GaxiosOptionsPrepared;
response?: GaxiosResponse<T> | undefined;
/**
* An error code.
* Can be a system error code, DOMException error name, or any error's 'code' property where it is a `string`.
*
* It is only a `number` when the cause is sourced from an API-level error (AIP-193).
*
* @see {@link https://nodejs.org/api/errors.html#errorcode error.code}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names DOMException#error_names}
* @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
*
* @example
* 'ECONNRESET'
*
* @example
* 'TimeoutError'
*
* @example
* 500
*/
code?: string | number;
/**
* An HTTP Status code.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status Response#status}
*
* @example
* 500
*/
status?: number;
/**
* @deprecated use {@link GaxiosError.cause} instead.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause Error#cause}
*
* @privateRemarks
*
* We will want to remove this property later as the modern `cause` property is better suited
* for displaying and relaying nested errors. Keeping this here makes the resulting
* error log larger than it needs to be.
*
*/
error?: Error | NodeJS.ErrnoException;
/**
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
*
* @see {@link GAXIOS_ERROR_SYMBOL}
* @see {@link GaxiosError[Symbol.hasInstance]}
* @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200}
* @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior}
*/
[GAXIOS_ERROR_SYMBOL]: string;
/**
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
*
* @see {@link GAXIOS_ERROR_SYMBOL}
* @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]}
*/
static [Symbol.hasInstance](instance: unknown): boolean;
constructor(message: string, config: GaxiosOptionsPrepared, response?: GaxiosResponse<T> | undefined, cause?: unknown);
}
type GaxiosResponseData = ReturnType<JSON['parse']> | GaxiosOptionsPrepared['data'];
export type GaxiosPromise<T = GaxiosResponseData> = Promise<GaxiosResponse<T>>;
export interface GaxiosResponse<T = GaxiosResponseData> extends Response {
config: GaxiosOptionsPrepared;
data: T;
}
export interface GaxiosMultipartOptions {
headers: Headers;
content: string | Readable;
}
/**
* Request options that are used to form the request.
*/
export interface GaxiosOptions extends RequestInit {
/**
* Optional method to override making the actual HTTP request. Useful
* for writing tests.
*/
adapter?: <T = GaxiosResponseData>(options: GaxiosOptionsPrepared, defaultAdapter: (options: GaxiosOptionsPrepared) => GaxiosPromise<T>) => GaxiosPromise<T>;
url?: string | URL;
baseURL?: string | URL;
/**
* The data to send in the {@link RequestInit.body} of the request. Objects will be
* serialized as JSON, except for:
* - `ArrayBuffer`
* - `Blob`
* - `Buffer` (Node.js)
* - `DataView`
* - `File`
* - `FormData`
* - `ReadableStream`
* - `stream.Readable` (Node.js)
* - strings
* - `TypedArray` (e.g. `Uint8Array`, `BigInt64Array`)
* - `URLSearchParams`
* - all other objects where:
* - headers['Content-Type'] === 'application/x-www-form-urlencoded' (serialized as `URLSearchParams`)
*
* In all other cases, if you would like to prevent `application/json` as the
* default `Content-Type` header you must provide a string or readable stream
* rather than an object, e.g.:
*
* ```ts
* {data: JSON.stringify({some: 'data'})}
* {data: fs.readFile('./some-data.jpeg')}
* ```
*/
data?: _BodyInit | ArrayBuffer | Blob | Buffer | DataView | File | FormData | ReadableStream | Readable | string | ArrayBufferView | URLSearchParams | {};
/**
* The maximum size of the http response `Content-Length` in bytes allowed.
*/
maxContentLength?: number;
/**
* The maximum number of redirects to follow. Defaults to 20.
*
* @deprecated non-spec. Should use `20` if enabled per-spec: https://fetch.spec.whatwg.org/#http-redirect-fetch
*/
maxRedirects?: number;
/**
* @deprecated non-spec. Should use `20` if enabled per-spec: https://fetch.spec.whatwg.org/#http-redirect-fetch
*/
follow?: number;
/**
* A collection of parts to send as a `Content-Type: multipart/related` request.
*
* This is passed to {@link RequestInit.body}.
*/
multipart?: GaxiosMultipartOptions[];
params?: GaxiosResponseData;
/**
* @deprecated Use {@link URLSearchParams} instead and pass this directly to {@link GaxiosOptions.data `data`}.
*/
paramsSerializer?: (params: {
[index: string]: string | number;
}) => string;
/**
* A timeout for the request, in milliseconds. No timeout by default.
*/
timeout?: number;
/**
* @deprecated ignored
*/
onUploadProgress?: (progressEvent: GaxiosResponseData) => void;
/**
* If the `fetchImplementation` is native `fetch`, the
* stream is a `ReadableStream`, otherwise `readable.Stream`
*/
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream' | 'unknown';
agent?: Agent | ((parsedUrl: URL) => Agent);
validateStatus?: (status: number) => boolean;
retryConfig?: RetryConfig;
retry?: boolean;
/**
* @deprecated non-spec. https://github.com/node-fetch/node-fetch/issues/1438
*/
size?: number;
/**
* Implementation of `fetch` to use when making the API call. Will use `fetch` by default.
*
* @example
*
* let customFetchCalled = false;
* const myFetch = (...args: Parameters<typeof fetch>) => {
* customFetchCalled = true;
* return fetch(...args);
* };
*
* {fetchImplementation: myFetch};
*/
fetchImplementation?: typeof fetch;
cert?: string;
key?: string;
/**
* An optional proxy to use for requests.
* Available via `process.env.HTTP_PROXY` and `process.env.HTTPS_PROXY` as well - with a preference for the this config option when multiple are available.
* The {@link GaxiosOptions.agent `agent`} option overrides this.
*
* @see {@link GaxiosOptions.noProxy}
* @see {@link GaxiosOptions.agent}
*/
proxy?: string | URL;
/**
* A list for excluding traffic for proxies.
* Available via `process.env.NO_PROXY` as well as a common-separated list of strings - merged with any local `noProxy` rules.
*
* - When provided a string, it is matched by
* - Wildcard `*.` and `.` matching are available. (e.g. `.example.com` or `*.example.com`)
* - When provided a URL, it is matched by the `.origin` property.
* - For example, requesting `https://example.com` with the following `noProxy`s would result in a no proxy use:
* - new URL('https://example.com')
* - new URL('https://example.com:443')
* - The following would be used with a proxy:
* - new URL('http://example.com:80')
* - new URL('https://example.com:8443')
* - When provided a regular expression it is used to match the stringified URL
*
* @see {@link GaxiosOptions.proxy}
*/
noProxy?: (string | URL | RegExp)[];
/**
* An experimental error redactor.
*
* @remarks
*
* This does not replace the requirement for an active Data Loss Prevention (DLP) provider. For DLP suggestions, see:
* - https://cloud.google.com/sensitive-data-protection/docs/redacting-sensitive-data#dlp_deidentify_replace_infotype-nodejs
* - https://cloud.google.com/sensitive-data-protection/docs/infotypes-reference#credentials_and_secrets
*
* @experimental
*/
errorRedactor?: typeof defaultErrorRedactor | false;
}
export interface GaxiosOptionsPrepared extends GaxiosOptions {
headers: Headers;
url: URL;
}
/**
* Gaxios retry configuration.
*/
export interface RetryConfig {
/**
* The number of times to retry the request. Defaults to 3.
*/
retry?: number;
/**
* The number of retries already attempted.
*/
currentRetryAttempt?: number;
/**
* The amount of time to initially delay the retry, in ms. Defaults to 100ms.
*/
retryDelay?: number;
/**
* The HTTP Methods that will be automatically retried.
* Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE']
*/
httpMethodsToRetry?: string[];
/**
* The HTTP response status codes that will automatically be retried.
* Defaults to: [[100, 199], [408, 408], [429, 429], [500, 599]]
*/
statusCodesToRetry?: number[][];
/**
* Function to invoke when a retry attempt is made.
*/
onRetryAttempt?: (err: GaxiosError) => Promise<void> | void;
/**
* Function to invoke which determines if you should retry
*/
shouldRetry?: (err: GaxiosError) => Promise<boolean> | boolean;
/**
* When there is no response, the number of retries to attempt. Defaults to 2.
*/
noResponseRetries?: number;
/**
* Function to invoke which returns a promise. After the promise resolves,
* the retry will be triggered. If provided, this will be used in-place of
* the `retryDelay`
*/
retryBackoff?: (err: GaxiosError, defaultBackoffMs: number) => Promise<void>;
/**
* Time that the initial request was made. Users should not set this directly.
*/
timeOfFirstRequest?: number;
/**
* The length of time to keep retrying in ms. The last sleep period will
* be shortened as necessary, so that the last retry runs at deadline (and not
* considerably beyond it). The total time starting from when the initial
* request is sent, after which an error will be returned, regardless of the
* retrying attempts made meanwhile. Defaults to Number.MAX_SAFE_INTEGER indicating to effectively
* ignore totalTimeout.
*/
totalTimeout?: number;
maxRetryDelay?: number;
retryDelayMultiplier?: number;
}
/**
* An experimental error redactor.
*
* @param config Config to potentially redact properties of
* @param response Config to potentially redact properties of
*
* @experimental
*/
export declare function defaultErrorRedactor<O extends GaxiosOptionsPrepared, R extends GaxiosResponse<GaxiosResponseData>>(data: {
config?: O;
response?: R;
}): {
config?: O;
response?: R;
};
export {};

View File

@@ -0,0 +1,303 @@
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import extend from 'extend';
import util from './util.cjs';
const pkg = util.pkg;
/**
* Support `instanceof` operator for `GaxiosError`s in different versions of this library.
*
* @see {@link GaxiosError[Symbol.hasInstance]}
*/
export const GAXIOS_ERROR_SYMBOL = Symbol.for(`${pkg.name}-gaxios-error`);
export class GaxiosError extends Error {
config;
response;
/**
* An error code.
* Can be a system error code, DOMException error name, or any error's 'code' property where it is a `string`.
*
* It is only a `number` when the cause is sourced from an API-level error (AIP-193).
*
* @see {@link https://nodejs.org/api/errors.html#errorcode error.code}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names DOMException#error_names}
* @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
*
* @example
* 'ECONNRESET'
*
* @example
* 'TimeoutError'
*
* @example
* 500
*/
code;
/**
* An HTTP Status code.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status Response#status}
*
* @example
* 500
*/
status;
/**
* @deprecated use {@link GaxiosError.cause} instead.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause Error#cause}
*
* @privateRemarks
*
* We will want to remove this property later as the modern `cause` property is better suited
* for displaying and relaying nested errors. Keeping this here makes the resulting
* error log larger than it needs to be.
*
*/
error;
/**
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
*
* @see {@link GAXIOS_ERROR_SYMBOL}
* @see {@link GaxiosError[Symbol.hasInstance]}
* @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200}
* @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior}
*/
[GAXIOS_ERROR_SYMBOL] = pkg.version;
/**
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
*
* @see {@link GAXIOS_ERROR_SYMBOL}
* @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]}
*/
static [Symbol.hasInstance](instance) {
if (instance &&
typeof instance === 'object' &&
GAXIOS_ERROR_SYMBOL in instance &&
instance[GAXIOS_ERROR_SYMBOL] === pkg.version) {
return true;
}
// fallback to native
return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance);
}
constructor(message, config, response, cause) {
super(message, { cause });
this.config = config;
this.response = response;
this.error = cause instanceof Error ? cause : undefined;
// deep-copy config as we do not want to mutate
// the existing config for future retries/use
this.config = extend(true, {}, config);
if (this.response) {
this.response.config = extend(true, {}, this.response.config);
}
if (this.response) {
try {
this.response.data = translateData(this.config.responseType,
// workaround for `node-fetch`'s `.data` deprecation...
this.response?.bodyUsed ? this.response?.data : undefined);
}
catch {
// best effort - don't throw an error within an error
// we could set `this.response.config.responseType = 'unknown'`, but
// that would mutate future calls with this config object.
}
this.status = this.response.status;
}
if (cause instanceof DOMException) {
// The DOMException's equivalent to code is its name
// E.g.: name = `TimeoutError`, code = number
// https://developer.mozilla.org/en-US/docs/Web/API/DOMException/name
this.code = cause.name;
}
else if (cause &&
typeof cause === 'object' &&
'code' in cause &&
(typeof cause.code === 'string' || typeof cause.code === 'number')) {
this.code = cause.code;
}
}
/**
* An AIP-193 conforming error extractor.
*
* @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
*
* @internal
* @expiremental
*
* @param res the response object
* @returns the extracted error information
*/
static extractAPIErrorFromResponse(res, defaultErrorMessage = 'The request failed') {
let message = defaultErrorMessage;
// Use res.data as the error message
if (typeof res.data === 'string') {
message = res.data;
}
if (res.data &&
typeof res.data === 'object' &&
'error' in res.data &&
res.data.error &&
!res.ok) {
if (typeof res.data.error === 'string') {
return {
message: res.data.error,
code: res.status,
status: res.statusText,
};
}
if (typeof res.data.error === 'object') {
// extract status from data.message
message =
'message' in res.data.error &&
typeof res.data.error.message === 'string'
? res.data.error.message
: message;
// extract status from data.error
const status = 'status' in res.data.error &&
typeof res.data.error.status === 'string'
? res.data.error.status
: res.statusText;
// extract code from data.error
const code = 'code' in res.data.error && typeof res.data.error.code === 'number'
? res.data.error.code
: res.status;
if ('errors' in res.data.error &&
Array.isArray(res.data.error.errors)) {
const errorMessages = [];
for (const e of res.data.error.errors) {
if (typeof e === 'object' &&
'message' in e &&
typeof e.message === 'string') {
errorMessages.push(e.message);
}
}
return Object.assign({
message: errorMessages.join('\n') || message,
code,
status,
}, res.data.error);
}
return Object.assign({
message,
code,
status,
}, res.data.error);
}
}
return {
message,
code: res.status,
status: res.statusText,
};
}
}
function translateData(responseType, data) {
switch (responseType) {
case 'stream':
return data;
case 'json':
return JSON.parse(JSON.stringify(data));
case 'arraybuffer':
return JSON.parse(Buffer.from(data).toString('utf8'));
case 'blob':
return JSON.parse(data.text());
default:
return data;
}
}
/**
* An experimental error redactor.
*
* @param config Config to potentially redact properties of
* @param response Config to potentially redact properties of
*
* @experimental
*/
export function defaultErrorRedactor(data) {
const REDACT = '<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.';
function redactHeaders(headers) {
if (!headers)
return;
headers.forEach((_, key) => {
// any casing of `Authentication`
// any casing of `Authorization`
// anything containing secret, such as 'client secret'
if (/^authentication$/i.test(key) ||
/^authorization$/i.test(key) ||
/secret/i.test(key))
headers.set(key, REDACT);
});
}
function redactString(obj, key) {
if (typeof obj === 'object' &&
obj !== null &&
typeof obj[key] === 'string') {
const text = obj[key];
if (/grant_type=/i.test(text) ||
/assertion=/i.test(text) ||
/secret/i.test(text)) {
obj[key] = REDACT;
}
}
}
function redactObject(obj) {
if (!obj || typeof obj !== 'object') {
return;
}
else if (obj instanceof FormData ||
obj instanceof URLSearchParams ||
// support `node-fetch` FormData/URLSearchParams
('forEach' in obj && 'set' in obj)) {
obj.forEach((_, key) => {
if (['grant_type', 'assertion'].includes(key) || /secret/.test(key)) {
obj.set(key, REDACT);
}
});
}
else {
if ('grant_type' in obj) {
obj['grant_type'] = REDACT;
}
if ('assertion' in obj) {
obj['assertion'] = REDACT;
}
if ('client_secret' in obj) {
obj['client_secret'] = REDACT;
}
}
}
if (data.config) {
redactHeaders(data.config.headers);
redactString(data.config, 'data');
redactObject(data.config.data);
redactString(data.config, 'body');
redactObject(data.config.body);
if (data.config.url.searchParams.has('token')) {
data.config.url.searchParams.set('token', REDACT);
}
if (data.config.url.searchParams.has('client_secret')) {
data.config.url.searchParams.set('client_secret', REDACT);
}
}
if (data.response) {
defaultErrorRedactor({ config: data.response.config });
redactHeaders(data.response.headers);
// workaround for `node-fetch`'s `.data` deprecation...
if (data.response.bodyUsed) {
redactString(data.response, 'data');
redactObject(data.response.data);
}
}
return data;
}
//# sourceMappingURL=common.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,104 @@
import { Agent } from 'http';
import { GaxiosOptions, GaxiosOptionsPrepared, GaxiosPromise, GaxiosResponse } from './common.js';
import { GaxiosInterceptorManager } from './interceptor.js';
/**
* An interface for enforcing `fetch`-type compliance.
*
* @remarks
*
* This provides type guarantees during build-time, ensuring the `fetch` method is 1:1
* compatible with the `fetch` API.
*/
interface FetchCompliance {
fetch: typeof fetch;
}
export declare class Gaxios implements FetchCompliance {
#private;
protected agentCache: Map<string | URL, Agent | ((parsedUrl: URL) => Agent)>;
/**
* Default HTTP options that will be used for every HTTP request.
*/
defaults: GaxiosOptions;
/**
* Interceptors
*/
interceptors: {
request: GaxiosInterceptorManager<GaxiosOptionsPrepared>;
response: GaxiosInterceptorManager<GaxiosResponse>;
};
/**
* The Gaxios class is responsible for making HTTP requests.
* @param defaults The default set of options to be used for this instance.
*/
constructor(defaults?: GaxiosOptions);
/**
* A {@link fetch `fetch`} compliant API for {@link Gaxios}.
*
* @remarks
*
* This is useful as a drop-in replacement for `fetch` API usage.
*
* @example
*
* ```ts
* const gaxios = new Gaxios();
* const myFetch: typeof fetch = (...args) => gaxios.fetch(...args);
* await myFetch('https://example.com');
* ```
*
* @param args `fetch` API or `Gaxios#request` parameters
* @returns the {@link Response} with Gaxios-added properties
*/
fetch<T = unknown>(...args: Parameters<typeof fetch> | Parameters<Gaxios['request']>): GaxiosPromise<T>;
/**
* Perform an HTTP request with the given options.
* @param opts Set of HTTP options that will be used for this HTTP request.
*/
request<T = ReturnType<JSON['parse']>>(opts?: GaxiosOptions): GaxiosPromise<T>;
private _defaultAdapter;
/**
* Internal, retryable version of the `request` method.
* @param opts Set of HTTP options that will be used for this HTTP request.
*/
protected _request<T = ReturnType<JSON['parse']>>(opts: GaxiosOptionsPrepared): GaxiosPromise<T>;
private getResponseData;
/**
* By default, throw for any non-2xx status code
* @param status status code from the HTTP response
*/
private validateStatus;
/**
* Attempts to parse a response by looking at the Content-Type header.
* @param {Response} response the HTTP response.
* @returns a promise that resolves to the response data.
*/
private getResponseDataFromContentType;
/**
* Creates an async generator that yields the pieces of a multipart/related request body.
* This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive
* multipart/related requests are not currently supported.
*
* @param {GaxiosMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body.
* @param {string} boundary the boundary string to be placed between each part.
*/
private getMultipartRequest;
/**
* Merges headers.
* If the base headers do not exist a new `Headers` object will be returned.
*
* @remarks
*
* Using this utility can be helpful when the headers are not known to exist:
* - if they exist as `Headers`, that instance will be used
* - it improves performance and allows users to use their existing references to their `Headers`
* - if they exist in another form (`HeadersInit`), they will be used to create a new `Headers` object
* - if the base headers do not exist a new `Headers` object will be created
*
* @param base headers to append/overwrite to
* @param append headers to append/overwrite with
* @returns the base headers instance with merged `Headers`
*/
static mergeHeaders(base?: HeadersInit, ...append: HeadersInit[]): Headers;
}
type HeadersInit = ConstructorParameters<typeof Headers>[0];
export {};

View File

@@ -0,0 +1,557 @@
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var _a;
import extend from 'extend';
import { Agent as HTTPSAgent } from 'https';
import { GaxiosError, defaultErrorRedactor, } from './common.js';
import { getRetryConfig } from './retry.js';
import { Readable } from 'stream';
import { GaxiosInterceptorManager } from './interceptor.js';
const randomUUID = async () => globalThis.crypto?.randomUUID() || (await import('crypto')).randomUUID();
const HTTP_STATUS_NO_CONTENT = 204;
export class Gaxios {
agentCache = new Map();
/**
* Default HTTP options that will be used for every HTTP request.
*/
defaults;
/**
* Interceptors
*/
interceptors;
/**
* The Gaxios class is responsible for making HTTP requests.
* @param defaults The default set of options to be used for this instance.
*/
constructor(defaults) {
this.defaults = defaults || {};
this.interceptors = {
request: new GaxiosInterceptorManager(),
response: new GaxiosInterceptorManager(),
};
}
/**
* A {@link fetch `fetch`} compliant API for {@link Gaxios}.
*
* @remarks
*
* This is useful as a drop-in replacement for `fetch` API usage.
*
* @example
*
* ```ts
* const gaxios = new Gaxios();
* const myFetch: typeof fetch = (...args) => gaxios.fetch(...args);
* await myFetch('https://example.com');
* ```
*
* @param args `fetch` API or `Gaxios#request` parameters
* @returns the {@link Response} with Gaxios-added properties
*/
fetch(...args) {
// Up to 2 parameters in either overload
const input = args[0];
const init = args[1];
let url = undefined;
const headers = new Headers();
// prepare URL
if (typeof input === 'string') {
url = new URL(input);
}
else if (input instanceof URL) {
url = input;
}
else if (input && input.url) {
url = new URL(input.url);
}
// prepare headers
if (input && typeof input === 'object' && 'headers' in input) {
_a.mergeHeaders(headers, input.headers);
}
if (init) {
_a.mergeHeaders(headers, new Headers(init.headers));
}
// prepare request
if (typeof input === 'object' && !(input instanceof URL)) {
// input must have been a non-URL object
return this.request({ ...init, ...input, headers, url });
}
else {
// input must have been a string or URL
return this.request({ ...init, headers, url });
}
}
/**
* Perform an HTTP request with the given options.
* @param opts Set of HTTP options that will be used for this HTTP request.
*/
async request(opts = {}) {
let prepared = await this.#prepareRequest(opts);
prepared = await this.#applyRequestInterceptors(prepared);
return this.#applyResponseInterceptors(this._request(prepared));
}
async _defaultAdapter(config) {
const fetchImpl = config.fetchImplementation ||
this.defaults.fetchImplementation ||
(await _a.#getFetch());
// node-fetch v3 warns when `data` is present
// https://github.com/node-fetch/node-fetch/issues/1000
const preparedOpts = { ...config };
delete preparedOpts.data;
const res = (await fetchImpl(config.url, preparedOpts));
const data = await this.getResponseData(config, res);
if (!Object.getOwnPropertyDescriptor(res, 'data')?.configurable) {
// Work-around for `node-fetch` v3 as accessing `data` would otherwise throw
Object.defineProperties(res, {
data: {
configurable: true,
writable: true,
enumerable: true,
value: data,
},
});
}
// Keep object as an instance of `Response`
return Object.assign(res, { config, data });
}
/**
* Internal, retryable version of the `request` method.
* @param opts Set of HTTP options that will be used for this HTTP request.
*/
async _request(opts) {
try {
let translatedResponse;
if (opts.adapter) {
translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this));
}
else {
translatedResponse = await this._defaultAdapter(opts);
}
if (!opts.validateStatus(translatedResponse.status)) {
if (opts.responseType === 'stream') {
const response = [];
for await (const chunk of translatedResponse.data) {
response.push(chunk);
}
translatedResponse.data = response.toString();
}
const errorInfo = GaxiosError.extractAPIErrorFromResponse(translatedResponse, `Request failed with status code ${translatedResponse.status}`);
throw new GaxiosError(errorInfo?.message, opts, translatedResponse, errorInfo);
}
return translatedResponse;
}
catch (e) {
let err;
if (e instanceof GaxiosError) {
err = e;
}
else if (e instanceof Error) {
err = new GaxiosError(e.message, opts, undefined, e);
}
else {
err = new GaxiosError('Unexpected Gaxios Error', opts, undefined, e);
}
const { shouldRetry, config } = await getRetryConfig(err);
if (shouldRetry && config) {
err.config.retryConfig.currentRetryAttempt =
config.retryConfig.currentRetryAttempt;
// The error's config could be redacted - therefore we only want to
// copy the retry state over to the existing config
opts.retryConfig = err.config?.retryConfig;
// re-prepare timeout for the next request
this.#appendTimeoutToSignal(opts);
return this._request(opts);
}
if (opts.errorRedactor) {
opts.errorRedactor(err);
}
throw err;
}
}
async getResponseData(opts, res) {
if (res.status === HTTP_STATUS_NO_CONTENT) {
return '';
}
if (opts.maxContentLength &&
res.headers.has('content-length') &&
opts.maxContentLength <
Number.parseInt(res.headers?.get('content-length') || '')) {
throw new GaxiosError("Response's `Content-Length` is over the limit.", opts, Object.assign(res, { config: opts }));
}
switch (opts.responseType) {
case 'stream':
return res.body;
case 'json': {
const data = await res.text();
try {
return JSON.parse(data);
}
catch {
return data;
}
}
case 'arraybuffer':
return res.arrayBuffer();
case 'blob':
return res.blob();
case 'text':
return res.text();
default:
return this.getResponseDataFromContentType(res);
}
}
#urlMayUseProxy(url, noProxy = []) {
const candidate = new URL(url);
const noProxyList = [...noProxy];
const noProxyEnvList = (process.env.NO_PROXY ?? process.env.no_proxy)?.split(',') || [];
for (const rule of noProxyEnvList) {
noProxyList.push(rule.trim());
}
for (const rule of noProxyList) {
// Match regex
if (rule instanceof RegExp) {
if (rule.test(candidate.toString())) {
return false;
}
}
// Match URL
else if (rule instanceof URL) {
if (rule.origin === candidate.origin) {
return false;
}
}
// Match string regex
else if (rule.startsWith('*.') || rule.startsWith('.')) {
const cleanedRule = rule.replace(/^\*\./, '.');
if (candidate.hostname.endsWith(cleanedRule)) {
return false;
}
}
// Basic string match
else if (rule === candidate.origin ||
rule === candidate.hostname ||
rule === candidate.href) {
return false;
}
}
return true;
}
/**
* Applies the request interceptors. The request interceptors are applied after the
* call to prepareRequest is completed.
*
* @param {GaxiosOptionsPrepared} options The current set of options.
*
* @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
*/
async #applyRequestInterceptors(options) {
let promiseChain = Promise.resolve(options);
for (const interceptor of this.interceptors.request.values()) {
if (interceptor) {
promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
}
}
return promiseChain;
}
/**
* Applies the response interceptors. The response interceptors are applied after the
* call to request is made.
*
* @param {GaxiosOptionsPrepared} options The current set of options.
*
* @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
*/
async #applyResponseInterceptors(response) {
let promiseChain = Promise.resolve(response);
for (const interceptor of this.interceptors.response.values()) {
if (interceptor) {
promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
}
}
return promiseChain;
}
/**
* Validates the options, merges them with defaults, and prepare request.
*
* @param options The original options passed from the client.
* @returns Prepared options, ready to make a request
*/
async #prepareRequest(options) {
// Prepare Headers - copy in order to not mutate the original objects
const preparedHeaders = new Headers(this.defaults.headers);
_a.mergeHeaders(preparedHeaders, options.headers);
// Merge options
const opts = extend(true, {}, this.defaults, options);
if (!opts.url) {
throw new Error('URL is required.');
}
if (opts.baseURL) {
opts.url = new URL(opts.url, opts.baseURL);
}
// don't modify the properties of a default or provided URL
opts.url = new URL(opts.url);
if (opts.params) {
if (opts.paramsSerializer) {
let additionalQueryParams = opts.paramsSerializer(opts.params);
if (additionalQueryParams.startsWith('?')) {
additionalQueryParams = additionalQueryParams.slice(1);
}
const prefix = opts.url.toString().includes('?') ? '&' : '?';
opts.url = opts.url + prefix + additionalQueryParams;
}
else {
const url = opts.url instanceof URL ? opts.url : new URL(opts.url);
for (const [key, value] of new URLSearchParams(opts.params)) {
url.searchParams.append(key, value);
}
opts.url = url;
}
}
if (typeof options.maxContentLength === 'number') {
opts.size = options.maxContentLength;
}
if (typeof options.maxRedirects === 'number') {
opts.follow = options.maxRedirects;
}
const shouldDirectlyPassData = typeof opts.data === 'string' ||
opts.data instanceof ArrayBuffer ||
opts.data instanceof Blob ||
// Node 18 does not have a global `File` object
(globalThis.File && opts.data instanceof File) ||
opts.data instanceof FormData ||
opts.data instanceof Readable ||
opts.data instanceof ReadableStream ||
opts.data instanceof String ||
opts.data instanceof URLSearchParams ||
ArrayBuffer.isView(opts.data) || // `Buffer` (Node.js), `DataView`, `TypedArray`
/**
* @deprecated `node-fetch` or another third-party's request types
*/
['Blob', 'File', 'FormData'].includes(opts.data?.constructor?.name || '');
if (opts.multipart?.length) {
const boundary = await randomUUID();
preparedHeaders.set('content-type', `multipart/related; boundary=${boundary}`);
opts.body = Readable.from(this.getMultipartRequest(opts.multipart, boundary));
}
else if (shouldDirectlyPassData) {
opts.body = opts.data;
}
else if (typeof opts.data === 'object') {
if (preparedHeaders.get('Content-Type') ===
'application/x-www-form-urlencoded') {
// If www-form-urlencoded content type has been set, but data is
// provided as an object, serialize the content
opts.body = opts.paramsSerializer
? opts.paramsSerializer(opts.data)
: new URLSearchParams(opts.data);
}
else {
if (!preparedHeaders.has('content-type')) {
preparedHeaders.set('content-type', 'application/json');
}
opts.body = JSON.stringify(opts.data);
}
}
else if (opts.data) {
opts.body = opts.data;
}
opts.validateStatus = opts.validateStatus || this.validateStatus;
opts.responseType = opts.responseType || 'unknown';
if (!preparedHeaders.has('accept') && opts.responseType === 'json') {
preparedHeaders.set('accept', 'application/json');
}
const proxy = opts.proxy ||
process?.env?.HTTPS_PROXY ||
process?.env?.https_proxy ||
process?.env?.HTTP_PROXY ||
process?.env?.http_proxy;
if (opts.agent) {
// don't do any of the following options - use the user-provided agent.
}
else if (proxy && this.#urlMayUseProxy(opts.url, opts.noProxy)) {
const HttpsProxyAgent = await _a.#getProxyAgent();
if (this.agentCache.has(proxy)) {
opts.agent = this.agentCache.get(proxy);
}
else {
opts.agent = new HttpsProxyAgent(proxy, {
cert: opts.cert,
key: opts.key,
});
this.agentCache.set(proxy, opts.agent);
}
}
else if (opts.cert && opts.key) {
// Configure client for mTLS
if (this.agentCache.has(opts.key)) {
opts.agent = this.agentCache.get(opts.key);
}
else {
opts.agent = new HTTPSAgent({
cert: opts.cert,
key: opts.key,
});
this.agentCache.set(opts.key, opts.agent);
}
}
if (typeof opts.errorRedactor !== 'function' &&
opts.errorRedactor !== false) {
opts.errorRedactor = defaultErrorRedactor;
}
if (opts.body && !('duplex' in opts)) {
/**
* required for Node.js and the type isn't available today
* @link https://github.com/nodejs/node/issues/46221
* @link https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1483
*/
opts.duplex = 'half';
}
this.#appendTimeoutToSignal(opts);
return Object.assign(opts, {
headers: preparedHeaders,
url: opts.url instanceof URL ? opts.url : new URL(opts.url),
});
}
#appendTimeoutToSignal(opts) {
if (opts.timeout) {
const timeoutSignal = AbortSignal.timeout(opts.timeout);
if (opts.signal && !opts.signal.aborted) {
opts.signal = AbortSignal.any([opts.signal, timeoutSignal]);
}
else {
opts.signal = timeoutSignal;
}
}
}
/**
* By default, throw for any non-2xx status code
* @param status status code from the HTTP response
*/
validateStatus(status) {
return status >= 200 && status < 300;
}
/**
* Attempts to parse a response by looking at the Content-Type header.
* @param {Response} response the HTTP response.
* @returns a promise that resolves to the response data.
*/
async getResponseDataFromContentType(response) {
let contentType = response.headers.get('Content-Type');
if (contentType === null) {
// Maintain existing functionality by calling text()
return response.text();
}
contentType = contentType.toLowerCase();
if (contentType.includes('application/json')) {
let data = await response.text();
try {
data = JSON.parse(data);
}
catch {
// continue
}
return data;
}
else if (contentType.match(/^text\//)) {
return response.text();
}
else {
// If the content type is something not easily handled, just return the raw data (blob)
return response.blob();
}
}
/**
* Creates an async generator that yields the pieces of a multipart/related request body.
* This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive
* multipart/related requests are not currently supported.
*
* @param {GaxiosMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body.
* @param {string} boundary the boundary string to be placed between each part.
*/
async *getMultipartRequest(multipartOptions, boundary) {
const finale = `--${boundary}--`;
for (const currentPart of multipartOptions) {
const partContentType = currentPart.headers.get('Content-Type') || 'application/octet-stream';
const preamble = `--${boundary}\r\nContent-Type: ${partContentType}\r\n\r\n`;
yield preamble;
if (typeof currentPart.content === 'string') {
yield currentPart.content;
}
else {
yield* currentPart.content;
}
yield '\r\n';
}
yield finale;
}
/**
* A cache for the lazily-loaded proxy agent.
*
* Should use {@link Gaxios[#getProxyAgent]} to retrieve.
*/
// using `import` to dynamically import the types here
static #proxyAgent;
/**
* A cache for the lazily-loaded fetch library.
*
* Should use {@link Gaxios[#getFetch]} to retrieve.
*/
//
static #fetch;
/**
* Imports, caches, and returns a proxy agent - if not already imported
*
* @returns A proxy agent
*/
static async #getProxyAgent() {
this.#proxyAgent ||= (await import('https-proxy-agent')).HttpsProxyAgent;
return this.#proxyAgent;
}
static async #getFetch() {
const hasWindow = typeof window !== 'undefined' && !!window;
this.#fetch ||= hasWindow
? window.fetch
: (await import('node-fetch')).default;
return this.#fetch;
}
/**
* Merges headers.
* If the base headers do not exist a new `Headers` object will be returned.
*
* @remarks
*
* Using this utility can be helpful when the headers are not known to exist:
* - if they exist as `Headers`, that instance will be used
* - it improves performance and allows users to use their existing references to their `Headers`
* - if they exist in another form (`HeadersInit`), they will be used to create a new `Headers` object
* - if the base headers do not exist a new `Headers` object will be created
*
* @param base headers to append/overwrite to
* @param append headers to append/overwrite with
* @returns the base headers instance with merged `Headers`
*/
static mergeHeaders(base, ...append) {
base = base instanceof Headers ? base : new Headers(base);
for (const headers of append) {
const add = headers instanceof Headers ? headers : new Headers(headers);
add.forEach((value, key) => {
// set-cookie is the only header that would repeat.
// A bit of background: https://developer.mozilla.org/en-US/docs/Web/API/Headers/getSetCookie
key === 'set-cookie' ? base.append(key, value) : base.set(key, value);
});
}
return base;
}
}
_a = Gaxios;
//# sourceMappingURL=gaxios.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
import { GaxiosOptions } from './common.js';
import { Gaxios } from './gaxios.js';
export { GaxiosError, GaxiosPromise, GaxiosResponse, GaxiosOptionsPrepared, RetryConfig, } from './common.js';
export { Gaxios, GaxiosOptions };
export * from './interceptor.js';
/**
* The default instance used when the `request` method is directly
* invoked.
*/
export declare const instance: Gaxios;
/**
* Make an HTTP request using the given options.
* @param opts Options for the request
*/
export declare function request<T>(opts: GaxiosOptions): Promise<import("./common.js").GaxiosResponse<T>>;

View File

@@ -0,0 +1,29 @@
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Gaxios } from './gaxios.js';
export { GaxiosError, } from './common.js';
export { Gaxios };
export * from './interceptor.js';
/**
* The default instance used when the `request` method is directly
* invoked.
*/
export const instance = new Gaxios();
/**
* Make an HTTP request using the given options.
* @param opts Options for the request
*/
export async function request(opts) {
return instance.request(opts);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAEnC,OAAO,EACL,WAAW,GAKZ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAC,MAAM,EAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AAEjC;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,IAAI,MAAM,EAAE,CAAC;AAErC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAI,IAAmB;IAClD,OAAO,QAAQ,CAAC,OAAO,CAAI,IAAI,CAAC,CAAC;AACnC,CAAC"}

View File

@@ -0,0 +1,25 @@
import { GaxiosError, GaxiosOptionsPrepared, GaxiosResponse } from './common.js';
/**
* Interceptors that can be run for requests or responses. These interceptors run asynchronously.
*/
export interface GaxiosInterceptor<T extends GaxiosOptionsPrepared | GaxiosResponse> {
/**
* Function to be run when applying an interceptor.
*
* @param {T} configOrResponse The current configuration or response.
* @returns {Promise<T>} Promise that resolves to the modified set of options or response.
*/
resolved?: (configOrResponse: T) => Promise<T>;
/**
* Function to be run if the previous call to resolved throws / rejects or the request results in an invalid status
* as determined by the call to validateStatus.
*
* @param {GaxiosError} err The error thrown from the previously called resolved function.
*/
rejected?: (err: GaxiosError) => void;
}
/**
* Class to manage collections of GaxiosInterceptors for both requests and responses.
*/
export declare class GaxiosInterceptorManager<T extends GaxiosOptionsPrepared | GaxiosResponse> extends Set<GaxiosInterceptor<T> | null> {
}

View File

@@ -0,0 +1,18 @@
// Copyright 2024 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Class to manage collections of GaxiosInterceptors for both requests and responses.
*/
export class GaxiosInterceptorManager extends Set {
}
//# sourceMappingURL=interceptor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"interceptor.js","sourceRoot":"","sources":["../../../src/interceptor.ts"],"names":[],"mappings":"AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AA0BjC;;GAEG;AACH,MAAM,OAAO,wBAEX,SAAQ,GAAgC;CAAG"}

View File

@@ -0,0 +1,8 @@
import { GaxiosError } from './common.js';
export declare function getRetryConfig(err: GaxiosError): Promise<{
shouldRetry: boolean;
config?: undefined;
} | {
shouldRetry: boolean;
config: import("./common.js").GaxiosOptionsPrepared;
}>;

View File

@@ -0,0 +1,162 @@
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export async function getRetryConfig(err) {
let config = getConfig(err);
if (!err || !err.config || (!config && !err.config.retry)) {
return { shouldRetry: false };
}
config = config || {};
config.currentRetryAttempt = config.currentRetryAttempt || 0;
config.retry =
config.retry === undefined || config.retry === null ? 3 : config.retry;
config.httpMethodsToRetry = config.httpMethodsToRetry || [
'GET',
'HEAD',
'PUT',
'OPTIONS',
'DELETE',
];
config.noResponseRetries =
config.noResponseRetries === undefined || config.noResponseRetries === null
? 2
: config.noResponseRetries;
config.retryDelayMultiplier = config.retryDelayMultiplier
? config.retryDelayMultiplier
: 2;
config.timeOfFirstRequest = config.timeOfFirstRequest
? config.timeOfFirstRequest
: Date.now();
config.totalTimeout = config.totalTimeout
? config.totalTimeout
: Number.MAX_SAFE_INTEGER;
config.maxRetryDelay = config.maxRetryDelay
? config.maxRetryDelay
: Number.MAX_SAFE_INTEGER;
// If this wasn't in the list of status codes where we want
// to automatically retry, return.
const retryRanges = [
// https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
// 1xx - Retry (Informational, request still processing)
// 2xx - Do not retry (Success)
// 3xx - Do not retry (Redirect)
// 4xx - Do not retry (Client errors)
// 408 - Retry ("Request Timeout")
// 429 - Retry ("Too Many Requests")
// 5xx - Retry (Server errors)
[100, 199],
[408, 408],
[429, 429],
[500, 599],
];
config.statusCodesToRetry = config.statusCodesToRetry || retryRanges;
// Put the config back into the err
err.config.retryConfig = config;
// Determine if we should retry the request
const shouldRetryFn = config.shouldRetry || shouldRetryRequest;
if (!(await shouldRetryFn(err))) {
return { shouldRetry: false, config: err.config };
}
const delay = getNextRetryDelay(config);
// We're going to retry! Increment the counter.
err.config.retryConfig.currentRetryAttempt += 1;
// Create a promise that invokes the retry after the backOffDelay
const backoff = config.retryBackoff
? config.retryBackoff(err, delay)
: new Promise(resolve => {
setTimeout(resolve, delay);
});
// Notify the user if they added an `onRetryAttempt` handler
if (config.onRetryAttempt) {
await config.onRetryAttempt(err);
}
// Return the promise in which recalls Gaxios to retry the request
await backoff;
return { shouldRetry: true, config: err.config };
}
/**
* Determine based on config if we should retry the request.
* @param err The GaxiosError passed to the interceptor.
*/
function shouldRetryRequest(err) {
const config = getConfig(err);
if ((err.config.signal?.aborted && err.code !== 'TimeoutError') ||
err.code === 'AbortError') {
return false;
}
// If there's no config, or retries are disabled, return.
if (!config || config.retry === 0) {
return false;
}
// Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc)
if (!err.response &&
(config.currentRetryAttempt || 0) >= config.noResponseRetries) {
return false;
}
// Only retry with configured HttpMethods.
if (!config.httpMethodsToRetry ||
!config.httpMethodsToRetry.includes(err.config.method?.toUpperCase() || 'GET')) {
return false;
}
// If this wasn't in the list of status codes where we want
// to automatically retry, return.
if (err.response && err.response.status) {
let isInRange = false;
for (const [min, max] of config.statusCodesToRetry) {
const status = err.response.status;
if (status >= min && status <= max) {
isInRange = true;
break;
}
}
if (!isInRange) {
return false;
}
}
// If we are out of retry attempts, return
config.currentRetryAttempt = config.currentRetryAttempt || 0;
if (config.currentRetryAttempt >= config.retry) {
return false;
}
return true;
}
/**
* Acquire the raxConfig object from an GaxiosError if available.
* @param err The Gaxios error with a config object.
*/
function getConfig(err) {
if (err && err.config && err.config.retryConfig) {
return err.config.retryConfig;
}
return;
}
/**
* Gets the delay to wait before the next retry.
*
* @param {RetryConfig} config The current set of retry options
* @returns {number} the amount of ms to wait before the next retry attempt.
*/
function getNextRetryDelay(config) {
// Calculate time to wait with exponential backoff.
// If this is the first retry, look for a configured retryDelay.
const retryDelay = config.currentRetryAttempt
? 0
: (config.retryDelay ?? 100);
// Formula: retryDelay + ((retryDelayMultiplier^currentRetryAttempt - 1 / 2) * 1000)
const calculatedDelay = retryDelay +
((Math.pow(config.retryDelayMultiplier, config.currentRetryAttempt) - 1) /
2) *
1000;
const maxAllowableDelay = config.totalTimeout - (Date.now() - config.timeOfFirstRequest);
return Math.min(calculatedDelay, maxAllowableDelay, config.maxRetryDelay);
}
//# sourceMappingURL=retry.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../../src/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,eAAe,GACnB,UAAU;QACV,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,oBAAqB,EAAE,MAAM,CAAC,mBAAoB,CAAC,GAAG,CAAC,CAAC;YACxE,CAAC,CAAC;YACF,IAAI,CAAC;IACT,MAAM,iBAAiB,GACrB,MAAM,CAAC,YAAa,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,kBAAmB,CAAC,CAAC;IAEnE,OAAO,IAAI,CAAC,GAAG,CAAC,eAAe,EAAE,iBAAiB,EAAE,MAAM,CAAC,aAAc,CAAC,CAAC;AAC7E,CAAC"}

View File

@@ -0,0 +1,15 @@
// Copyright 2023 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const pkg = require('../../../package.json');
module.exports = { pkg };
//# sourceMappingURL=util.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"util.cjs","sourceRoot":"","sources":["../../../src/util.cts"],"names":[],"mappings":"AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,MAAM,GAAG,GAGL,OAAO,CAAC,uBAAuB,CAAC,CAAC;iBAE5B,EAAC,GAAG,EAAC"}

View File

@@ -0,0 +1,7 @@
declare const _default: {
pkg: {
name: string;
version: string;
};
};
export = _default;

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,123 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import assert from 'assert';
import { execFile } from 'child_process';
import fs from 'fs';
import mv from 'mv';
import ncp from 'ncp';
import path from 'path';
import tmp from 'tmp';
import { promisify } from 'util';
import { describe, it, before, after } from 'mocha';
import { packNTest } from 'pack-n-play';
import { createServer } from 'node:http';
import util from '../src/util.cjs';
/**
* Optionally keep the staging directory between tests.
*/
const KEEP_STAGING_DIRECTORY = false;
const mvp = promisify(mv);
const ncpp = promisify(ncp);
const pkg = util.pkg;
const exec = promisify(execFile);
describe('📦 pack and install', () => {
let stagingDir;
let stagingPath;
before(() => {
stagingDir = tmp.dirSync({
keep: KEEP_STAGING_DIRECTORY,
unsafeCleanup: true,
});
stagingPath = stagingDir.name;
});
after('cleanup staging', () => {
if (!KEEP_STAGING_DIRECTORY) {
stagingDir.removeCallback();
}
});
describe('pack-n-play', () => {
let server;
let url;
before(async () => {
server = createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' });
res.end(`Hello, ${req.headers['user-agent'] || 'World'}`);
});
await new Promise((resolve, reject) => {
server.on('error', reject);
server.listen(0, resolve);
});
const address = server.address();
if (typeof address === 'string') {
url = address;
}
else {
const base = new URL('http://localhost');
base.host = address.address;
base.port = address.port.toString();
url = base.toString();
}
});
after(() => {
server.close();
});
it('supports ESM', async () => {
await packNTest({
sample: {
description: 'import as ESM',
esm: `
import {Gaxios} from 'gaxios';
const gaxios = new Gaxios();
await gaxios.request({url: '${url}'});
`,
},
});
});
it('supports CJS', async () => {
await packNTest({
sample: {
description: 'require as CJS',
cjs: `
const {Gaxios} = require('gaxios');
const gaxios = new Gaxios();
gaxios.request({url: '${url}'}).then(console.log);
`,
},
});
});
});
describe('webpack', () => {
/**
* Create a staging directory with temp fixtures used to test on a fresh
* application.
*/
before('pack and install', async () => {
await exec('npm', ['pack']);
const tarball = `${pkg.name}-${pkg.version}.tgz`;
await mvp(tarball, `${stagingPath}/gaxios.tgz`);
await ncpp('system-test/fixtures/sample', `${stagingPath}/`);
await exec('npm', ['install'], { cwd: `${stagingPath}/` });
});
it('should be able to webpack the library', async () => {
// we expect npm install is executed in the before hook
await exec('npx', ['webpack'], { cwd: `${stagingPath}/` });
const bundle = path.join(stagingPath, 'dist', 'bundle.min.js');
const stat = fs.statSync(bundle);
assert(stat.size < 256 * 1024);
}).timeout(20000);
});
});
//# sourceMappingURL=test.install.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"test.install.js","sourceRoot":"","sources":["../../../system-test/test.install.ts"],"names":[],"mappings":"AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAC,QAAQ,EAAC,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EAAC,SAAS,EAAC,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAC,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAC,MAAM,OAAO,CAAC;AAClD,OAAO,EAAC,SAAS,EAAC,MAAM,aAAa,CAAC;AAEtC,OAAO,EAAC,YAAY,EAAS,MAAM,WAAW,CAAC;AAE/C,OAAO,IAAI,MAAM,iBAAiB,CAAC;AAEnC;;GAEG;AACH,MAA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,CAAC;YAC5B,MAAM,OAAO,GAAG,GAAG,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,OAAO,MAAM,CAAC;YACjD,MAAM,GAAG,CAAC,OAAO,EAAE,GAAG,WAAW,aAAa,CAAC,CAAC;YAChD,MAAM,IAAI,CAAC,6BAA6B,EAAE,GAAG,WAAW,GAAG,CAAC,CAAC;YAC7D,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC,SAAS,CAAC,EAAE,EAAC,GAAG,EAAE,GAAG,WAAW,GAAG,EAAC,CAAC,CAAC;QAC3D,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,uCAAuC,EAAE,KAAK,IAAI,EAAE;YACrD,uDAAuD;YACvD,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC,SAAS,CAAC,EAAE,EAAC,GAAG,EAAE,GAAG,WAAW,GAAG,EAAC,CAAC,CAAC;YACzD,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,eAAe,CAAC,CAAC;YAC/D,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;YACjC,MAAM,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC;QACjC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,23 @@
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import assert from 'assert';
import { describe, it } from 'mocha';
import * as main from '../src/index.js';
describe('📝 main exports', () => {
it('should export all the types', () => {
assert(main.Gaxios);
assert(main.GaxiosError);
assert(main.GaxiosInterceptorManager);
});
});
//# sourceMappingURL=test.index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"test.index.js","sourceRoot":"","sources":["../../../test/test.index.ts"],"names":[],"mappings":"AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAC,QAAQ,EAAE,EAAE,EAAC,MAAM,OAAO,CAAC;AACnC,OAAO,KAAK,IAAI,MAAM,iBAAiB,CAAC;AAExC,QAAQ,CAAC,iBAAiB,EAAE,GAAG,EAAE;IAC/B,EAAE,CAAC,6BAA6B,EAAE,GAAG,EAAE;QACrC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACpB,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACzB,MAAM,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;IACxC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,362 @@
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import assert from 'assert';
import nock from 'nock';
import { describe, it, afterEach } from 'mocha';
import { Gaxios, GaxiosError, request } from '../src/index.js';
nock.disableNetConnect();
const url = 'https://example.com';
function getConfig(err) {
const e = err;
if (e && e.config && e.config.retryConfig) {
return e.config.retryConfig;
}
return;
}
afterEach(() => {
nock.cleanAll();
});
describe('🛸 retry & exponential backoff', () => {
it('should provide an expected set of defaults', async () => {
const scope = nock(url).get('/').times(4).reply(500);
await assert.rejects(request({ url, retry: true }), (e) => {
scope.done();
const config = getConfig(e);
if (!config) {
assert.fail('no config available');
}
assert.strictEqual(config.currentRetryAttempt, 3);
assert.strictEqual(config.retry, 3);
assert.strictEqual(config.noResponseRetries, 2);
const expectedMethods = ['GET', 'HEAD', 'PUT', 'OPTIONS', 'DELETE'];
for (const method of config.httpMethodsToRetry) {
assert(expectedMethods.indexOf(method) > -1);
}
const expectedStatusCodes = [
[100, 199],
[408, 408],
[429, 429],
[500, 599],
];
const statusCodesToRetry = config.statusCodesToRetry;
for (let i = 0; i < statusCodesToRetry.length; i++) {
const [min, max] = statusCodesToRetry[i];
const [expMin, expMax] = expectedStatusCodes[i];
assert.strictEqual(min, expMin);
assert.strictEqual(max, expMax);
}
return true;
});
});
it('should retry on 500 on the main export', async () => {
const body = { buttered: '🥖' };
const scopes = [
nock(url).get('/').reply(500),
nock(url).get('/').reply(200, body),
];
const res = await request({
url,
retry: true,
});
assert.deepStrictEqual(res.data, body);
scopes.forEach(s => s.done());
});
it('should not retry on a post', async () => {
const scope = nock(url).post('/').reply(500);
await assert.rejects(request({ url, method: 'POST', retry: true }), (e) => {
const config = getConfig(e);
return config.currentRetryAttempt === 0;
});
scope.done();
});
it('should not retry if user aborted request', async () => {
const ac = new AbortController();
const config = {
method: 'GET',
url: 'https://google.com',
signal: ac.signal,
retryConfig: { retry: 10, noResponseRetries: 10 },
};
const req = request(config);
ac.abort();
try {
await req;
throw Error('unreachable');
}
catch (err) {
assert(err instanceof GaxiosError);
assert(err.config);
assert.strictEqual(err.config.retryConfig?.currentRetryAttempt, 0);
}
});
it('should retry at least the configured number of times', async () => {
const body = { dippy: '🥚' };
const scopes = [
nock(url).get('/').times(3).reply(500),
nock(url).get('/').reply(200, body),
];
const cfg = { url, retryConfig: { retry: 4 } };
const res = await request(cfg);
assert.deepStrictEqual(res.data, body);
scopes.forEach(s => s.done());
});
it('should not retry more than configured', async () => {
const scope = nock(url).get('/').twice().reply(500);
const cfg = { url, retryConfig: { retry: 1 } };
await assert.rejects(request(cfg), (e) => {
return getConfig(e).currentRetryAttempt === 1;
});
scope.done();
});
it('should not retry on 4xx errors', async () => {
const scope = nock(url).get('/').reply(404);
await assert.rejects(request({ url, retry: true }), (e) => {
const cfg = getConfig(e);
return cfg.currentRetryAttempt === 0;
});
scope.done();
});
it('should retain the baseURL on retry', async () => {
const body = { pumpkin: '🥧' };
const url = '/path';
const baseURL = 'http://example.com';
const scope = nock(baseURL).get(url).reply(500).get(url).reply(200, body);
const gaxios = new Gaxios({ baseURL });
const res = await gaxios.request({
url,
retry: true,
});
assert.deepStrictEqual(res.data, body);
scope.done();
});
it('should not retry if retries set to 0', async () => {
const scope = nock(url).get('/').reply(500);
const cfg = { url, retryConfig: { retry: 0 } };
await assert.rejects(request(cfg), (e) => {
const cfg = getConfig(e);
return cfg.currentRetryAttempt === 0;
});
scope.done();
});
it('should notify on retry attempts', async () => {
const body = { buttered: '🥖' };
const scopes = [
nock(url).get('/').reply(500),
nock(url).get('/').reply(200, body),
];
let flipped = false;
const config = {
url,
retryConfig: {
onRetryAttempt: err => {
const cfg = getConfig(err);
assert.strictEqual(cfg.currentRetryAttempt, 1);
flipped = true;
},
},
};
await request(config);
assert.strictEqual(flipped, true);
scopes.forEach(s => s.done());
});
it('accepts async onRetryAttempt handler', async () => {
const body = { buttered: '🥖' };
const scopes = [
nock(url).get('/').reply(500),
nock(url).get('/').reply(200, body),
];
let flipped = false;
const config = {
url,
retryConfig: {
onRetryAttempt: async (err) => {
const cfg = getConfig(err);
assert.strictEqual(cfg.currentRetryAttempt, 1);
flipped = true;
},
},
};
await request(config);
assert.strictEqual(flipped, true);
scopes.forEach(s => s.done());
});
it('should support overriding the shouldRetry method', async () => {
const scope = nock(url).get('/').reply(500);
const config = {
url,
retryConfig: {
shouldRetry: () => {
return false;
},
},
};
await assert.rejects(request(config), (e) => {
const cfg = getConfig(e);
return cfg.currentRetryAttempt === 0;
});
scope.done();
});
it('should support overriding the shouldRetry method with a promise', async () => {
const scope = nock(url).get('/').reply(500);
const config = {
url,
retryConfig: {
shouldRetry: async () => {
return false;
},
},
};
await assert.rejects(request(config), (e) => {
const cfg = getConfig(e);
return cfg.currentRetryAttempt === 0;
});
scope.done();
});
it('should retry on ENOTFOUND', async () => {
const body = { spicy: '🌮' };
const scopes = [
nock(url).get('/').reply(500, { code: 'ENOTFOUND' }),
nock(url).get('/').reply(200, body),
];
const res = await request({ url, retry: true });
assert.deepStrictEqual(res.data, body);
scopes.forEach(s => s.done());
});
it('should retry on ETIMEDOUT', async () => {
const body = { sizzling: '🥓' };
const scopes = [
nock(url).get('/').reply(500, { code: 'ETIMEDOUT' }),
nock(url).get('/').reply(200, body),
];
const res = await request({ url, retry: true });
assert.deepStrictEqual(res.data, body);
scopes.forEach(s => s.done());
});
it('should allow configuring noResponseRetries', async () => {
// `nock` is not listening, therefore it should fail
const config = { url, retryConfig: { noResponseRetries: 0 } };
await assert.rejects(request(config), (e) => {
return (e.code === 'ENETUNREACH' &&
e.config.retryConfig?.currentRetryAttempt === 0);
});
});
it('should delay the initial retry by 100ms by default', async () => {
const scope = nock(url).get('/').reply(500).get('/').reply(200, {});
const start = Date.now();
await request({
url,
retry: true,
});
const delay = Date.now() - start;
assert.ok(delay > 100 && delay < 199);
scope.done();
});
it('should respect the retryDelay if configured', async () => {
const scope = nock(url).get('/').reply(500).get('/').reply(200, {});
const start = Date.now();
await request({
url,
retryConfig: {
retryDelay: 500,
},
});
const delay = Date.now() - start;
assert.ok(delay > 500 && delay < 599);
scope.done();
});
it('should respect retryDelayMultiplier if configured', async () => {
const scope = nock(url)
.get('/')
.reply(500)
.get('/')
.reply(500)
.get('/')
.reply(200, {});
const start = Date.now();
await request({
url,
retryConfig: {
retryDelayMultiplier: 3,
},
});
const delay = Date.now() - start;
assert.ok(delay > 1000 && delay < 1999);
scope.done();
});
it('should respect totalTimeout if configured', async () => {
const scope = nock(url)
.get('/')
.reply(500)
.get('/')
.reply(500)
.get('/')
.reply(200, {});
const start = Date.now();
await request({
url,
retryConfig: {
retryDelayMultiplier: 100,
totalTimeout: 3000,
},
});
const delay = Date.now() - start;
assert.ok(delay > 3000 && delay < 3999);
scope.done();
});
it('should respect maxRetryDelay if configured', async () => {
const scope = nock(url)
.get('/')
.reply(500)
.get('/')
.reply(500)
.get('/')
.reply(200, {});
const start = Date.now();
await request({
url,
retryConfig: {
retryDelayMultiplier: 100,
maxRetryDelay: 4000,
},
});
const delay = Date.now() - start;
assert.ok(delay > 4000 && delay < 4999);
scope.done();
});
it('should retry on `timeout`', async () => {
const scope = nock(url).get('/').delay(500).reply(400).get('/').reply(204);
const gaxios = new Gaxios();
const timeout = 100;
async function onRetryAttempt({ config, message }) {
assert(config.signal?.reason instanceof DOMException);
assert.equal(config.signal.reason.name, 'TimeoutError');
assert.match(message, /timeout/i);
// increase timeout to something higher to avoid time-sensitive flaky tests
// note: the second `nock` GET is not delayed like the first one
config.timeout = 10000;
}
const res = await gaxios.request({
url,
timeout,
// NOTE: `node-fetch` does not yet support `TimeoutError` - testing with native `fetch` for now.
fetchImplementation: fetch,
retryConfig: {
onRetryAttempt,
},
});
assert.equal(res.status, 204);
assert.equal(res.config?.retryConfig?.currentRetryAttempt, 1);
scope.done();
});
});
//# sourceMappingURL=test.retry.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,107 @@
{
"name": "gaxios",
"version": "7.1.4",
"description": "A simple common HTTP client specifically for Google APIs and services.",
"main": "build/cjs/src/index.js",
"types": "build/cjs/src/index.d.ts",
"files": [
"build/"
],
"exports": {
".": {
"import": {
"types": "./build/esm/src/index.d.ts",
"default": "./build/esm/src/index.js"
},
"require": {
"types": "./build/cjs/src/index.d.ts",
"default": "./build/cjs/src/index.js"
}
}
},
"scripts": {
"lint": "gts check --no-inline-config",
"test": "c8 mocha build/esm/test",
"presystem-test": "npm run compile",
"system-test": "mocha build/esm/system-test --timeout 80000",
"compile": "tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",
"fix": "gts fix",
"prepare": "npm run compile",
"pretest": "npm run compile",
"webpack": "webpack",
"prebrowser-test": "npm run compile",
"browser-test": "node build/browser-test/browser-test-runner.js",
"docs": "jsdoc -c .jsdoc.js",
"docs-test": "linkinator docs",
"predocs-test": "npm run docs",
"samples-test": "cd samples/ && npm link ../ && npm test && cd ../",
"prelint": "cd samples; npm link ../; npm install",
"clean": "gts clean"
},
"repository": {
"type": "git",
"directory": "packages/gaxios",
"url": "https://github.com/googleapis/google-cloud-node-core.git"
},
"keywords": [
"google"
],
"engines": {
"node": ">=18"
},
"author": "Google, LLC",
"license": "Apache-2.0",
"devDependencies": {
"@babel/plugin-proposal-private-methods": "^7.18.6",
"@types/cors": "^2.8.6",
"@types/express": "^5.0.0",
"@types/extend": "^3.0.1",
"@types/mocha": "^10.0.10",
"@types/multiparty": "4.2.1",
"@types/mv": "^2.1.0",
"@types/ncp": "^2.0.8",
"@types/node": "^22.13.1",
"@types/sinon": "^17.0.3",
"@types/tmp": "^0.2.6",
"assert": "^2.0.0",
"browserify": "^17.0.0",
"c8": "^10.1.3",
"cors": "^2.8.5",
"express": "^5.0.0",
"gts": "^6.0.2",
"is-docker": "^3.0.0",
"jsdoc": "^4.0.4",
"jsdoc-fresh": "^5.0.0",
"jsdoc-region-tag": "^4.0.0",
"karma": "^6.0.0",
"karma-chrome-launcher": "^3.0.0",
"karma-coverage": "^2.0.0",
"karma-firefox-launcher": "^2.0.0",
"karma-mocha": "^2.0.0",
"karma-remap-coverage": "^0.1.5",
"karma-sourcemap-loader": "^0.4.0",
"karma-webpack": "^5.0.1",
"linkinator": "^6.1.2",
"mocha": "^11.1.0",
"multiparty": "^4.2.1",
"mv": "^2.1.1",
"ncp": "^2.0.0",
"nock": "^14.0.5",
"null-loader": "^4.0.1",
"pack-n-play": "^4.0.0",
"puppeteer": "^24.0.0",
"sinon": "^21.0.0",
"stream-browserify": "^3.0.0",
"tmp": "0.2.5",
"ts-loader": "^9.5.2",
"typescript": "5.8.3",
"webpack": "^5.97.1",
"webpack-cli": "^6.0.1"
},
"dependencies": {
"extend": "^3.0.2",
"https-proxy-agent": "^7.0.1",
"node-fetch": "^3.3.2"
},
"homepage": "https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"
}

View File

@@ -0,0 +1,219 @@
/// <reference types="node" />
import {RequestOptions} from 'http';
import {FormData} from 'formdata-polyfill/esm.min.js';
import {
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync
} from 'fetch-blob/from.js';
type AbortSignal = {
readonly aborted: boolean;
addEventListener: (type: 'abort', listener: (this: AbortSignal) => void) => void;
removeEventListener: (type: 'abort', listener: (this: AbortSignal) => void) => void;
};
export type HeadersInit = Headers | Record<string, string> | Iterable<readonly [string, string]> | Iterable<Iterable<string>>;
export {
FormData,
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync
};
/**
* This Fetch API interface allows you to perform various actions on HTTP request and response headers.
* These actions include retrieving, setting, adding to, and removing.
* A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.
* You can add to this using methods like append() (see Examples.)
* In all methods of this interface, header names are matched by case-insensitive byte sequence.
* */
export class Headers {
constructor(init?: HeadersInit);
append(name: string, value: string): void;
delete(name: string): void;
get(name: string): string | null;
has(name: string): boolean;
set(name: string, value: string): void;
forEach(
callbackfn: (value: string, key: string, parent: Headers) => void,
thisArg?: any
): void;
[Symbol.iterator](): IterableIterator<[string, string]>;
/**
* Returns an iterator allowing to go through all key/value pairs contained in this object.
*/
entries(): IterableIterator<[string, string]>;
/**
* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object.
*/
keys(): IterableIterator<string>;
/**
* Returns an iterator allowing to go through all values of the key/value pairs contained in this object.
*/
values(): IterableIterator<string>;
/** Node-fetch extension */
raw(): Record<string, string[]>;
}
export interface RequestInit {
/**
* A BodyInit object or null to set request's body.
*/
body?: BodyInit | null;
/**
* A Headers object, an object literal, or an array of two-item arrays to set request's headers.
*/
headers?: HeadersInit;
/**
* A string to set request's method.
*/
method?: string;
/**
* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect.
*/
redirect?: RequestRedirect;
/**
* An AbortSignal to set request's signal.
*/
signal?: AbortSignal | null;
/**
* A string whose value is a same-origin URL, "about:client", or the empty string, to set requests referrer.
*/
referrer?: string;
/**
* A referrer policy to set requests referrerPolicy.
*/
referrerPolicy?: ReferrerPolicy;
// Node-fetch extensions to the whatwg/fetch spec
agent?: RequestOptions['agent'] | ((parsedUrl: URL) => RequestOptions['agent']);
compress?: boolean;
counter?: number;
follow?: number;
hostname?: string;
port?: number;
protocol?: string;
size?: number;
highWaterMark?: number;
insecureHTTPParser?: boolean;
}
export interface ResponseInit {
headers?: HeadersInit;
status?: number;
statusText?: string;
}
export type BodyInit =
| Blob
| Buffer
| URLSearchParams
| FormData
| NodeJS.ReadableStream
| string;
declare class BodyMixin {
constructor(body?: BodyInit, options?: {size?: number});
readonly body: NodeJS.ReadableStream | null;
readonly bodyUsed: boolean;
readonly size: number;
/** @deprecated Use `body.arrayBuffer()` instead. */
buffer(): Promise<Buffer>;
arrayBuffer(): Promise<ArrayBuffer>;
formData(): Promise<FormData>;
blob(): Promise<Blob>;
json(): Promise<unknown>;
text(): Promise<string>;
}
// `Body` must not be exported as a class since it's not exported from the JavaScript code.
export interface Body extends Pick<BodyMixin, keyof BodyMixin> {}
export type RequestRedirect = 'error' | 'follow' | 'manual';
export type ReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'same-origin' | 'origin' | 'strict-origin' | 'origin-when-cross-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url';
export type RequestInfo = string | Request;
export class Request extends BodyMixin {
constructor(input: URL | RequestInfo, init?: RequestInit);
/**
* Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header.
*/
readonly headers: Headers;
/**
* Returns request's HTTP method, which is "GET" by default.
*/
readonly method: string;
/**
* Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default.
*/
readonly redirect: RequestRedirect;
/**
* Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler.
*/
readonly signal: AbortSignal;
/**
* Returns the URL of request as a string.
*/
readonly url: string;
/**
* A string whose value is a same-origin URL, "about:client", or the empty string, to set requests referrer.
*/
readonly referrer: string;
/**
* A referrer policy to set requests referrerPolicy.
*/
readonly referrerPolicy: ReferrerPolicy;
clone(): Request;
}
type ResponseType = 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect';
export class Response extends BodyMixin {
constructor(body?: BodyInit | null, init?: ResponseInit);
readonly headers: Headers;
readonly ok: boolean;
readonly redirected: boolean;
readonly status: number;
readonly statusText: string;
readonly type: ResponseType;
readonly url: string;
clone(): Response;
static error(): Response;
static redirect(url: string, status?: number): Response;
static json(data: any, init?: ResponseInit): Response;
}
export class FetchError extends Error {
constructor(message: string, type: string, systemError?: Record<string, unknown>);
name: 'FetchError';
[Symbol.toStringTag]: 'FetchError';
type: string;
code?: string;
errno?: string;
}
export class AbortError extends Error {
type: string;
name: 'AbortError';
[Symbol.toStringTag]: 'AbortError';
}
export function isRedirect(code: number): boolean;
export default function fetch(url: URL | RequestInfo, init?: RequestInit): Promise<Response>;

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2016 - 2020 Node Fetch Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,872 @@
<div align="center">
<img src="docs/media/Banner.svg" alt="Node Fetch"/>
<br>
<p>A light-weight module that brings <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API</a> to Node.js.</p>
<a href="https://github.com/node-fetch/node-fetch/actions"><img src="https://github.com/node-fetch/node-fetch/workflows/CI/badge.svg?branch=master" alt="Build status"></a>
<a href="https://coveralls.io/github/node-fetch/node-fetch"><img src="https://img.shields.io/coveralls/github/node-fetch/node-fetch" alt="Coverage status"></a>
<a href="https://packagephobia.now.sh/result?p=node-fetch"><img src="https://badgen.net/packagephobia/install/node-fetch" alt="Current version"></a>
<a href="https://www.npmjs.com/package/node-fetch"><img src="https://img.shields.io/npm/v/node-fetch" alt="Install size"></a>
<a href="https://github.com/sindresorhus/awesome-nodejs"><img src="https://awesome.re/mentioned-badge.svg" alt="Mentioned in Awesome Node.js"></a>
<a href="https://discord.gg/Zxbndcm"><img src="https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord" alt="Discord"></a>
<br>
<br>
<b>Consider supporting us on our Open Collective:</b>
<br>
<br>
<a href="https://opencollective.com/node-fetch"><img src="https://opencollective.com/node-fetch/donate/button.png?color=blue" alt="Open Collective"></a>
</div>
---
**You might be looking for the [v2 docs](https://github.com/node-fetch/node-fetch/tree/2.x#readme)**
<!-- TOC -->
- [Motivation](#motivation)
- [Features](#features)
- [Difference from client-side fetch](#difference-from-client-side-fetch)
- [Installation](#installation)
- [Loading and configuring the module](#loading-and-configuring-the-module)
- [Upgrading](#upgrading)
- [Common Usage](#common-usage)
- [Plain text or HTML](#plain-text-or-html)
- [JSON](#json)
- [Simple Post](#simple-post)
- [Post with JSON](#post-with-json)
- [Post with form parameters](#post-with-form-parameters)
- [Handling exceptions](#handling-exceptions)
- [Handling client and server errors](#handling-client-and-server-errors)
- [Handling cookies](#handling-cookies)
- [Advanced Usage](#advanced-usage)
- [Streams](#streams)
- [Accessing Headers and other Metadata](#accessing-headers-and-other-metadata)
- [Extract Set-Cookie Header](#extract-set-cookie-header)
- [Post data using a file](#post-data-using-a-file)
- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)
- [API](#api)
- [fetch(url[, options])](#fetchurl-options)
- [Options](#options)
- [Default Headers](#default-headers)
- [Custom Agent](#custom-agent)
- [Custom highWaterMark](#custom-highwatermark)
- [Insecure HTTP Parser](#insecure-http-parser)
- [Class: Request](#class-request)
- [new Request(input[, options])](#new-requestinput-options)
- [Class: Response](#class-response)
- [new Response([body[, options]])](#new-responsebody-options)
- [response.ok](#responseok)
- [response.redirected](#responseredirected)
- [response.type](#responsetype)
- [Class: Headers](#class-headers)
- [new Headers([init])](#new-headersinit)
- [Interface: Body](#interface-body)
- [body.body](#bodybody)
- [body.bodyUsed](#bodybodyused)
- [body.arrayBuffer()](#bodyarraybuffer)
- [body.blob()](#bodyblob)
- [body.formData()](#formdata)
- [body.json()](#bodyjson)
- [body.text()](#bodytext)
- [Class: FetchError](#class-fetcherror)
- [Class: AbortError](#class-aborterror)
- [TypeScript](#typescript)
- [Acknowledgement](#acknowledgement)
- [Team](#team)
- [Former](#former)
- [License](#license)
<!-- /TOC -->
## Motivation
Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.
See Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).
## Features
- Stay consistent with `window.fetch` API.
- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.
- Use native promise and async functions.
- Use native Node streams for body, on both request and response.
- Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.
- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.
## Difference from client-side fetch
- See known differences:
- [As of v3.x](docs/v3-LIMITS.md)
- [As of v2.x](docs/v2-LIMITS.md)
- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.
- Pull requests are welcomed too!
## Installation
Current stable release (`3.x`) requires at least Node.js 12.20.0.
```sh
npm install node-fetch
```
## Loading and configuring the module
### ES Modules (ESM)
```js
import fetch from 'node-fetch';
```
### CommonJS
`node-fetch` from v3 is an ESM-only module - you are not able to import it with `require()`.
If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2.
```sh
npm install node-fetch@2
```
Alternatively, you can use the async `import()` function from CommonJS to load `node-fetch` asynchronously:
```js
// mod.cjs
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
```
### Providing global access
To use `fetch()` without importing it, you can patch the `global` object in node:
```js
// fetch-polyfill.js
import fetch, {
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync,
FormData,
Headers,
Request,
Response,
} from 'node-fetch'
if (!globalThis.fetch) {
globalThis.fetch = fetch
globalThis.Headers = Headers
globalThis.Request = Request
globalThis.Response = Response
}
// index.js
import './fetch-polyfill'
// ...
```
## Upgrading
Using an old version of node-fetch? Check out the following files:
- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)
- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)
- [Changelog](https://github.com/node-fetch/node-fetch/releases)
## Common Usage
NOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).
### Plain text or HTML
```js
import fetch from 'node-fetch';
const response = await fetch('https://github.com/');
const body = await response.text();
console.log(body);
```
### JSON
```js
import fetch from 'node-fetch';
const response = await fetch('https://api.github.com/users/github');
const data = await response.json();
console.log(data);
```
### Simple Post
```js
import fetch from 'node-fetch';
const response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});
const data = await response.json();
console.log(data);
```
### Post with JSON
```js
import fetch from 'node-fetch';
const body = {a: 1};
const response = await fetch('https://httpbin.org/post', {
method: 'post',
body: JSON.stringify(body),
headers: {'Content-Type': 'application/json'}
});
const data = await response.json();
console.log(data);
```
### Post with form parameters
`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.
NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:
```js
import fetch from 'node-fetch';
const params = new URLSearchParams();
params.append('a', 1);
const response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});
const data = await response.json();
console.log(data);
```
### Handling exceptions
NOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.
Wrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.
```js
import fetch from 'node-fetch';
try {
await fetch('https://domain.invalid/');
} catch (error) {
console.log(error);
}
```
### Handling client and server errors
It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:
```js
import fetch from 'node-fetch';
class HTTPResponseError extends Error {
constructor(response) {
super(`HTTP Error Response: ${response.status} ${response.statusText}`);
this.response = response;
}
}
const checkStatus = response => {
if (response.ok) {
// response.status >= 200 && response.status < 300
return response;
} else {
throw new HTTPResponseError(response);
}
}
const response = await fetch('https://httpbin.org/status/400');
try {
checkStatus(response);
} catch (error) {
console.error(error);
const errorBody = await error.response.text();
console.error(`Error body: ${errorBody}`);
}
```
### Handling cookies
Cookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.
## Advanced Usage
### Streams
The "Node.js way" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.
```js
import {createWriteStream} from 'node:fs';
import {pipeline} from 'node:stream';
import {promisify} from 'node:util'
import fetch from 'node-fetch';
const streamPipeline = promisify(pipeline);
const response = await fetch('https://github.githubassets.com/images/modules/logos_page/Octocat.png');
if (!response.ok) throw new Error(`unexpected response ${response.statusText}`);
await streamPipeline(response.body, createWriteStream('./octocat.png'));
```
In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch
errors -- the longer a response runs, the more likely it is to encounter an error.
```js
import fetch from 'node-fetch';
const response = await fetch('https://httpbin.org/stream/3');
try {
for await (const chunk of response.body) {
console.dir(JSON.parse(chunk.toString()));
}
} catch (err) {
console.error(err.stack);
}
```
In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams
did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors
directly from the stream and wait on it response to fully close.
```js
import fetch from 'node-fetch';
const read = async body => {
let error;
body.on('error', err => {
error = err;
});
for await (const chunk of body) {
console.dir(JSON.parse(chunk.toString()));
}
return new Promise((resolve, reject) => {
body.on('close', () => {
error ? reject(error) : resolve();
});
});
};
try {
const response = await fetch('https://httpbin.org/stream/3');
await read(response.body);
} catch (err) {
console.error(err.stack);
}
```
### Accessing Headers and other Metadata
```js
import fetch from 'node-fetch';
const response = await fetch('https://github.com/');
console.log(response.ok);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers.raw());
console.log(response.headers.get('content-type'));
```
### Extract Set-Cookie Header
Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.
```js
import fetch from 'node-fetch';
const response = await fetch('https://example.com');
// Returns an array of values, instead of a string of comma-separated values
console.log(response.headers.raw()['set-cookie']);
```
### Post data using a file
```js
import fetch, {
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync,
} from 'node-fetch'
const mimetype = 'text/plain'
const blob = fileFromSync('./input.txt', mimetype)
const url = 'https://httpbin.org/post'
const response = await fetch(url, { method: 'POST', body: blob })
const data = await response.json()
console.log(data)
```
node-fetch comes with a spec-compliant [FormData] implementations for posting
multipart/form-data payloads
```js
import fetch, { FormData, File, fileFrom } from 'node-fetch'
const httpbin = 'https://httpbin.org/post'
const formData = new FormData()
const binary = new Uint8Array([ 97, 98, 99 ])
const abc = new File([binary], 'abc.txt', { type: 'text/plain' })
formData.set('greeting', 'Hello, world!')
formData.set('file-upload', abc, 'new name.txt')
const response = await fetch(httpbin, { method: 'POST', body: formData })
const data = await response.json()
console.log(data)
```
If you for some reason need to post a stream coming from any arbitrary place,
then you can append a [Blob] or a [File] look-a-like item.
The minimum requirement is that it has:
1. A `Symbol.toStringTag` getter or property that is either `Blob` or `File`
2. A known size.
3. And either a `stream()` method or a `arrayBuffer()` method that returns a ArrayBuffer.
The `stream()` must return any async iterable object as long as it yields Uint8Array (or Buffer)
so Node.Readable streams and whatwg streams works just fine.
```js
formData.append('upload', {
[Symbol.toStringTag]: 'Blob',
size: 3,
*stream() {
yield new Uint8Array([97, 98, 99])
},
arrayBuffer() {
return new Uint8Array([97, 98, 99]).buffer
}
}, 'abc.txt')
```
### Request cancellation with AbortSignal
You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).
An example of timing out a request after 150ms could be achieved as the following:
```js
import fetch, { AbortError } from 'node-fetch';
// AbortController was added in node v14.17.0 globally
const AbortController = globalThis.AbortController || await import('abort-controller')
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
}, 150);
try {
const response = await fetch('https://example.com', {signal: controller.signal});
const data = await response.json();
} catch (error) {
if (error instanceof AbortError) {
console.log('request was aborted');
}
} finally {
clearTimeout(timeout);
}
```
See [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.
## API
### fetch(url[, options])
- `url` A string representing the URL for fetching
- `options` [Options](#fetch-options) for the HTTP(S) request
- Returns: <code>Promise&lt;[Response](#class-response)&gt;</code>
Perform an HTTP(S) fetch.
`url` should be an absolute URL, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.
<a id="fetch-options"></a>
### Options
The default values are shown after each option key.
```js
{
// These properties are part of the Fetch Standard
method: 'GET',
headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)
body: null, // Request body. can be null, or a Node.js Readable stream
redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect
signal: null, // Pass an instance of AbortSignal to optionally abort requests
// The following properties are node-fetch extensions
follow: 20, // maximum redirect count. 0 to not follow redirect
compress: true, // support gzip/deflate content encoding. false to disable
size: 0, // maximum response body size in bytes. 0 to disable
agent: null, // http(s).Agent instance or function that returns an instance (see below)
highWaterMark: 16384, // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.
insecureHTTPParser: false // Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.
}
```
#### Default Headers
If no values are set, the following request headers will be sent automatically:
| Header | Value |
| ------------------- | ------------------------------------------------------ |
| `Accept-Encoding` | `gzip, deflate, br` (when `options.compress === true`) |
| `Accept` | `*/*` |
| `Content-Length` | _(automatically calculated, if possible)_ |
| `Host` | _(host and port information from the target URI)_ |
| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |
| `User-Agent` | `node-fetch` |
Note: when `body` is a `Stream`, `Content-Length` is not set automatically.
#### Custom Agent
The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:
- Support self-signed certificate
- Use only IPv4 or IPv6
- Custom DNS Lookup
See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.
If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample.
In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.
```js
import http from 'node:http';
import https from 'node:https';
const httpAgent = new http.Agent({
keepAlive: true
});
const httpsAgent = new https.Agent({
keepAlive: true
});
const options = {
agent: function(_parsedURL) {
if (_parsedURL.protocol == 'http:') {
return httpAgent;
} else {
return httpsAgent;
}
}
};
```
<a id="custom-highWaterMark"></a>
#### Custom highWaterMark
Stream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.
The recommended way to fix this problem is to resolve cloned response in parallel:
```js
import fetch from 'node-fetch';
const response = await fetch('https://example.com');
const r1 = response.clone();
const results = await Promise.all([response.json(), r1.text()]);
console.log(results[0]);
console.log(results[1]);
```
If for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:
```js
import fetch from 'node-fetch';
const response = await fetch('https://example.com', {
// About 1MB
highWaterMark: 1024 * 1024
});
const result = await res.clone().arrayBuffer();
console.dir(result);
```
#### Insecure HTTP Parser
Passed through to the `insecureHTTPParser` option on http(s).request. See [`http.request`](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for more information.
#### Manual Redirect
The `redirect: 'manual'` option for node-fetch is different from the browser & specification, which
results in an [opaque-redirect filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-opaque-redirect).
node-fetch gives you the typical [basic filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-basic) instead.
```js
import fetch from 'node-fetch';
const response = await fetch('https://httpbin.org/status/301', { redirect: 'manual' });
if (response.status === 301 || response.status === 302) {
const locationURL = new URL(response.headers.get('location'), response.url);
const response2 = await fetch(locationURL, { redirect: 'manual' });
console.dir(response2);
}
```
<a id="class-request"></a>
### Class: Request
An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.
Due to the nature of Node.js, the following properties are not implemented at this moment:
- `type`
- `destination`
- `mode`
- `credentials`
- `cache`
- `integrity`
- `keepalive`
The following node-fetch extension properties are provided:
- `follow`
- `compress`
- `counter`
- `agent`
- `highWaterMark`
See [options](#fetch-options) for exact meaning of these extensions.
#### new Request(input[, options])
<small>_(spec-compliant)_</small>
- `input` A string representing a URL, or another `Request` (which will be cloned)
- `options` [Options](#fetch-options) for the HTTP(S) request
Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).
In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.
<a id="class-response"></a>
### Class: Response
An HTTP(S) response. This class implements the [Body](#iface-body) interface.
The following properties are not implemented in node-fetch at this moment:
- `trailer`
#### new Response([body[, options]])
<small>_(spec-compliant)_</small>
- `body` A `String` or [`Readable` stream][node-readable]
- `options` A [`ResponseInit`][response-init] options dictionary
Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).
Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.
#### response.ok
<small>_(spec-compliant)_</small>
Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.
#### response.redirected
<small>_(spec-compliant)_</small>
Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.
#### response.type
<small>_(deviation from spec)_</small>
Convenience property representing the response's type. node-fetch only supports `'default'` and `'error'` and does not make use of [filtered responses](https://fetch.spec.whatwg.org/#concept-filtered-response).
<a id="class-headers"></a>
### Class: Headers
This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.
#### new Headers([init])
<small>_(spec-compliant)_</small>
- `init` Optional argument to pre-fill the `Headers` object
Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.
```js
// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class
import {Headers} from 'node-fetch';
const meta = {
'Content-Type': 'text/xml'
};
const headers = new Headers(meta);
// The above is equivalent to
const meta = [['Content-Type', 'text/xml']];
const headers = new Headers(meta);
// You can in fact use any iterable objects, like a Map or even another Headers
const meta = new Map();
meta.set('Content-Type', 'text/xml');
const headers = new Headers(meta);
const copyOfHeaders = new Headers(headers);
```
<a id="iface-body"></a>
### Interface: Body
`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.
#### body.body
<small>_(deviation from spec)_</small>
- Node.js [`Readable` stream][node-readable]
Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].
#### body.bodyUsed
<small>_(spec-compliant)_</small>
- `Boolean`
A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.
#### body.arrayBuffer()
#### body.formData()
#### body.blob()
#### body.json()
#### body.text()
`fetch` comes with methods to parse `multipart/form-data` payloads as well as
`x-www-form-urlencoded` bodies using `.formData()` this comes from the idea that
Service Worker can intercept such messages before it's sent to the server to
alter them. This is useful for anybody building a server so you can use it to
parse & consume payloads.
<details>
<summary>Code example</summary>
```js
import http from 'node:http'
import { Response } from 'node-fetch'
http.createServer(async function (req, res) {
const formData = await new Response(req, {
headers: req.headers // Pass along the boundary value
}).formData()
const allFields = [...formData]
const file = formData.get('uploaded-files')
const arrayBuffer = await file.arrayBuffer()
const text = await file.text()
const whatwgReadableStream = file.stream()
// other was to consume the request could be to do:
const json = await new Response(req).json()
const text = await new Response(req).text()
const arrayBuffer = await new Response(req).arrayBuffer()
const blob = await new Response(req, {
headers: req.headers // So that `type` inherits `Content-Type`
}.blob()
})
```
</details>
<a id="class-fetcherror"></a>
### Class: FetchError
<small>_(node-fetch extension)_</small>
An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.
<a id="class-aborterror"></a>
### Class: AbortError
<small>_(node-fetch extension)_</small>
An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.
## TypeScript
**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**
For older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):
```sh
npm install --save-dev @types/node-fetch@2.x
```
## Acknowledgement
Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.
## Team
| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |
| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.ch) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |
###### Former
- [Timothy Gu](https://github.com/timothygu)
- [Jared Kantrowitz](https://github.com/jkantr)
## License
[MIT](LICENSE.md)
[whatwg-fetch]: https://fetch.spec.whatwg.org/
[response-init]: https://fetch.spec.whatwg.org/#responseinit
[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams
[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers
[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md
[FormData]: https://developer.mozilla.org/en-US/docs/Web/API/FormData
[Blob]: https://developer.mozilla.org/en-US/docs/Web/API/Blob
[File]: https://developer.mozilla.org/en-US/docs/Web/API/File

View File

@@ -0,0 +1,131 @@
{
"name": "node-fetch",
"version": "3.3.2",
"description": "A light-weight module that brings Fetch API to node.js",
"main": "./src/index.js",
"sideEffects": false,
"type": "module",
"files": [
"src",
"@types/index.d.ts"
],
"types": "./@types/index.d.ts",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"scripts": {
"test": "mocha",
"coverage": "c8 report --reporter=text-lcov | coveralls",
"test-types": "tsd",
"lint": "xo"
},
"repository": {
"type": "git",
"url": "https://github.com/node-fetch/node-fetch.git"
},
"keywords": [
"fetch",
"http",
"promise",
"request",
"curl",
"wget",
"xhr",
"whatwg"
],
"author": "David Frank",
"license": "MIT",
"bugs": {
"url": "https://github.com/node-fetch/node-fetch/issues"
},
"homepage": "https://github.com/node-fetch/node-fetch",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/node-fetch"
},
"devDependencies": {
"abort-controller": "^3.0.0",
"abortcontroller-polyfill": "^1.7.1",
"busboy": "^1.4.0",
"c8": "^7.7.2",
"chai": "^4.3.4",
"chai-as-promised": "^7.1.1",
"chai-iterator": "^3.0.2",
"chai-string": "^1.5.0",
"coveralls": "^3.1.0",
"form-data": "^4.0.0",
"formdata-node": "^4.2.4",
"mocha": "^9.1.3",
"p-timeout": "^5.0.0",
"stream-consumers": "^1.0.1",
"tsd": "^0.14.0",
"xo": "^0.39.1"
},
"dependencies": {
"data-uri-to-buffer": "^4.0.0",
"fetch-blob": "^3.1.4",
"formdata-polyfill": "^4.0.10"
},
"tsd": {
"cwd": "@types",
"compilerOptions": {
"esModuleInterop": true
}
},
"xo": {
"envs": [
"node",
"browser"
],
"ignores": [
"example.js"
],
"rules": {
"complexity": 0,
"import/extensions": 0,
"import/no-useless-path-segments": 0,
"import/no-anonymous-default-export": 0,
"import/no-named-as-default": 0,
"unicorn/import-index": 0,
"unicorn/no-array-reduce": 0,
"unicorn/prefer-node-protocol": 0,
"unicorn/numeric-separators-style": 0,
"unicorn/explicit-length-check": 0,
"capitalized-comments": 0,
"node/no-unsupported-features/es-syntax": 0,
"@typescript-eslint/member-ordering": 0
},
"overrides": [
{
"files": "test/**/*.js",
"envs": [
"node",
"mocha"
],
"rules": {
"max-nested-callbacks": 0,
"no-unused-expressions": 0,
"no-warning-comments": 0,
"new-cap": 0,
"guard-for-in": 0,
"unicorn/no-array-for-each": 0,
"unicorn/prevent-abbreviations": 0,
"promise/prefer-await-to-then": 0,
"ava/no-import-test-files": 0
}
}
]
},
"runkitExampleFilename": "example.js",
"release": {
"branches": [
"+([0-9]).x",
"main",
"next",
{
"name": "beta",
"prerelease": true
}
]
}
}

View File

@@ -0,0 +1,397 @@
/**
* Body.js
*
* Body interface provides common methods for Request and Response
*/
import Stream, {PassThrough} from 'node:stream';
import {types, deprecate, promisify} from 'node:util';
import {Buffer} from 'node:buffer';
import Blob from 'fetch-blob';
import {FormData, formDataToBlob} from 'formdata-polyfill/esm.min.js';
import {FetchError} from './errors/fetch-error.js';
import {FetchBaseError} from './errors/base.js';
import {isBlob, isURLSearchParameters} from './utils/is.js';
const pipeline = promisify(Stream.pipeline);
const INTERNALS = Symbol('Body internals');
/**
* Body mixin
*
* Ref: https://fetch.spec.whatwg.org/#body
*
* @param Stream body Readable stream
* @param Object opts Response options
* @return Void
*/
export default class Body {
constructor(body, {
size = 0
} = {}) {
let boundary = null;
if (body === null) {
// Body is undefined or null
body = null;
} else if (isURLSearchParameters(body)) {
// Body is a URLSearchParams
body = Buffer.from(body.toString());
} else if (isBlob(body)) {
// Body is blob
} else if (Buffer.isBuffer(body)) {
// Body is Buffer
} else if (types.isAnyArrayBuffer(body)) {
// Body is ArrayBuffer
body = Buffer.from(body);
} else if (ArrayBuffer.isView(body)) {
// Body is ArrayBufferView
body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
} else if (body instanceof Stream) {
// Body is stream
} else if (body instanceof FormData) {
// Body is FormData
body = formDataToBlob(body);
boundary = body.type.split('=')[1];
} else {
// None of the above
// coerce to string then buffer
body = Buffer.from(String(body));
}
let stream = body;
if (Buffer.isBuffer(body)) {
stream = Stream.Readable.from(body);
} else if (isBlob(body)) {
stream = Stream.Readable.from(body.stream());
}
this[INTERNALS] = {
body,
stream,
boundary,
disturbed: false,
error: null
};
this.size = size;
if (body instanceof Stream) {
body.on('error', error_ => {
const error = error_ instanceof FetchBaseError ?
error_ :
new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_);
this[INTERNALS].error = error;
});
}
}
get body() {
return this[INTERNALS].stream;
}
get bodyUsed() {
return this[INTERNALS].disturbed;
}
/**
* Decode response as ArrayBuffer
*
* @return Promise
*/
async arrayBuffer() {
const {buffer, byteOffset, byteLength} = await consumeBody(this);
return buffer.slice(byteOffset, byteOffset + byteLength);
}
async formData() {
const ct = this.headers.get('content-type');
if (ct.startsWith('application/x-www-form-urlencoded')) {
const formData = new FormData();
const parameters = new URLSearchParams(await this.text());
for (const [name, value] of parameters) {
formData.append(name, value);
}
return formData;
}
const {toFormData} = await import('./utils/multipart-parser.js');
return toFormData(this.body, ct);
}
/**
* Return raw response as Blob
*
* @return Promise
*/
async blob() {
const ct = (this.headers && this.headers.get('content-type')) || (this[INTERNALS].body && this[INTERNALS].body.type) || '';
const buf = await this.arrayBuffer();
return new Blob([buf], {
type: ct
});
}
/**
* Decode response as json
*
* @return Promise
*/
async json() {
const text = await this.text();
return JSON.parse(text);
}
/**
* Decode response as text
*
* @return Promise
*/
async text() {
const buffer = await consumeBody(this);
return new TextDecoder().decode(buffer);
}
/**
* Decode response as buffer (non-spec api)
*
* @return Promise
*/
buffer() {
return consumeBody(this);
}
}
Body.prototype.buffer = deprecate(Body.prototype.buffer, 'Please use \'response.arrayBuffer()\' instead of \'response.buffer()\'', 'node-fetch#buffer');
// In browsers, all properties are enumerable.
Object.defineProperties(Body.prototype, {
body: {enumerable: true},
bodyUsed: {enumerable: true},
arrayBuffer: {enumerable: true},
blob: {enumerable: true},
json: {enumerable: true},
text: {enumerable: true},
data: {get: deprecate(() => {},
'data doesn\'t exist, use json(), text(), arrayBuffer(), or body instead',
'https://github.com/node-fetch/node-fetch/issues/1000 (response)')}
});
/**
* Consume and convert an entire Body to a Buffer.
*
* Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
*
* @return Promise
*/
async function consumeBody(data) {
if (data[INTERNALS].disturbed) {
throw new TypeError(`body used already for: ${data.url}`);
}
data[INTERNALS].disturbed = true;
if (data[INTERNALS].error) {
throw data[INTERNALS].error;
}
const {body} = data;
// Body is null
if (body === null) {
return Buffer.alloc(0);
}
/* c8 ignore next 3 */
if (!(body instanceof Stream)) {
return Buffer.alloc(0);
}
// Body is stream
// get ready to actually consume the body
const accum = [];
let accumBytes = 0;
try {
for await (const chunk of body) {
if (data.size > 0 && accumBytes + chunk.length > data.size) {
const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, 'max-size');
body.destroy(error);
throw error;
}
accumBytes += chunk.length;
accum.push(chunk);
}
} catch (error) {
const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error);
throw error_;
}
if (body.readableEnded === true || body._readableState.ended === true) {
try {
if (accum.every(c => typeof c === 'string')) {
return Buffer.from(accum.join(''));
}
return Buffer.concat(accum, accumBytes);
} catch (error) {
throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error);
}
} else {
throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
}
}
/**
* Clone body given Res/Req instance
*
* @param Mixed instance Response or Request instance
* @param String highWaterMark highWaterMark for both PassThrough body streams
* @return Mixed
*/
export const clone = (instance, highWaterMark) => {
let p1;
let p2;
let {body} = instance[INTERNALS];
// Don't allow cloning a used body
if (instance.bodyUsed) {
throw new Error('cannot clone body after it is used');
}
// Check that body is a stream and not form-data object
// note: we can't clone the form-data object without having it as a dependency
if ((body instanceof Stream) && (typeof body.getBoundary !== 'function')) {
// Tee instance body
p1 = new PassThrough({highWaterMark});
p2 = new PassThrough({highWaterMark});
body.pipe(p1);
body.pipe(p2);
// Set instance body to teed body and return the other teed body
instance[INTERNALS].stream = p1;
body = p2;
}
return body;
};
const getNonSpecFormDataBoundary = deprecate(
body => body.getBoundary(),
'form-data doesn\'t follow the spec and requires special treatment. Use alternative package',
'https://github.com/node-fetch/node-fetch/issues/1167'
);
/**
* Performs the operation "extract a `Content-Type` value from |object|" as
* specified in the specification:
* https://fetch.spec.whatwg.org/#concept-bodyinit-extract
*
* This function assumes that instance.body is present.
*
* @param {any} body Any options.body input
* @returns {string | null}
*/
export const extractContentType = (body, request) => {
// Body is null or undefined
if (body === null) {
return null;
}
// Body is string
if (typeof body === 'string') {
return 'text/plain;charset=UTF-8';
}
// Body is a URLSearchParams
if (isURLSearchParameters(body)) {
return 'application/x-www-form-urlencoded;charset=UTF-8';
}
// Body is blob
if (isBlob(body)) {
return body.type || null;
}
// Body is a Buffer (Buffer, ArrayBuffer or ArrayBufferView)
if (Buffer.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
return null;
}
if (body instanceof FormData) {
return `multipart/form-data; boundary=${request[INTERNALS].boundary}`;
}
// Detect form data input from form-data module
if (body && typeof body.getBoundary === 'function') {
return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;
}
// Body is stream - can't really do much about this
if (body instanceof Stream) {
return null;
}
// Body constructor defaults other things to string
return 'text/plain;charset=UTF-8';
};
/**
* The Fetch Standard treats this as if "total bytes" is a property on the body.
* For us, we have to explicitly get it with a function.
*
* ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
*
* @param {any} obj.body Body object from the Body instance.
* @returns {number | null}
*/
export const getTotalBytes = request => {
const {body} = request[INTERNALS];
// Body is null or undefined
if (body === null) {
return 0;
}
// Body is Blob
if (isBlob(body)) {
return body.size;
}
// Body is Buffer
if (Buffer.isBuffer(body)) {
return body.length;
}
// Detect form data input from form-data module
if (body && typeof body.getLengthSync === 'function') {
return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
}
// Body is stream
return null;
};
/**
* Write a Body to a Node.js WritableStream (e.g. http.Request) object.
*
* @param {Stream.Writable} dest The stream to write to.
* @param obj.body Body object from the Body instance.
* @returns {Promise<void>}
*/
export const writeToStream = async (dest, {body}) => {
if (body === null) {
// Body is null
dest.end();
} else {
// Body is stream
await pipeline(body, dest);
}
};

View File

@@ -0,0 +1,10 @@
import {FetchBaseError} from './base.js';
/**
* AbortError interface for cancelled requests
*/
export class AbortError extends FetchBaseError {
constructor(message, type = 'aborted') {
super(message, type);
}
}

View File

@@ -0,0 +1,17 @@
export class FetchBaseError extends Error {
constructor(message, type) {
super(message);
// Hide custom error implementation details from end-users
Error.captureStackTrace(this, this.constructor);
this.type = type;
}
get name() {
return this.constructor.name;
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
}

View File

@@ -0,0 +1,26 @@
import {FetchBaseError} from './base.js';
/**
* @typedef {{ address?: string, code: string, dest?: string, errno: number, info?: object, message: string, path?: string, port?: number, syscall: string}} SystemError
*/
/**
* FetchError interface for operational errors
*/
export class FetchError extends FetchBaseError {
/**
* @param {string} message - Error message for human
* @param {string} [type] - Error type for machine
* @param {SystemError} [systemError] - For Node.js system error
*/
constructor(message, type, systemError) {
super(message, type);
// When err.type is `system`, err.erroredSysCall contains system error and err.code contains system error code
if (systemError) {
// eslint-disable-next-line no-multi-assign
this.code = this.errno = systemError.code;
this.erroredSysCall = systemError.syscall;
}
}
}

Some files were not shown because too many files have changed in this diff Show More