Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / gcp-metadata / build / src / index.js
1 "use strict";
2 /**
3  * Copyright 2018 Google LLC
4  *
5  * Distributed under MIT license.
6  * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
7  */
8 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9     return new (P || (P = Promise))(function (resolve, reject) {
10         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
12         function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
13         step((generator = generator.apply(thisArg, _arguments || [])).next());
14     });
15 };
16 Object.defineProperty(exports, "__esModule", { value: true });
17 const gaxios_1 = require("gaxios");
18 const jsonBigint = require('json-bigint');
19 exports.HOST_ADDRESS = 'http://metadata.google.internal.';
20 exports.BASE_PATH = '/computeMetadata/v1';
21 exports.BASE_URL = exports.HOST_ADDRESS + exports.BASE_PATH;
22 exports.HEADER_NAME = 'Metadata-Flavor';
23 exports.HEADER_VALUE = 'Google';
24 exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE });
25 // Accepts an options object passed from the user to the API. In previous
26 // versions of the API, it referred to a `Request` or an `Axios` request
27 // options object.  Now it refers to an object with very limited property
28 // names. This is here to help ensure users don't pass invalid options when
29 // they  upgrade from 0.4 to 0.5 to 0.8.
30 function validate(options) {
31     Object.keys(options).forEach(key => {
32         switch (key) {
33             case 'params':
34             case 'property':
35             case 'headers':
36                 break;
37             case 'qs':
38                 throw new Error(`'qs' is not a valid configuration option. Please use 'params' instead.`);
39             default:
40                 throw new Error(`'${key}' is not a valid configuration option.`);
41         }
42     });
43 }
44 function metadataAccessor(type, options, noResponseRetries = 3) {
45     return __awaiter(this, void 0, void 0, function* () {
46         options = options || {};
47         if (typeof options === 'string') {
48             options = { property: options };
49         }
50         let property = '';
51         if (typeof options === 'object' && options.property) {
52             property = '/' + options.property;
53         }
54         validate(options);
55         try {
56             const res = yield gaxios_1.request({
57                 url: `${exports.BASE_URL}/${type}${property}`,
58                 headers: Object.assign({}, exports.HEADERS, options.headers),
59                 retryConfig: { noResponseRetries },
60                 params: options.params,
61                 responseType: 'text'
62             });
63             // NOTE: node.js converts all incoming headers to lower case.
64             if (res.headers[exports.HEADER_NAME.toLowerCase()] !== exports.HEADER_VALUE) {
65                 throw new Error(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header.`);
66             }
67             else if (!res.data) {
68                 throw new Error('Invalid response from the metadata service');
69             }
70             if (typeof res.data === 'string') {
71                 try {
72                     return jsonBigint.parse(res.data);
73                 }
74                 catch (_a) {
75                     /* ignore */
76                 }
77             }
78             return res.data;
79         }
80         catch (e) {
81             if (e.response && e.response.status !== 200) {
82                 e.message = `Unsuccessful response status code. ${e.message}`;
83             }
84             throw e;
85         }
86     });
87 }
88 // tslint:disable-next-line no-any
89 function instance(options) {
90     return metadataAccessor('instance', options);
91 }
92 exports.instance = instance;
93 // tslint:disable-next-line no-any
94 function project(options) {
95     return metadataAccessor('project', options);
96 }
97 exports.project = project;
98 /**
99  * Determine if the metadata server is currently available.
100  */
101 function isAvailable() {
102     return __awaiter(this, void 0, void 0, function* () {
103         try {
104             // Attempt to read instance metadata. As configured, this will
105             // retry 3 times if there is a valid response, and fail fast
106             // if there is an ETIMEDOUT or ENOTFOUND error.
107             yield metadataAccessor('instance', undefined, 0);
108             return true;
109         }
110         catch (err) {
111             // Failure to resolve the metadata service means that it is not available.
112             if (err.code && (err.code === 'ENOTFOUND' || err.code === 'ENOENT')) {
113                 return false;
114             }
115             // Throw unexpected errors.
116             throw err;
117         }
118     });
119 }
120 exports.isAvailable = isAvailable;
121 //# sourceMappingURL=index.js.map