UNPKG

9.92 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6const url_1 = __importDefault(require("url"));
7const bitcoinjs_lib_1 = require("bitcoinjs-lib");
8const config_1 = require("./config");
9const logger_1 = require("./logger");
10/**
11 * @ignore
12 */
13exports.BLOCKSTACK_HANDLER = 'blockstack';
14/**
15 * Time
16 * @private
17 * @ignore
18 */
19function nextYear() {
20 return new Date(new Date().setFullYear(new Date().getFullYear() + 1));
21}
22exports.nextYear = nextYear;
23/**
24 * Time
25 * @private
26 * @ignore
27 */
28function nextMonth() {
29 return new Date(new Date().setMonth(new Date().getMonth() + 1));
30}
31exports.nextMonth = nextMonth;
32/**
33 * Time
34 * @private
35 * @ignore
36 */
37function nextHour() {
38 return new Date(new Date().setHours(new Date().getHours() + 1));
39}
40exports.nextHour = nextHour;
41/**
42 * Query Strings
43 * @private
44 * @ignore
45 */
46function updateQueryStringParameter(uri, key, value) {
47 const re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i');
48 const separator = uri.indexOf('?') !== -1 ? '&' : '?';
49 if (uri.match(re)) {
50 return uri.replace(re, `$1${key}=${value}$2`);
51 }
52 else {
53 return `${uri}${separator}${key}=${value}`;
54 }
55}
56exports.updateQueryStringParameter = updateQueryStringParameter;
57/**
58 * Versioning
59 * @param {string} v1 - the left half of the version inequality
60 * @param {string} v2 - right half of the version inequality
61 * @returns {bool} iff v1 >= v2
62 * @private
63 * @ignore
64 */
65function isLaterVersion(v1, v2) {
66 if (v1 === undefined) {
67 v1 = '0.0.0';
68 }
69 if (v2 === undefined) {
70 v2 = '0.0.0';
71 }
72 const v1tuple = v1.split('.').map(x => parseInt(x, 10));
73 const v2tuple = v2.split('.').map(x => parseInt(x, 10));
74 for (let index = 0; index < v2.length; index++) {
75 if (index >= v1.length) {
76 v2tuple.push(0);
77 }
78 if (v1tuple[index] < v2tuple[index]) {
79 return false;
80 }
81 }
82 return true;
83}
84exports.isLaterVersion = isLaterVersion;
85/**
86 * Time
87 * @private
88 * @ignore
89 */
90function hexStringToECPair(skHex) {
91 const ecPairOptions = {
92 network: config_1.config.network.layer1,
93 compressed: true
94 };
95 if (skHex.length === 66) {
96 if (skHex.slice(64) !== '01') {
97 throw new Error('Improperly formatted private-key hex string. 66-length hex usually '
98 + 'indicates compressed key, but last byte must be == 1');
99 }
100 return bitcoinjs_lib_1.ECPair.fromPrivateKey(Buffer.from(skHex.slice(0, 64), 'hex'), ecPairOptions);
101 }
102 else if (skHex.length === 64) {
103 ecPairOptions.compressed = false;
104 return bitcoinjs_lib_1.ECPair.fromPrivateKey(Buffer.from(skHex, 'hex'), ecPairOptions);
105 }
106 else {
107 throw new Error('Improperly formatted private-key hex string: length should be 64 or 66.');
108 }
109}
110exports.hexStringToECPair = hexStringToECPair;
111/**
112 *
113 * @ignore
114 */
115function ecPairToHexString(secretKey) {
116 const ecPointHex = secretKey.privateKey.toString('hex');
117 if (secretKey.compressed) {
118 return `${ecPointHex}01`;
119 }
120 else {
121 return ecPointHex;
122 }
123}
124exports.ecPairToHexString = ecPairToHexString;
125/**
126 * Time
127 * @private
128 * @ignore
129 */
130function ecPairToAddress(keyPair) {
131 return bitcoinjs_lib_1.address.toBase58Check(bitcoinjs_lib_1.crypto.hash160(keyPair.publicKey), keyPair.network.pubKeyHash);
132}
133exports.ecPairToAddress = ecPairToAddress;
134/**
135 * UUIDs
136 * @private
137 * @ignore
138 */
139function makeUUID4() {
140 let d = new Date().getTime();
141 if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
142 d += performance.now(); // use high-precision timer if available
143 }
144 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
145 const r = (d + Math.random() * 16) % 16 | 0;
146 d = Math.floor(d / 16);
147 return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
148 });
149}
150exports.makeUUID4 = makeUUID4;
151/**
152 * Checks if both urls pass the same origin check & are absolute
153 * @param {[type]} uri1 first uri to check
154 * @param {[type]} uri2 second uri to check
155 * @return {Boolean} true if they pass the same origin check
156 * @private
157 * @ignore
158 */
159function isSameOriginAbsoluteUrl(uri1, uri2) {
160 const parsedUri1 = url_1.default.parse(uri1);
161 const parsedUri2 = url_1.default.parse(uri2);
162 const port1 = parseInt(parsedUri1.port || '0', 10) | 0 || (parsedUri1.protocol === 'https:' ? 443 : 80);
163 const port2 = parseInt(parsedUri2.port || '0', 10) | 0 || (parsedUri2.protocol === 'https:' ? 443 : 80);
164 const match = {
165 scheme: parsedUri1.protocol === parsedUri2.protocol,
166 hostname: parsedUri1.hostname === parsedUri2.hostname,
167 port: port1 === port2,
168 absolute: (uri1.includes('http://') || uri1.includes('https://'))
169 && (uri2.includes('http://') || uri2.includes('https://'))
170 };
171 return match.scheme && match.hostname && match.port && match.absolute;
172}
173exports.isSameOriginAbsoluteUrl = isSameOriginAbsoluteUrl;
174/**
175 * Returns the global scope `Window`, `WorkerGlobalScope`, or `NodeJS.Global` if available in the
176 * currently executing environment.
177 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
178 * @see https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/self
179 * @see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope
180 *
181 * This could be switched to `globalThis` once it is standardized and widely available.
182 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
183 */
184function getGlobalScope() {
185 if (typeof self !== 'undefined') {
186 return self;
187 }
188 if (typeof window !== 'undefined') {
189 return window;
190 }
191 // This function is meant to be called when accessing APIs that are typically only available in
192 // web-browser/DOM environments, but we also want to support situations where running in Node.js
193 // environment, and a polyfill was added to the Node.js `global` object scope without adding the
194 // `window` global object as well.
195 if (typeof global !== 'undefined') {
196 return global;
197 }
198 throw new Error('Unexpected runtime environment - no supported global scope (`window`, `self`, `global`) available');
199}
200function getAPIUsageErrorMessage(scopeObject, apiName, usageDesc) {
201 if (usageDesc) {
202 return `Use of '${usageDesc}' requires \`${apiName}\` which is unavailable on the '${scopeObject}' object within the currently executing environment.`;
203 }
204 else {
205 return `\`${apiName}\` is unavailable on the '${scopeObject}' object within the currently executing environment.`;
206 }
207}
208/**
209 * Returns an object from the global scope (`Window` or `WorkerGlobalScope`) if it
210 * is available within the currently executing environment.
211 * When executing within the Node.js runtime these APIs are unavailable and will be
212 * `undefined` unless the API is provided via polyfill.
213 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
214 * @ignore
215 */
216function getGlobalObject(name, { throwIfUnavailable, usageDesc, returnEmptyObject } = {}) {
217 let globalScope;
218 try {
219 globalScope = getGlobalScope();
220 if (globalScope) {
221 const obj = globalScope[name];
222 if (obj) {
223 return obj;
224 }
225 }
226 }
227 catch (error) {
228 logger_1.Logger.error(`Error getting object '${name}' from global scope '${globalScope}': ${error}`);
229 }
230 if (throwIfUnavailable) {
231 const errMsg = getAPIUsageErrorMessage(globalScope, name, usageDesc);
232 logger_1.Logger.error(errMsg);
233 throw new Error(errMsg);
234 }
235 if (returnEmptyObject) {
236 return {};
237 }
238 return undefined;
239}
240exports.getGlobalObject = getGlobalObject;
241/**
242 * Returns a specified subset of objects from the global scope (`Window` or `WorkerGlobalScope`)
243 * if they are available within the currently executing environment.
244 * When executing within the Node.js runtime these APIs are unavailable will be `undefined`
245 * unless the API is provided via polyfill.
246 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
247 * @ignore
248 */
249function getGlobalObjects(names, { throwIfUnavailable, usageDesc, returnEmptyObject } = {}) {
250 let globalScope;
251 try {
252 globalScope = getGlobalScope();
253 }
254 catch (error) {
255 logger_1.Logger.error(`Error getting global scope: ${error}`);
256 if (throwIfUnavailable) {
257 const errMsg = getAPIUsageErrorMessage(globalScope, names[0], usageDesc);
258 logger_1.Logger.error(errMsg);
259 throw errMsg;
260 }
261 else if (returnEmptyObject) {
262 globalScope = {};
263 }
264 }
265 const result = {};
266 for (let i = 0; i < names.length; i++) {
267 const name = names[i];
268 try {
269 if (globalScope) {
270 const obj = globalScope[name];
271 if (obj) {
272 result[name] = obj;
273 }
274 else if (throwIfUnavailable) {
275 const errMsg = getAPIUsageErrorMessage(globalScope, name, usageDesc);
276 logger_1.Logger.error(errMsg);
277 throw new Error(errMsg);
278 }
279 else if (returnEmptyObject) {
280 result[name] = {};
281 }
282 }
283 }
284 catch (error) {
285 if (throwIfUnavailable) {
286 const errMsg = getAPIUsageErrorMessage(globalScope, name, usageDesc);
287 logger_1.Logger.error(errMsg);
288 throw new Error(errMsg);
289 }
290 }
291 }
292 return result;
293}
294exports.getGlobalObjects = getGlobalObjects;
295//# sourceMappingURL=utils.js.map
\No newline at end of file