UNPKG

8.38 kBJavaScriptView Raw
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License. See License.txt in the project root for license information.
3import { v4 as uuidv4 } from "uuid";
4import { Constants } from "./constants";
5/**
6 * A constant that indicates whether the environment is node.js or browser based.
7 */
8export var isNode = typeof process !== "undefined" &&
9 !!process.version &&
10 !!process.versions &&
11 !!process.versions.node;
12/**
13 * Checks if a parsed URL is HTTPS
14 *
15 * @param {object} urlToCheck The url to check
16 * @return {boolean} True if the URL is HTTPS; false otherwise.
17 */
18export function urlIsHTTPS(urlToCheck) {
19 return urlToCheck.protocol.toLowerCase() === Constants.HTTPS;
20}
21/**
22 * Encodes an URI.
23 *
24 * @param {string} uri The URI to be encoded.
25 * @return {string} The encoded URI.
26 */
27export function encodeUri(uri) {
28 return encodeURIComponent(uri)
29 .replace(/!/g, "%21")
30 .replace(/"/g, "%27")
31 .replace(/\(/g, "%28")
32 .replace(/\)/g, "%29")
33 .replace(/\*/g, "%2A");
34}
35/**
36 * Returns a stripped version of the Http Response which only contains body,
37 * headers and the status.
38 *
39 * @param {HttpOperationResponse} response The Http Response
40 *
41 * @return {object} The stripped version of Http Response.
42 */
43export function stripResponse(response) {
44 var strippedResponse = {};
45 strippedResponse.body = response.bodyAsText;
46 strippedResponse.headers = response.headers;
47 strippedResponse.status = response.status;
48 return strippedResponse;
49}
50/**
51 * Returns a stripped version of the Http Request that does not contain the
52 * Authorization header.
53 *
54 * @param {WebResource} request The Http Request object
55 *
56 * @return {WebResource} The stripped version of Http Request.
57 */
58export function stripRequest(request) {
59 var strippedRequest = request.clone();
60 if (strippedRequest.headers) {
61 strippedRequest.headers.remove("authorization");
62 }
63 return strippedRequest;
64}
65/**
66 * Validates the given uuid as a string
67 *
68 * @param {string} uuid The uuid as a string that needs to be validated
69 *
70 * @return {boolean} True if the uuid is valid; false otherwise.
71 */
72export function isValidUuid(uuid) {
73 var validUuidRegex = new RegExp("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", "ig");
74 return validUuidRegex.test(uuid);
75}
76/**
77 * Provides an array of values of an object. For example
78 * for a given object { "a": "foo", "b": "bar" }, the method returns ["foo", "bar"].
79 *
80 * @param {object} obj An object whose properties need to be enumerated so that it"s values can be provided as an array
81 *
82 * @return {any[]} An array of values of the given object.
83 */
84export function objectValues(obj) {
85 var result = [];
86 if (obj && obj instanceof Object) {
87 for (var key in obj) {
88 if (obj.hasOwnProperty(key)) {
89 result.push(obj[key]);
90 }
91 }
92 }
93 else {
94 throw new Error("The provided object " + JSON.stringify(obj, undefined, 2) + " is not a valid object that can be " + "enumerated to provide its values as an array.");
95 }
96 return result;
97}
98/**
99 * Generated UUID
100 *
101 * @return {string} RFC4122 v4 UUID.
102 */
103export function generateUuid() {
104 return uuidv4();
105}
106/**
107 * Executes an array of promises sequentially. Inspiration of this method is here:
108 * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!
109 *
110 * @param {Array} promiseFactories An array of promise factories(A function that return a promise)
111 *
112 * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain.
113 * If not provided then the promise chain starts with undefined.
114 *
115 * @return A chain of resolved or rejected promises
116 */
117export function executePromisesSequentially(promiseFactories, kickstart) {
118 var result = Promise.resolve(kickstart);
119 promiseFactories.forEach(function (promiseFactory) {
120 result = result.then(promiseFactory);
121 });
122 return result;
123}
124/**
125 * Merges source object into the target object
126 * @param {object} source The object that needs to be merged
127 *
128 * @param {object} target The object to be merged into
129 *
130 * @returns {object} Returns the merged target object.
131 */
132export function mergeObjects(source, target) {
133 Object.keys(source).forEach(function (key) {
134 target[key] = source[key];
135 });
136 return target;
137}
138/**
139 * A wrapper for setTimeout that resolves a promise after t milliseconds.
140 * @param {number} t The number of milliseconds to be delayed.
141 * @param {T} value The value to be resolved with after a timeout of t milliseconds.
142 * @returns {Promise<T>} Resolved promise
143 */
144export function delay(t, value) {
145 return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); });
146}
147/**
148 * Converts a Promise to a callback.
149 * @param {Promise<any>} promise The Promise to be converted to a callback
150 * @returns {Function} A function that takes the callback (cb: Function): void
151 * @deprecated generated code should instead depend on responseToBody
152 */
153export function promiseToCallback(promise) {
154 if (typeof promise.then !== "function") {
155 throw new Error("The provided input is not a Promise.");
156 }
157 return function (cb) {
158 promise.then(function (data) {
159 cb(undefined, data);
160 }, function (err) {
161 cb(err);
162 });
163 };
164}
165/**
166 * Converts a Promise to a service callback.
167 * @param {Promise<HttpOperationResponse>} promise - The Promise of HttpOperationResponse to be converted to a service callback
168 * @returns {Function} A function that takes the service callback (cb: ServiceCallback<T>): void
169 */
170export function promiseToServiceCallback(promise) {
171 if (typeof promise.then !== "function") {
172 throw new Error("The provided input is not a Promise.");
173 }
174 return function (cb) {
175 promise.then(function (data) {
176 process.nextTick(cb, undefined, data.parsedBody, data.request, data);
177 }, function (err) {
178 process.nextTick(cb, err);
179 });
180 };
181}
182export function prepareXMLRootList(obj, elementName) {
183 var _a;
184 if (!Array.isArray(obj)) {
185 obj = [obj];
186 }
187 return _a = {}, _a[elementName] = obj, _a;
188}
189/**
190 * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor
191 * @param {object} targetCtor The target object on which the properties need to be applied.
192 * @param {Array<object>} sourceCtors An array of source objects from which the properties need to be taken.
193 */
194export function applyMixins(targetCtor, sourceCtors) {
195 sourceCtors.forEach(function (sourceCtors) {
196 Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) {
197 targetCtor.prototype[name] = sourceCtors.prototype[name];
198 });
199 });
200}
201var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
202/**
203 * Indicates whether the given string is in ISO 8601 format.
204 * @param {string} value The value to be validated for ISO 8601 duration format.
205 * @return {boolean} `true` if valid, `false` otherwise.
206 */
207export function isDuration(value) {
208 return validateISODuration.test(value);
209}
210/**
211 * Replace all of the instances of searchValue in value with the provided replaceValue.
212 * @param {string | undefined} value The value to search and replace in.
213 * @param {string} searchValue The value to search for in the value argument.
214 * @param {string} replaceValue The value to replace searchValue with in the value argument.
215 * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue.
216 */
217export function replaceAll(value, searchValue, replaceValue) {
218 return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || "");
219}
220/**
221 * Determines whether the given enity is a basic/primitive type
222 * (string, number, boolean, null, undefined).
223 * @param value Any entity
224 * @return boolean - true is it is primitive type, false otherwise.
225 */
226export function isPrimitiveType(value) {
227 return (typeof value !== "object" && typeof value !== "function") || value === null;
228}
229//# sourceMappingURL=utils.js.map
\No newline at end of file