NPM Dependencies UPDATE

This commit is contained in:
Luis Fernando Molina committed 2018-05-02 10:22:14 +02:00
1 parent d3bc5e34f6
commit 5bfb4ff32a
732 files changed
+13367 -62155

No files matched your search

+4 -2
View File
@@ -2,11 +2,13 @@
If you would like to become an active contributor to this project please follow the instructions provided in [Microsoft Azure Projects Contribution Guidelines](https://azure.github.io/guidelines/).
Look at issues in the repository labeled 'good first issue' to choose what'd you liked to jump into!
## Project Steup
The Azure Storage development team uses Visual Studio Code so instructions will be tailored to that preference. However, any preferred IDE or other toolset should be usable.
### Install
* Node v0.10, v0.12 or v4
* Node v4 or above
* [Visual Studio Code](https://code.visualstudio.com/)
### Development Environment Setup
@@ -73,7 +75,7 @@ The following are the minimum requirements for any pull request that must be met
Changes should be based on the **dev** branch, not master as master is considered publicly released code. Each breaking change should be recorded in [BreakingChanges.md](BreakingChanges.md).
### Adding Features for All Platforms
We strive to release each new feature for each of our environments at the same time. Therefore, we ask that all contributions be written for Node v0.10 and later.
We strive to release each new feature for each of our environments at the same time. Therefore, we ask that all contributions be written for Node v4 and later.
### Review Process
We expect all guidelines to be met before accepting a pull request. As such, we will work with you to address issues we find by leaving comments in your code. Please understand that it may take a few iterations before the code is accepted as we maintain high standards on code quality. Once we feel comfortable with a contribution, we will validate the change and accept the pull request.
+19
View File
@@ -1,6 +1,25 @@
Note: This is an Azure Storage only package. The all up Azure node sdk still has the old storage bits in there. In a future release, those storage bits will be removed and an npm dependency to this storage node sdk will
be taken. This is a GA release and the changes described below indicate the changes from the Azure node SDK 0.9.8 available here - https://github.com/Azure/azure-sdk-for-node.
2018.04 Version 2.8.2
ALL
* Improved JSDoc to clarify Node.js `Writable` and `Readable` stream.
* Updated CONTRIBUTION.md about the Node.js supported versions.
BLOB
* Fixed a TypeScript definition error that `blobService.getUrl()` misses `snapshotId` parameter.
FILE
* Fixed a README.MD mistake for `FileService` example.
2018.03 Version 2.8.1
ALL
* Updated request and validator package dependencies to reduce vulnerability.
* Fix a type assignment bug in tests for env variables.
* Improved documents.
2018.02 Version 2.8.0
ALL
+105 -87
View File
@@ -1,22 +1,22 @@
# Microsoft Azure Storage SDK for Node.js
# Microsoft Azure Storage SDK for Node.js and JavaScript for Browsers
[![NPM version](https://badge.fury.io/js/azure-storage.svg)](http://badge.fury.io/js/azure-storage) [![Slack](https://azurestorageslack.azurewebsites.net/badge.svg)]( https://azurestorageslack.azurewebsites.net)
* Master [![Build Status](https://travis-ci.org/Azure/azure-storage-node.svg?branch=master)](https://travis-ci.org/Azure/azure-storage-node/branches) [![Coverage Status](https://coveralls.io/repos/Azure/azure-storage-node/badge.svg?branch=master&service=github)](https://coveralls.io/github/Azure/azure-storage-node?branch=master)
* Dev [![Build Status](https://travis-ci.org/Azure/azure-storage-node.svg?branch=dev)](https://travis-ci.org/Azure/azure-storage-node/branches) [![Coverage Status](https://coveralls.io/repos/Azure/azure-storage-node/badge.svg?branch=dev&service=github)](https://coveralls.io/github/Azure/azure-storage-node?branch=dev)
This project provides a Node.js package and a browser compatible [JavaScript Client Library](#azure-storage-javascript-client-library-for-browsers) that makes it easy to consume and manage Microsoft Azure Storage Services.
This project provides a Node.js package and a browser compatible [JavaScript Client Library](https://github.com/Azure/azure-storage-node#azure-storage-javascript-client-library-for-browsers) that makes it easy to consume and manage Microsoft Azure Storage Services.
> If you are looking for the Node.js SDK for other Azure services, visit [https://github.com/Azure/azure-sdk-for-node](https://github.com/Azure/azure-sdk-for-node).
# Features
- Tables
- Create/Delete Tables
- Query/Create/Read/Update/Delete Entities
- Blobs
- Create/Delete Containers
- Create/Read/Update/Delete Blobs
- Tables
- Create/Delete Tables
- Query/Create/Read/Update/Delete Entities
- Files
- Create/Delete Shares
- Create/Delete Directories
@@ -51,83 +51,6 @@ When using the Storage SDK, you must provide connection information for the stor
* Constructors - For example, `var tableSvc = azure.createTableService(accountName, accountKey);`
### Table Storage
To ensure a table exists, call **createTableIfNotExists**:
```Javascript
var azure = require('azure-storage');
var tableService = azure.createTableService();
tableService.createTableIfNotExists('mytable', function(error, result, response) {
if (!error) {
// result contains true if created; false if already exists
}
});
```
A new entity can be added by calling **insertEntity**:
```Javascript
var azure = require('azure-storage');
var tableService = azure.createTableService();
var entGen = azure.TableUtilities.entityGenerator;
var entity = {
PartitionKey: entGen.String('part2'),
RowKey: entGen.String('row1'),
boolValueTrue: entGen.Boolean(true),
boolValueFalse: entGen.Boolean(false),
intValue: entGen.Int32(42),
dateValue: entGen.DateTime(new Date(Date.UTC(2011, 10, 25))),
complexDateValue: entGen.DateTime(new Date(Date.UTC(2013, 02, 16, 01, 46, 20)))
};
tableService.insertEntity('mytable', entity, function(error, result, response) {
if (!error) {
// result contains the ETag for the new entity
}
});
```
Instead of creating entities manually, you can use **entityGenerator**:
```Javascript
var azure = require('azure-storage');
var entGen = azure.TableUtilities.entityGenerator;
var task = {
PartitionKey: entGen.String('hometasks'),
RowKey: entGen.String('1'),
description: entGen.String('take out the trash'),
dueDate: entGen.DateTime(new Date(Date.UTC(2015, 6, 20)))
};
```
The method **retrieveEntity** can then be used to fetch the entity that was just inserted:
```Javascript
var azure = require('azure-storage');
var tableService = azure.createTableService();
tableService.retrieveEntity('mytable', 'part2', 'row1', function(error, result, response) {
if (!error) {
// result contains the entity
}
});
```
Use **TableQuery** to build complex queries:
```Javascript
var azure = require('azure-storage');
var tableService = azure.createTableService();
var query = new azure.TableQuery()
.top(5)
.where('PartitionKey eq ?', 'part2');
tableService.queryEntities('mytable', query, null, function(error, result, response) {
if (!error) {
// result.entries contains entities matching the query
}
});
```
### Blob Storage
The **createContainerIfNotExists** method can be used to create a
@@ -197,6 +120,101 @@ var token = blobService.generateSharedAccessSignature(containerName, blobName, s
var sasUrl = blobService.getUrl(containerName, blobName, token);
```
### Table Storage
To ensure a table exists, call **createTableIfNotExists**:
```Javascript
var azure = require('azure-storage');
var tableService = azure.createTableService();
tableService.createTableIfNotExists('mytable', function(error, result, response) {
if (!error) {
// result contains true if created; false if already exists
}
});
```
A new entity can be added by calling **insertEntity** or **insertOrReplaceEntity**:
```Javascript
var azure = require('azure-storage');
var tableService = azure.createTableService();
var entGen = azure.TableUtilities.entityGenerator;
var entity = {
PartitionKey: entGen.String('part2'),
RowKey: entGen.String('row1'),
boolValueTrue: entGen.Boolean(true),
boolValueFalse: entGen.Boolean(false),
intValue: entGen.Int32(42),
dateValue: entGen.DateTime(new Date(Date.UTC(2011, 10, 25))),
complexDateValue: entGen.DateTime(new Date(Date.UTC(2013, 02, 16, 01, 46, 20)))
};
tableService.insertEntity('mytable', entity, function(error, result, response) {
if (!error) {
// result contains the ETag for the new entity
}
});
```
Instead of creating entities manually, you can use **entityGenerator**:
```Javascript
var azure = require('azure-storage');
var entGen = azure.TableUtilities.entityGenerator;
var task = {
PartitionKey: entGen.String('hometasks'),
RowKey: entGen.String('1'),
description: entGen.String('take out the trash'),
dueDate: entGen.DateTime(new Date(Date.UTC(2015, 6, 20)))
};
```
The method **retrieveEntity** can then be used to fetch the entity that was just inserted:
```Javascript
var azure = require('azure-storage');
var tableService = azure.createTableService();
tableService.retrieveEntity('mytable', 'part2', 'row1', function(error, result, response) {
if (!error) {
// result contains the entity
}
});
```
The method **replaceEntity** or **insertOrReplaceEntity** can be called to update/edit an existing entry. In the following example we asssume that an entity `'part2', 'row1'` with a field `'taskDone'` set to `false` already exists.
```Javascript
var azure = require('azure-storage');
var tableService = azure.createTableService();
var entity = {
PartitionKey: entGen.String('part2'),
RowKey: entGen.String('row1'),
taskDone: entGen.Boolean(true),
};
tableService.insertOrReplaceEntity('mytable', entity, function(error, result, response) {
if (!error) {
// result contains the entity with field 'taskDone' set to `true`
}
});
```
Use **TableQuery** to build complex queries:
```Javascript
var azure = require('azure-storage');
var tableService = azure.createTableService();
var query = new azure.TableQuery()
.top(5)
.where('PartitionKey eq ?', 'part2');
tableService.queryEntities('mytable', query, null, function(error, result, response) {
if (!error) {
// result.entries contains entities matching the query
}
});
```
### Queue Storage
The **createQueueIfNotExists** method can be used to ensure a queue exists:
@@ -265,8 +283,8 @@ var fileService = azure.createFileService();
fileService.createDirectoryIfNotExists('taskshare', 'taskdirectory', function(error, result, response) {
if (!error) {
// if result = true, share was created.
// if result = false, share already existed.
// if result.created = true, share was created.
// if result.created = false, share already existed.
}
});
```
@@ -493,11 +511,11 @@ On Linux, please use `export` other than `set` to set the variables.
# Azure Storage JavaScript Client Library for Browsers
* JavaScript Client Library is currently in Preview. Questions and feedback are welcome in our [Slack channel](https://azurestorageslack.azurewebsites.net).
* Questions and feedback are welcome in our [Slack channel](https://azurestorageslack.azurewebsites.net).
Azure Storage Node.js Client Library is compatible with [Browserify](http://browserify.org/). This means you can bundle your Node.js application which depends on the Node.js Client Library using Browserify.
You can also choose to download the JavaScript Client Library provided by us, or generate the library by yourself. Please refer to the [README.md](browser/README.md) under `browser` folder for detailed usage guidelines.
You can also choose to download the JavaScript Client Library provided by us, or generate the library by yourself. Please refer to the [README.md](https://github.com/Azure/azure-storage-node/blob/master/browser/README.md) under `browser` folder for detailed usage guidelines.
## Downloading Azure Storage JavaScript Client Library
@@ -505,7 +523,7 @@ It's recommended to use the Azure Storage JavaScript Client Library provided by
## Generating Azure Storage JavaScript Client Library
We also provide browserify bundle scripts which generate Azure Storage JavaScript Client Library. The bundle script reduces the size of the Storage Client Library by splitting into smaller files, one per storage service and a common shared file. For more detailed information, refer to [README.md](browser/README.md) under `browser` folder.
We also provide browserify bundle scripts which generate Azure Storage JavaScript Client Library. The bundle script reduces the size of the Storage Client Library by splitting into smaller files, one per storage service. For more detailed information, refer to [README.md](https://github.com/Azure/azure-storage-node/blob/master/browser/README.md) under `browser` folder.
# JsDoc
+15
View File
@@ -1,5 +1,20 @@
Note: This is the change log file for Azure Storage JavaScript Client Library.
2018.04 Version 2.8.100+2.8.2
* Fixed a bug that retry policy will not retry for XHR error in browsers.
* Updated README.md under browser folder to make it more clear about the zip file downloading link.
* Updated github.io API reference title to include JavaScript.
* Updated local HTTP server requirements for IE11 and Chrome 56 in samples and documents.
* Added support for running UT/FT in browsers like Chrome based on Karma, with command `npm run jstest`.
* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.8.2.
2018.03 Version 0.2.8-preview.15
* Supported UMD module standard.
* Dropped `azure-storage.common.js`.
* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.8.1.
2018.02 Version 0.2.8-preview.14
* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.8.0.
+52 -47
View File
@@ -2,47 +2,69 @@
* Join the community discussion on Slack! [![Slack](https://azurestorageslack.azurewebsites.net/badge.svg)]( https://azurestorageslack.azurewebsites.net)
There are 5 generated JavaScript files for Azure Storage JavaScript Client Library:
- `azure-storage.common.js` contains the common part for other 4 JavaScript files.
- `azure-storage.table.js` contains the Azure Storage table service operation logic, which depends on azure-storage.common.js
- `azure-storage.blob.js` contains the Azure Storage blob service operation logic, which depends on azure-storage.common.js
- `azure-storage.queue.js` contains the Azure Storage queue service operation logic, which depends on azure-storage.common.js
- `azure-storage.file.js` contains the Azure Storage file service operation logic, which depends on azure-storage.common.js
## Downloading
We also provide samples to guide you quickly start with the Azure Storage JavaScript Client Library. In the [JavaScript Client Library zip file](https://aka.ms/downloadazurestoragejs) or [azure-storage-node/browser/samples](samples), you will find 4 HTML samples:
- `sample-table.html` demonstrates how to operate with Azure Storage table service in the browser
- `sample-blob.html` demonstrates how to operate with Azure Storage blob service in the browser
- `sample-queue.html` demonstrates how to operate with Azure Storage queue service in the browser
- `sample-file.html` demonstrates how to operate with Azure Storage file service in the browser
It's recommended to use the Azure Storage JavaScript Client Library provided by us. Please [download the latest library](https://aka.ms/downloadazurestoragejs).
There are 8 generated JavaScript files for Azure Storage JavaScript Client Library:
- `azure-storage.blob.js` and `azure-storage.blob.min.js` contain the Azure Storage blob service operation logic
- `azure-storage.table.js` and `azure-storage.table.min.js` contain the Azure Storage table service operation logic
- `azure-storage.queue.js` and `azure-storage.queue.min.js` contain the Azure Storage queue service operation logic
- `azure-storage.file.js` and `azure-storage.file.min.js` contain the Azure Storage file service operation logic
We also provide samples to guide you quickly start with the Azure Storage JavaScript Client Library. In the [JavaScript Client Library zip file](https://aka.ms/downloadazurestoragejs) or following online links, you will find 4 HTML samples:
- [sample-blob.html](https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-blob.html) demonstrates how to operate with Azure Storage blob service in the browser
- [sample-table.html](https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-table.html) demonstrates how to operate with Azure Storage table service in the browser
- [sample-queue.html](https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-queue.html) demonstrates how to operate with Azure Storage queue service in the browser
- [sample-file.html](https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-file.html) demonstrates how to operate with Azure Storage file service in the browser
After generating the JavaScript Client Library, you can try the samples in browsers such as Chrome/Edge/Firefox directly.
**Note**: An HTTP server should be set to host the samples for IE browser.
**Note**: An HTTP server should be set to host the samples for IE11 and Chrome (56 or newer versions).
## Limitations
Or you can directly try with following online samples:
- [sample-blob](https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-blob.html)
- [sample-table](https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-table.html)
- [sample-queue](https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-queue.html)
- [sample-file](https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-file.html)
The Azure Storage JavaScript Client Library is currently in preview stage, there are some known issues or limitations as follows.
## Module Support
### Compatibility
Above JavaScript files are all [UMD compatible](https://github.com/umdjs/umd). You can load them in a CommonJS or AMD environment by JavaScript module loaders. If no module system is found, following global variables will be set:
- `AzureStorage.Blob`
- `AzureStorage.Table`
- `AzureStorage.Queue`
- `AzureStorage.File`
Compatibility with mobile browsers have not been fully validated, please open issues when you get errors. Current validated browsers are as below:
## Compatibility
| Chrome | Firefox | Internet Explorer | Microsoft Edge |
|------------|----------|--------------------|-----------------|
| v64 | v58 | v11 | v41 |
Compatibility with mobile browsers have not been fully validated, please open issues when you get errors.
# Running Tests against Browsers
Running tests against Chrome by default. The Storage Account should be configured with CORS support before running test. Please see above online samples about how to configure CORS rules for an account.
```
set AZURE_STORAGE_CONNECTION_STRING="valid storage connection string"
npm install
npm run jstest
```
## Generating a Custom Azure Storage JavaScript Client Library
If you wish to customize the library and generate the Azure Storage JavaScript Client Library, you can follow the following steps.
We provide browserify bundle scripts which generate Azure Storage JavaScript Client Library. The bundle script reduces the size of the Storage Client Library by splitting into smaller files, one per storage service and a common shared file.
We provide browserify bundle scripts which generate Azure Storage JavaScript Client Library. The bundle script reduces the size of the Storage Client Library by splitting into smaller files, one per storage service.
The generated JavaScript Client Library includes 5 separated JavaScript files:
- `azure-storage.common.js`
- `azure-storage.table.js`
The generated JavaScript Client Library includes 8 separated JavaScript files:
- `azure-storage.blob.js`
- `azure-storage.table.js`
- `azure-storage.queue.js`
- `azure-storage.file.js`
- `azure-storage.blob.min.js`
- `azure-storage.table.min.js`
- `azure-storage.queue.min.js`
- `azure-storage.file.min.js`
Let's get started to generate the Azure Storage JavaScript Client Library!
@@ -73,34 +95,17 @@ npm install
We provide bundle scripts to help quickly generate the JavaScript Client Library. At the root directory of the cloned repo:
```Batchfile
npm run genjs
npm run genjs [VERSION_NUMBER]
```
### Step 4: Finding the Generated JavaScript Files
If everything goes well, the generated JavaScript files should be saved to `azure-storage-node/browser/bundle`. There will be 5 generated JavaScript files totally:
- `azure-storage.common.js`
- `azure-storage.table.js`
If everything goes well, the generated JavaScript files should be saved to `azure-storage-node/browser/bundle`. There will be 8 generated JavaScript files totally:
- `azure-storage.blob.js`
- `azure-storage.table.js`
- `azure-storage.queue.js`
- `azure-storage.file.js`
### Step 5: JavaScript Files Minify
You are able to minify the generated JavaScript files with your favorite minify tools. Here we show the minify process with Node.js minify tool [uglifyJS](https://github.com/mishoo/UglifyJS2).
Install uglifyJS:
```Batchfile
npm install -g uglify-js
```
Minify the JavaScript files:
```Batchfile
uglifyjs --compress --mangle -- azure-storage.common.js > azure-storage.common.min.js
uglifyjs --compress --mangle -- azure-storage.table.js > azure-storage.table.min.js
uglifyjs --compress --mangle -- azure-storage.blob.js > azure-storage.blob.min.js
uglifyjs --compress --mangle -- azure-storage.queue.js > azure-storage.queue.min.js
uglifyjs --compress --mangle -- azure-storage.file.js > azure-storage.file.min.js
```
- `azure-storage.blob.min.js`
- `azure-storage.table.min.js`
- `azure-storage.queue.min.js`
- `azure-storage.file.min.js`
+19 -23
View File
@@ -14,9 +14,7 @@
// limitations under the License.
//
var AzureStorage = window.AzureStorage || {};
AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
module.exports.generateDevelopmentStorageCredentials = function (proxyUri) {
var devStore = 'UseDevelopmentStorage=true;';
if(proxyUri){
devStore += 'DevelopmentStorageProxyUri=' + proxyUri;
@@ -27,18 +25,18 @@ AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
var BlobService = require('../lib/services/blob/blobservice.browser');
AzureStorage.BlobService = BlobService;
AzureStorage.BlobUtilities = require('../lib/services/blob/blobutilities');
module.exports.BlobService = BlobService;
module.exports.BlobUtilities = require('../lib/services/blob/blobutilities');
AzureStorage.createBlobService = function (storageAccountOrConnectionString, storageAccessKey, host) {
module.exports.createBlobService = function (storageAccountOrConnectionString, storageAccessKey, host) {
return new BlobService(storageAccountOrConnectionString, storageAccessKey, host, null);
};
AzureStorage.createBlobServiceWithSas = function (host, sasToken) {
module.exports.createBlobServiceWithSas = function (host, sasToken) {
return new BlobService(null, null, host, sasToken);
};
AzureStorage.createBlobServiceAnonymous = function (host) {
module.exports.createBlobServiceAnonymous = function (host) {
return new BlobService(null, null, host, null);
};
@@ -46,7 +44,7 @@ var azureCommon = require('../lib/common/common.browser');
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKey = azureCommon.SharedKey;
AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
module.exports.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
{
var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey);
var sharedKey = new SharedKey(storageSettings._name, storageSettings._key);
@@ -54,20 +52,18 @@ AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrCon
return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy);
};
AzureStorage.Constants = azureCommon.Constants;
AzureStorage.StorageUtilities = azureCommon.StorageUtilities;
AzureStorage.AccessCondition = azureCommon.AccessCondition;
module.exports.Constants = azureCommon.Constants;
module.exports.StorageUtilities = azureCommon.StorageUtilities;
module.exports.AccessCondition = azureCommon.AccessCondition;
AzureStorage.SR = azureCommon.SR;
AzureStorage.StorageServiceClient = StorageServiceClient;
AzureStorage.Logger = azureCommon.Logger;
AzureStorage.WebResource = azureCommon.WebResource;
AzureStorage.Validate = azureCommon.validate;
AzureStorage.date = azureCommon.date;
module.exports.SR = azureCommon.SR;
module.exports.StorageServiceClient = StorageServiceClient;
module.exports.Logger = azureCommon.Logger;
module.exports.WebResource = azureCommon.WebResource;
module.exports.Validate = azureCommon.validate;
module.exports.date = azureCommon.date;
// Other filters
AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
window.AzureStorage = AzureStorage;
module.exports.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
module.exports.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
module.exports.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
+18 -22
View File
@@ -14,9 +14,7 @@
// limitations under the License.
//
var AzureStorage = window.AzureStorage || {};
AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
module.exports.generateDevelopmentStorageCredentials = function (proxyUri) {
var devStore = 'UseDevelopmentStorage=true;';
if(proxyUri){
devStore += 'DevelopmentStorageProxyUri=' + proxyUri;
@@ -27,14 +25,14 @@ AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
var FileService = require('../lib/services/file/fileservice.browser');
AzureStorage.FileService = FileService;
AzureStorage.FileUtilities = require('../lib/services/file/fileutilities');
module.exports.FileService = FileService;
module.exports.FileUtilities = require('../lib/services/file/fileutilities');
AzureStorage.createFileService = function (storageAccountOrConnectionString, storageAccessKey, host) {
module.exports.createFileService = function (storageAccountOrConnectionString, storageAccessKey, host) {
return new FileService(storageAccountOrConnectionString, storageAccessKey, host);
};
AzureStorage.createFileServiceWithSas = function (hostUri, sasToken) {
module.exports.createFileServiceWithSas = function (hostUri, sasToken) {
return new FileService(null, null, hostUri, sasToken);
};
@@ -42,7 +40,7 @@ var azureCommon = require('../lib/common/common.browser');
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKey = azureCommon.SharedKey;
AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
module.exports.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
{
var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey);
var sharedKey = new SharedKey(storageSettings._name, storageSettings._key);
@@ -50,20 +48,18 @@ AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrCon
return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy);
};
AzureStorage.Constants = azureCommon.Constants;
AzureStorage.StorageUtilities = azureCommon.StorageUtilities;
AzureStorage.AccessCondition = azureCommon.AccessCondition;
module.exports.Constants = azureCommon.Constants;
module.exports.StorageUtilities = azureCommon.StorageUtilities;
module.exports.AccessCondition = azureCommon.AccessCondition;
AzureStorage.SR = azureCommon.SR;
AzureStorage.StorageServiceClient = StorageServiceClient;
AzureStorage.Logger = azureCommon.Logger;
AzureStorage.WebResource = azureCommon.WebResource;
AzureStorage.Validate = azureCommon.validate;
AzureStorage.date = azureCommon.date;
module.exports.SR = azureCommon.SR;
module.exports.StorageServiceClient = StorageServiceClient;
module.exports.Logger = azureCommon.Logger;
module.exports.WebResource = azureCommon.WebResource;
module.exports.Validate = azureCommon.validate;
module.exports.date = azureCommon.date;
// Other filters
AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
window.AzureStorage = AzureStorage;
module.exports.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
module.exports.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
module.exports.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
+19 -23
View File
@@ -14,9 +14,7 @@
// limitations under the License.
//
var AzureStorage = window.AzureStorage || {};
AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
module.exports.generateDevelopmentStorageCredentials = function (proxyUri) {
var devStore = 'UseDevelopmentStorage=true;';
if(proxyUri){
devStore += 'DevelopmentStorageProxyUri=' + proxyUri;
@@ -27,15 +25,15 @@ AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
var QueueService = require('../lib/services/queue/queueservice');
AzureStorage.QueueService = QueueService;
AzureStorage.QueueUtilities = require('../lib/services/queue/queueutilities');
AzureStorage.QueueMessageEncoder = require('../lib/services/queue/queuemessageencoder');
module.exports.QueueService = QueueService;
module.exports.QueueUtilities = require('../lib/services/queue/queueutilities');
module.exports.QueueMessageEncoder = require('../lib/services/queue/queuemessageencoder');
AzureStorage.createQueueService = function (storageAccountOrConnectionString, storageAccessKey, host) {
module.exports.createQueueService = function (storageAccountOrConnectionString, storageAccessKey, host) {
return new QueueService(storageAccountOrConnectionString, storageAccessKey, host);
};
AzureStorage.createQueueServiceWithSas = function(hostUri, sasToken) {
module.exports.createQueueServiceWithSas = function(hostUri, sasToken) {
return new QueueService(null, null, hostUri, sasToken);
};
@@ -43,7 +41,7 @@ var azureCommon = require('../lib/common/common.browser');
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKey = azureCommon.SharedKey;
AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
module.exports.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
{
var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey);
var sharedKey = new SharedKey(storageSettings._name, storageSettings._key);
@@ -51,20 +49,18 @@ AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrCon
return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy);
};
AzureStorage.Constants = azureCommon.Constants;
AzureStorage.StorageUtilities = azureCommon.StorageUtilities;
AzureStorage.AccessCondition = azureCommon.AccessCondition;
module.exports.Constants = azureCommon.Constants;
module.exports.StorageUtilities = azureCommon.StorageUtilities;
module.exports.AccessCondition = azureCommon.AccessCondition;
AzureStorage.SR = azureCommon.SR;
AzureStorage.StorageServiceClient = StorageServiceClient;
AzureStorage.Logger = azureCommon.Logger;
AzureStorage.WebResource = azureCommon.WebResource;
AzureStorage.Validate = azureCommon.validate;
AzureStorage.date = azureCommon.date;
module.exports.SR = azureCommon.SR;
module.exports.StorageServiceClient = StorageServiceClient;
module.exports.Logger = azureCommon.Logger;
module.exports.WebResource = azureCommon.WebResource;
module.exports.Validate = azureCommon.validate;
module.exports.date = azureCommon.date;
// Other filters
AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
window.AzureStorage = AzureStorage;
module.exports.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
module.exports.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
module.exports.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
+20 -24
View File
@@ -14,9 +14,7 @@
// limitations under the License.
//
var AzureStorage = window.AzureStorage || {};
AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
module.exports.generateDevelopmentStorageCredentials = function (proxyUri) {
var devStore = 'UseDevelopmentStorage=true;';
if(proxyUri){
devStore += 'DevelopmentStorageProxyUri=' + proxyUri;
@@ -26,16 +24,16 @@ AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
};
var TableService = require('../lib/services/table/tableservice');
AzureStorage.TableService = TableService;
AzureStorage.TableQuery = require('../lib/services/table/tablequery');
AzureStorage.TableBatch = require('../lib/services/table/tablebatch');
AzureStorage.TableUtilities = require('../lib/services/table/tableutilities');
module.exports.TableService = TableService;
module.exports.TableQuery = require('../lib/services/table/tablequery');
module.exports.TableBatch = require('../lib/services/table/tablebatch');
module.exports.TableUtilities = require('../lib/services/table/tableutilities');
AzureStorage.createTableService = function (storageAccountOrConnectionString, storageAccessKey, host) {
module.exports.createTableService = function (storageAccountOrConnectionString, storageAccessKey, host) {
return new TableService(storageAccountOrConnectionString, storageAccessKey, host);
};
AzureStorage.createTableServiceWithSas = function (hostUri, sasToken) {
module.exports.createTableServiceWithSas = function (hostUri, sasToken) {
return new TableService(null, null, hostUri, sasToken);
};
@@ -43,7 +41,7 @@ var azureCommon = require('../lib/common/common.browser');
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKey = azureCommon.SharedKey;
AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
module.exports.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
{
var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey);
var sharedKey = new SharedKey(storageSettings._name, storageSettings._key);
@@ -51,20 +49,18 @@ AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrCon
return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy);
};
AzureStorage.Constants = azureCommon.Constants;
AzureStorage.StorageUtilities = azureCommon.StorageUtilities;
AzureStorage.AccessCondition = azureCommon.AccessCondition;
module.exports.Constants = azureCommon.Constants;
module.exports.StorageUtilities = azureCommon.StorageUtilities;
module.exports.AccessCondition = azureCommon.AccessCondition;
AzureStorage.SR = azureCommon.SR;
AzureStorage.StorageServiceClient = StorageServiceClient;
AzureStorage.Logger = azureCommon.Logger;
AzureStorage.WebResource = azureCommon.WebResource;
AzureStorage.Validate = azureCommon.validate;
AzureStorage.date = azureCommon.date;
module.exports.SR = azureCommon.SR;
module.exports.StorageServiceClient = StorageServiceClient;
module.exports.Logger = azureCommon.Logger;
module.exports.WebResource = azureCommon.WebResource;
module.exports.Validate = azureCommon.validate;
module.exports.date = azureCommon.date;
// Other filters
AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
window.AzureStorage = AzureStorage;
module.exports.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
module.exports.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
module.exports.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
+46 -19
View File
@@ -15,35 +15,62 @@
//
var browserify = require('browserify');
var factor = require('factor-bundle');
var fs = require('fs');
var path = require('path');
var UglifyJS = require('uglify-js');
var version = process.argv[2] || process.env.AZURE_STORAGE_JAVASCRIPT_VERSION || '';
var license = [
'// Azure Storage JavaScript Client Library ' + version,
'// Copyright (c) Microsoft and contributors. All rights reserved.'
].join('\n') + '\n';
var outputFolder = 'bundle';
var outputFolderPath = path.resolve(__dirname, outputFolder);
console.log('Generating Azure Storage JavaScript Client Library to ' + outputFolderPath + ' ...\n');
console.log('Generating Azure Storage JavaScript Client Library to ' + outputFolderPath + ' ...');
if (version === '') {
console.warn(
'No version number provided.',
'You can set up a version number by first parameter of bundle.js or environment value AZURE_STORAGE_JAVASCRIPT_VERSION'
);
}
if (!fs.existsSync(outputFolderPath)) {
fs.mkdirSync(outputFolderPath);
}
var b = browserify([
path.resolve(__dirname, 'azure-storage.blob.export.js'),
path.resolve(__dirname, 'azure-storage.file.export.js'),
path.resolve(__dirname, 'azure-storage.queue.export.js'),
path.resolve(__dirname, 'azure-storage.table.export.js')
], {require: ['stream', 'util', 'buffer']});
function build(exportFilePath, outputFilePath, moduleName, isMinify) {
browserify(exportFilePath, {standalone: moduleName}).bundle(function (err, src) {
if (err) {
console.error('Failed when parsing', exportFilePath, err);
return;
}
b.plugin(factor, {
outputs: [
path.resolve(outputFolderPath, 'azure-storage.blob.js'),
path.resolve(outputFolderPath, 'azure-storage.file.js'),
path.resolve(outputFolderPath, 'azure-storage.queue.js'),
path.resolve(outputFolderPath, 'azure-storage.table.js')
]
});
var code = (src || '').toString();
if (isMinify) {
result = UglifyJS.minify(code.trim());
if (result.error) {
console.error('Minify failed when parsing', exportFilePath, err);
return;
}
b.bundle().pipe(
fs.createWriteStream(path.resolve(outputFolderPath, 'azure-storage.common.js'))
);
code = result.code;
}
var ws = fs.createWriteStream(outputFilePath);
ws.write(license);
ws.write(code);
ws.end();
});
}
build(path.resolve(__dirname, 'azure-storage.blob.export.js'), path.resolve(outputFolderPath, 'azure-storage.blob.js'), 'AzureStorage.Blob');
build(path.resolve(__dirname, 'azure-storage.table.export.js'), path.resolve(outputFolderPath, 'azure-storage.table.js'), 'AzureStorage.Table');
build(path.resolve(__dirname, 'azure-storage.queue.export.js'), path.resolve(outputFolderPath, 'azure-storage.queue.js'), 'AzureStorage.Queue');
build(path.resolve(__dirname, 'azure-storage.file.export.js'), path.resolve(outputFolderPath, 'azure-storage.file.js'), 'AzureStorage.File');
build(path.resolve(__dirname, 'azure-storage.blob.export.js'), path.resolve(outputFolderPath, 'azure-storage.blob.min.js'), 'AzureStorage.Blob', true);
build(path.resolve(__dirname, 'azure-storage.table.export.js'), path.resolve(outputFolderPath, 'azure-storage.table.min.js'), 'AzureStorage.Table', true);
build(path.resolve(__dirname, 'azure-storage.queue.export.js'), path.resolve(outputFolderPath, 'azure-storage.queue.min.js'), 'AzureStorage.Queue', true);
build(path.resolve(__dirname, 'azure-storage.file.export.js'), path.resolve(outputFolderPath, 'azure-storage.file.min.js'), 'AzureStorage.File', true);
+12 -15
View File
@@ -17,7 +17,7 @@
<div class="panel panel-danger">
<div class="panel-body">
<b>Note</b>: You may need set up a HTTP server to host this sample for IE browser, because IndexedDB is only available on websites with http or https URL schemes in IE. Azure Storage JavaScript Client Library currently depends on IndexedDB.
<b>Note</b>: You may need set up a HTTP server to host this sample for IE11 and latest Chrome.
</div>
</div>
@@ -40,10 +40,9 @@
<h2 id="step2">Step 2: Importing Azure Storage JavaScript Client Library</h2>
<p>
Importing <code>azure-storage.common.js</code> and <code>azure-storage.blob.js</code> in your HTML file for blob operations, and make sure <code>azure-storage.common.js</code> is in front of <code>azure-storage.blob.js</code>.
Importing <code>azure-storage.blob.js</code> in your HTML file for blob operations.
<p>
<pre>
&lt;script src="azure-storage.common.js"&gt;&lt;/script&gt;
&lt;script src="azure-storage.blob.js"&gt;&lt;/script&gt;
</pre>
@@ -54,15 +53,16 @@
</p>
<pre>
var blobUri = 'https://' + 'STORAGE_ACCOUNT' + '.blob.core.windows.net';
var blobService = AzureStorage.createBlobServiceWithSas(blobUri, 'SAS_TOKEN');
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, 'SAS_TOKEN');
</pre>
<p>
In Azure Storage JavaScript Client Library, a global variable <code>AzureStorage</code> is the start point where we can create service objects for blob/table/queue/file and access to the storage utilities.
You can load Azure Storage JavaScript Client Library in a CommonJS or AMD environment by JavaScript module loaders. If no module system is found, global variable <code>AzureStorage.Blob</code> will be set, which is the start point where we can create service objects for blob and access to the storage utilities.
</p>
<div class="panel panel-primary">
<div class="panel-body">
<b>How to get full detailed API definitions? </b> Currently, the JavaScript Client Library shares the same API definitions with Node.js SDK.
Please check API details on <a href="http://azure.github.io/azure-storage-node/">Azure Storage Node.js API reference documents</a>. The JavaScript global variable <code>AzureStorage</code> is just like the object <code>require('azure-storage')</code> returns in Node.js.
<b>How to get full detailed API definitions? </b> Currently, the JavaScript Client Library shares almost the same API definitions with Node.js SDK, besides Node.js runtime specific APIs.
Please check API details on <a href="http://azure.github.io/azure-storage-node/">Azure Storage API reference documents</a>. The JavaScript global variable <code>AzureStorage.Blob</code> is just like the object <code>require('azure-storage')</code> returns in Node.js, but limits to Blob related interfaces.
Go to <a href="https://azure.github.io/azure-storage-node/BlobService.html">BlobService</a> to view possible methods provided by <code>BlobService</code> class.
</div>
</div>
<div class="panel panel-danger">
@@ -264,16 +264,13 @@ blobService.deleteBlobIfExists(container, blob, function(error, result) {
<h3 id="step6">Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library</h3>
<ul>
<li>1. Setting CORS rules for your selected Azure-Storage account blob service.</li>
<li>2. Including "azure-storage.common.js" in the html file.</li>
<li>3. Including functional file(s) needed, such as "azure-storage.blob.js" for blob operation.</li>
<li>4. Using keyword "AzureStorage" to access to Azure storage JavaScript APIs.</li>
<li>5. Referring to <a href="http://azure.github.io/azure-storage-node/">Azure Storage Node.js SDK documents</a> for detailed API definitions which keep same with JavaScript APIs.</li>
<li>2. Including functional file(s) needed, such as "azure-storage.blob.js" for blob operation.</li>
<li>3. Using keyword "AzureStorage.Blob" to access to Azure storage JavaScript APIs for blobs.</li>
<li>4. Referring to <a href="http://azure.github.io/azure-storage-node/">API documents</a> for detailed API definitions.</li>
</ul>
<p> You can view the source code of this sample for detailed reference. </p>
</div>
<!-- azure-storage.common.js also exports Node.js module stream, util and buffer -->
<script src="../bundle/azure-storage.common.js"></script>
<script src="../bundle/azure-storage.blob.js"></script>
<script>
@@ -305,7 +302,7 @@ blobService.deleteBlobIfExists(container, blob, function(error, result) {
return null;
blobUri = 'https://' + account + '.blob.core.windows.net';
var blobService = AzureStorage.createBlobServiceWithSas(blobUri, sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, sas).withFilter(new AzureStorage.Blob.ExponentialRetryPolicyFilter());
return blobService;
}
@@ -366,7 +363,7 @@ blobService.deleteBlobIfExists(container, blob, function(error, result) {
return;
var container = document.getElementById('newcontainer').value;
if (!AzureStorage.Validate.containerNameIsValid(container, function(err, res){})) {
if (!AzureStorage.Blob.Validate.containerNameIsValid(container, function(err, res){})) {
alert('Invalid container name!');
return;
}
+12 -14
View File
@@ -18,7 +18,7 @@
<div class="panel panel-danger">
<div class="panel-body">
<b>Note</b>: You may need set up a HTTP server to host this sample for IE browser, because IndexedDB is only available on websites with http or https URL schemes in IE. Azure Storage JavaScript Client Library currently depends on IndexedDB.
<b>Note</b>: You may need set up a HTTP server to host this sample for IE11 and latest Chrome.
</div>
</div>
@@ -41,10 +41,9 @@
<h2 id="step2">Step 2: Importing Azure Storage JavaScript Files</h2>
<p>
Importing <code>azure-storage.common.js</code> and <code>azure-storage.file.js</code> in your HTML file for file operations, and make sure <code>azure-storage.common.js</code> is in front of <code>azure-storage.file.js</code>.
Importing <code>azure-storage.file.js</code> in your HTML file for file operations.
<p>
<pre>
&lt;script src="azure-storage.common.js"&gt;&lt;/script&gt;
&lt;script src="azure-storage.file.js"&gt;&lt;/script&gt;
</pre>
@@ -55,15 +54,16 @@
</p>
<pre>
var fileUri = 'https://' + 'STORAGE_ACCOUNT' + '.file.core.windows.net';
var fileService = AzureStorage.createFileServiceWithSas(fileUri, 'SAS_TOKEN');
var fileService = AzureStorage.File.createFileServiceWithSas(fileUri, 'SAS_TOKEN');
</pre>
<p>
In Azure Storage JavaScript Client Library, a global variable <code>AzureStorage</code> is the start point where we can create service objects for blob/table/queue/file and access to the storage utilities.
You can load Azure Storage JavaScript Client Library in a CommonJS or AMD environment by JavaScript module loaders. If no module system is found, global variable <code>AzureStorage.File</code> will be set, which is the start point where we can create service objects for file and access to the storage utilities.
</p>
<div class="panel panel-primary">
<div class="panel-body">
<b>How to get full detailed API definitions? </b> Currently, the JavaScript Client Library shares the same API definitions with Node.js SDK.
Please check API details on <a href="http://azure.github.io/azure-storage-node/">Azure Storage Node.js API reference documents</a>. The JavaScript global variable <code>AzureStorage</code> is just like the object <code>require('azure-storage')</code> returns in Node.js.
<b>How to get full detailed API definitions? </b> Currently, the JavaScript Client Library shares almost the same API definitions with Node.js SDK, besides Node.js runtime specific APIs.
Please check API details on <a href="http://azure.github.io/azure-storage-node/">Azure Storage API reference documents</a>. The JavaScript global variable <code>AzureStorage.File</code> is just like the object <code>require('azure-storage')</code> returns in Node.js, but limits to File related interfaces.
Go to <a href="https://azure.github.io/azure-storage-node/FileService.html">FileService</a> to view possible methods provided by <code>FileService</code> class.
</div>
</div>
<div class="panel panel-danger">
@@ -265,15 +265,13 @@ fileService.deleteFileIfExists('myfileshare', 'mydirectory', 'myfile', function(
<h3 id="step6">Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library</h3>
<ul>
<li>1. Setting CORS rules for your selected Azure-Storage account file service.</li>
<li>2. Including "azure-storage.common.js" in the html file.</li>
<li>3. Including functional file(s) needed, such as "azure-storage.file.js" for file operation.</li>
<li>4. Using keyword "AzureStorage" to access to Azure storage JavaScript APIs.</li>
<li>5. Referring to <a href="http://azure.github.io/azure-storage-node/">Azure Storage Node.js SDK documents</a> for detailed API definitions which keep same with JavaScript APIs.</li>
<li>2. Including functional file(s) needed, such as "azure-storage.file.js" for file operation.</li>
<li>3. Using keyword "AzureStorage.File" to access to Azure storage JavaScript APIs for files.</li>
<li>4. Referring to <a href="http://azure.github.io/azure-storage-node/">API documents</a> for detailed API definitions.</li>
</ul>
<p> You can view the source code of this sample for detailed reference. </p>
</div>
<script src="../bundle/azure-storage.common.js"></script>
<script src="../bundle/azure-storage.file.js"></script>
<script>
@@ -307,7 +305,7 @@ fileService.deleteFileIfExists('myfileshare', 'mydirectory', 'myfile', function(
return null;
fileUri = 'https://' + account + '.file.core.windows.net';
var fileService = AzureStorage.createFileServiceWithSas(fileUri, sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
var fileService = AzureStorage.File.createFileServiceWithSas(fileUri, sas).withFilter(new AzureStorage.File.ExponentialRetryPolicyFilter());
return fileService;
}
@@ -371,7 +369,7 @@ fileService.deleteFileIfExists('myfileshare', 'mydirectory', 'myfile', function(
return;
var share = document.getElementById('newfileshare').value;
if (!AzureStorage.Validate.shareNameIsValid(share, function(err, res){})) {
if (!AzureStorage.File.Validate.shareNameIsValid(share, function(err, res){})) {
alert('Invalid share name!');
return;
}
+16 -19
View File
@@ -19,7 +19,7 @@
<div class="panel panel-danger">
<div class="panel-body">
<b>Note</b>: You may need set up a HTTP server to host this sample for IE browser, because IndexedDB is only available on websites with http or https URL schemes in IE. Azure Storage JavaScript Client Library currently depends on IndexedDB.
<b>Note</b>: You may need set up a HTTP server to host this sample for IE11 and latest Chrome.
</div>
</div>
@@ -42,10 +42,9 @@
<h2 id="step2">Step 2: Importing Azure Storage JavaScript Client Library</h2>
<p>
Importing <code>azure-storage.common.js</code> and <code>azure-storage.queue.js</code> in your HTML file for queue operations, and make sure <code>azure-storage.common.js</code> is in front of <code>azure-storage.queue.js</code>.
Importing <code>azure-storage.queue.js</code> in your HTML file for queue operations.
<p>
<pre>
&lt;script src="azure-storage.common.js"&gt;&lt;/script&gt;
&lt;script src="azure-storage.queue.js"&gt;&lt;/script&gt;
</pre>
@@ -56,15 +55,16 @@
</p>
<pre>
var queueUri = 'https://' + 'STORAGE_ACCOUNT' + '.queue.core.windows.net';
var queueService = AzureStorage.createQueueServiceWithSas(queueUri, 'SAS_TOKEN');
var queueService = AzureStorage.Queue.createQueueServiceWithSas(queueUri, 'SAS_TOKEN');
</pre>
<p>
In Azure Storage JavaScript Client Library, a global variable <code>AzureStorage</code> is the start point where we can create service objects for blob/table/queue/file and access to the storage utilities.
You can load Azure Storage JavaScript Client Library in a CommonJS or AMD environment by JavaScript module loaders. If no module system is found, global variable <code>AzureStorage.Queue</code> will be set, which is the start point where we can create service objects for queue and access to the storage utilities.
</p>
<div class="panel panel-primary">
<div class="panel-body">
<b>How to get full detailed API definitions? </b> Currently, the JavaScript Client Library shares the same API definitions with Node.js SDK.
Please check API details on <a href="http://azure.github.io/azure-storage-node/">Azure Storage Node.js API reference documents</a>. The JavaScript global variable <code>AzureStorage</code> is just like the object <code>require('azure-storage')</code> returns in Node.js.
<b>How to get full detailed API definitions? </b> Currently, the JavaScript Client Library shares almost the same API definitions with Node.js SDK, besides Node.js runtime specific APIs.
Please check API details on <a href="http://azure.github.io/azure-storage-node/">Azure Storage API reference documents</a>. The JavaScript global variable <code>AzureStorage.Queue</code> is just like the object <code>require('azure-storage')</code> returns in Node.js, but limits to Queue related interfaces.
Go to <a href="https://azure.github.io/azure-storage-node/QueueService.html">QueueService</a> to view possible methods provided by <code>QueueService</code> class.
</div>
</div>
<div class="panel panel-danger">
@@ -136,7 +136,7 @@ queueService.deleteQueueIfExists('myqueue', function(error, result) {
<p> A storage <b>Message</b>, in any format, of up to 64 KB. The maximum time that a message can remain in the queue is 7 days.</p>
<div class="panel panel-primary">
<div class="panel-body">
<b>Note: </b> Azure Storage JavaScript Client Library provides <code>var encoder = new AzureStorage.QueueMessageEncoder.TextBase64QueueMessageEncoder()</code> which is a Base64 encoder and docoder.
<b>Note: </b> Azure Storage JavaScript Client Library provides <code>var encoder = new AzureStorage.Queue.QueueMessageEncoder.TextBase64QueueMessageEncoder()</code> which is a Base64 encoder and docoder.
If a message content string is encoded with <code>encoder.encode()</code>, remember to decode it with <code>encoder.decode()</code> after peek the message.
</div>
</div>
@@ -158,7 +158,7 @@ queueService.peekMessages('myqueue', {numOfMessages: 32}, function (error, resul
<h3>Create Message</h3>
<p><code>QueueService</code> provides <code>createMessage</code> for creating a new message to a queue.</p>
<pre>
var encoder = new AzureStorage.QueueMessageEncoder.TextBase64QueueMessageEncoder();
var encoder = new AzureStorage.Queue.QueueMessageEncoder.TextBase64QueueMessageEncoder();
queueService.createMessage('myqueue', encoder.encode('mymessage'), function (error, results, response) {
if (error) {
// Create message error
@@ -187,7 +187,7 @@ queueService.getMessages('myqueue', function(error, result, response) {
<h3>Update Message</h3>
<p><code>QueueService</code> provides <code>getMessages</code> and <code>updateMessage</code> for updating next message in a queue.</p>
<pre>
var encoder = new AzureStorage.QueueMessageEncoder.TextBase64QueueMessageEncoder();
var encoder = new AzureStorage.Queue.QueueMessageEncoder.TextBase64QueueMessageEncoder();
queueService.getMessages('myqueue', function(error, result, response) {
if(!error){
// Got the message
@@ -219,23 +219,20 @@ queueService.getMessages('myqueue', function(error, result, response) {
<h2 id="step6">Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library</h2>
<ul>
<li>1. Setting CORS rules for your selected Azure-Storage account queue service.</li>
<li>2. Including "azure-storage.common.js" in the html file.</li>
<li>3. Including functional file(s) needed, such as "azure-storage.queue.js" for queue operation.</li>
<li>4. Using keyword "AzureStorage" to access to Azure storage JavaScript APIs.</li>
<li>5. Referring to <a href="http://azure.github.io/azure-storage-node/">Azure Storage Node.js SDK documents</a> for detailed API definitions which keep same with JavaScript APIs.</li>
<li>2. Including functional file(s) needed, such as "azure-storage.queue.js" for queue operation.</li>
<li>3. Using keyword "AzureStorage.Queue" to access to Azure storage JavaScript APIs for queues.</li>
<li>4. Referring to <a href="http://azure.github.io/azure-storage-node/">API documents</a> for detailed API definitions.</li>
</ul>
<p> You can view the source code of this sample for detailed reference. </p>
</div>
<!-- azure-storage.common.js also exports Node.js module stream, util and buffer -->
<script src="../bundle/azure-storage.common.js"></script>
<script src="../bundle/azure-storage.queue.js"></script>
<script>
var account = document.getElementById('account').value;
var sas = document.getElementById('sas').value;
var queue = '';
var queueUri = '';
var encoder = new AzureStorage.QueueMessageEncoder.TextBase64QueueMessageEncoder();
var encoder = new AzureStorage.Queue.QueueMessageEncoder.TextBase64QueueMessageEncoder();
function checkParameters() {
account = document.getElementById('account').value;
@@ -260,7 +257,7 @@ queueService.getMessages('myqueue', function(error, result, response) {
return null;
queueUri = 'https://' + account + '.queue.core.windows.net';
var queueService = AzureStorage.createQueueServiceWithSas(queueUri, sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
var queueService = AzureStorage.Queue.createQueueServiceWithSas(queueUri, sas).withFilter(new AzureStorage.Queue.ExponentialRetryPolicyFilter());
return queueService;
}
@@ -304,7 +301,7 @@ queueService.getMessages('myqueue', function(error, result, response) {
return;
var queue = document.getElementById('newqueue').value;
if (!AzureStorage.Validate.queueNameIsValid(queue, function(err, res){})) {
if (!AzureStorage.Queue.Validate.queueNameIsValid(queue, function(err, res){})) {
alert('Invalid queue name!');
return;
}
+14 -17
View File
@@ -19,7 +19,7 @@
<div class="panel panel-danger">
<div class="panel-body">
<b>Note</b>: You may need set up a HTTP server to host this sample for IE browser, because IndexedDB is only available on websites with http or https URL schemes in IE. Azure Storage JavaScript Client Library currently depends on IndexedDB.
<b>Note</b>: You may need set up a HTTP server to host this sample for IE11 and latest Chrome.
</div>
</div>
@@ -42,10 +42,9 @@
<h2 id="step2">Step 2: Importing Azure Storage JavaScript Client Library</h2>
<p>
Importing <code>azure-storage.common.js</code> and <code>azure-storage.table.js</code> in your HTML file for table operations, and make sure <code>azure-storage.common.js</code> is in front of <code>azure-storage.table.js</code>.
Importing <code>azure-storage.table.js</code> in your HTML file for table operations.
<p>
<pre>
&lt;script src="azure-storage.common.js"&gt;&lt;/script&gt;
&lt;script src="azure-storage.table.js"&gt;&lt;/script&gt;
</pre>
@@ -56,15 +55,16 @@
</p>
<pre>
var tableUri = 'https://' + 'STORAGE_ACCOUNT' + '.table.core.windows.net';
var tableService = AzureStorage.createTableServiceWithSas(tableUri, 'SAS_TOKEN');
var tableService = AzureStorage.Table.createTableServiceWithSas(tableUri, 'SAS_TOKEN');
</pre>
<p>
In Azure Storage JavaScript Client Library, a global variable <code>AzureStorage</code> is the start point where we can create service objects for blob/table/queue/file and access to the storage utilities.
You can load Azure Storage JavaScript Client Library in a CommonJS or AMD environment by JavaScript module loaders. If no module system is found, global variable <code>AzureStorage.Table</code> will be set, which is the start point where we can create service objects for table and access to the storage utilities.
</p>
<div class="panel panel-primary">
<div class="panel-body">
<b>How to get full detailed API definitions? </b> Currently, the JavaScript Client Library shares the same API definitions with Node.js SDK.
Please check API details on <a href="http://azure.github.io/azure-storage-node/">Azure Storage Node.js API reference documents</a>. The JavaScript global variable <code>AzureStorage</code> is just like the object <code>require('azure-storage')</code> returns in Node.js.
<b>How to get full detailed API definitions? </b> Currently, the JavaScript Client Library shares almost the same API definitions with Node.js SDK, besides Node.js runtime specific APIs.
Please check API details on <a href="http://azure.github.io/azure-storage-node/">Azure Storage API reference documents</a>. The JavaScript global variable <code>AzureStorage.Table</code> is just like the object <code>require('azure-storage')</code> returns in Node.js, but limits to Table related interfaces.
Go to <a href="https://azure.github.io/azure-storage-node/TableService.html">TableService</a> to view possible methods provided by <code>TableService</code> class.
</div>
</div>
<div class="panel panel-danger">
@@ -139,7 +139,7 @@ tableService.deleteTableIfExists('mytable', function(error, result) {
<h3>Query Entities</h3>
<p><code>TableService</code> provides <code>queryEntities</code> for querying a table under a storage account.</p>
<pre>
var tableQuery = new AzureStorage.TableQuery().top(200);
var tableQuery = new AzureStorage.Table.TableQuery().top(200);
tableService.queryEntities('mytable', tableQuery, null, function(error, result) {
if (error) {
// Query entities error
@@ -204,16 +204,13 @@ tableService.deleteEntity('mytable', deleteEntity, function(error, result, respo
<h3 id="step6">Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library</h3>
<ul>
<li>1. Setting CORS rules for your selected Azure-Storage account table service.</li>
<li>2. Including "azure-storage.common.js" in the html file.</li>
<li>3. Including functional file(s) needed, such as "azure-storage.table.js" for table operation.</li>
<li>4. Using keyword "AzureStorage" to access to Azure storage JavaScript APIs.</li>
<li>5. Referring to <a href="http://azure.github.io/azure-storage-node/">Azure Storage Node.js SDK documents</a> for detailed API definitions which keep same with JavaScript APIs.</li>
<li>2. Including functional file(s) needed, such as "azure-storage.table.js" for table operation.</li>
<li>3. Using keyword "AzureStorage.Table" to access to Azure storage JavaScript APIs for tables.</li>
<li>4. Referring to <a href="http://azure.github.io/azure-storage-node/">API documents</a> for detailed API definitions.</li>
</ul>
<p> You can view the source code of this sample for detailed reference. </p>
</div>
<!-- azure-storage.common.js also exports Node.js module stream, util and buffer -->
<script src="../bundle/azure-storage.common.js"></script>
<script src="../bundle/azure-storage.table.js"></script>
<script>
@@ -245,7 +242,7 @@ tableService.deleteEntity('mytable', deleteEntity, function(error, result, respo
return null;
tableUri = 'https://' + account + '.table.core.windows.net';
var tableService = AzureStorage.createTableServiceWithSas(tableUri, sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
var tableService = AzureStorage.Table.createTableServiceWithSas(tableUri, sas).withFilter(new AzureStorage.Table.ExponentialRetryPolicyFilter());
return tableService;
}
@@ -287,7 +284,7 @@ tableService.deleteEntity('mytable', deleteEntity, function(error, result, respo
return;
var table = document.getElementById('newtable').value;
if (!AzureStorage.Validate.tableNameIsValid(table, function(err, res){})) {
if (!AzureStorage.Table.Validate.tableNameIsValid(table, function(err, res){})) {
alert('Invalid table name!');
return;
}
@@ -335,7 +332,7 @@ tableService.deleteEntity('mytable', deleteEntity, function(error, result, respo
}
document.getElementById('result').innerHTML = 'Loading table entities...';
var tableQuery = new AzureStorage.TableQuery().top(200);
var tableQuery = new AzureStorage.Table.TableQuery().top(200);
tableService.queryEntities(table, tableQuery, null, function(error, results) {
if (error) {
alert('List table entities error, please open browser console to view detailed error');
+411
View File
@@ -0,0 +1,411 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// 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 assert = require('assert');
var TestSuite = require('../../../test/framework/test-suite');
var testUtil = require('../../../test/framework/util');
var suite = new TestSuite('blobservice-upload-browser');
if (testUtil.isBrowser()) {
var azure = AzureStorage.Blob;
var containerNamesPrefix = 'upload-test-container-';
var blobNamesPrefix = 'upload-teset-blob-';
var containerName;
var blobName;
describe('BlobServiceUpload', function () {
before(function (done) {
blobService = azure.createBlobService(process.env['AZURE_STORAGE_CONNECTION_STRING']);
assert.notEqual(null, blobService, 'blobService should not be null');
containerName = suite.getName(containerNamesPrefix);
blobService.createContainerIfNotExists(containerName, function (err) {
assert.equal(err, null);
done();
});
});
after(function (done) {
blobService.deleteContainerIfExists(containerName, function (err) {
assert.equal(err, null);
done();
});
});
beforeEach(function () {
blobName = suite.getName(blobNamesPrefix);
});
afterEach(function () {
});
describe('createBlockBlobFromBrowserFile', function () {
it('upload block blob with invalid type should not work', function () {
try {
blobService.createBlockBlobFromBrowserFile(containerName, blobName, 'abcde', function (err, res, resp) { });
} catch (e) {
assert.notEqual(e, null);
}
});
it('upload block blob with md5 calculation should work', function (done) {
var size = 7 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, { storeBlobContentMD5: true }, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
assert.notEqual(res.contentSettings.contentMD5, null);
done();
});
});
});
it('upload block blob with 0 bytes should work', function (done) {
var size = 0;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.blobType, AzureStorage.Blob.Constants.BlobConstants.BlobTypes.BLOCK);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('upload block blob with 4 * 1024 * 1024 - 1 bytes should work', function (done) {
var size = 4 * 1024 * 1024 - 1;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('upload block blob with 4 * 1024 * 1024 bytes should work', function (done) {
var size = 4 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('upload block blob with 4 * 1024 * 1024 + 1 bytes should work', function (done) {
var size = 4 * 1024 * 1024 + 1;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('upload block blob with 128 * 1024 * 1024 bytes should work', function (done) {
var size = 128 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
});
describe('createPageBlobFromBrowserFile', function () {
it('upload page blob with invalid type should not work', function () {
try {
blobService.createPageBlobFromBrowserFile(containerName, blobName, 'abcde', function (err, res, resp) { });
} catch (e) {
assert.notEqual(e, null);
}
});
it('upload page blob with md5 calculation should work', function (done) {
var size = 3 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createPageBlobFromBrowserFile(containerName, blobName, file, { storeBlobContentMD5: true }, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
assert.notEqual(res.contentSettings.contentMD5, null);
done();
});
});
});
it('upload page blob with 0 bytes should work', function (done) {
var file = testUtil.getBrowserFile(blobName, 0);
blobService.createPageBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.blobType, AzureStorage.Blob.Constants.BlobConstants.BlobTypes.PAGE);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, 0);
done();
});
});
});
it('upload page blob with 4 * 1024 * 1024 - 1 bytes should not work', function () {
var size = 4 * 1024 * 1024 - 1;
var file = testUtil.getBrowserFile(blobName, size);
try {
blobService.createPageBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { });
} catch (e) {
assert.notEqual(e, null);
}
});
it('upload page blob with 4 * 1024 * 1024 bytes should work', function (done) {
var size = 4 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createPageBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('upload page blob with 128 * 1024 * 1024 bytes should work', function (done) {
var size = 128 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createPageBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
});
describe('createAppendBlobFromBrowserFile', function () {
it('upload append blob with invalid type should not work', function () {
try {
blobService.createAppendBlobFromBrowserFile(containerName, blobName, 'abcde', function (err, res, resp) { });
} catch (e) {
assert.notEqual(e, null);
}
});
it('upload append blob with md5 calculation should work', function (done) {
var size = 7 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, { storeBlobContentMD5: true }, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
assert.notEqual(res.contentSettings.contentMD5, null);
done();
});
});
});
it('upload append blob with 0 bytes should work', function (done) {
var file = testUtil.getBrowserFile(blobName, 0);
blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.blobType, AzureStorage.Blob.Constants.BlobConstants.BlobTypes.APPEND);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, 0);
done();
});
});
});
it('upload append blob with 4 * 1024 * 1024 - 1 bytes should work', function (done) {
var size = 4 * 1024 * 1024 - 1;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('upload append blob with 4 * 1024 * 1024 bytes should work', function (done) {
var size = 4 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('upload append blob with 4 * 1024 * 1024 + 1 bytes should work', function (done) {
var size = 4 * 1024 * 1024 + 1;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('upload append blob with 128 * 1024 * 1024 bytes should work', function (done) {
var size = 128 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
});
describe('appendFromBrowserFile', function () {
beforeEach(function (done) {
var size = 2 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('append blob with 0 bytes should work', function (done) {
var file = testUtil.getBrowserFile(blobName, 0);
blobService.appendFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.blobType, AzureStorage.Blob.Constants.BlobConstants.BlobTypes.APPEND);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, 2 * 1024 * 1024);
done();
});
});
});
it('append blob with 4 * 1024 * 1024 - 1 bytes should work', function (done) {
var size = 4 * 1024 * 1024 - 1;
var file = testUtil.getBrowserFile(blobName, size);
blobService.appendFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size + 2 * 1024 * 1024);
done();
});
});
});
it('append blob with 4 * 1024 * 1024 bytes should work', function (done) {
var size = 4 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.appendFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size + 2 * 1024 * 1024);
done();
});
});
});
it('append blob with 4 * 1024 * 1024 + 1 bytes should work', function (done) {
var size = 4 * 1024 * 1024 + 1;
var file = testUtil.getBrowserFile(blobName, size);
blobService.appendFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size + 2 * 1024 * 1024);
done();
});
});
});
it('append blob with 128 * 1024 * 1024 bytes should work', function (done) {
var size = 128 * 1024 * 1024;
var file = testUtil.getBrowserFile(blobName, size);
blobService.appendFromBrowserFile(containerName, blobName, file, function (err, res, resp) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, blobName);
assert.equal(res.contentLength, size + 2 * 1024 * 1024);
done();
});
});
});
});
});
}
+62
View File
@@ -0,0 +1,62 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// 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 browserify = require('browserify');
var fs = require('fs');
var path = require('path');
var bs = browserify([
path.resolve(__dirname, '../../test/services/queue/queueservice-tests.js'),
path.resolve(__dirname, '../../test/services/table/tablebatch-tests.js'),
path.resolve(__dirname, '../../test/services/table/tabledatatype-tests.js'),
path.resolve(__dirname, '../../test/services/table/tablepayload-tests.js'),
path.resolve(__dirname, '../../test/services/table/tablequery-tests.js'),
path.resolve(__dirname, '../../test/services/table/tableservice-gb-tests.js'),
path.resolve(__dirname, '../../test/services/table/tableservice-tests.js'),
path.resolve(__dirname, '../../test/services/blob/blobservice-archive-tests.js'),
path.resolve(__dirname, '../../test/services/blob/blobservice-container-tests.js'),
path.resolve(__dirname, '../../test/services/blob/blobservice-lease-tests.js'),
path.resolve(__dirname, '../../test/services/blob/blobservice-sse-tests.js'),
path.resolve(__dirname, '../../test/services/blob/blobservice-tests.js'),
path.resolve(__dirname, '../../test/services/blob/blobservice-uploaddownload-tests.js'),
path.resolve(__dirname, '../../test/services/file/fileservice-directory-tests.js'),
path.resolve(__dirname, '../../test/services/file/fileservice-file-tests.js'),
path.resolve(__dirname, '../../test/services/file/fileservice-share-tests.js'),
path.resolve(__dirname, '../../test/services/file/fileservice-sharesnapshot-tests.js'),
path.resolve(__dirname, '../../test/services/file/fileservice-sse-tests.js'),
path.resolve(__dirname, '../../test/services/file/fileservice-tests.js'),
path.resolve(__dirname, '../../test/services/file/fileservice-uploaddownload-tests.js'),
path.resolve(__dirname, '../../test/common/connectionstringparsertests.js'),
path.resolve(__dirname, '../../test/common/secondarytests.js'),
path.resolve(__dirname, '../../test/common/servicesettingstests.js'),
path.resolve(__dirname, '../../test/common/servicestatstests.js'),
path.resolve(__dirname, '../../test/common/sharedkey-tests.js'),
path.resolve(__dirname, '../../test/common/storageserviceclienttests.js'),
path.resolve(__dirname, '../../test/common/storageservicesettingstests.js'),
path.resolve(__dirname, '../../test/common/filters/exponentialretrypolicyfilter-tests.js'),
path.resolve(__dirname, '../../test/common/filters/linearretrypolicyfilter-tests.js'),
path.resolve(__dirname, '../../test/common/util/iso8061date-tests.js'),
path.resolve(__dirname, '../../test/common/util/util-tests.js'),
path.resolve(__dirname, '../../test/common/util/validate-tests.js'),
path.resolve(__dirname, '../../test/azure-tests.js'),
path.resolve(__dirname, '../../test/accountsas-tests.js'),
path.resolve(__dirname, './file/fileservice-upload.js'),
path.resolve(__dirname, './blob/blobservice-upload.js')
], { require: ['https'] }).bundle();
bs.pipe(
fs.createWriteStream(path.resolve(__dirname, './browser.tests.bundled.js'))
);
+155
View File
@@ -0,0 +1,155 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// 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 assert = require('assert');
var TestSuite = require('../../../test/framework/test-suite');
var testUtil = require('../../../test/framework/util');
var suite = new TestSuite('fileservice-upload-browser');
if (testUtil.isBrowser()) {
var azure = AzureStorage.File;
var shareNamesPrefix = 'upload-test-share-';
var fileNamesPrefix = 'upload-test-file-';
var shareName;
var fileName;
describe('FileServiceUpload', function () {
before(function (done) {
fileService = azure.createFileService(process.env['AZURE_STORAGE_CONNECTION_STRING']);
assert.notEqual(null, fileService, 'FileService should not be null');
shareName = suite.getName(shareNamesPrefix);
fileService.createShareIfNotExists(shareName, function (err) {
assert.equal(err, null);
done();
});
});
after(function (done) {
fileService.deleteShareIfExists(shareName, function (err) {
assert.equal(err, null);
done();
});
});
beforeEach(function () {
fileName = suite.getName(fileNamesPrefix);
});
afterEach(function (done) {
fileService.deleteFileIfExists(shareName, '', fileName, function (err) {
assert.equal(err, null);
done();
});
});
describe('createFileFromBrowserFile', function () {
it('upload file with invalid type should not work', function () {
try {
fileService.createFileFromBrowserFile(shareName, '', fileName, 'abcde', function (err, res, resp) {});
} catch (e) {
assert.notEqual(e, null);
}
});
it('upload file with md5 calculation should work', function (done) {
var size = 33 * 1024 * 1024;
var file = testUtil.getBrowserFile(fileName, size);
fileService.createFileFromBrowserFile(shareName, '', fileName, file, { storeFileContentMD5: true}, function (err, res, resp) {
assert.equal(err, null);
fileService.getFileProperties(shareName, '', fileName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, fileName);
assert.equal(res.contentLength, size);
assert.notEqual(res.contentSettings.contentMD5, null);
done();
});
});
});
it('upload file with 0 bytes should work', function (done) {
var file = testUtil.getBrowserFile(fileName, 0);
fileService.createFileFromBrowserFile(shareName, '', fileName, file, function (err, res, resp) {
assert.equal(err, null);
fileService.getFileProperties(shareName, '', fileName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, fileName);
assert.equal(res.contentLength, 0);
done();
});
});
});
it('upload file with 4 * 1024 * 1024 - 1 bytes should work', function (done) {
var size = 4 * 1024 * 1024 - 1;
var file = testUtil.getBrowserFile(fileName, size);
fileService.createFileFromBrowserFile(shareName, '', fileName, file, function (err, res, resp) {
assert.equal(err, null);
fileService.getFileProperties(shareName, '', fileName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, fileName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('upload file with 4 * 1024 * 1024 bytes should work', function (done) {
var size = 4 * 1024 * 1024;
var file = testUtil.getBrowserFile(fileName, size);
fileService.createFileFromBrowserFile(shareName, '', fileName, file, function (err, res, resp) {
assert.equal(err, null);
fileService.getFileProperties(shareName, '', fileName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, fileName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('upload file with 4 * 1024 * 1024 + 1 bytes should work', function (done) {
var size = 4 * 1024 * 1024 + 1;
var file = testUtil.getBrowserFile(fileName, size);
fileService.createFileFromBrowserFile(shareName, '', fileName, file, function (err, res, resp) {
assert.equal(err, null);
fileService.getFileProperties(shareName, '', fileName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, fileName);
assert.equal(res.contentLength, size);
done();
});
});
});
it('upload file with 128 * 1024 * 1024 bytes should work', function (done) {
var size = 128 * 1024 * 1024;
var file = testUtil.getBrowserFile(fileName, size);
fileService.createFileFromBrowserFile(shareName, '', fileName, file, function (err, res, resp) {
assert.equal(err, null);
fileService.getFileProperties(shareName, '', fileName, function (err, res) {
assert.equal(err, null);
assert.equal(res.name, fileName);
assert.equal(res.contentLength, size);
done();
});
});
});
});
});
}
+1 -1
View File
@@ -10,7 +10,7 @@
"dateFormat" : "ddd MMM Do YYYY",
"outputSourceFiles" : true,
"outputSourcePath" : true,
"systemName" : "Microsoft Azure Storage Client Library for node.js",
"systemName" : "Microsoft Azure Storage Client Library for Node.js and JavaScript",
"footer" : "",
"navType" : "vertical",
"theme" : "cosmo",
+90
View File
@@ -0,0 +1,90 @@
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],
plugins: [
'karma-mocha',
'karma-mocha-reporter',
'karma-chrome-launcher',
'karma-edge-launcher',
'karma-firefox-launcher',
'karma-ie-launcher',
'karma-env-preprocessor'
],
// list of files / patterns to load in the browser
files: [
'browser/bundle/azure-storage.blob.js',
'browser/bundle/azure-storage.table.js',
'browser/bundle/azure-storage.queue.js',
'browser/bundle/azure-storage.file.js',
'browser/test/browser.tests.bundled.js'
],
// list of files / patterns to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'**/*.js': ['env'],
},
// inject following environment values into browser testing with window.__env__
// environment values MUST be exported or set with same console running "karma start"
// https://www.npmjs.com/package/karma-env-preprocessor
envPreprocessor: [
'AZURE_STORAGE_CONNECTION_STRING',
'AZURE_STORAGE_CONNECTION_STRING_SSE_ENABLED_ACCOUNT',
'AZURE_STORAGE_CONNECTION_STRING_BLOB_ACCOUNT',
'AZURE_STORAGE_CONNECTION_STRING_PREMIUM_ACCOUNT'
],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
// 'Chrome', 'Firefox', 'Edge', 'IE'
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: 1,
browserNoActivityTimeout: 600000,
client: {
mocha: {
// change Karma's debug.html to the mocha web reporter
reporter: 'html',
timeout: '600000'
}
}
})
}
+2 -1
View File
@@ -138,7 +138,8 @@ RetryPolicyFilter._handle = function (self, requestOptions, next) {
returnObject.error.code === 'ETIMEDOUT' ||
returnObject.error.code === 'ESOCKETTIMEDOUT' ||
returnObject.error.code === 'ECONNRESET' ||
returnObject.error.code === 'EAI_AGAIN'
returnObject.error.code === 'EAI_AGAIN' ||
returnObject.error.message === 'XHR error' // stream-http XHR network error message in browsers
)
)
) {
+1 -1
View File
@@ -53,7 +53,7 @@ function SharedKey(storageAccount, storageAccessKey, usePathStyleUri) {
* @param {SharedAccessServices} sharedAccessPolicy.AccessPolicy.Services The services (blob, file, queue, table) for a shared access signature associated with this shared access policy.
* Refer to `Constants.AccountSasConstants.Services`.
* @param {SharedAccessResourceTypes} sharedAccessPolicy.AccessPolicy.ResourceTypes The resource type for a shared access signature associated with this shared access policy.
* Refer to `Constants.AccountSasConstants.ResourceTypes`.
* Refer to `Constants.AccountSasConstants.Resources`.
* @param {SharedAccessPermissions} sharedAccessPolicy.AccessPolicy.Permissions The permissions for a shared access signature.
* Refer to `Constants.AccountSasConstants.Permissions`.
* @param {date} sharedAccessPolicy.AccessPolicy.Start The time at which the Shared Access Signature becomes valid.
+1 -1
View File
@@ -244,7 +244,7 @@ FileReadStream.prototype.destroy = function () {
}
// when the stream is closed immediately after creating it
if (!validator.isInt(this._fd)) {
if (!validator.isInt('' + this._fd)) {
this.once('open', close);
return;
}
+1 -1
View File
@@ -37,7 +37,7 @@ var Constants = {
* @const
* @type {string}
*/
USER_AGENT_PRODUCT_VERSION: '2.8.0',
USER_AGENT_PRODUCT_VERSION: '2.8.2',
/**
* The number of default concurrent requests for parallel operation.
+15 -15
View File
@@ -1625,7 +1625,7 @@ BlobService.prototype.setBlobMetadata = function (container, blob, metadata, opt
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `[result]{@link BlobResult}` will contain the blob information.
* `response` will contain information related to this operation.
* @return {Stream}
* @return {Readable} A Node.js Readable stream.
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
@@ -1662,7 +1662,7 @@ BlobService.prototype.createReadStream = function (container, blob, optionsOrCal
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {Stream} writeStream The write stream.
* @param {Writable} writeStream The Node.js Writable stream.
* @param {object} [options] The request options.
* @param {boolean} [options.skipSizeCheck] Skip the size check to perform direct download.
* Set the option to true for small blobs.
@@ -2335,7 +2335,7 @@ BlobService.prototype.generateSharedAccessSignature = function (container, blob,
* @param {string} [blob] The blob name.
* @param {string} [sasToken] The Shared Access Signature token.
* @param {boolean} [primary] A boolean representing whether to use the primary or the secondary endpoint.
* @param {boolean} [snapshotId] The snapshot identifier.
* @param {string} [snapshotId] The snapshot identifier.
* @return {string} The formatted URL string.
* @example
* var azure = require('azure-storage');
@@ -2540,7 +2540,7 @@ BlobService.prototype.createPageBlobFromStream = function (container, blob, stre
* if an error occurs; otherwise `[result]{@link BlobResult}` will contain
* the blob information.
* `response` will contain information related to this operation.
* @return {Stream}
* @return {Writable} A Node.js Writable stream.
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
@@ -2592,7 +2592,7 @@ BlobService.prototype.createWriteStreamToExistingPageBlob = function (container,
* if an error occurs; otherwise `[result]{@link BlobResult}` will contain
* the blob information.
* `response` will contain information related to this operation.
* @return {Stream}
* @return {Writable} A Node.js Writable stream.
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
@@ -2611,7 +2611,7 @@ BlobService.prototype.createWriteStreamToNewPageBlob = function (container, blob
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {Stream} readStream The read stream.
* @param {Readable} readStream The Node.js Readable stream.
* @param {int} rangeStart The range start.
* @param {int} rangeEnd The range end.
* @param {object} [options] The request options.
@@ -3182,7 +3182,7 @@ BlobService.prototype.createBlockBlobFromText = function (container, blob, text,
* if an error occurs; otherwise `[result]{@link BlobResult}` will contain
* the blob information.
* `response` will contain information related to this operation.
* @return {Stream}
* @return {Writable} A Node.js Writable stream.
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
@@ -3199,7 +3199,7 @@ BlobService.prototype.createWriteStreamToBlockBlob = function (container, blob,
* @param {string} blockId The block identifier.
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {Stream} readStream The read stream.
* @param {Readable} readStream The Node.js Readable stream.
* @param {int} streamLength The stream length.
* @param {object} [options] The request options.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
@@ -3739,7 +3739,7 @@ BlobService.prototype.createAppendBlobFromText = function (container, blob, text
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback The callback function.
* @return {Stream}
* @return {Writable} A Node.js Writable stream.
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
@@ -3785,7 +3785,7 @@ BlobService.prototype.createWriteStreamToNewAppendBlob = function (container, bl
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback The callback function.
* @return {Stream}
* @return {Writable} A Node.js Writable stream.
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
@@ -3902,7 +3902,7 @@ BlobService.prototype.appendFromText = function (container, blob, text, optionsO
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {Stream} readStream The read stream.
* @param {Readable} readStream The Node.js Readable stream.
* @param {int} streamLength The stream length.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
@@ -4186,7 +4186,7 @@ BlobService.prototype._createBlobFromText = function (container, blob, blobType,
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback The callback function.
* @return {Stream}
* @return {Writable} A Node.js Writable stream.
*/
BlobService.prototype._createWriteStreamToBlob = function (container, blob, blobType, length, createNewBlob, optionsOrCallback, callback) {
var userOptions;
@@ -4720,7 +4720,7 @@ BlobService.prototype._leaseImpl = function (container, blob, leaseId, leaseActi
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} text The text string.
* @param {Stream} readStream The read stream.
* @param {Readable} readStream The Node.js Readable stream.
* @param {int} rangeStart The range start.
* @param {int} rangeEnd The range end.
* @param {object} [options] The request options.
@@ -5324,7 +5324,7 @@ BlobService.prototype._setRangeContentMD5Header = function (webResource, options
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} blobType The type of blob to download: block blob, page blob or append blob.
* @param {Stream} writeStream The write stream.
* @param {Writable} writeStream The Node.js Writable stream.
* @param {object} [options] The request options.
* @param {SpeedSummary} [options.speedSummary] The download tracker objects.
* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading.
@@ -5530,7 +5530,7 @@ BlobService.prototype._getBlobToRangeStream = function (container, blob, blobTyp
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {Stream} writeStream The write stream.
* @param {Writable} writeStream The Node.js Writable stream.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
+9 -9
View File
@@ -1730,7 +1730,7 @@ FileService.prototype.generateSharedAccessSignature = function (share, directory
* @param {string} [file] The file name. File names may not start or end with the delimiter '/'.
* @param {string} [sasToken] The Shared Access Signature token.
* @param {boolean} [primary] A boolean representing whether to use the primary or the secondary endpoint.
* @param {boolean} [shareSnapshotId] The snapshot identifier of the share.
* @param {string} [shareSnapshotId] The snapshot identifier of the share.
* @return {string} The formatted URL string.
* @example
* var azure = require('azure-storage');
@@ -2394,7 +2394,7 @@ FileService.prototype.getFileToText = function (share, directory, file, optionsO
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `[result]{@link FileResult}` will contain the file information.
* `response` will contain information related to this operation.
* @return {Stream}
* @return {Readable} A Node.js Readable stream.
* @example
* var azure = require('azure-storage');
* var fileService = azure.createFileService();
@@ -2435,7 +2435,7 @@ FileService.prototype.createReadStream = function (share, directory, file, optio
* @param {string} share The share name.
* @param {string} directory The directory name. Use '' to refer to the base directory.
* @param {string} file The file name. File names may not start or end with the delimiter '/'.
* @param {Stream} writeStream The write stream.
* @param {Writable} writeStream The Node.js Writable stream.
* @param {object} [options] The request options.
* @param {string} [options.shareSnapshotId] The snapshot identifier of the share.
* @param {boolean} [options.skipSizeCheck] Skip the size check to perform direct download.
@@ -2672,7 +2672,7 @@ FileService.prototype.clearRange = function (share, directory, file, rangeStart,
* @param {string} share The share name.
* @param {string} directory The directory name. Use '' to refer to the base directory.
* @param {string} file The file name. File names may not start or end with the delimiter '/'.
* @param {Stream} readStream The read stream.
* @param {Readable} readStream The Node.js Readable stream.
* @param {int} rangeStart The range start.
* @param {int} rangeEnd The range end.
* @param {object} [options] The request options.
@@ -2927,7 +2927,7 @@ FileService.prototype.createFileFromStream = function(share, directory, file, st
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `[result]{@link FileResult}` will contain the file information.
* `response` will contain information related to this operation.
* @return {Stream}
* @return {Writable} A Node.js Writable stream.
* @example
* var azure = require('azure-storage');
* var FileService = azure.createFileService();
@@ -2998,7 +2998,7 @@ FileService.prototype.createWriteStreamToExistingFile = function (share, directo
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `[result]{@link FileResult}` will contain the file information.
* `response` will contain information related to this operation.
* @return {Stream}
* @return {Writable} A Node.js Writable stream.
* @example
* var azure = require('azure-storage');
* var FileService = azure.createFileService();
@@ -3176,7 +3176,7 @@ FileService.prototype.abortCopyFile = function (share, directory, file, copyId,
* @param {string} directory The directory name. Use '' to refer to the base directory.
* @param {string} file The file name. File names may not start or end with the delimiter '/'.
* @param {string} text The text string.
* @param {Stream} readStream The read stream.
* @param {Readable} readStream The Node.js Readable stream.
* @param {int} rangeStart The range start.
* @param {int} rangeEnd The range end.
* @param {object} [options] The request options.
@@ -3382,7 +3382,7 @@ FileService.prototype._createFileFromChunkStream = function(share, directory, fi
* @param {string} share The share name.
* @param {string} directory The directory name. Use '' to refer to the base directory.
* @param {string} file The file name. File names may not start or end with the delimiter '/'.
* @param {Stream} writeStream The write stream.
* @param {Writable} writeStream The Node.js Writable stream.
* @param {object} [options] The request options.
* @param {string} [options.shareSnapshotId] The snapshot identifier of the share.
* @param {string} [options.rangeStart] Return only the bytes of the file in the specified range.
@@ -3457,7 +3457,7 @@ FileService.prototype._getFileToStream = function (share, directory, file, write
* @param {string} share The share name.
* @param {string} directory The directory name. Use '' to refer to the base directory.
* @param {string} file The file name. File names may not start or end with the delimiter '/'.
* @param {Stream} writeStream The write stream.
* @param {Writable} writeStream The Node.js Writable stream.
* @param {object} [options] The request options.
* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading.
* @param {string} [options.rangeStart] Return only the bytes of the file in the specified range.
-15
View File
@@ -1,15 +0,0 @@
#!/bin/sh
basedir=`dirname "$0"`
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../uuid/bin/uuid" "$@"
ret=$?
else
node "$basedir/../uuid/bin/uuid" "$@"
ret=$?
fi
exit $ret
-7
View File
@@ -1,7 +0,0 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\uuid\bin\uuid" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\uuid\bin\uuid" %*
)
+1
View File
@@ -0,0 +1 @@
test
+5
View File
@@ -0,0 +1,5 @@
language: node_js
node_js:
- "0.10"
- 0.8
- 0.6
+59
View File
@@ -0,0 +1,59 @@
[![Build Status][1]][2] [![dependency status][9]][10] [![dev dependency status][11]][12]
# extend() for Node.js <sup>[![Version Badge][8]][3]</sup>
`node-extend` is a port of the classic extend() method from jQuery. It behaves as you expect. It is simple, tried and true.
## Installation
This package is available on [npm][3] as: `extend`
``` sh
npm install extend
```
## Usage
**Syntax:** extend **(** [`deep`], `target`, `object1`, [`objectN`] **)**
*Extend one object with one or more others, returning the modified object.*
Keep in mind that the target object will be modified, and will be returned from extend().
If a boolean true is specified as the first argument, extend performs a deep copy, recursively copying any objects it finds. Otherwise, the copy will share structure with the original object(s).
Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over.
### Arguments
* `deep` *Boolean* (optional)
If set, the merge becomes recursive (i.e. deep copy).
* `target` *Object*
The object to extend.
* `object1` *Object*
The object that will be merged into the first.
* `objectN` *Object* (Optional)
More objects to merge into the first.
## License
`node-extend` is licensed under the [MIT License][4].
## Acknowledgements
All credit to the jQuery authors for perfecting this amazing utility.
Ported to Node.js by [Stefan Thomas][5] with contributions by [Jonathan Buchanan][6] and [Jordan Harband][7].
[1]: https://travis-ci.org/justmoon/node-extend.png
[2]: https://travis-ci.org/justmoon/node-extend
[3]: https://npmjs.org/package/extend
[4]: http://opensource.org/licenses/MIT
[5]: https://github.com/justmoon
[6]: https://github.com/insin
[7]: https://github.com/ljharb
[8]: http://vb.teelaun.ch/justmoon/node-extend.svg
[9]: https://david-dm.org/justmoon/node-extend.png
[10]: https://david-dm.org/justmoon/node-extend
[11]: https://david-dm.org/justmoon/node-extend/dev-status.png
[12]: https://david-dm.org/justmoon/node-extend#info=devDependencies
+78
View File
@@ -0,0 +1,78 @@
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
function isPlainObject(obj) {
if (!obj || toString.call(obj) !== '[object Object]' || obj.nodeType || obj.setInterval)
return false;
var has_own_constructor = hasOwn.call(obj, 'constructor');
var has_is_property_of_method = hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !has_own_constructor && !has_is_property_of_method)
return false;
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
};
module.exports = function extend() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && typeof target !== "function") {
target = {};
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = Array.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && Array.isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
+62
View File
@@ -0,0 +1,62 @@
{
"_from": "extend@~1.2.1",
"_id": "extend@1.2.1",
"_inBundle": false,
"_integrity": "sha1-oPX9bPyDpf5J72mNYOyKYk3UV2w=",
"_location": "/azure-storage/extend",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "extend@~1.2.1",
"name": "extend",
"escapedName": "extend",
"rawSpec": "~1.2.1",
"saveSpec": null,
"fetchSpec": "~1.2.1"
},
"_requiredBy": [
"/azure-storage"
],
"_resolved": "https://registry.npmjs.org/extend/-/extend-1.2.1.tgz",
"_shasum": "a0f5fd6cfc83a5fe49ef698d60ec8a624dd4576c",
"_spec": "extend@~1.2.1",
"_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AACharly-Extraction-Bot\\node_modules\\azure-storage",
"author": {
"name": "Stefan Thomas",
"email": "justmoon@members.fsf.org",
"url": "http://www.justmoon.net"
},
"bugs": {
"url": "https://github.com/justmoon/node-extend/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Jordan Harband",
"url": "https://github.com/ljharb"
}
],
"dependencies": {},
"deprecated": false,
"description": "Port of jQuery.extend for Node.js",
"devDependencies": {
"tape": "~1.1.0"
},
"homepage": "https://github.com/justmoon/node-extend#readme",
"keywords": [
"extend",
"clone",
"merge"
],
"main": "index",
"name": "extend",
"repository": {
"type": "git",
"url": "git+https://github.com/justmoon/node-extend.git"
},
"scripts": {
"test": "node test/index.js"
},
"version": "1.2.1"
}
+49 -67
View File
@@ -28,6 +28,7 @@ request('http://www.google.com', function (error, response, body) {
## Table of contents
- [Streaming](#streaming)
- [Promises & Async/Await](#promises--asyncawait)
- [Forms](#forms)
- [HTTP Authentication](#http-authentication)
- [Custom HTTP Headers](#custom-http-headers)
@@ -142,6 +143,22 @@ You can still use intermediate proxies, the requests will still follow HTTP forw
---
## Promises & Async/Await
`request` supports both streaming and callback interfaces natively. If you'd like `request` to return a Promise instead, you can use an alternative interface wrapper for `request`. These wrappers can be useful if you prefer to work with Promises, or if you'd like to use `async`/`await` in ES2017.
Several alternative interfaces are provided by the request team, including:
- [`request-promise`](https://github.com/request/request-promise) (uses [Bluebird](https://github.com/petkaantonov/bluebird) Promises)
- [`request-promise-native`](https://github.com/request/request-promise-native) (uses native Promises)
- [`request-promise-any`](https://github.com/request/request-promise-any) (uses [any-promise](https://www.npmjs.com/package/any-promise) Promises)
[back to top](#table-of-contents)
---
## Forms
`request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.
@@ -608,7 +625,7 @@ request.get(options);
### Using `options.agentOptions`
In the example below, we call an API requires client side SSL certificate
In the example below, we call an API that requires client side SSL certificate
(in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol:
```js
@@ -667,7 +684,7 @@ request.get({
The `options.har` property will override the values: `url`, `method`, `qs`, `headers`, `form`, `formData`, `body`, `json`, as well as construct multipart data and read files from disk when `request.postData.params[].fileName` is present without a matching `value`.
a validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.
A validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.
```js
var request = require('request')
@@ -726,7 +743,7 @@ The first argument can be either a `url` or an `options` object. The only requir
- `qs` - object containing querystring values to be appended to the `uri`
- `qsParseOptions` - object containing options to pass to the [qs.parse](https://github.com/hapijs/qs#parsing-objects) method. Alternatively pass options to the [querystring.parse](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_parse_str_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`
- `qsStringifyOptions` - object containing options to pass to the [qs.stringify](https://github.com/hapijs/qs#stringifying) method. Alternatively pass options to the [querystring.stringify](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`. For example, to change the way arrays are converted to query strings using the `qs` module pass the `arrayFormat` option with one of `indices|brackets|repeat`
- `useQuerystring` - If true, use `querystring` to stringify and parse
- `useQuerystring` - if true, use `querystring` to stringify and parse
querystrings, otherwise use `qs` (default: `false`). Set this option to
`true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the
default `foo[0]=bar&foo[1]=baz`.
@@ -735,7 +752,7 @@ The first argument can be either a `url` or an `options` object. The only requir
- `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer`, `String` or `ReadStream`. If `json` is `true`, then `body` must be a JSON-serializable object.
- `form` - when passed an object or a querystring, this sets `body` to a querystring representation of value, and adds `Content-type: application/x-www-form-urlencoded` header. When passed no options, a `FormData` instance is returned (and is piped to request). See "Forms" section above.
- `formData` - Data to pass for a `multipart/form-data` request. See
- `formData` - data to pass for a `multipart/form-data` request. See
[Forms](#forms) section above.
- `multipart` - array of objects which contain their own headers and `body`
attributes. Sends a `multipart/related` request. See [Forms](#forms) section
@@ -752,11 +769,11 @@ The first argument can be either a `url` or an `options` object. The only requir
---
- `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
- `oauth` - Options for OAuth HMAC-SHA1 signing. See documentation above.
- `hawk` - Options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example).
- `auth` - a hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
- `oauth` - options for OAuth HMAC-SHA1 signing. See documentation above.
- `hawk` - options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example).
- `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`, and optionally `session` (note that this only works for services that require session as part of the canonical string). Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services). If you want to use AWS sign version 4 use the parameter `sign_version` with value `4` otherwise the default is version 2. **Note:** you need to `npm install aws4` first.
- `httpSignature` - Options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options.
- `httpSignature` - options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options.
---
@@ -768,9 +785,9 @@ The first argument can be either a `url` or an `options` object. The only requir
---
- `encoding` - Encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`. Anything else **(including the default value of `undefined`)** will be passed as the [encoding](http://nodejs.org/api/buffer.html#buffer_buffer) parameter to `toString()` (meaning this is effectively `utf8` by default). (**Note:** if you expect binary data, you should set `encoding: null`.)
- `gzip` - If `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. **Note:** Automatic decoding of the response content is performed on the body data returned through `request` (both through the `request` stream and passed to the callback function) but is not performed on the `response` stream (available from the `response` event) which is the unmodified `http.IncomingMessage` object which may contain compressed data. See example below.
- `jar` - If `true`, remember cookies for future use (or define your custom cookie jar; see examples section)
- `encoding` - encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`. Anything else **(including the default value of `undefined`)** will be passed as the [encoding](http://nodejs.org/api/buffer.html#buffer_buffer) parameter to `toString()` (meaning this is effectively `utf8` by default). (**Note:** if you expect binary data, you should set `encoding: null`.)
- `gzip` - if `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. **Note:** Automatic decoding of the response content is performed on the body data returned through `request` (both through the `request` stream and passed to the callback function) but is not performed on the `response` stream (available from the `response` event) which is the unmodified `http.IncomingMessage` object which may contain compressed data. See example below.
- `jar` - if `true`, remember cookies for future use (or define your custom cookie jar; see examples section)
---
@@ -778,14 +795,14 @@ The first argument can be either a `url` or an `options` object. The only requir
- `agentClass` - alternatively specify your agent's class name
- `agentOptions` - and pass its options. **Note:** for HTTPS see [tls API doc for TLS/SSL options](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback) and the [documentation above](#using-optionsagentoptions).
- `forever` - set to `true` to use the [forever-agent](https://github.com/request/forever-agent) **Note:** Defaults to `http(s).Agent({keepAlive:true})` in node 0.12+
- `pool` - An object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as your options allow for it). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool. **Note:** `pool` is used only when the `agent` option is not specified.
- `pool` - an object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as your options allow for it). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool. **Note:** `pool` is used only when the `agent` option is not specified.
- A `maxSockets` property can also be provided on the `pool` object to set the max number of sockets for all agents created (ex: `pool: {maxSockets: Infinity}`).
- Note that if you are sending multiple requests in a loop and creating
multiple new `pool` objects, `maxSockets` will not work as intended. To
work around this, either use [`request.defaults`](#requestdefaultsoptions)
with your pool options or create the pool object with the `maxSockets`
property outside of the loop.
- `timeout` - Integer containing the number of milliseconds to wait for a
- `timeout` - integer containing the number of milliseconds to wait for a
server to send response headers (and start the response body) before aborting
the request. Note that if the underlying TCP connection cannot be established,
the OS-wide TCP connection timeout will overrule the `timeout` option ([the
@@ -795,9 +812,9 @@ default in Linux can be anywhere from 20-120 seconds][linux-timeout]).
---
- `localAddress` - Local interface to bind for network connections.
- `proxy` - An HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`)
- `strictSSL` - If `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option.
- `localAddress` - local interface to bind for network connections.
- `proxy` - an HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`)
- `strictSSL` - if `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option.
- `tunnel` - controls the behavior of
[HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling)
as follows:
@@ -805,14 +822,14 @@ default in Linux can be anywhere from 20-120 seconds][linux-timeout]).
- `true` - always tunnel to the destination by making a `CONNECT` request to
the proxy
- `false` - request the destination as a `GET` request.
- `proxyHeaderWhiteList` - A whitelist of headers to send to a
- `proxyHeaderWhiteList` - a whitelist of headers to send to a
tunneling proxy.
- `proxyHeaderExclusiveList` - A whitelist of headers to send
- `proxyHeaderExclusiveList` - a whitelist of headers to send
exclusively to a tunneling proxy and not to destination.
---
- `time` - If `true`, the request-response cycle (including all redirects) is timed at millisecond resolution. When set, the following properties are added to the response object:
- `time` - if `true`, the request-response cycle (including all redirects) is timed at millisecond resolution. When set, the following properties are added to the response object:
- `elapsedTime` Duration of the entire request/response in milliseconds (*deprecated*).
- `responseStartTime` Timestamp when the response began (in Unix Epoch milliseconds) (*deprecated*).
- `timingStart` Timestamp of the start of the request (in Unix Epoch milliseconds).
@@ -830,7 +847,7 @@ default in Linux can be anywhere from 20-120 seconds][linux-timeout]).
- `download`: Duration of HTTP download (`timings.end` - `timings.response`)
- `total`: Duration entire HTTP round-trip (`timings.end`)
- `har` - A [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-1.2) for details)*
- `har` - a [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-1.2) for details)*
- `callback` - alternatively pass the request's callback in the options object
The callback argument gets 3 arguments:
@@ -874,55 +891,19 @@ var specialRequest = baseRequest.defaults({
})
```
### request.put
### request.METHOD()
Same as `request()`, but defaults to `method: "PUT"`.
These HTTP method convenience functions act just like `request()` but with a default method already set for you:
```js
request.put(url)
```
- *request.get()*: Defaults to `method: "GET"`.
- *request.post()*: Defaults to `method: "POST"`.
- *request.put()*: Defaults to `method: "PUT"`.
- *request.patch()*: Defaults to `method: "PATCH"`.
- *request.del() / request.delete()*: Defaults to `method: "DELETE"`.
- *request.head()*: Defaults to `method: "HEAD"`.
- *request.options()*: Defaults to `method: "OPTIONS"`.
### request.patch
Same as `request()`, but defaults to `method: "PATCH"`.
```js
request.patch(url)
```
### request.post
Same as `request()`, but defaults to `method: "POST"`.
```js
request.post(url)
```
### request.head
Same as `request()`, but defaults to `method: "HEAD"`.
```js
request.head(url)
```
### request.del / request.delete
Same as `request()`, but defaults to `method: "DELETE"`.
```js
request.del(url)
request.delete(url)
```
### request.get
Same as `request()` (for uniformity).
```js
request.get(url)
```
### request.cookie
### request.cookie()
Function that creates a new cookie.
@@ -1036,7 +1017,8 @@ the server sent a compressed response.
console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
console.log('the decoded data is: ' + body)
}
).on('data', function(data) {
)
.on('data', function(data) {
// decompressed data as it is received
console.log('decoded chunk: ' + data)
})
+13 -14
View File
@@ -14,15 +14,14 @@
'use strict'
var extend = require('extend')
, cookies = require('./lib/cookies')
, helpers = require('./lib/helpers')
var extend = require('extend')
var cookies = require('./lib/cookies')
var helpers = require('./lib/helpers')
var paramsHaveRequestBody = helpers.paramsHaveRequestBody
// organize params for patch, post, put, head, del
function initParams(uri, options, callback) {
function initParams (uri, options, callback) {
if (typeof options === 'function') {
callback = options
}
@@ -66,6 +65,7 @@ function verbFunc (verb) {
// define like this to please codeintel/intellisense IDEs
request.get = verbFunc('get')
request.head = verbFunc('head')
request.options = verbFunc('options')
request.post = verbFunc('post')
request.put = verbFunc('put')
request.patch = verbFunc('patch')
@@ -81,7 +81,6 @@ request.cookie = function (str) {
}
function wrapRequestMethod (method, options, requester, verb) {
return function (uri, opts, callback) {
var params = initParams(uri, opts, callback)
@@ -112,15 +111,15 @@ request.defaults = function (options, requester) {
options = {}
}
var defaults = wrapRequestMethod(self, options, requester)
var defaults = wrapRequestMethod(self, options, requester)
var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete']
verbs.forEach(function(verb) {
defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
verbs.forEach(function (verb) {
defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
})
defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
defaults.jar = self.jar
defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
defaults.jar = self.jar
defaults.defaults = self.defaults
return defaults
}
@@ -146,11 +145,11 @@ request.initParams = initParams
// Backwards compatibility for request.debug
Object.defineProperty(request, 'debug', {
enumerable : true,
get : function() {
enumerable: true,
get: function () {
return request.Request.debug
},
set : function(debug) {
set: function (debug) {
request.Request.debug = debug
}
})
+5 -6
View File
@@ -1,12 +1,11 @@
'use strict'
var caseless = require('caseless')
, uuid = require('uuid')
, helpers = require('./helpers')
var uuid = require('uuid')
var helpers = require('./helpers')
var md5 = helpers.md5
, toBase64 = helpers.toBase64
var toBase64 = helpers.toBase64
function Auth (request) {
// define all public properties here
@@ -126,7 +125,7 @@ Auth.prototype.digest = function (method, path, authHeader) {
Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
var self = this
, request = self.request
var request = self.request
var authHeader
if (bearer === undefined && user === undefined) {
@@ -143,7 +142,7 @@ Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
Auth.prototype.onResponse = function (response) {
var self = this
, request = self.request
var request = self.request
if (!self.hasAuth || self.sentAuth) { return null }
+7 -8
View File
@@ -3,10 +3,9 @@
var tough = require('tough-cookie')
var Cookie = tough.Cookie
, CookieJar = tough.CookieJar
var CookieJar = tough.CookieJar
exports.parse = function(str) {
exports.parse = function (str) {
if (str && str.uri) {
str = str.uri
}
@@ -17,23 +16,23 @@ exports.parse = function(str) {
}
// Adapt the sometimes-Async api of tough.CookieJar to our requirements
function RequestJar(store) {
function RequestJar (store) {
var self = this
self._jar = new CookieJar(store, {looseMode: true})
}
RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) {
RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) {
var self = this
return self._jar.setCookieSync(cookieOrStr, uri, options || {})
}
RequestJar.prototype.getCookieString = function(uri) {
RequestJar.prototype.getCookieString = function (uri) {
var self = this
return self._jar.getCookieStringSync(uri)
}
RequestJar.prototype.getCookies = function(uri) {
RequestJar.prototype.getCookies = function (uri) {
var self = this
return self._jar.getCookiesSync(uri)
}
exports.jar = function(store) {
exports.jar = function (store) {
return new RequestJar(store)
}
+18 -18
View File
@@ -1,33 +1,33 @@
'use strict'
function formatHostname(hostname) {
function formatHostname (hostname) {
// canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
return hostname.replace(/^\.*/, '.').toLowerCase()
}
function parseNoProxyZone(zone) {
function parseNoProxyZone (zone) {
zone = zone.trim().toLowerCase()
var zoneParts = zone.split(':', 2)
, zoneHost = formatHostname(zoneParts[0])
, zonePort = zoneParts[1]
, hasPort = zone.indexOf(':') > -1
var zoneHost = formatHostname(zoneParts[0])
var zonePort = zoneParts[1]
var hasPort = zone.indexOf(':') > -1
return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
}
function uriInNoProxy(uri, noProxy) {
function uriInNoProxy (uri, noProxy) {
var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
, hostname = formatHostname(uri.hostname)
, noProxyList = noProxy.split(',')
var hostname = formatHostname(uri.hostname)
var noProxyList = noProxy.split(',')
// iterate through the noProxyList until it finds a match.
return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) {
return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) {
var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
, hostnameMatched = (
isMatchedAt > -1 &&
(isMatchedAt === hostname.length - noProxyZone.hostname.length)
)
var hostnameMatched = (
isMatchedAt > -1 &&
(isMatchedAt === hostname.length - noProxyZone.hostname.length)
)
if (noProxyZone.hasPort) {
return (port === noProxyZone.port) && hostnameMatched
@@ -37,7 +37,7 @@ function uriInNoProxy(uri, noProxy) {
})
}
function getProxyFromURI(uri) {
function getProxyFromURI (uri) {
// Decide the proper request proxy to use based on the request URI object and the
// environmental variables (NO_PROXY, HTTP_PROXY, etc.)
// respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
@@ -60,14 +60,14 @@ function getProxyFromURI(uri) {
if (uri.protocol === 'http:') {
return process.env.HTTP_PROXY ||
process.env.http_proxy || null
process.env.http_proxy || null
}
if (uri.protocol === 'https:') {
return process.env.HTTPS_PROXY ||
process.env.https_proxy ||
process.env.HTTP_PROXY ||
process.env.http_proxy || null
process.env.https_proxy ||
process.env.HTTP_PROXY ||
process.env.http_proxy || null
}
// if none of that works, return null
+5 -15
View File
@@ -71,14 +71,10 @@ Har.prototype.prep = function (data) {
'multipart/related',
'multipart/form-data',
'multipart/alternative'])) {
// reset values
data.postData.mimeType = 'multipart/form-data'
}
else if (some([
} else if (some([
'application/x-www-form-urlencoded'])) {
if (!data.postData.params) {
data.postData.text = ''
} else {
@@ -87,14 +83,11 @@ Har.prototype.prep = function (data) {
// always overwrite
data.postData.text = qs.stringify(data.postData.paramsObj)
}
}
else if (some([
} else if (some([
'text/json',
'text/x-json',
'application/json',
'application/x-json'])) {
data.postData.mimeType = 'application/json'
if (data.postData.text) {
@@ -168,14 +161,12 @@ Har.prototype.options = function (options) {
}
if (test('application/x-www-form-urlencoded')) {
options.form = req.postData.paramsObj
}
else if (test('application/json')) {
} else if (test('application/json')) {
if (req.postData.jsonObj) {
options.body = req.postData.jsonObj
options.json = true
}
}
else if (test('multipart/form-data')) {
} else if (test('multipart/form-data')) {
options.formData = {}
req.postData.params.forEach(function (param) {
@@ -202,8 +193,7 @@ Har.prototype.options = function (options) {
options.formData[param.name] = attachment
})
}
else {
} else {
if (req.postData.text) {
options.body = req.postData.text
}
+10 -10
View File
@@ -1,14 +1,14 @@
'use strict'
var jsonSafeStringify = require('json-stringify-safe')
, crypto = require('crypto')
, Buffer = require('safe-buffer').Buffer
var crypto = require('crypto')
var Buffer = require('safe-buffer').Buffer
var defer = typeof setImmediate === 'undefined'
? process.nextTick
: setImmediate
function paramsHaveRequestBody(params) {
function paramsHaveRequestBody (params) {
return (
params.body ||
params.requestBodyStream ||
@@ -57,10 +57,10 @@ function version () {
}
exports.paramsHaveRequestBody = paramsHaveRequestBody
exports.safeStringify = safeStringify
exports.md5 = md5
exports.isReadStream = isReadStream
exports.toBase64 = toBase64
exports.copy = copy
exports.version = version
exports.defer = defer
exports.safeStringify = safeStringify
exports.md5 = md5
exports.isReadStream = isReadStream
exports.toBase64 = toBase64
exports.copy = copy
exports.version = version
exports.defer = defer
+6 -7
View File
@@ -1,10 +1,9 @@
'use strict'
var uuid = require('uuid')
, CombinedStream = require('combined-stream')
, isstream = require('isstream')
, Buffer = require('safe-buffer').Buffer
var CombinedStream = require('combined-stream')
var isstream = require('isstream')
var Buffer = require('safe-buffer').Buffer
function Multipart (request) {
this.request = request
@@ -15,8 +14,8 @@ function Multipart (request) {
Multipart.prototype.isChunked = function (options) {
var self = this
, chunked = false
, parts = options.data || options
var chunked = false
var parts = options.data || options
if (!parts.forEach) {
self.request.emit('error', new Error('Argument error, options.multipart.'))
@@ -103,7 +102,7 @@ Multipart.prototype.onRequest = function (options) {
var self = this
var chunked = self.isChunked(options)
, parts = options.data || options
var parts = options.data || options
self.setHeaders(chunked)
self.chunked = chunked
+21 -21
View File
@@ -1,13 +1,12 @@
'use strict'
var url = require('url')
, qs = require('qs')
, caseless = require('caseless')
, uuid = require('uuid')
, oauth = require('oauth-sign')
, crypto = require('crypto')
, Buffer = require('safe-buffer').Buffer
var qs = require('qs')
var caseless = require('caseless')
var uuid = require('uuid')
var oauth = require('oauth-sign')
var crypto = require('crypto')
var Buffer = require('safe-buffer').Buffer
function OAuth (request) {
this.request = request
@@ -23,7 +22,7 @@ OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib)
oa.oauth_version = '1.0'
}
if (!oa.oauth_timestamp) {
oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString()
}
if (!oa.oauth_nonce) {
oa.oauth_nonce = uuid().replace(/-/g, '')
@@ -32,11 +31,11 @@ OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib)
oa.oauth_signature_method = 'HMAC-SHA1'
}
var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key
var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key // eslint-disable-line camelcase
delete oa.oauth_consumer_secret
delete oa.oauth_private_key
var token_secret = oa.oauth_token_secret
var token_secret = oa.oauth_token_secret // eslint-disable-line camelcase
delete oa.oauth_token_secret
var realm = oa.oauth_realm
@@ -51,8 +50,9 @@ OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib)
method,
baseurl,
params,
consumer_secret_or_private_key,
token_secret)
consumer_secret_or_private_key, // eslint-disable-line camelcase
token_secret // eslint-disable-line camelcase
)
if (realm) {
oa.realm = realm
@@ -61,7 +61,7 @@ OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib)
return oa
}
OAuth.prototype.buildBodyHash = function(_oauth, body) {
OAuth.prototype.buildBodyHash = function (_oauth, body) {
if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) {
this.request.emit('error', new Error('oauth: ' + _oauth.signature_method +
' signature_method not supported with body_hash signing.'))
@@ -96,16 +96,16 @@ OAuth.prototype.onRequest = function (_oauth) {
self.params = _oauth
var uri = self.request.uri || {}
, method = self.request.method || ''
, headers = caseless(self.request.headers)
, body = self.request.body || ''
, qsLib = self.request.qsLib || qs
var method = self.request.method || ''
var headers = caseless(self.request.headers)
var body = self.request.body || ''
var qsLib = self.request.qsLib || qs
var form
, query
, contentType = headers.get('content-type') || ''
, formContentType = 'application/x-www-form-urlencoded'
, transport = _oauth.transport_method || 'header'
var query
var contentType = headers.get('content-type') || ''
var formContentType = 'application/x-www-form-urlencoded'
var transport = _oauth.transport_method || 'header'
if (contentType.slice(0, formContentType.length) === formContentType) {
contentType = formContentType
+2 -3
View File
@@ -1,8 +1,7 @@
'use strict'
var qs = require('qs')
, querystring = require('querystring')
var querystring = require('querystring')
function Querystring (request) {
this.request = request
@@ -13,7 +12,7 @@ function Querystring (request) {
}
Querystring.prototype.init = function (options) {
if (this.lib) {return}
if (this.lib) { return }
this.useQuerystring = options.useQuerystring
this.lib = (this.useQuerystring ? querystring : qs)
+7 -10
View File
@@ -9,7 +9,7 @@ function Redirect (request) {
this.followRedirects = true
this.followAllRedirects = false
this.followOriginalHttpMethod = false
this.allowRedirect = function () {return true}
this.allowRedirect = function () { return true }
this.maxRedirects = 10
this.redirects = []
this.redirectsFollowed = 0
@@ -44,7 +44,7 @@ Redirect.prototype.onRequest = function (options) {
Redirect.prototype.redirectTo = function (response) {
var self = this
, request = self.request
var request = self.request
var redirectTo = null
if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
@@ -78,7 +78,7 @@ Redirect.prototype.redirectTo = function (response) {
Redirect.prototype.onResponse = function (response) {
var self = this
, request = self.request
var request = self.request
var redirectTo = self.redirectTo(response)
if (!redirectTo || !self.allowRedirect.call(request, response)) {
@@ -112,13 +112,10 @@ Redirect.prototype.onResponse = function (response) {
delete request.agent
}
self.redirects.push(
{ statusCode : response.statusCode
, redirectUri: redirectTo
}
)
if (self.followAllRedirects && request.method !== 'HEAD'
&& response.statusCode !== 401 && response.statusCode !== 307) {
self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo })
if (self.followAllRedirects && request.method !== 'HEAD' &&
response.statusCode !== 401 && response.statusCode !== 307) {
request.method = self.followOriginalHttpMethod ? request.method : 'GET'
}
// request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
+25 -26
View File
@@ -1,7 +1,7 @@
'use strict'
var url = require('url')
, tunnel = require('tunnel-agent')
var tunnel = require('tunnel-agent')
var defaultProxyHeaderWhiteList = [
'accept',
@@ -31,10 +31,10 @@ var defaultProxyHeaderExclusiveList = [
'proxy-authorization'
]
function constructProxyHost(uriObject) {
function constructProxyHost (uriObject) {
var port = uriObject.port
, protocol = uriObject.protocol
, proxyHost = uriObject.hostname + ':'
var protocol = uriObject.protocol
var proxyHost = uriObject.hostname + ':'
if (port) {
proxyHost += port
@@ -47,7 +47,7 @@ function constructProxyHost(uriObject) {
return proxyHost
}
function constructProxyHeaderWhiteList(headers, proxyHeaderWhiteList) {
function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) {
var whiteList = proxyHeaderWhiteList
.reduce(function (set, header) {
set[header.toLowerCase()] = true
@@ -68,41 +68,40 @@ function constructTunnelOptions (request, proxyHeaders) {
var proxy = request.proxy
var tunnelOptions = {
proxy : {
host : proxy.hostname,
port : +proxy.port,
proxyAuth : proxy.auth,
headers : proxyHeaders
proxy: {
host: proxy.hostname,
port: +proxy.port,
proxyAuth: proxy.auth,
headers: proxyHeaders
},
headers : request.headers,
ca : request.ca,
cert : request.cert,
key : request.key,
passphrase : request.passphrase,
pfx : request.pfx,
ciphers : request.ciphers,
rejectUnauthorized : request.rejectUnauthorized,
secureOptions : request.secureOptions,
secureProtocol : request.secureProtocol
headers: request.headers,
ca: request.ca,
cert: request.cert,
key: request.key,
passphrase: request.passphrase,
pfx: request.pfx,
ciphers: request.ciphers,
rejectUnauthorized: request.rejectUnauthorized,
secureOptions: request.secureOptions,
secureProtocol: request.secureProtocol
}
return tunnelOptions
}
function constructTunnelFnName(uri, proxy) {
function constructTunnelFnName (uri, proxy) {
var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http')
var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http')
return [uriProtocol, proxyProtocol].join('Over')
}
function getTunnelFn(request) {
function getTunnelFn (request) {
var uri = request.uri
var proxy = request.proxy
var tunnelFnName = constructTunnelFnName(uri, proxy)
return tunnel[tunnelFnName]
}
function Tunnel (request) {
this.request = request
this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList
@@ -114,8 +113,8 @@ function Tunnel (request) {
Tunnel.prototype.isEnabled = function () {
var self = this
, request = self.request
// Tunnel HTTPS by default. Allow the user to override this setting.
var request = self.request
// Tunnel HTTPS by default. Allow the user to override this setting.
// If self.tunnelOverride is set (the user specified a value), use it.
if (typeof self.tunnelOverride !== 'undefined') {
@@ -133,7 +132,7 @@ Tunnel.prototype.isEnabled = function () {
Tunnel.prototype.setup = function (options) {
var self = this
, request = self.request
var request = self.request
options = options || {}
@@ -1,49 +1,36 @@
{
"_args": [
[
"extend@~3.0.0",
"c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage\\node_modules\\request"
]
],
"_from": "extend@>=3.0.0-0 <3.1.0-0",
"_from": "extend@~3.0.1",
"_id": "extend@3.0.1",
"_inCache": true,
"_inBundle": false,
"_integrity": "sha1-p1Xqe8Gt/MWjHOfnYtuq3F5jZEQ=",
"_location": "/azure-storage/request/extend",
"_nodeVersion": "7.9.0",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/extend-3.0.1.tgz_1493357803699_0.1708133383654058"
},
"_npmUser": {
"email": "ljharb@gmail.com",
"name": "ljharb"
},
"_npmVersion": "4.2.0",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "extend@~3.0.1",
"name": "extend",
"raw": "extend@~3.0.0",
"rawSpec": "~3.0.0",
"scope": null,
"spec": ">=3.0.0-0 <3.1.0-0",
"type": "range"
"escapedName": "extend",
"rawSpec": "~3.0.1",
"saveSpec": null,
"fetchSpec": "~3.0.1"
},
"_requiredBy": [
"/azure-storage/request"
],
"_resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz",
"_shasum": "a755ea7bc1adfcc5a31ce7e762dbaadc5e636444",
"_shrinkwrap": null,
"_spec": "extend@~3.0.0",
"_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage\\node_modules\\request",
"_spec": "extend@~3.0.1",
"_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AACharly-Extraction-Bot\\node_modules\\azure-storage\\node_modules\\request",
"author": {
"email": "justmoon@members.fsf.org",
"name": "Stefan Thomas",
"email": "justmoon@members.fsf.org",
"url": "http://www.justmoon.net"
},
"bugs": {
"url": "https://github.com/justmoon/node-extend/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Jordan Harband",
@@ -51,6 +38,7 @@
}
],
"dependencies": {},
"deprecated": false,
"description": "Port of jQuery.extend for node.js and the browser",
"devDependencies": {
"@ljharb/eslint-config": "^11.0.0",
@@ -59,33 +47,15 @@
"jscs": "^3.0.7",
"tape": "^4.6.3"
},
"directories": {},
"dist": {
"shasum": "a755ea7bc1adfcc5a31ce7e762dbaadc5e636444",
"tarball": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz"
},
"gitHead": "138b515df4d628bb1742254ede5d2551c0fecae7",
"homepage": "https://github.com/justmoon/node-extend#readme",
"installable": true,
"keywords": [
"clone",
"extend",
"clone",
"merge"
],
"license": "MIT",
"main": "index",
"maintainers": [
{
"name": "justmoon",
"email": "justmoon@members.fsf.org"
},
{
"name": "ljharb",
"email": "ljharb@gmail.com"
}
],
"name": "extend",
"optionalDependencies": {},
"repository": {
"type": "git",
"url": "git+https://github.com/justmoon/node-extend.git"
+41 -80
View File
@@ -1,81 +1,68 @@
{
"_args": [
[
"request@~2.81.0",
"c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage"
]
],
"_from": "request@>=2.81.0-0 <2.82.0-0",
"_id": "request@2.81.0",
"_inCache": true,
"_from": "request@~2.83.0",
"_id": "request@2.83.0",
"_inBundle": false,
"_integrity": "sha512-lR3gD69osqm6EYLk9wB/G1W/laGWjzH90t1vEa2xuxHD5KUrSzp9pUSfTm+YC5Nxt2T8nMPEvKlhbQayU7bgFw==",
"_location": "/azure-storage/request",
"_nodeVersion": "7.2.1",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/request-2.81.0.tgz_1489075005134_0.036041518207639456"
},
"_npmUser": {
"email": "simeonvelichkov@gmail.com",
"name": "simov"
},
"_npmVersion": "2.15.11",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "request@~2.83.0",
"name": "request",
"raw": "request@~2.81.0",
"rawSpec": "~2.81.0",
"scope": null,
"spec": ">=2.81.0-0 <2.82.0-0",
"type": "range"
"escapedName": "request",
"rawSpec": "~2.83.0",
"saveSpec": null,
"fetchSpec": "~2.83.0"
},
"_requiredBy": [
"/azure-storage"
],
"_resolved": "https://registry.npmjs.org/request/-/request-2.81.0.tgz",
"_shasum": "c6928946a0e06c5f8d6f8a9333469ffda46298a0",
"_shrinkwrap": null,
"_spec": "request@~2.81.0",
"_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage",
"_resolved": "https://registry.npmjs.org/request/-/request-2.83.0.tgz",
"_shasum": "ca0b65da02ed62935887808e6f510381034e3356",
"_spec": "request@~2.83.0",
"_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AACharly-Extraction-Bot\\node_modules\\azure-storage",
"author": {
"email": "mikeal.rogers@gmail.com",
"name": "Mikeal Rogers"
"name": "Mikeal Rogers",
"email": "mikeal.rogers@gmail.com"
},
"bugs": {
"url": "http://github.com/request/request/issues"
},
"bundleDependencies": false,
"dependencies": {
"aws-sign2": "~0.6.0",
"aws4": "^1.2.1",
"aws-sign2": "~0.7.0",
"aws4": "^1.6.0",
"caseless": "~0.12.0",
"combined-stream": "~1.0.5",
"extend": "~3.0.0",
"extend": "~3.0.1",
"forever-agent": "~0.6.1",
"form-data": "~2.1.1",
"har-validator": "~4.2.1",
"hawk": "~3.1.3",
"http-signature": "~1.1.0",
"form-data": "~2.3.1",
"har-validator": "~5.0.3",
"hawk": "~6.0.2",
"http-signature": "~1.2.0",
"is-typedarray": "~1.0.0",
"isstream": "~0.1.2",
"json-stringify-safe": "~5.0.1",
"mime-types": "~2.1.7",
"oauth-sign": "~0.8.1",
"performance-now": "^0.2.0",
"qs": "~6.4.0",
"safe-buffer": "^5.0.1",
"stringstream": "~0.0.4",
"tough-cookie": "~2.3.0",
"mime-types": "~2.1.17",
"oauth-sign": "~0.8.2",
"performance-now": "^2.1.0",
"qs": "~6.5.1",
"safe-buffer": "^5.1.1",
"stringstream": "~0.0.5",
"tough-cookie": "~2.3.3",
"tunnel-agent": "^0.6.0",
"uuid": "^3.0.0"
"uuid": "^3.1.0"
},
"deprecated": false,
"description": "Simplified HTTP request client.",
"devDependencies": {
"bluebird": "^3.2.1",
"browserify": "^13.0.1",
"browserify-istanbul": "^2.0.0",
"buffer-equal": "^1.0.0",
"codecov": "^1.0.1",
"codecov": "^2.0.2",
"coveralls": "^2.11.4",
"eslint": "^2.5.3",
"function-bind": "^1.0.2",
"istanbul": "^0.4.0",
"karma": "^1.1.1",
@@ -87,32 +74,25 @@
"phantomjs-prebuilt": "^2.1.3",
"rimraf": "^2.2.8",
"server-destroy": "^1.0.1",
"standard": "^9.0.0",
"tape": "^4.6.0",
"taper": "^0.5.0"
},
"directories": {},
"dist": {
"shasum": "c6928946a0e06c5f8d6f8a9333469ffda46298a0",
"tarball": "https://registry.npmjs.org/request/-/request-2.81.0.tgz"
},
"engines": {
"node": ">= 4"
},
"files": [
"index.js",
"lib/",
"index.js",
"request.js"
],
"gitHead": "a0cdc704c19e63e6f1740e173bb003c51eef524c",
"greenkeeper": {
"ignore": [
"eslint",
"har-validator",
"hawk"
"hawk",
"har-validator"
]
},
"homepage": "https://github.com/request/request#readme",
"installable": true,
"keywords": [
"http",
"simple",
@@ -121,36 +101,17 @@
],
"license": "Apache-2.0",
"main": "index.js",
"maintainers": [
{
"name": "mikeal",
"email": "mikeal.rogers@gmail.com"
},
{
"name": "nylen",
"email": "jnylen@gmail.com"
},
{
"name": "fredkschott",
"email": "fkschott@gmail.com"
},
{
"name": "simov",
"email": "simeonvelichkov@gmail.com"
}
],
"name": "request",
"optionalDependencies": {},
"repository": {
"type": "git",
"url": "git+https://github.com/request/request.git"
},
"scripts": {
"lint": "eslint lib/ *.js tests/ && echo Lint passed.",
"lint": "standard",
"test": "npm run lint && npm run test-ci && npm run test-browser",
"test-browser": "node tests/browser/start.js",
"test-ci": "taper tests/test-*.js",
"test-cov": "istanbul cover tape tests/test-*.js"
},
"version": "2.81.0"
"version": "2.83.0"
}
+101 -114
View File
@@ -1,48 +1,47 @@
'use strict'
var http = require('http')
, https = require('https')
, url = require('url')
, util = require('util')
, stream = require('stream')
, zlib = require('zlib')
, hawk = require('hawk')
, aws2 = require('aws-sign2')
, aws4 = require('aws4')
, httpSignature = require('http-signature')
, mime = require('mime-types')
, stringstream = require('stringstream')
, caseless = require('caseless')
, ForeverAgent = require('forever-agent')
, FormData = require('form-data')
, extend = require('extend')
, isstream = require('isstream')
, isTypedArray = require('is-typedarray').strict
, helpers = require('./lib/helpers')
, cookies = require('./lib/cookies')
, getProxyFromURI = require('./lib/getProxyFromURI')
, Querystring = require('./lib/querystring').Querystring
, Har = require('./lib/har').Har
, Auth = require('./lib/auth').Auth
, OAuth = require('./lib/oauth').OAuth
, Multipart = require('./lib/multipart').Multipart
, Redirect = require('./lib/redirect').Redirect
, Tunnel = require('./lib/tunnel').Tunnel
, now = require('performance-now')
, Buffer = require('safe-buffer').Buffer
var https = require('https')
var url = require('url')
var util = require('util')
var stream = require('stream')
var zlib = require('zlib')
var hawk = require('hawk')
var aws2 = require('aws-sign2')
var aws4 = require('aws4')
var httpSignature = require('http-signature')
var mime = require('mime-types')
var stringstream = require('stringstream')
var caseless = require('caseless')
var ForeverAgent = require('forever-agent')
var FormData = require('form-data')
var extend = require('extend')
var isstream = require('isstream')
var isTypedArray = require('is-typedarray').strict
var helpers = require('./lib/helpers')
var cookies = require('./lib/cookies')
var getProxyFromURI = require('./lib/getProxyFromURI')
var Querystring = require('./lib/querystring').Querystring
var Har = require('./lib/har').Har
var Auth = require('./lib/auth').Auth
var OAuth = require('./lib/oauth').OAuth
var Multipart = require('./lib/multipart').Multipart
var Redirect = require('./lib/redirect').Redirect
var Tunnel = require('./lib/tunnel').Tunnel
var now = require('performance-now')
var Buffer = require('safe-buffer').Buffer
var safeStringify = helpers.safeStringify
, isReadStream = helpers.isReadStream
, toBase64 = helpers.toBase64
, defer = helpers.defer
, copy = helpers.copy
, version = helpers.version
, globalCookieJar = cookies.jar()
var isReadStream = helpers.isReadStream
var toBase64 = helpers.toBase64
var defer = helpers.defer
var copy = helpers.copy
var version = helpers.version
var globalCookieJar = cookies.jar()
var globalPool = {}
function filterForNonReserved(reserved, options) {
function filterForNonReserved (reserved, options) {
// Filter out properties that are not reserved.
// Reserved values are passed in at call site.
@@ -56,7 +55,7 @@ function filterForNonReserved(reserved, options) {
return object
}
function filterOutReservedFunctions(reserved, options) {
function filterOutReservedFunctions (reserved, options) {
// Filter out properties that are functions and are reserved.
// Reserved values are passed in at call site.
@@ -69,11 +68,10 @@ function filterOutReservedFunctions(reserved, options) {
}
}
return object
}
// Return a simpler request object to allow serialization
function requestToJSON() {
function requestToJSON () {
var self = this
return {
uri: self.uri,
@@ -83,7 +81,7 @@ function requestToJSON() {
}
// Return a simpler response object to allow serialization
function responseToJSON() {
function responseToJSON () {
var self = this
return {
statusCode: self.statusCode,
@@ -134,7 +132,7 @@ util.inherits(Request, stream.Stream)
// Debugging
Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
function debug() {
function debug () {
if (Request.debug) {
console.error('REQUEST %s', util.format.apply(util, arguments))
}
@@ -258,7 +256,7 @@ Request.prototype.init = function (options) {
self.rejectUnauthorized = false
}
if (!self.uri.pathname) {self.uri.pathname = '/'}
if (!self.uri.pathname) { self.uri.pathname = '/' }
if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
// Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
@@ -300,8 +298,7 @@ Request.prototype.init = function (options) {
self.jar(self._jar || options.jar)
if (!self.uri.port) {
if (self.uri.protocol === 'http:') {self.uri.port = 80}
else if (self.uri.protocol === 'https:') {self.uri.port = 443}
if (self.uri.protocol === 'http:') { self.uri.port = 80 } else if (self.uri.protocol === 'https:') { self.uri.port = 443 }
}
if (self.proxy && !self.tunnel) {
@@ -388,12 +385,12 @@ Request.prototype.init = function (options) {
}
if (self.uri.auth && !self.hasHeader('authorization')) {
var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item) })
self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
}
if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item) })
var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
self.setHeader('proxy-authorization', authHeader)
}
@@ -425,11 +422,9 @@ Request.prototype.init = function (options) {
var length
if (typeof self.body === 'string') {
length = Buffer.byteLength(self.body)
}
else if (Array.isArray(self.body)) {
length = self.body.reduce(function (a, b) {return a + b.length}, 0)
}
else {
} else if (Array.isArray(self.body)) {
length = self.body.reduce(function (a, b) { return a + b.length }, 0)
} else {
length = self.body.length
}
@@ -451,8 +446,8 @@ Request.prototype.init = function (options) {
}
var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
, defaultModules = {'http:':http, 'https:':https}
, httpModules = self.httpModules || {}
var defaultModules = {'http:': http, 'https:': https}
var httpModules = self.httpModules || {}
self.httpModule = httpModules[protocol] || defaultModules[protocol]
@@ -517,9 +512,9 @@ Request.prototype.init = function (options) {
}
}
// self.on('pipe', function () {
// console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
// })
// self.on('pipe', function () {
// console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
// })
})
defer(function () {
@@ -531,8 +526,7 @@ Request.prototype.init = function (options) {
if (self._form) {
if (!self._auth.hasAuth) {
self._form.pipe(self)
}
else if (self._auth.hasAuth && self._auth.sentAuth) {
} else if (self._auth.hasAuth && self._auth.sentAuth) {
self._form.pipe(self)
}
}
@@ -583,7 +577,6 @@ Request.prototype.init = function (options) {
self.ntick = true
})
}
Request.prototype.getNewAgent = function () {
@@ -778,21 +771,22 @@ Request.prototype.start = function () {
self.req.on('response', self.onRequestResponse.bind(self))
self.req.on('error', self.onRequestError.bind(self))
self.req.on('drain', function() {
self.req.on('drain', function () {
self.emit('drain')
})
self.req.on('socket', function(socket) {
self.req.on('socket', function (socket) {
// `._connecting` was the old property which was made public in node v6.1.0
var isConnecting = socket._connecting || socket.connecting
if (self.timing) {
self.timings.socket = now() - self.startTimeNow
if (isConnecting) {
var onLookupTiming = function() {
var onLookupTiming = function () {
self.timings.lookup = now() - self.startTimeNow
}
var onConnectTiming = function() {
var onConnectTiming = function () {
self.timings.connect = now() - self.startTimeNow
}
@@ -800,14 +794,14 @@ Request.prototype.start = function () {
socket.once('connect', onConnectTiming)
// clean up timing event listeners if needed on error
self.req.once('error', function() {
self.req.once('error', function () {
socket.removeListener('lookup', onLookupTiming)
socket.removeListener('connect', onConnectTiming)
})
}
}
var setReqTimeout = function() {
var setReqTimeout = function () {
// This timeout sets the amount of time to wait *between* bytes sent
// from the server once connected.
//
@@ -829,7 +823,7 @@ Request.prototype.start = function () {
// keep-alive connection) do not bother. This is important since we won't
// get a 'connect' event for an already connected socket.
if (isConnecting) {
var onReqSockConnect = function() {
var onReqSockConnect = function () {
socket.removeListener('connect', onReqSockConnect)
clearTimeout(self.timeoutTimer)
self.timeoutTimer = null
@@ -838,7 +832,7 @@ Request.prototype.start = function () {
socket.on('connect', onReqSockConnect)
self.req.on('error', function(err) {
self.req.on('error', function (err) { // eslint-disable-line handle-callback-err
socket.removeListener('connect', onReqSockConnect)
})
@@ -870,8 +864,8 @@ Request.prototype.onRequestError = function (error) {
if (self._aborted) {
return
}
if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
&& self.agent.addRequestNoreuse) {
if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' &&
self.agent.addRequestNoreuse) {
self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
self.start()
self.req.end()
@@ -892,7 +886,7 @@ Request.prototype.onRequestResponse = function (response) {
}
debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
response.on('end', function() {
response.on('end', function () {
if (self.timing) {
self.timings.end = now() - self.startTimeNow
response.timingStart = self.startTime
@@ -948,8 +942,8 @@ Request.prototype.onRequestResponse = function (response) {
// XXX This is different on 0.10, because SSL is strict by default
if (self.httpModule === https &&
self.strictSSL && (!response.hasOwnProperty('socket') ||
!response.socket.authorized)) {
self.strictSSL && (!response.hasOwnProperty('socket') ||
!response.socket.authorized)) {
debug('strict ssl error', self.uri.href)
var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
self.emit('error', new Error('SSL Error: ' + sslErr))
@@ -974,7 +968,7 @@ Request.prototype.onRequestResponse = function (response) {
var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
var addCookie = function (cookie) {
//set the cookie if it's domain in the href's domain.
// set the cookie if it's domain in the href's domain.
try {
targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
} catch (e) {
@@ -1010,13 +1004,13 @@ Request.prototype.onRequestResponse = function (response) {
var noBody = function (code) {
return (
self.method === 'HEAD'
self.method === 'HEAD' ||
// Informational
|| (code >= 100 && code < 200)
(code >= 100 && code < 200) ||
// No Content
|| code === 204
code === 204 ||
// Not Modified
|| code === 304
code === 304
)
}
@@ -1030,8 +1024,8 @@ Request.prototype.onRequestResponse = function (response) {
// by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does.
var zlibOptions = {
flush: zlib.Z_SYNC_FLUSH
, finishFlush: zlib.Z_SYNC_FLUSH
flush: zlib.Z_SYNC_FLUSH,
finishFlush: zlib.Z_SYNC_FLUSH
}
if (contentEncoding === 'gzip') {
@@ -1093,13 +1087,11 @@ Request.prototype.onRequestResponse = function (response) {
responseContent.on('error', function (error) {
self.emit('error', error)
})
responseContent.on('close', function () {self.emit('close')})
responseContent.on('close', function () { self.emit('close') })
if (self.callback) {
self.readResponseBody(response)
}
//if no callback
else {
} else { // if no callback
self.on('end', function () {
if (self._aborted) {
debug('aborted', self.uri.href)
@@ -1114,10 +1106,10 @@ Request.prototype.onRequestResponse = function (response) {
Request.prototype.readResponseBody = function (response) {
var self = this
debug('reading response\'s body')
debug("reading response's body")
var buffers = []
, bufferLength = 0
, strings = []
var bufferLength = 0
var strings = []
self.on('data', function (chunk) {
if (!Buffer.isBuffer(chunk)) {
@@ -1178,8 +1170,7 @@ Request.prototype.abort = function () {
if (self.req) {
self.req.abort()
}
else if (self.response) {
} else if (self.response) {
self.response.destroy()
}
@@ -1195,8 +1186,7 @@ Request.prototype.pipeDest = function (dest) {
var ctname = response.caseless.has('content-type')
if (dest.setHeader) {
dest.setHeader(ctname, response.headers[ctname])
}
else {
} else {
dest.headers[ctname] = response.headers[ctname]
}
}
@@ -1267,7 +1257,7 @@ Request.prototype.form = function (form) {
}
// create form-data object
self._form = new FormData()
self._form.on('error', function(err) {
self._form.on('error', function (err) {
err.message = 'form-data: ' + err.message
self.emit('error', err)
self.abort()
@@ -1342,8 +1332,8 @@ Request.prototype.getHeader = function (name, headers) {
Request.prototype.enableUnixSocket = function () {
// Get the socket & request paths from the URL
var unixParts = this.uri.path.split(':')
, host = unixParts[0]
, path = unixParts[1]
var host = unixParts[0]
var path = unixParts[1]
// Apply unix properties to request
this.socketPath = host
this.uri.pathname = path
@@ -1353,7 +1343,6 @@ Request.prototype.enableUnixSocket = function () {
this.uri.isUnix = true
}
Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
var self = this
@@ -1369,7 +1358,7 @@ Request.prototype.aws = function (opts, now) {
return self
}
if (opts.sign_version == 4 || opts.sign_version == '4') {
if (opts.sign_version === 4 || opts.sign_version === '4') {
// use aws4
var options = {
host: self.uri.host,
@@ -1390,20 +1379,19 @@ Request.prototype.aws = function (opts, now) {
if (signRes.headers['X-Amz-Security-Token']) {
self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
}
}
else {
} else {
// default: use aws-sign2
var date = new Date()
self.setHeader('date', date.toUTCString())
var auth =
{ key: opts.key
, secret: opts.secret
, verb: self.method.toUpperCase()
, date: date
, contentType: self.getHeader('content-type') || ''
, md5: self.getHeader('content-md5') || ''
, amazonHeaders: aws2.canonicalizeHeaders(self.headers)
}
var auth = {
key: opts.key,
secret: opts.secret,
verb: self.method.toUpperCase(),
date: date,
contentType: self.getHeader('content-type') || '',
md5: self.getHeader('content-md5') || '',
amazonHeaders: aws2.canonicalizeHeaders(self.headers)
}
var path = self.uri.path
if (opts.bucket && path) {
auth.resource = '/' + opts.bucket + path
@@ -1423,10 +1411,10 @@ Request.prototype.aws = function (opts, now) {
Request.prototype.httpSignature = function (opts) {
var self = this
httpSignature.signRequest({
getHeader: function(header) {
getHeader: function (header) {
return self.getHeader(header, self.headers)
},
setHeader: function(header, value) {
setHeader: function (header, value) {
self.setHeader(header, value)
},
method: self.method,
@@ -1463,13 +1451,13 @@ Request.prototype.jar = function (jar) {
} else {
var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
var urihref = self.uri.href
//fetch cookie in the Specified host
// fetch cookie in the Specified host
if (targetCookieJar) {
cookies = targetCookieJar.getCookieString(urihref)
}
}
//if need cookie and cookie is not empty
// if need cookie and cookie is not empty
if (cookies && cookies.length) {
if (self.originalCookieHeader) {
// Don't overwrite existing Cookie header
@@ -1482,7 +1470,6 @@ Request.prototype.jar = function (jar) {
return self
}
// Stream API
Request.prototype.pipe = function (dest, opts) {
var self = this
@@ -1505,7 +1492,7 @@ Request.prototype.pipe = function (dest, opts) {
}
Request.prototype.write = function () {
var self = this
if (self._aborted) {return}
if (self._aborted) { return }
if (!self._started) {
self.start()
@@ -1516,7 +1503,7 @@ Request.prototype.write = function () {
}
Request.prototype.end = function (chunk) {
var self = this
if (self._aborted) {return}
if (self._aborted) { return }
if (chunk) {
self.write(chunk)
-47
View File
@@ -1,47 +0,0 @@
{
"root": true,
"env": {
"browser": true,
"commonjs": true,
"node": true,
"mocha": true
},
"extends": ["eslint:recommended"],
"rules": {
"array-bracket-spacing": ["warn", "never"],
"arrow-body-style": ["warn", "as-needed"],
"arrow-parens": ["warn", "as-needed"],
"arrow-spacing": "warn",
"brace-style": ["warn", "1tbs"],
"camelcase": "warn",
"comma-spacing": ["warn", {"after": true}],
"dot-notation": "warn",
"eqeqeq": ["warn", "smart"],
"indent": ["warn", 2, {
"SwitchCase": 1,
"FunctionDeclaration": {"parameters": 1},
"MemberExpression": 1,
"CallExpression": {"arguments": 1}
}],
"key-spacing": ["warn", {"beforeColon": false, "afterColon": true, "mode": "minimum"}],
"keyword-spacing": "warn",
"no-console": "off",
"no-empty": "off",
"no-multi-spaces": "warn",
"no-redeclare": "off",
"no-restricted-globals": ["warn", "Promise"],
"no-trailing-spaces": "warn",
"no-undef": "error",
"no-unused-vars": ["warn", {"args": "none"}],
"one-var": ["warn", "never"],
"padded-blocks": ["warn", "never"],
"object-curly-spacing": ["warn", "never"],
"quotes": ["warn", "single"],
"react/prop-types": "off",
"react/jsx-no-bind": "off",
"semi": ["warn", "always"],
"space-before-blocks": ["warn", "always"],
"space-before-function-paren": ["warn", "never"],
"space-in-parens": ["warn", "never"]
}
}
-5
View File
@@ -1,5 +0,0 @@
Robert Kieffer <robert@broofa.com>
Christoph Tavan <dev@tavan.de>
AJ ONeal <coolaj86@gmail.com>
Vincent Voyer <vincent@zeroload.net>
Roman Shtylman <shtylman@gmail.com>
-57
View File
@@ -1,57 +0,0 @@
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="3.2.1"></a>
## [3.2.1](https://github.com/kelektiv/node-uuid/compare/v3.1.0...v3.2.1) (2018-01-16)
### Bug Fixes
* use msCrypto if available. Fixes [#241](https://github.com/kelektiv/node-uuid/issues/241) ([#247](https://github.com/kelektiv/node-uuid/issues/247)) ([1fef18b](https://github.com/kelektiv/node-uuid/commit/1fef18b))
<a name="3.2.0"></a>
# [3.2.0](https://github.com/kelektiv/node-uuid/compare/v3.1.0...v3.2.0) (2018-01-16)
### Bug Fixes
* remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/kelektiv/node-uuid/commit/09fa824))
* use msCrypto if available. Fixes [#241](https://github.com/kelektiv/node-uuid/issues/241) ([#247](https://github.com/kelektiv/node-uuid/issues/247)) ([1fef18b](https://github.com/kelektiv/node-uuid/commit/1fef18b))
### Features
* Add v3 Support ([#217](https://github.com/kelektiv/node-uuid/issues/217)) ([d94f726](https://github.com/kelektiv/node-uuid/commit/d94f726))
# 3.0.1 (2016-11-28)
* split uuid versions into separate files
# 3.0.0 (2016-11-17)
* remove .parse and .unparse
# 2.0.0
* Removed uuid.BufferClass
# 1.4.0
* Improved module context detection
* Removed public RNG functions
# 1.3.2
* Improve tests and handling of v1() options (Issue #24)
* Expose RNG option to allow for perf testing with different generators
# 1.3.0
* Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)!
* Support for node.js crypto API
* De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code
-293
View File
@@ -1,293 +0,0 @@
<!--
-- This file is auto-generated from README_js.md. Changes should be made there.
-->
# uuid [![Build Status](https://secure.travis-ci.org/kelektiv/node-uuid.svg?branch=master)](http://travis-ci.org/kelektiv/node-uuid) #
Simple, fast generation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDS.
Features:
* Support for version 1, 3, 4 and 5 UUIDs
* Cross-platform
* Uses cryptographically-strong random number APIs (when available)
* Zero-dependency, small footprint (... but not [this small](https://gist.github.com/982883))
[**Deprecation warning**: The use of `require('uuid')` is deprecated and will not be
supported after version 3.x of this module. Instead, use `require('uuid/[v1|v3|v4|v5]')` as shown in the examples below.]
## Quickstart - CommonJS (Recommended)
```shell
npm install uuid
```
Then generate your uuid version of choice ...
Version 1 (timestamp):
```javascript
const uuidv1 = require('uuid/v1');
uuidv1(); // ⇨ 'f64f2940-fae4-11e7-8c5f-ef356f279131'
```
Version 3 (namespace):
```javascript
const uuidv3 = require('uuid/v3');
// ... using predefined DNS namespace (for domain names)
uuidv3('hello.example.com', uuidv3.DNS); // ⇨ '9125a8dc-52ee-365b-a5aa-81b0b3681cf6'
// ... using predefined URL namespace (for, well, URLs)
uuidv3('http://example.com/hello', uuidv3.URL); // ⇨ 'c6235813-3ba4-3801-ae84-e0a6ebb7d138'
// ... using a custom namespace
//
// Note: Custom namespaces should be a UUID string specific to your application!
// E.g. the one here was generated using this modules `uuid` CLI.
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
uuidv3('Hello, World!', MY_NAMESPACE); // ⇨ 'e8b5a51d-11c8-3310-a6ab-367563f20686'
```
Version 4 (random):
```javascript
const uuidv4 = require('uuid/v4');
uuidv4(); // ⇨ '416ac246-e7ac-49ff-93b4-f7e94d997e6b'
```
Version 5 (namespace):
```javascript
const uuidv5 = require('uuid/v5');
// ... using predefined DNS namespace (for domain names)
uuidv5('hello.example.com', uuidv5.DNS); // ⇨ 'fdda765f-fc57-5604-a269-52a7df8164ec'
// ... using predefined URL namespace (for, well, URLs)
uuidv5('http://example.com/hello', uuidv5.URL); // ⇨ '3bbcee75-cecc-5b56-8031-b6641c1ed1f1'
// ... using a custom namespace
//
// Note: Custom namespaces should be a UUID string specific to your application!
// E.g. the one here was generated using this modules `uuid` CLI.
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681'
```
## Quickstart - Browser-ready Versions
Browser-ready versions of this module are available via [wzrd.in](https://github.com/jfhbrook/wzrd.in).
For version 1 uuids:
```html
<script src="http://wzrd.in/standalone/uuid%2Fv1@latest"></script>
<script>
uuidv1(); // -> v1 UUID
</script>
```
For version 3 uuids:
```html
<script src="http://wzrd.in/standalone/uuid%2Fv3@latest"></script>
<script>
uuidv3('http://example.com/hello', uuidv3.URL); // -> v3 UUID
</script>
```
For version 4 uuids:
```html
<script src="http://wzrd.in/standalone/uuid%2Fv4@latest"></script>
<script>
uuidv4(); // -> v4 UUID
</script>
```
For version 5 uuids:
```html
<script src="http://wzrd.in/standalone/uuid%2Fv5@latest"></script>
<script>
uuidv5('http://example.com/hello', uuidv5.URL); // -> v5 UUID
</script>
```
## API
### Version 1
```javascript
const uuidv1 = require('uuid/v1');
// Incantations
uuidv1();
uuidv1(options);
uuidv1(options, buffer, offset);
```
Generate and return a RFC4122 v1 (timestamp-based) UUID.
* `options` - (Object) Optional uuid state to apply. Properties may include:
* `node` - (Array) Node id as Array of 6 bytes (per 4.1.6). Default: Randomly generated ID. See note 1.
* `clockseq` - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used.
* `msecs` - (Number) Time in milliseconds since unix Epoch. Default: The current time is used.
* `nsecs` - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if `msecs` is unspecified. Default: internal uuid counter is used, as per 4.2.1.2.
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
* `offset` - (Number) Starting index in `buffer` at which to begin writing.
Returns `buffer`, if specified, otherwise the string form of the UUID
Note: The <node> id is generated guaranteed to stay constant for the lifetime of the current JS runtime. (Future versions of this module may use persistent storage mechanisms to extend this guarantee.)
Example: Generate string UUID with fully-specified options
```javascript
const v1options = {
node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
clockseq: 0x1234,
msecs: new Date('2011-11-01').getTime(),
nsecs: 5678
};
uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab'
```
Example: In-place generation of two binary IDs
```javascript
// Generate two ids in an array
const arr = new Array();
uuidv1(null, arr, 0); // ⇨ [ 246, 87, 141, 176, 250, 228, 17, 231, 146, 52, 239, 53, 111, 39, 145, 49 ]
uuidv1(null, arr, 16); // ⇨ [ 246, 87, 141, 176, 250, 228, 17, 231, 146, 52, 239, 53, 111, 39, 145, 49, 246, 87, 180, 192, 250, 228, 17, 231, 146, 52, 239, 53, 111, 39, 145, 49 ]
```
### Version 3
```javascript
const uuidv3 = require('uuid/v3');
// Incantations
uuidv3(name, namespace);
uuidv3(name, namespace, buffer);
uuidv3(name, namespace, buffer, offset);
```
Generate and return a RFC4122 v3 UUID.
* `name` - (String | Array[]) "name" to create UUID with
* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0
Returns `buffer`, if specified, otherwise the string form of the UUID
Example:
```javascript
uuidv3('hello world', MY_NAMESPACE); // ⇨ '042ffd34-d989-321c-ad06-f60826172424'
```
### Version 4
```javascript
const uuidv4 = require('uuid/v4')
// Incantations
uuidv4();
uuidv4(options);
uuidv4(options, buffer, offset);
```
Generate and return a RFC4122 v4 UUID.
* `options` - (Object) Optional uuid state to apply. Properties may include:
* `random` - (Number[16]) Array of 16 numbers (0-255) to use in place of randomly generated values
* `rng` - (Function) Random # generator function that returns an Array[16] of byte values (0-255)
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
* `offset` - (Number) Starting index in `buffer` at which to begin writing.
Returns `buffer`, if specified, otherwise the string form of the UUID
Example: Generate string UUID with predefined `random` values
```javascript
const v4options = {
random: [
0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea,
0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36
]
};
uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836'
```
Example: Generate two IDs in a single buffer
```javascript
const buffer = new Array();
uuidv4(null, buffer, 0); // ⇨ [ 175, 10, 162, 184, 217, 255, 77, 139, 161, 80, 41, 200, 70, 238, 196, 250 ]
uuidv4(null, buffer, 16); // ⇨ [ 175, 10, 162, 184, 217, 255, 77, 139, 161, 80, 41, 200, 70, 238, 196, 250, 75, 162, 105, 153, 48, 238, 77, 58, 169, 56, 158, 207, 106, 160, 47, 239 ]
```
### Version 5
```javascript
const uuidv5 = require('uuid/v5');
// Incantations
uuidv5(name, namespace);
uuidv5(name, namespace, buffer);
uuidv5(name, namespace, buffer, offset);
```
Generate and return a RFC4122 v5 UUID.
* `name` - (String | Array[]) "name" to create UUID with
* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0
Returns `buffer`, if specified, otherwise the string form of the UUID
Example:
```javascript
uuidv5('hello world', MY_NAMESPACE); // ⇨ '9f282611-e0fd-5650-8953-89c8e342da0b'
```
## Command Line
UUIDs can be generated from the command line with the `uuid` command.
```shell
$ uuid
ddeb27fb-d9a0-4624-be4d-4615062daed4
$ uuid v1
02d37060-d446-11e7-a9fa-7bdae751ebe1
```
Type `uuid --help` for usage details
## Testing
```shell
npm test
```
----
Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd)
-280
View File
@@ -1,280 +0,0 @@
```javascript --hide
runmd.onRequire = path => path.replace(/^uuid/, './');
```
# uuid [![Build Status](https://secure.travis-ci.org/kelektiv/node-uuid.svg?branch=master)](http://travis-ci.org/kelektiv/node-uuid) #
Simple, fast generation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDS.
Features:
* Support for version 1, 3, 4 and 5 UUIDs
* Cross-platform
* Uses cryptographically-strong random number APIs (when available)
* Zero-dependency, small footprint (... but not [this small](https://gist.github.com/982883))
[**Deprecation warning**: The use of `require('uuid')` is deprecated and will not be
supported after version 3.x of this module. Instead, use `require('uuid/[v1|v3|v4|v5]')` as shown in the examples below.]
## Quickstart - CommonJS (Recommended)
```shell
npm install uuid
```
Then generate your uuid version of choice ...
Version 1 (timestamp):
```javascript --run v1
const uuidv1 = require('uuid/v1');
uuidv1(); // RESULT
```
Version 3 (namespace):
```javascript --run v3
const uuidv3 = require('uuid/v3');
// ... using predefined DNS namespace (for domain names)
uuidv3('hello.example.com', uuidv3.DNS); // RESULT
// ... using predefined URL namespace (for, well, URLs)
uuidv3('http://example.com/hello', uuidv3.URL); // RESULT
// ... using a custom namespace
//
// Note: Custom namespaces should be a UUID string specific to your application!
// E.g. the one here was generated using this modules `uuid` CLI.
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
uuidv3('Hello, World!', MY_NAMESPACE); // RESULT
```
Version 4 (random):
```javascript --run v4
const uuidv4 = require('uuid/v4');
uuidv4(); // RESULT
```
Version 5 (namespace):
```javascript --run v5
const uuidv5 = require('uuid/v5');
// ... using predefined DNS namespace (for domain names)
uuidv5('hello.example.com', uuidv5.DNS); // RESULT
// ... using predefined URL namespace (for, well, URLs)
uuidv5('http://example.com/hello', uuidv5.URL); // RESULT
// ... using a custom namespace
//
// Note: Custom namespaces should be a UUID string specific to your application!
// E.g. the one here was generated using this modules `uuid` CLI.
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
uuidv5('Hello, World!', MY_NAMESPACE); // RESULT
```
## Quickstart - Browser-ready Versions
Browser-ready versions of this module are available via [wzrd.in](https://github.com/jfhbrook/wzrd.in).
For version 1 uuids:
```html
<script src="http://wzrd.in/standalone/uuid%2Fv1@latest"></script>
<script>
uuidv1(); // -> v1 UUID
</script>
```
For version 3 uuids:
```html
<script src="http://wzrd.in/standalone/uuid%2Fv3@latest"></script>
<script>
uuidv3('http://example.com/hello', uuidv3.URL); // -> v3 UUID
</script>
```
For version 4 uuids:
```html
<script src="http://wzrd.in/standalone/uuid%2Fv4@latest"></script>
<script>
uuidv4(); // -> v4 UUID
</script>
```
For version 5 uuids:
```html
<script src="http://wzrd.in/standalone/uuid%2Fv5@latest"></script>
<script>
uuidv5('http://example.com/hello', uuidv5.URL); // -> v5 UUID
</script>
```
## API
### Version 1
```javascript
const uuidv1 = require('uuid/v1');
// Incantations
uuidv1();
uuidv1(options);
uuidv1(options, buffer, offset);
```
Generate and return a RFC4122 v1 (timestamp-based) UUID.
* `options` - (Object) Optional uuid state to apply. Properties may include:
* `node` - (Array) Node id as Array of 6 bytes (per 4.1.6). Default: Randomly generated ID. See note 1.
* `clockseq` - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used.
* `msecs` - (Number) Time in milliseconds since unix Epoch. Default: The current time is used.
* `nsecs` - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if `msecs` is unspecified. Default: internal uuid counter is used, as per 4.2.1.2.
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
* `offset` - (Number) Starting index in `buffer` at which to begin writing.
Returns `buffer`, if specified, otherwise the string form of the UUID
Note: The <node> id is generated guaranteed to stay constant for the lifetime of the current JS runtime. (Future versions of this module may use persistent storage mechanisms to extend this guarantee.)
Example: Generate string UUID with fully-specified options
```javascript --run v1
const v1options = {
node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
clockseq: 0x1234,
msecs: new Date('2011-11-01').getTime(),
nsecs: 5678
};
uuidv1(v1options); // RESULT
```
Example: In-place generation of two binary IDs
```javascript --run v1
// Generate two ids in an array
const arr = new Array();
uuidv1(null, arr, 0); // RESULT
uuidv1(null, arr, 16); // RESULT
```
### Version 3
```javascript
const uuidv3 = require('uuid/v3');
// Incantations
uuidv3(name, namespace);
uuidv3(name, namespace, buffer);
uuidv3(name, namespace, buffer, offset);
```
Generate and return a RFC4122 v3 UUID.
* `name` - (String | Array[]) "name" to create UUID with
* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0
Returns `buffer`, if specified, otherwise the string form of the UUID
Example:
```javascript --run v3
uuidv3('hello world', MY_NAMESPACE); // RESULT
```
### Version 4
```javascript
const uuidv4 = require('uuid/v4')
// Incantations
uuidv4();
uuidv4(options);
uuidv4(options, buffer, offset);
```
Generate and return a RFC4122 v4 UUID.
* `options` - (Object) Optional uuid state to apply. Properties may include:
* `random` - (Number[16]) Array of 16 numbers (0-255) to use in place of randomly generated values
* `rng` - (Function) Random # generator function that returns an Array[16] of byte values (0-255)
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
* `offset` - (Number) Starting index in `buffer` at which to begin writing.
Returns `buffer`, if specified, otherwise the string form of the UUID
Example: Generate string UUID with predefined `random` values
```javascript --run v4
const v4options = {
random: [
0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea,
0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36
]
};
uuidv4(v4options); // RESULT
```
Example: Generate two IDs in a single buffer
```javascript --run v4
const buffer = new Array();
uuidv4(null, buffer, 0); // RESULT
uuidv4(null, buffer, 16); // RESULT
```
### Version 5
```javascript
const uuidv5 = require('uuid/v5');
// Incantations
uuidv5(name, namespace);
uuidv5(name, namespace, buffer);
uuidv5(name, namespace, buffer, offset);
```
Generate and return a RFC4122 v5 UUID.
* `name` - (String | Array[]) "name" to create UUID with
* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0
Returns `buffer`, if specified, otherwise the string form of the UUID
Example:
```javascript --run v5
uuidv5('hello world', MY_NAMESPACE); // RESULT
```
## Command Line
UUIDs can be generated from the command line with the `uuid` command.
```shell
$ uuid
ddeb27fb-d9a0-4624-be4d-4615062daed4
$ uuid v1
02d37060-d446-11e7-a9fa-7bdae751ebe1
```
Type `uuid --help` for usage details
## Testing
```shell
npm test
```
-65
View File
@@ -1,65 +0,0 @@
#!/usr/bin/env node
var assert = require('assert');
function usage() {
console.log('Usage:');
console.log(' uuid');
console.log(' uuid v1');
console.log(' uuid v3 <name> <namespace uuid>');
console.log(' uuid v4');
console.log(' uuid v5 <name> <namespace uuid>');
console.log(' uuid --help');
console.log('\nNote: <namespace uuid> may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122');
}
var args = process.argv.slice(2);
if (args.indexOf('--help') >= 0) {
usage();
process.exit(0);
}
var version = args.shift() || 'v4';
switch (version) {
case 'v1':
var uuidV1 = require('../v1');
console.log(uuidV1());
break;
case 'v3':
var uuidV3 = require('../v3');
var name = args.shift();
var namespace = args.shift();
assert(name != null, 'v3 name not specified');
assert(namespace != null, 'v3 namespace not specified');
if (namespace == 'URL') namespace = uuidV3.URL;
if (namespace == 'DNS') namespace = uuidV3.DNS;
console.log(uuidV3(name, namespace));
break;
case 'v4':
var uuidV4 = require('../v4');
console.log(uuidV4());
break;
case 'v5':
var uuidV5 = require('../v5');
var name = args.shift();
var namespace = args.shift();
assert(name != null, 'v5 name not specified');
assert(namespace != null, 'v5 namespace not specified');
if (namespace == 'URL') namespace = uuidV5.URL;
if (namespace == 'DNS') namespace = uuidV5.DNS;
console.log(uuidV5(name, namespace));
break;
default:
usage();
process.exit(1);
}
-8
View File
@@ -1,8 +0,0 @@
var v1 = require('./v1');
var v4 = require('./v4');
var uuid = v4;
uuid.v1 = v1;
uuid.v4 = v4;
module.exports = uuid;
-23
View File
@@ -1,23 +0,0 @@
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
byteToHex[i] = (i + 0x100).toString(16).substr(1);
}
function bytesToUuid(buf, offset) {
var i = offset || 0;
var bth = byteToHex;
return bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]];
}
module.exports = bytesToUuid;
-216
View File
@@ -1,216 +0,0 @@
/*
* Browser-compatible JavaScript MD5
*
* Modification of JavaScript MD5
* https://github.com/blueimp/JavaScript-MD5
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*
* Based on
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
'use strict';
function md5(bytes) {
if (typeof(bytes) == 'string') {
var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
bytes = new Array(msg.length);
for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i);
}
return md5ToHexEncodedArray(
wordsToMd5(
bytesToWords(bytes)
, bytes.length * 8)
);
}
/*
* Convert an array of little-endian words to an array of bytes
*/
function md5ToHexEncodedArray(input) {
var i;
var x;
var output = [];
var length32 = input.length * 32;
var hexTab = '0123456789abcdef';
var hex;
for (i = 0; i < length32; i += 8) {
x = (input[i >> 5] >>> (i % 32)) & 0xFF;
hex = parseInt(hexTab.charAt((x >>> 4) & 0x0F) + hexTab.charAt(x & 0x0F), 16);
output.push(hex);
}
return output;
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function wordsToMd5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << (len % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var i;
var olda;
var oldb;
var oldc;
var oldd;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for (i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5ff(a, b, c, d, x[i], 7, -680876936);
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5gg(b, c, d, a, x[i], 20, -373897302);
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5hh(d, a, b, c, x[i], 11, -358537222);
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5ii(a, b, c, d, x[i], 6, -198630844);
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safeAdd(a, olda);
b = safeAdd(b, oldb);
c = safeAdd(c, oldc);
d = safeAdd(d, oldd);
}
return [a, b, c, d];
}
/*
* Convert an array bytes to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function bytesToWords(input) {
var i;
var output = [];
output[(input.length >> 2) - 1] = undefined;
for (i = 0; i < output.length; i += 1) {
output[i] = 0;
}
var length8 = input.length * 8;
for (i = 0; i < length8; i += 8) {
output[i >> 5] |= (input[(i / 8)] & 0xFF) << (i % 32);
}
return output;
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safeAdd(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bitRotateLeft(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5cmn(q, a, b, x, s, t) {
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
}
function md5ff(a, b, c, d, x, s, t) {
return md5cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5gg(a, b, c, d, x, s, t) {
return md5cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5hh(a, b, c, d, x, s, t) {
return md5cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5ii(a, b, c, d, x, s, t) {
return md5cmn(c ^ (b | (~d)), a, b, x, s, t);
}
module.exports = md5;
-25
View File
@@ -1,25 +0,0 @@
'use strict';
var crypto = require('crypto');
function md5(bytes) {
if (typeof Buffer.from === 'function') {
// Modern Buffer API
if (Array.isArray(bytes)) {
bytes = Buffer.from(bytes);
} else if (typeof bytes === 'string') {
bytes = Buffer.from(bytes, 'utf8');
}
} else {
// Pre-v4 Buffer API
if (Array.isArray(bytes)) {
bytes = new Buffer(bytes);
} else if (typeof bytes === 'string') {
bytes = new Buffer(bytes, 'utf8');
}
}
return crypto.createHash('md5').update(bytes).digest();
}
module.exports = md5;
-32
View File
@@ -1,32 +0,0 @@
// Unique ID creation requires a high quality random # generator. In the
// browser this is a little complicated due to unknown quality of Math.random()
// and inconsistent support for the `crypto` API. We do the best we can via
// feature-detection
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) ||
(typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto));
if (getRandomValues) {
// WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
module.exports = function whatwgRNG() {
getRandomValues(rnds8);
return rnds8;
};
} else {
// Math.random()-based (RNG)
//
// If all else fails, use Math.random(). It's fast, but is of unspecified
// quality.
var rnds = new Array(16);
module.exports = function mathRNG() {
for (var i = 0, r; i < 16; i++) {
if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return rnds;
};
}
-8
View File
@@ -1,8 +0,0 @@
// Unique ID creation requires a high quality random # generator. In node.js
// this is pretty straight-forward - we use the crypto API.
var crypto = require('crypto');
module.exports = function nodeRNG() {
return crypto.randomBytes(16);
};
-89
View File
@@ -1,89 +0,0 @@
// Adapted from Chris Veness' SHA1 code at
// http://www.movable-type.co.uk/scripts/sha1.html
'use strict';
function f(s, x, y, z) {
switch (s) {
case 0: return (x & y) ^ (~x & z);
case 1: return x ^ y ^ z;
case 2: return (x & y) ^ (x & z) ^ (y & z);
case 3: return x ^ y ^ z;
}
}
function ROTL(x, n) {
return (x << n) | (x>>> (32 - n));
}
function sha1(bytes) {
var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
if (typeof(bytes) == 'string') {
var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
bytes = new Array(msg.length);
for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i);
}
bytes.push(0x80);
var l = bytes.length/4 + 2;
var N = Math.ceil(l/16);
var M = new Array(N);
for (var i=0; i<N; i++) {
M[i] = new Array(16);
for (var j=0; j<16; j++) {
M[i][j] =
bytes[i * 64 + j * 4] << 24 |
bytes[i * 64 + j * 4 + 1] << 16 |
bytes[i * 64 + j * 4 + 2] << 8 |
bytes[i * 64 + j * 4 + 3];
}
}
M[N - 1][14] = ((bytes.length - 1) * 8) /
Math.pow(2, 32); M[N - 1][14] = Math.floor(M[N - 1][14]);
M[N - 1][15] = ((bytes.length - 1) * 8) & 0xffffffff;
for (var i=0; i<N; i++) {
var W = new Array(80);
for (var t=0; t<16; t++) W[t] = M[i][t];
for (var t=16; t<80; t++) {
W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
}
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
for (var t=0; t<80; t++) {
var s = Math.floor(t/20);
var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
e = d;
d = c;
c = ROTL(b, 30) >>> 0;
b = a;
a = T;
}
H[0] = (H[0] + a) >>> 0;
H[1] = (H[1] + b) >>> 0;
H[2] = (H[2] + c) >>> 0;
H[3] = (H[3] + d) >>> 0;
H[4] = (H[4] + e) >>> 0;
}
return [
H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff,
H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff,
H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff,
H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff,
H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff
];
}
module.exports = sha1;
-25
View File
@@ -1,25 +0,0 @@
'use strict';
var crypto = require('crypto');
function sha1(bytes) {
if (typeof Buffer.from === 'function') {
// Modern Buffer API
if (Array.isArray(bytes)) {
bytes = Buffer.from(bytes);
} else if (typeof bytes === 'string') {
bytes = Buffer.from(bytes, 'utf8');
}
} else {
// Pre-v4 Buffer API
if (Array.isArray(bytes)) {
bytes = new Buffer(bytes);
} else if (typeof bytes === 'string') {
bytes = new Buffer(bytes, 'utf8');
}
}
return crypto.createHash('sha1').update(bytes).digest();
}
module.exports = sha1;
-53
View File
@@ -1,53 +0,0 @@
var bytesToUuid = require('./bytesToUuid');
function uuidToBytes(uuid) {
// Note: We assume we're being passed a valid uuid string
var bytes = [];
uuid.replace(/[a-fA-F0-9]{2}/g, function(hex) {
bytes.push(parseInt(hex, 16));
});
return bytes;
}
function stringToBytes(str) {
str = unescape(encodeURIComponent(str)); // UTF8 escape
var bytes = new Array(str.length);
for (var i = 0; i < str.length; i++) {
bytes[i] = str.charCodeAt(i);
}
return bytes;
}
module.exports = function(name, version, hashfunc) {
var generateUUID = function(value, namespace, buf, offset) {
var off = buf && offset || 0;
if (typeof(value) == 'string') value = stringToBytes(value);
if (typeof(namespace) == 'string') namespace = uuidToBytes(namespace);
if (!Array.isArray(value)) throw TypeError('value must be an array of bytes');
if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values');
// Per 4.3
var bytes = hashfunc(namespace.concat(value));
bytes[6] = (bytes[6] & 0x0f) | version;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
if (buf) {
for (var idx = 0; idx < 16; ++idx) {
buf[off+idx] = bytes[idx];
}
}
return buf || bytesToUuid(bytes);
};
generateUUID.name = name;
// Pre-defined namespaces, per Appendix C
generateUUID.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
generateUUID.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
return generateUUID;
};
-123
View File
@@ -1,123 +0,0 @@
{
"_args": [
[
"uuid@^3.0.0",
"c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage"
]
],
"_from": "uuid@>=3.0.0-0 <4.0.0-0",
"_id": "uuid@3.2.1",
"_inCache": true,
"_location": "/azure-storage/uuid",
"_nodeVersion": "7.10.1",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/uuid-3.2.1.tgz_1516124697652_0.3172094284091145"
},
"_npmUser": {
"email": "robert@broofa.com",
"name": "broofa"
},
"_npmVersion": "5.5.1",
"_phantomChildren": {},
"_requested": {
"name": "uuid",
"raw": "uuid@^3.0.0",
"rawSpec": "^3.0.0",
"scope": null,
"spec": ">=3.0.0-0 <4.0.0-0",
"type": "range"
},
"_requiredBy": [
"/azure-storage",
"/azure-storage/request"
],
"_resolved": "https://registry.npmjs.org/uuid/-/uuid-3.2.1.tgz",
"_shasum": "12c528bb9d58d0b9265d9a2f6f0fe8be17ff1f14",
"_shrinkwrap": null,
"_spec": "uuid@^3.0.0",
"_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage",
"bin": {
"uuid": "./bin/uuid"
},
"browser": {
"./lib/md5.js": "./lib/md5-browser.js",
"./lib/rng.js": "./lib/rng-browser.js",
"./lib/sha1.js": "./lib/sha1-browser.js"
},
"bugs": {
"url": "https://github.com/kelektiv/node-uuid/issues"
},
"contributors": [
{
"name": "Robert Kieffer",
"email": "robert@broofa.com"
},
{
"name": "Christoph Tavan",
"email": "dev@tavan.de"
},
{
"name": "AJ ONeal",
"email": "coolaj86@gmail.com"
},
{
"name": "Vincent Voyer",
"email": "vincent@zeroload.net"
},
{
"name": "Roman Shtylman",
"email": "shtylman@gmail.com"
}
],
"dependencies": {},
"description": "RFC4122 (v1, v4, and v5) UUIDs",
"devDependencies": {
"eslint": "4.5.0",
"mocha": "3.1.2",
"runmd": "1.0.1",
"standard-version": "4.2.0"
},
"directories": {},
"dist": {
"integrity": "sha512-jZnMwlb9Iku/O3smGWvZhauCf6cvvpKi4BKRiliS3cxnI+Gz9j5MEpTz2UFuXiKPJocb7gnsLHwiS05ige5BEA==",
"shasum": "12c528bb9d58d0b9265d9a2f6f0fe8be17ff1f14",
"tarball": "https://registry.npmjs.org/uuid/-/uuid-3.2.1.tgz"
},
"gitHead": "ce7d3176fc927ab83b4e29b8d5a37b7243ce3360",
"homepage": "https://github.com/kelektiv/node-uuid#readme",
"installable": true,
"keywords": [
"guid",
"rfc4122",
"uuid"
],
"license": "MIT",
"maintainers": [
{
"name": "broofa",
"email": "robert@broofa.com"
},
{
"name": "defunctzombie",
"email": "shtylman@gmail.com"
},
{
"name": "vvo",
"email": "vincent.voyer@gmail.com"
}
],
"name": "uuid",
"optionalDependencies": {},
"repository": {
"type": "git",
"url": "git+https://github.com/kelektiv/node-uuid.git"
},
"scripts": {
"md": "runmd --watch --output=README.md README_js.md",
"prepare": "runmd --output=README.md README_js.md",
"release": "standard-version",
"test": "mocha test/test.js"
},
"version": "3.2.1"
}
-109
View File
@@ -1,109 +0,0 @@
var rng = require('./lib/rng');
var bytesToUuid = require('./lib/bytesToUuid');
// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
var _nodeId;
var _clockseq;
// Previous uuid creation time
var _lastMSecs = 0;
var _lastNSecs = 0;
// See https://github.com/broofa/node-uuid for API details
function v1(options, buf, offset) {
var i = buf && offset || 0;
var b = buf || [];
options = options || {};
var node = options.node || _nodeId;
var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
// node and clockseq need to be initialized to random values if they're not
// specified. We do this lazily to minimize issues related to insufficient
// system entropy. See #189
if (node == null || clockseq == null) {
var seedBytes = rng();
if (node == null) {
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
node = _nodeId = [
seedBytes[0] | 0x01,
seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
];
}
if (clockseq == null) {
// Per 4.2.2, randomize (14 bit) clockseq
clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
}
}
// UUID timestamps are 100 nano-second units since the Gregorian epoch,
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
// Per 4.2.1.2, use count of uuid's generated during the current clock
// cycle to simulate higher resolution clock
var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
// Time since last uuid creation (in msecs)
var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
// Per 4.2.1.2, Bump clockseq on clock regression
if (dt < 0 && options.clockseq === undefined) {
clockseq = clockseq + 1 & 0x3fff;
}
// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
// time interval
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
nsecs = 0;
}
// Per 4.2.1.2 Throw error if too many uuids are requested
if (nsecs >= 10000) {
throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq;
// Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs += 12219292800000;
// `time_low`
var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
b[i++] = tl >>> 24 & 0xff;
b[i++] = tl >>> 16 & 0xff;
b[i++] = tl >>> 8 & 0xff;
b[i++] = tl & 0xff;
// `time_mid`
var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
b[i++] = tmh >>> 8 & 0xff;
b[i++] = tmh & 0xff;
// `time_high_and_version`
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
b[i++] = tmh >>> 16 & 0xff;
// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++] = clockseq >>> 8 | 0x80;
// `clock_seq_low`
b[i++] = clockseq & 0xff;
// `node`
for (var n = 0; n < 6; ++n) {
b[i + n] = node[n];
}
return buf ? buf : bytesToUuid(b);
}
module.exports = v1;
-4
View File
@@ -1,4 +0,0 @@
var v35 = require('./lib/v35.js');
var md5 = require('./lib/md5');
module.exports = v35('v3', 0x30, md5);
-29
View File
@@ -1,29 +0,0 @@
var rng = require('./lib/rng');
var bytesToUuid = require('./lib/bytesToUuid');
function v4(options, buf, offset) {
var i = buf && offset || 0;
if (typeof(options) == 'string') {
buf = options === 'binary' ? new Array(16) : null;
options = null;
}
options = options || {};
var rnds = options.random || (options.rng || rng)();
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = (rnds[6] & 0x0f) | 0x40;
rnds[8] = (rnds[8] & 0x3f) | 0x80;
// Copy bytes to buffer, if provided
if (buf) {
for (var ii = 0; ii < 16; ++ii) {
buf[i + ii] = rnds[ii];
}
}
return buf || bytesToUuid(rnds);
}
module.exports = v4;
-3
View File
@@ -1,3 +0,0 @@
var v35 = require('./lib/v35.js');
var sha1 = require('./lib/sha1');
module.exports = v35('v5', 0x50, sha1);
+419
View File
@@ -0,0 +1,419 @@
#### 9.4.1
- Patched a [REDOS](https://en.wikipedia.org/wiki/ReDoS) vulnerability in `isDataURI`
- New and improved locales
([#788](https://github.com/chriso/validator.js/pull/788))
#### 9.4.0
- Added an option to `isMobilePhone` to require a country code
([#769](https://github.com/chriso/validator.js/pull/769))
- New and improved locales
([#785](https://github.com/chriso/validator.js/pull/785))
#### 9.3.0
- New and improved locales
([#763](https://github.com/chriso/validator.js/pull/763),
[#768](https://github.com/chriso/validator.js/pull/768),
[#774](https://github.com/chriso/validator.js/pull/774),
[#777](https://github.com/chriso/validator.js/pull/777),
[#779](https://github.com/chriso/validator.js/pull/779))
#### 9.2.0
- Added an `isMimeType()` validator
([#760](https://github.com/chriso/validator.js/pull/760))
- New and improved locales
([#753](https://github.com/chriso/validator.js/pull/753),
[#755](https://github.com/chriso/validator.js/pull/755),
[#764](https://github.com/chriso/validator.js/pull/764))
#### 9.1.2
- Fixed a bug with the `isFloat` validator
([#752](https://github.com/chriso/validator.js/pull/752))
#### 9.1.1
- Locale fixes
([#738](https://github.com/chriso/validator.js/pull/738),
[#739](https://github.com/chriso/validator.js/pull/739))
#### 9.1.0
- Added an `isISO31661Alpha2()` validator
([#734](https://github.com/chriso/validator.js/pull/734))
- New locales
([#735](https://github.com/chriso/validator.js/pull/735),
[#737](https://github.com/chriso/validator.js/pull/737))
#### 9.0.0
- `normalizeEmail()` no longer validates the email address
([#725](https://github.com/chriso/validator.js/pull/725))
- Added locale-aware validation to `isFloat()` and `isDecimal()`
([#721](https://github.com/chriso/validator.js/pull/721))
- Added an `isPort()` validator
([#733](https://github.com/chriso/validator.js/pull/733))
- New locales
([#731](https://github.com/chriso/validator.js/pull/731))
#### 8.2.0
- Added an `isHash()` validator
([#711](https://github.com/chriso/validator.js/pull/711))
- Control decimal places in `isCurrency()`
([#713](https://github.com/chriso/validator.js/pull/713))
- New and improved locales
([#700](https://github.com/chriso/validator.js/pull/700),
[#701](https://github.com/chriso/validator.js/pull/701),
[#714](https://github.com/chriso/validator.js/pull/714),
[#715](https://github.com/chriso/validator.js/pull/715),
[#718](https://github.com/chriso/validator.js/pull/718))
#### 8.1.0
- Fix `require('validator/lib/isIS8601')` calls
([#688](https://github.com/chriso/validator.js/issues/688))
- Added an `isLatLong()` and `isPostalCode()` validator
([#684](https://github.com/chriso/validator.js/pull/684))
- Allow comma in email display names
([#692](https://github.com/chriso/validator.js/pull/692))
- Add missing string to `unescape()`
([#690](https://github.com/chriso/validator.js/pull/690))
- Fix `isMobilePhone()` with Node <= 6.x
([#681](https://github.com/chriso/validator.js/issues/681))
- New locales
([#695](https://github.com/chriso/validator.js/pull/695))
#### 8.0.0
- `isURL()` now requires the `require_tld: false` option to validate `localhost`
([#675](https://github.com/chriso/validator.js/issues/675))
- `isURL()` now rejects URLs that are protocol only
([#642](https://github.com/chriso/validator.js/issues/642))
- Fixed a bug where `isMobilePhone()` would silently return false if the locale was invalid or unsupported
([#657](https://github.com/chriso/validator.js/issues/657))
#### 7.2.0
- Added an option to validate any phone locale
([#663](https://github.com/chriso/validator.js/pull/663))
- Fixed a bug in credit card validation
([#672](https://github.com/chriso/validator.js/pull/672))
- Disallow whitespace, including unicode whitespace, in TLDs
([#677](https://github.com/chriso/validator.js/pull/677))
- New locales
([#673](https://github.com/chriso/validator.js/pull/673),
[#676](https://github.com/chriso/validator.js/pull/676))
#### 7.1.0
- Added an `isISRC()` validator for [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code)
([#660](https://github.com/chriso/validator.js/pull/660))
- Fixed a bug in credit card validation
([#670](https://github.com/chriso/validator.js/pull/670))
- Reduced the maximum allowed address in `isEmail()` based on
[RFC3696 errata](http://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690)
([#655](https://github.com/chriso/validator.js/issues/655))
- New locales
([#647](https://github.com/chriso/validator.js/pull/647),
[#667](https://github.com/chriso/validator.js/pull/667),
[#667](https://github.com/chriso/validator.js/pull/667),
[#671](https://github.com/chriso/validator.js/pull/671))
#### 7.0.0
- Remove `isDate()`
#### 6.3.0
- Allow values like `-.01` in `isFloat()`
([#618](https://github.com/chriso/validator.js/issues/618))
- New locales
([#616](https://github.com/chriso/validator.js/pull/616),
[#622](https://github.com/chriso/validator.js/pull/622),
[#627](https://github.com/chriso/validator.js/pull/627),
[#630](https://github.com/chriso/validator.js/pull/630))
#### 6.2.1
- Disallow `<` and `>` in URLs
([#613](https://github.com/chriso/validator.js/issues/613))
- New locales
([#610](https://github.com/chriso/validator.js/pull/610))
#### 6.2.0
- Added an option to require an email display name
([#607](https://github.com/chriso/validator.js/pull/607))
- Added support for `lt` and `gt` to `isInt()`
([#588](https://github.com/chriso/validator.js/pull/588))
- New locales
([#601](https://github.com/chriso/validator.js/pull/601))
#### 6.1.0
- Added support for greater or less than in `isFloat()`
([#544](https://github.com/chriso/validator.js/issues/544))
- Added support for ISSN validation via `isISSN()`
([#593](https://github.com/chriso/validator.js/pull/593))
- Fixed a bug in `normalizeEmail()`
([#594](https://github.com/chriso/validator.js/issues/594))
- New locales
([#585](https://github.com/chriso/validator.js/pull/585))
#### 6.0.0
- Renamed `isNull()` to `isEmpty()`
([#574](https://github.com/chriso/validator.js/issues/574))
- Backslash is now escaped in `escape()`
([#516](https://github.com/chriso/validator.js/issues/516))
- Improved `normalizeEmail()`
([#583](https://github.com/chriso/validator.js/pull/583))
- Allow leading zeroes by default in `isInt()`
([#532](https://github.com/chriso/validator.js/pull/532))
#### 5.7.0
- Added support for IPv6 in `isURL()`
([#564](https://github.com/chriso/validator.js/issues/564))
- Added support for urls without a host (e.g. `file:///foo.txt`) in `isURL()`
([#563](https://github.com/chriso/validator.js/issues/563))
- Added support for regular expressions in the `isURL()` host whitelist and blacklist
([#562](https://github.com/chriso/validator.js/issues/562))
- Added support for MasterCard 2-Series BIN
([#576](https://github.com/chriso/validator.js/pull/576))
- New locales
([#575](https://github.com/chriso/validator.js/pull/575),
[#552](https://github.com/chriso/validator.js/issues/552))
#### 5.6.0
- Added an `isMD5()` validator
([#557](https://github.com/chriso/validator.js/pull/557))
- Fixed an exceptional case in `isDate()`
([#566](https://github.com/chriso/validator.js/pull/566))
- New locales
([#559](https://github.com/chriso/validator.js/pull/559),
[#568](https://github.com/chriso/validator.js/pull/568),
[#571](https://github.com/chriso/validator.js/pull/571),
[#573](https://github.com/chriso/validator.js/pull/573))
#### 5.5.0
- Fixed a regex denial of service in `trim()` and `rtrim()`
([#556](https://github.com/chriso/validator.js/pull/556))
- Added an Algerian locale to `isMobilePhone()`
([#540](https://github.com/chriso/validator.js/pull/540))
- Fixed the Hungarian locale in `isAlpha()` and `isAlphanumeric()`
([#541](https://github.com/chriso/validator.js/pull/541))
- Added a Polish locale to `isMobilePhone()`
([#545](https://github.com/chriso/validator.js/pull/545))
#### 5.4.0
- Accept Union Pay credit cards in `isCreditCard()`
([#539](https://github.com/chriso/validator.js/pull/539))
- Added Danish locale to `isMobilePhone()`
([#538](https://github.com/chriso/validator.js/pull/538))
- Added Hungarian locales to `isAlpha()`, `isAlphanumeric()` and `isMobilePhone()`
([#537](https://github.com/chriso/validator.js/pull/537))
#### 5.3.0
- Added an `allow_leading_zeroes` option to `isInt()`
([#532](https://github.com/chriso/validator.js/pull/532))
- Adjust Chinese mobile phone validation
([#523](https://github.com/chriso/validator.js/pull/523))
- Added a Canadian locale to `isMobilePhone()`
([#524](https://github.com/chriso/validator.js/issues/524))
#### 5.2.0
- Added a `isDataURI()` validator
([#521](https://github.com/chriso/validator.js/pull/521))
- Added Czech locales
([#522](https://github.com/chriso/validator.js/pull/522))
- Fixed a bug with `isURL()` when protocol was missing and "://" appeared in the query
([#518](https://github.com/chriso/validator.js/issues/518))
#### 5.1.0
- Added a `unescape()` HTML function
([#509](https://github.com/chriso/validator.js/pull/509))
- Added a Malaysian locale to `isMobilePhone()`
([#507](https://github.com/chriso/validator.js/pull/507))
- Added Polish locales to `isAlpha()` and `isAlphanumeric()`
([#506](https://github.com/chriso/validator.js/pull/506))
- Added Turkish locales to `isAlpha()`, `isAlphanumeric()` and `isMobilePhone()`
([#512](https://github.com/chriso/validator.js/pull/512))
- Allow >1 underscore in hostnames when using `allow_underscores`
([#510](https://github.com/chriso/validator.js/issues/510))
#### 5.0.0
- Migrate to ES6
([#496](https://github.com/chriso/validator.js/pull/496))
- Break the library up so that individual functions can be imported
([#496](https://github.com/chriso/validator.js/pull/496))
- Remove auto-coercion of input to a string
([#496](https://github.com/chriso/validator.js/pull/496))
- Remove the `extend()` function
([#496](https://github.com/chriso/validator.js/pull/496))
- Added Arabic locales to `isAlpha()` and `isAlphanumeric()`
([#496](https://github.com/chriso/validator.js/pull/496#issuecomment-184781730))
- Fix validation of very large base64 strings
([#503](https://github.com/chriso/validator.js/pull/503))
#### 4.9.0
- Added a Russian locale to `isAlpha()` and `isAlphanumeric()`
([#499](https://github.com/chriso/validator.js/pull/499))
- Remove the restriction on adjacent hyphens in hostnames
([#500](https://github.com/chriso/validator.js/issues/500))
#### 4.8.0
- Added Spanish, French, Portuguese and Dutch support for `isAlpha()` and `isAlphanumeric()`
([#492](https://github.com/chriso/validator.js/pull/492))
- Added a Brazilian locale to `isMobilePhone()`
([#489](https://github.com/chriso/validator.js/pull/489))
- Reject IPv4 addresses with invalid zero padding
([#490](https://github.com/chriso/validator.js/pull/490))
- Fix the client-side version when used with RequireJS
([#494](https://github.com/chriso/validator.js/issues/494))
#### 4.7.1
- Use [node-depd](https://github.com/dougwilson/nodejs-depd) to print deprecation notices
([#487](https://github.com/chriso/validator.js/issues/487))
#### 4.7.0
- Print a deprecation warning if validator input is not a string
([1f67e1e](https://github.com/chriso/validator.js/commit/1f67e1e15198c0ae735151290dc8dc2bf14da254)).
Note that this will be an error in v5.
- Added a German locale to `isMobilePhone()`, `isAlpha()` and `isAlphanumeric()`
([#477](https://github.com/chriso/validator.js/pull/477))
- Added a Finnish locale to `isMobilePhone()`
([#455](https://github.com/chriso/validator.js/pull/455))
#### 4.6.1
- Fix coercion of objects: `Object.toString()` is `[object Object]` not `""`
([a57f3c8](https://github.com/chriso/validator.js/commit/a57f3c843c715fba2664ee22ec80e9e28e88e0a6))
#### 4.6.0
- Added a Spanish locale to `isMobilePhone()`
([#481](https://github.com/chriso/validator.js/pull/481))
- Fix string coercion of objects created with `Object.create(null)`
([#484](https://github.com/chriso/validator.js/issues/484))
#### 4.5.2
- Fix a timezone issue with short-form ISO 8601 dates, e.g.
`validator.isDate('2011-12-21')`
([#480](https://github.com/chriso/validator.js/issues/480))
#### 4.5.1
- Make `isLength()` / `isByteLength()` accept `{min, max}` as options object.
([#474](https://github.com/chriso/validator.js/issues/474))
#### 4.5.0
- Add validation for Indian mobile phone numbers
([#471](https://github.com/chriso/validator.js/pull/471))
- Tweak Greek and Chinese mobile phone validation
([#467](https://github.com/chriso/validator.js/pull/467),
[#468](https://github.com/chriso/validator.js/pull/468))
- Fixed a bug in `isDate()` when validating ISO 8601 dates without a timezone
([#472](https://github.com/chriso/validator.js/issues/472))
#### 4.4.1
- Allow triple hyphens in IDNA hostnames
([#466](https://github.com/chriso/validator.js/issues/466))
#### 4.4.0
- Added `isMACAddress()` validator
([#458](https://github.com/chriso/validator.js/pull/458))
- Added `isWhitelisted()` validator
([#462](https://github.com/chriso/validator.js/pull/462))
- Added a New Zealand locale to `isMobilePhone()`
([#452](https://github.com/chriso/validator.js/pull/452))
- Added options to control GMail address normalization
([#460](https://github.com/chriso/validator.js/pull/460))
#### 4.3.0
- Support Ember CLI module definitions
([#448](https://github.com/chriso/validator.js/pull/448))
- Added a Vietnam locale to `isMobilePhone()`
([#451](https://github.com/chriso/validator.js/pull/451))
#### 4.2.1
- Fix `isDate()` handling of RFC2822 timezones
([#447](https://github.com/chriso/validator.js/pull/447))
#### 4.2.0
- Fix `isDate()` handling of ISO8601 timezones
([#444](https://github.com/chriso/validator.js/pull/444))
- Fix the incorrect `isFloat('.') === true`
([#443](https://github.com/chriso/validator.js/pull/443))
- Added a Norwegian locale to `isMobilePhone()`
([#439](https://github.com/chriso/validator.js/pull/439))
#### 4.1.0
- General `isDate()` improvements
([#431](https://github.com/chriso/validator.js/pull/431))
- Tests now require node 4.0+
([#438](https://github.com/chriso/validator.js/pull/438))
#### 4.0.6
- Added a Taiwan locale to `isMobilePhone()`
([#432](https://github.com/chriso/validator.js/pull/432))
- Fixed a bug in `isBefore()` where it would return `null`
([#436](https://github.com/chriso/validator.js/pull/436))
#### 4.0.5
- Fixed a denial of service vulnerability in the `isEmail()` regex
([#152](https://github.com/chriso/validator.js/issues/152#issuecomment-131874928))
#### 4.0.4
- Reverted the leap year validation in `isDate()` as it introduced some regressions
([#422](https://github.com/chriso/validator.js/issues/422), [#423](https://github.com/chriso/validator.js/issues/423))
#### 4.0.3
- Added leap year validation to `isDate()`
([#418](https://github.com/chriso/validator.js/pull/418))
#### 4.0.2
- Fixed `isDecimal()` with an empty string
([#419](https://github.com/chriso/validator.js/issues/419))
#### 4.0.1
- Fixed `isByteLength()` with certain strings
([09f0c6d](https://github.com/chriso/validator.js/commit/09f0c6d2321f0c78af6a7de42e91b63955e4c01e))
- Put length restrictions on email parts
([#258](https://github.com/chriso/validator.js/issues/258#issuecomment-127173612))
#### 4.0.0
- Simplified the `isEmail()` regex and fixed some edge cases
([#258](https://github.com/chriso/validator.js/issues/258#issuecomment-127173612))
- Added ISO 8601 date validation via `isISO8601()`
([#373](https://github.com/chriso/validator.js/issues/373))
+20
View File
@@ -0,0 +1,20 @@
Copyright (c) 2016 Chris O'Hara <cohara87@gmail.com>
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.
+209
View File
@@ -0,0 +1,209 @@
# validator.js
[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Downloads][downloads-image]][npm-url]
A library of string validators and sanitizers.
## Strings only
**This library validates and sanitizes strings only.**
If you're not sure if your input is a string, coerce it using `input + ''`.
Passing anything other than a string is an error.
## Installation and Usage
### Server-side usage
Install the library with `npm install validator`
#### No ES6
```javascript
var validator = require('validator');
validator.isEmail('foo@bar.com'); //=> true
```
#### ES6
```javascript
import validator from 'validator';
```
Or, import only a subset of the library:
```javascript
import isEmail from 'validator/lib/isEmail';
```
### Client-side usage
The library can be loaded either as a standalone script, or through an [AMD][amd]-compatible loader
```html
<script type="text/javascript" src="validator.min.js"></script>
<script type="text/javascript">
validator.isEmail('foo@bar.com'); //=> true
</script>
```
The library can also be installed through [bower][bower]
```bash
$ bower install validator-js
```
## Validators
Here is a list of the validators currently available.
Validator | Description
--------------------------------------- | --------------------------------------
***contains(str, seed)*** | check if the string contains the seed.
**equals(str, comparison)** | check if the string matches the comparison.
**isAfter(str [, date])** | check if the string is a date that's after the specified date (defaults to now).
**isAlpha(str [, locale])** | check if the string contains only letters (a-zA-Z).<br/><br/>Locale is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-FR', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sk-SK', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`) and defaults to `en-US`.
**isAlphanumeric(str [, locale])** | check if the string contains only letters and numbers.<br/><br/>Locale is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-FR', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sk-SK', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`) and defaults to `en-US`.
**isAscii(str)** | check if the string contains ASCII chars only.
**isBase64(str)** | check if a string is base64 encoded.
**isBefore(str [, date])** | check if the string is a date that's before the specified date.
**isBoolean(str)** | check if a string is a boolean.
**isByteLength(str, options)** | check if the string's length (in UTF-8 bytes) falls in a range.<br/><br/>`options` is an object which defaults to `{min:0, max: undefined}`.
**isCreditCard(str)** | check if the string is a credit card.
**isCurrency(str, options)** | check if the string is a valid currency amount.<br/><br/>`options` is an object which defaults to `{symbol: '$', require_symbol: false, allow_space_after_symbol: false, symbol_after_digits: false, allow_negatives: true, parens_for_negatives: false, negative_sign_before_digits: false, negative_sign_after_digits: false, allow_negative_sign_placeholder: false, thousands_separator: ',', decimal_separator: '.', allow_decimal: true, require_decimal: false, digits_after_decimal: [2], allow_space_after_digits: false}`.<br/>**Note:** The array `digits_after_decimal` is filled with the exact number of digits allowd not a range, for example a range 1 to 3 will be given as [1, 2, 3].
**isDataURI(str)** | check if the string is a [data uri format](https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs).
**isDecimal(str, options)** | check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc.<br/><br/>`options` is an object which defaults to `{force_decimal: false, decimal_digits: '1,', locale: 'en-US'}`<br/><br/>`locale` determine the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-FR', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`.<br/>**Note:** `decimal_digits` is given as a range like '1,3', a specific value like '3' or min like '1,'.
**isDivisibleBy(str, number)** | check if the string is a number that's divisible by another.
**isEmail(str [, options])** | check if the string is an email.<br/><br/>`options` is an object which defaults to `{ allow_display_name: false, require_display_name: false, allow_utf8_local_part: true, require_tld: true }`. If `allow_display_name` is set to true, the validator will also match `Display Name <email-address>`. If `require_display_name` is set to true, the validator will reject strings without the format `Display Name <email-address>`. If `allow_utf8_local_part` is set to false, the validator will not allow any non-English UTF8 character in email address' local part. If `require_tld` is set to false, e-mail addresses without having TLD in their domain will also be matched.
**isEmpty(str)** | check if the string has a length of zero.
**isFQDN(str [, options])** | check if the string is a fully qualified domain name (e.g. domain.com).<br/><br/>`options` is an object which defaults to `{ require_tld: true, allow_underscores: false, allow_trailing_dot: false }`.
**isFloat(str [, options])** | check if the string is a float.<br/><br/>`options` is an object which can contain the keys `min`, `max`, `gt`, and/or `lt` to validate the float is within boundaries (e.g. `{ min: 7.22, max: 9.55 }`) it also has `locale` as an option.<br/><br/>`min` and `max` are equivalent to 'greater or equal' and 'less or equal', respectively while `gt` and `lt` are their strict counterparts.<br/><br/>`locale` determine the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-FR', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`.
**isFullWidth(str)** | check if the string contains any full-width chars.
**isHalfWidth(str)** | check if the string contains any half-width chars.
**isHash(str, algorithm)** | check if the string is a hash of type algorithm.<br/><br/>Algorithm is one of `['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b']`
**isHexColor(str)** | check if the string is a hexadecimal color.
**isHexadecimal(str)** | check if the string is a hexadecimal number.
**isIP(str [, version])** | check if the string is an IP (version 4 or 6).
**isISBN(str [, version])** | check if the string is an ISBN (version 10 or 13).
**isISSN(str [, options])** | check if the string is an [ISSN](https://en.wikipedia.org/wiki/International_Standard_Serial_Number).<br/><br/>`options` is an object which defaults to `{ case_sensitive: false, require_hyphen: false }`. If `case_sensitive` is true, ISSNs with a lowercase `'x'` as the check digit are rejected.
**isISIN(str)** | check if the string is an [ISIN][ISIN] (stock/security identifier).
**isISO8601(str)** | check if the string is a valid [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date.
**isISO31661Alpha2(str)** | check if the string is a valid [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) officially assigned country code.
**isISRC(str)** | check if the string is a [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code).
**isIn(str, values)** | check if the string is in a array of allowed values.
**isInt(str [, options])** | check if the string is an integer.<br/><br/>`options` is an object which can contain the keys `min` and/or `max` to check the integer is within boundaries (e.g. `{ min: 10, max: 99 }`). `options` can also contain the key `allow_leading_zeroes`, which when set to false will disallow integer values with leading zeroes (e.g. `{ allow_leading_zeroes: false }`). Finally, `options` can contain the keys `gt` and/or `lt` which will enforce integers being greater than or less than, respectively, the value provided (e.g. `{gt: 1, lt: 4}` for a number between 1 and 4).
**isJSON(str)** | check if the string is valid JSON (note: uses JSON.parse).
**isLatLong(str)**                     | check if the string is a valid latitude-longitude coordinate in the format `lat,long` or `lat, long`.
**isLength(str, options)** | check if the string's length falls in a range.<br/><br/>`options` is an object which defaults to `{min:0, max: undefined}`. Note: this function takes into account surrogate pairs.
**isLowercase(str)** | check if the string is lowercase.
**isMACAddress(str)** | check if the string is a MAC address.
**isMD5(str)** | check if the string is a MD5 hash.
**isMimeType(str)** | check if the string matches to a valid [MIME type](https://en.wikipedia.org/wiki/Media_type) format
**isMobilePhone(str, locale)** | check if the string is a mobile phone number,<br/><br/>(locale is one of `['ar-AE', 'ar-DZ', 'ar-EG', 'ar-JO', 'ar-SA', 'ar-SY', 'be-BY', 'bg-BG', 'cs-CZ', 'de-DE', 'da-DK', 'el-GR', 'en-AU', 'en-CA', 'en-GB', 'en-HK', 'en-IN', 'en-KE', 'en-NG', 'en-NZ', 'en-RW', 'en-SG', 'en-UG', 'en-US', 'en-TZ', 'en-ZA', 'en-ZM', 'en-PK', 'es-ES', 'et-EE', 'fa-IR', 'fi-FI', 'fr-FR', 'he-IL', 'hu-HU', 'it-IT', 'ja-JP', 'kk-KZ', 'ko-KR', 'lt-LT', 'ms-MY', 'nb-NO', 'nn-NO', 'pl-PL', 'pt-PT', 'pt-BR', 'ro-RO', 'ru-RU', 'sk-SK', 'sr-RS', 'th-TH', 'tr-TR', 'uk-UA', 'vi-VN', 'zh-CN', 'zh-HK', 'zh-TW']` OR 'any'. If 'any' is used, function will check if any of the locales match).<br/><br/>`options` is an optional object that can be supplied with the following keys: `strictMode`, if this is set to `true`, the mobile phone number must be supplied with the country code and therefore must start with `+`.
**isMongoId(str)** | check if the string is a valid hex-encoded representation of a [MongoDB ObjectId][mongoid].
**isMultibyte(str)** | check if the string contains one or more multibyte chars.
**isNumeric(str)** | check if the string contains only numbers.
**isPort(str)** | check if the string is a valid port number.
**isPostalCode(str, locale)** | check if the string is a postal code,<br/><br/>(locale is one of `[ 'AT', 'AU', 'BE', 'BG', 'CA', 'CH', 'CZ', 'DE', 'DK', 'DZ', 'ES', 'FI', 'FR', 'GB', 'GR', 'IL', 'IN', 'IS', 'IT', 'JP', 'KE', 'LI', 'MX', 'NL', 'NO', 'PL', 'PT', 'RO', 'RU', 'SA', 'SE', 'TW', 'US', 'ZA', 'ZM' ]` OR 'any'. If 'any' is used, function will check if any of the locals match).
**isSurrogatePair(str)** | check if the string contains any surrogate pairs chars.
**isURL(str [, options])** | check if the string is an URL.<br/><br/>`options` is an object which defaults to `{ protocols: ['http','https','ftp'], require_tld: true, require_protocol: false, require_host: true, require_valid_protocol: true, allow_underscores: false, host_whitelist: false, host_blacklist: false, allow_trailing_dot: false, allow_protocol_relative_urls: false }`.
**isUUID(str [, version])** | check if the string is a UUID (version 3, 4 or 5).
**isUppercase(str)** | check if the string is uppercase.
**isVariableWidth(str)** | check if the string contains a mixture of full and half-width chars.
**isWhitelisted(str, chars)** | checks characters if they appear in the whitelist.
**matches(str, pattern [, modifiers])** | check if string matches the pattern.<br/><br/>Either `matches('foo', /foo/i)` or `matches('foo', 'foo', 'i')`.
## Sanitizers
Here is a list of the sanitizers currently available.
Sanitizer | Description
-------------------------------------- | -------------------------------
**blacklist(input, chars)** | remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `blacklist(input, '\\[\\]')`.
**escape(input)** | replace `<`, `>`, `&`, `'`, `"` and `/` with HTML entities.
**unescape(input)** | replaces HTML encoded entities with `<`, `>`, `&`, `'`, `"` and `/`.
**ltrim(input [, chars])** | trim characters from the left-side of the input.
**normalizeEmail(email [, options])** | canonicalizes an email address. (This doesn't validate that the input is an email, if you want to validate the email use isEmail beforehand)<br/><br/>`options` is an object with the following keys and default values:<br/><ul><li>*all_lowercase: true* - Transforms the local part (before the @ symbol) of all email addresses to lowercase. Please note that this may violate RFC 5321, which gives providers the possibility to treat the local part of email addresses in a case sensitive way (although in practice most - yet not all - providers don't). The domain part of the email address is always lowercased, as it's case insensitive per RFC 1035.</li><li>*gmail_lowercase: true* - GMail addresses are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, GMail addresses are lowercased regardless of the value of this setting.</li><li>*gmail_remove_dots: true*: Removes dots from the local part of the email address, as GMail ignores them (e.g. "john.doe" and "johndoe" are considered equal).</li><li>*gmail_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@gmail.com" becomes "foo@gmail.com").</li><li>*gmail_convert_googlemaildotcom: true*: Converts addresses with domain @googlemail.com to @gmail.com, as they're equivalent.</li><li>*outlookdotcom_lowercase: true* - Outlook.com addresses (including Windows Live and Hotmail) are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, Outlook.com addresses are lowercased regardless of the value of this setting.</li><li>*outlookdotcom_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@outlook.com" becomes "foo@outlook.com").</li><li>*yahoo_lowercase: true* - Yahoo Mail addresses are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, Yahoo Mail addresses are lowercased regardless of the value of this setting.</li><li>*yahoo_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "-" sign (e.g. "foo-bar@yahoo.com" becomes "foo@yahoo.com").</li><li>*icloud_lowercase: true* - iCloud addresses (including MobileMe) are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, iCloud addresses are lowercased regardless of the value of this setting.</li><li>*icloud_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@icloud.com" becomes "foo@icloud.com").</li></ul>
**rtrim(input [, chars])** | trim characters from the right-side of the input.
**stripLow(input [, keep_new_lines])** | remove characters with a numerical value < 32 and 127, mostly control characters. If `keep_new_lines` is `true`, newline characters are preserved (`\n` and `\r`, hex `0xA` and `0xD`). Unicode-safe in JavaScript.
**toBoolean(input [, strict])** | convert the input string to a boolean. Everything except for `'0'`, `'false'` and `''` returns `true`. In strict mode only `'1'` and `'true'` return `true`.
**toDate(input)** | convert the input string to a date, or `null` if the input is not a date.
**toFloat(input)** | convert the input string to a float, or `NaN` if the input is not a float.
**toInt(input [, radix])** | convert the input string to an integer, or `NaN` if the input is not an integer.
**trim(input [, chars])** | trim characters (whitespace by default) from both sides of the input.
**whitelist(input, chars)** | remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `whitelist(input, '\\[\\]')`.
### XSS Sanitization
XSS sanitization was removed from the library in [2d5d6999](https://github.com/chriso/validator.js/commit/2d5d6999541add350fb396ef02dc42ca3215049e).
For an alternative, have a look at Yahoo's [xss-filters library](https://github.com/yahoo/xss-filters) or at [DOMPurify](https://github.com/cure53/DOMPurify).
## Contributing
In general, we follow the "fork-and-pull" Git workflow.
1. Fork the repo on GitHub
2. Clone the project to your own machine
3. Work on your fork
1. Make your changes and additions
2. Change or add tests if needed
3. Run tests and make sure they pass
4. Add changes to README.md if needed
4. Commit changes to your own branch
5. **Make sure** you merge the latest from "upstream" and resolve conflicts if there is any
6. Repeat step 3(3) above
7. Push your work back up to your fork
8. Submit a Pull request so that we can review your changes
## Tests
Tests are using mocha, to run the tests use:
```sh
$ npm test
```
## Reading
Remember, validating can be troublesome sometimes. See [A list of articles about programming assumptions commonly made that aren't true](https://github.com/jameslk/awesome-falsehoods).
## License (MIT)
```
Copyright (c) 2017 Chris O'Hara <cohara87@gmail.com>
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.
```
[downloads-image]: http://img.shields.io/npm/dm/validator.svg
[npm-url]: https://npmjs.org/package/validator
[npm-image]: http://img.shields.io/npm/v/validator.svg
[travis-url]: https://travis-ci.org/chriso/validator.js
[travis-image]: http://img.shields.io/travis/chriso/validator.js.svg
[amd]: http://requirejs.org/docs/whyamd.html
[bower]: http://bower.io/
[mongoid]: http://docs.mongodb.org/manual/reference/object-id/
[ISIN]: https://en.wikipedia.org/wiki/International_Securities_Identification_Number
+351
View File
@@ -0,0 +1,351 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _toDate = require('./lib/toDate');
var _toDate2 = _interopRequireDefault(_toDate);
var _toFloat = require('./lib/toFloat');
var _toFloat2 = _interopRequireDefault(_toFloat);
var _toInt = require('./lib/toInt');
var _toInt2 = _interopRequireDefault(_toInt);
var _toBoolean = require('./lib/toBoolean');
var _toBoolean2 = _interopRequireDefault(_toBoolean);
var _equals = require('./lib/equals');
var _equals2 = _interopRequireDefault(_equals);
var _contains = require('./lib/contains');
var _contains2 = _interopRequireDefault(_contains);
var _matches = require('./lib/matches');
var _matches2 = _interopRequireDefault(_matches);
var _isEmail = require('./lib/isEmail');
var _isEmail2 = _interopRequireDefault(_isEmail);
var _isURL = require('./lib/isURL');
var _isURL2 = _interopRequireDefault(_isURL);
var _isMACAddress = require('./lib/isMACAddress');
var _isMACAddress2 = _interopRequireDefault(_isMACAddress);
var _isIP = require('./lib/isIP');
var _isIP2 = _interopRequireDefault(_isIP);
var _isFQDN = require('./lib/isFQDN');
var _isFQDN2 = _interopRequireDefault(_isFQDN);
var _isBoolean = require('./lib/isBoolean');
var _isBoolean2 = _interopRequireDefault(_isBoolean);
var _isAlpha = require('./lib/isAlpha');
var _isAlpha2 = _interopRequireDefault(_isAlpha);
var _isAlphanumeric = require('./lib/isAlphanumeric');
var _isAlphanumeric2 = _interopRequireDefault(_isAlphanumeric);
var _isNumeric = require('./lib/isNumeric');
var _isNumeric2 = _interopRequireDefault(_isNumeric);
var _isPort = require('./lib/isPort');
var _isPort2 = _interopRequireDefault(_isPort);
var _isLowercase = require('./lib/isLowercase');
var _isLowercase2 = _interopRequireDefault(_isLowercase);
var _isUppercase = require('./lib/isUppercase');
var _isUppercase2 = _interopRequireDefault(_isUppercase);
var _isAscii = require('./lib/isAscii');
var _isAscii2 = _interopRequireDefault(_isAscii);
var _isFullWidth = require('./lib/isFullWidth');
var _isFullWidth2 = _interopRequireDefault(_isFullWidth);
var _isHalfWidth = require('./lib/isHalfWidth');
var _isHalfWidth2 = _interopRequireDefault(_isHalfWidth);
var _isVariableWidth = require('./lib/isVariableWidth');
var _isVariableWidth2 = _interopRequireDefault(_isVariableWidth);
var _isMultibyte = require('./lib/isMultibyte');
var _isMultibyte2 = _interopRequireDefault(_isMultibyte);
var _isSurrogatePair = require('./lib/isSurrogatePair');
var _isSurrogatePair2 = _interopRequireDefault(_isSurrogatePair);
var _isInt = require('./lib/isInt');
var _isInt2 = _interopRequireDefault(_isInt);
var _isFloat = require('./lib/isFloat');
var _isFloat2 = _interopRequireDefault(_isFloat);
var _isDecimal = require('./lib/isDecimal');
var _isDecimal2 = _interopRequireDefault(_isDecimal);
var _isHexadecimal = require('./lib/isHexadecimal');
var _isHexadecimal2 = _interopRequireDefault(_isHexadecimal);
var _isDivisibleBy = require('./lib/isDivisibleBy');
var _isDivisibleBy2 = _interopRequireDefault(_isDivisibleBy);
var _isHexColor = require('./lib/isHexColor');
var _isHexColor2 = _interopRequireDefault(_isHexColor);
var _isISRC = require('./lib/isISRC');
var _isISRC2 = _interopRequireDefault(_isISRC);
var _isMD = require('./lib/isMD5');
var _isMD2 = _interopRequireDefault(_isMD);
var _isHash = require('./lib/isHash');
var _isHash2 = _interopRequireDefault(_isHash);
var _isJSON = require('./lib/isJSON');
var _isJSON2 = _interopRequireDefault(_isJSON);
var _isEmpty = require('./lib/isEmpty');
var _isEmpty2 = _interopRequireDefault(_isEmpty);
var _isLength = require('./lib/isLength');
var _isLength2 = _interopRequireDefault(_isLength);
var _isByteLength = require('./lib/isByteLength');
var _isByteLength2 = _interopRequireDefault(_isByteLength);
var _isUUID = require('./lib/isUUID');
var _isUUID2 = _interopRequireDefault(_isUUID);
var _isMongoId = require('./lib/isMongoId');
var _isMongoId2 = _interopRequireDefault(_isMongoId);
var _isAfter = require('./lib/isAfter');
var _isAfter2 = _interopRequireDefault(_isAfter);
var _isBefore = require('./lib/isBefore');
var _isBefore2 = _interopRequireDefault(_isBefore);
var _isIn = require('./lib/isIn');
var _isIn2 = _interopRequireDefault(_isIn);
var _isCreditCard = require('./lib/isCreditCard');
var _isCreditCard2 = _interopRequireDefault(_isCreditCard);
var _isISIN = require('./lib/isISIN');
var _isISIN2 = _interopRequireDefault(_isISIN);
var _isISBN = require('./lib/isISBN');
var _isISBN2 = _interopRequireDefault(_isISBN);
var _isISSN = require('./lib/isISSN');
var _isISSN2 = _interopRequireDefault(_isISSN);
var _isMobilePhone = require('./lib/isMobilePhone');
var _isMobilePhone2 = _interopRequireDefault(_isMobilePhone);
var _isCurrency = require('./lib/isCurrency');
var _isCurrency2 = _interopRequireDefault(_isCurrency);
var _isISO = require('./lib/isISO8601');
var _isISO2 = _interopRequireDefault(_isISO);
var _isISO31661Alpha = require('./lib/isISO31661Alpha2');
var _isISO31661Alpha2 = _interopRequireDefault(_isISO31661Alpha);
var _isBase = require('./lib/isBase64');
var _isBase2 = _interopRequireDefault(_isBase);
var _isDataURI = require('./lib/isDataURI');
var _isDataURI2 = _interopRequireDefault(_isDataURI);
var _isMimeType = require('./lib/isMimeType');
var _isMimeType2 = _interopRequireDefault(_isMimeType);
var _isLatLong = require('./lib/isLatLong');
var _isLatLong2 = _interopRequireDefault(_isLatLong);
var _isPostalCode = require('./lib/isPostalCode');
var _isPostalCode2 = _interopRequireDefault(_isPostalCode);
var _ltrim = require('./lib/ltrim');
var _ltrim2 = _interopRequireDefault(_ltrim);
var _rtrim = require('./lib/rtrim');
var _rtrim2 = _interopRequireDefault(_rtrim);
var _trim = require('./lib/trim');
var _trim2 = _interopRequireDefault(_trim);
var _escape = require('./lib/escape');
var _escape2 = _interopRequireDefault(_escape);
var _unescape = require('./lib/unescape');
var _unescape2 = _interopRequireDefault(_unescape);
var _stripLow = require('./lib/stripLow');
var _stripLow2 = _interopRequireDefault(_stripLow);
var _whitelist = require('./lib/whitelist');
var _whitelist2 = _interopRequireDefault(_whitelist);
var _blacklist = require('./lib/blacklist');
var _blacklist2 = _interopRequireDefault(_blacklist);
var _isWhitelisted = require('./lib/isWhitelisted');
var _isWhitelisted2 = _interopRequireDefault(_isWhitelisted);
var _normalizeEmail = require('./lib/normalizeEmail');
var _normalizeEmail2 = _interopRequireDefault(_normalizeEmail);
var _toString = require('./lib/util/toString');
var _toString2 = _interopRequireDefault(_toString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var version = '9.4.1';
var validator = {
version: version,
toDate: _toDate2.default,
toFloat: _toFloat2.default,
toInt: _toInt2.default,
toBoolean: _toBoolean2.default,
equals: _equals2.default,
contains: _contains2.default,
matches: _matches2.default,
isEmail: _isEmail2.default,
isURL: _isURL2.default,
isMACAddress: _isMACAddress2.default,
isIP: _isIP2.default,
isFQDN: _isFQDN2.default,
isBoolean: _isBoolean2.default,
isAlpha: _isAlpha2.default,
isAlphanumeric: _isAlphanumeric2.default,
isNumeric: _isNumeric2.default,
isPort: _isPort2.default,
isLowercase: _isLowercase2.default,
isUppercase: _isUppercase2.default,
isAscii: _isAscii2.default,
isFullWidth: _isFullWidth2.default,
isHalfWidth: _isHalfWidth2.default,
isVariableWidth: _isVariableWidth2.default,
isMultibyte: _isMultibyte2.default,
isSurrogatePair: _isSurrogatePair2.default,
isInt: _isInt2.default,
isFloat: _isFloat2.default,
isDecimal: _isDecimal2.default,
isHexadecimal: _isHexadecimal2.default,
isDivisibleBy: _isDivisibleBy2.default,
isHexColor: _isHexColor2.default,
isISRC: _isISRC2.default,
isMD5: _isMD2.default,
isHash: _isHash2.default,
isJSON: _isJSON2.default,
isEmpty: _isEmpty2.default,
isLength: _isLength2.default,
isByteLength: _isByteLength2.default,
isUUID: _isUUID2.default,
isMongoId: _isMongoId2.default,
isAfter: _isAfter2.default,
isBefore: _isBefore2.default,
isIn: _isIn2.default,
isCreditCard: _isCreditCard2.default,
isISIN: _isISIN2.default,
isISBN: _isISBN2.default,
isISSN: _isISSN2.default,
isMobilePhone: _isMobilePhone2.default,
isPostalCode: _isPostalCode2.default,
isCurrency: _isCurrency2.default,
isISO8601: _isISO2.default,
isISO31661Alpha2: _isISO31661Alpha2.default,
isBase64: _isBase2.default,
isDataURI: _isDataURI2.default,
isMimeType: _isMimeType2.default,
isLatLong: _isLatLong2.default,
ltrim: _ltrim2.default,
rtrim: _rtrim2.default,
trim: _trim2.default,
escape: _escape2.default,
unescape: _unescape2.default,
stripLow: _stripLow2.default,
whitelist: _whitelist2.default,
blacklist: _blacklist2.default,
isWhitelisted: _isWhitelisted2.default,
normalizeEmail: _normalizeEmail2.default,
toString: _toString2.default
};
exports.default = validator;
module.exports = exports['default'];
+96
View File
@@ -0,0 +1,96 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var alpha = exports.alpha = {
'en-US': /^[A-Z]+$/i,
'bg-BG': /^[А-Я]+$/i,
'cs-CZ': /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,
'da-DK': /^[A-ZÆØÅ]+$/i,
'de-DE': /^[A-ZÄÖÜß]+$/i,
'el-GR': /^[Α-ω]+$/i,
'es-ES': /^[A-ZÁÉÍÑÓÚÜ]+$/i,
'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,
'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i,
'nb-NO': /^[A-ZÆØÅ]+$/i,
'nl-NL': /^[A-ZÁÉËÏÓÖÜÚ]+$/i,
'nn-NO': /^[A-ZÆØÅ]+$/i,
'hu-HU': /^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i,
'pl-PL': /^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i,
'pt-PT': /^[A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]+$/i,
'ru-RU': /^[А-ЯЁ]+$/i,
'sk-SK': /^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,
'sr-RS@latin': /^[A-ZČĆŽŠĐ]+$/i,
'sr-RS': /^[А-ЯЂЈЉЊЋЏ]+$/i,
'sv-SE': /^[A-ZÅÄÖ]+$/i,
'tr-TR': /^[A-ZÇĞİıÖŞÜ]+$/i,
'uk-UA': /^[А-ЩЬЮЯЄIЇҐі]+$/i,
ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/
};
var alphanumeric = exports.alphanumeric = {
'en-US': /^[0-9A-Z]+$/i,
'bg-BG': /^[0-9А-Я]+$/i,
'cs-CZ': /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,
'da-DK': /^[0-9A-ZÆØÅ]+$/i,
'de-DE': /^[0-9A-ZÄÖÜß]+$/i,
'el-GR': /^[0-9Α-ω]+$/i,
'es-ES': /^[0-9A-ZÁÉÍÑÓÚÜ]+$/i,
'fr-FR': /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,
'it-IT': /^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i,
'hu-HU': /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i,
'nb-NO': /^[0-9A-ZÆØÅ]+$/i,
'nl-NL': /^[0-9A-ZÁÉËÏÓÖÜÚ]+$/i,
'nn-NO': /^[0-9A-ZÆØÅ]+$/i,
'pl-PL': /^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$/i,
'pt-PT': /^[0-9A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]+$/i,
'ru-RU': /^[0-9А-ЯЁ]+$/i,
'sk-SK': /^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,
'sr-RS@latin': /^[0-9A-ZČĆŽŠĐ]+$/i,
'sr-RS': /^[0-9А-ЯЂЈЉЊЋЏ]+$/i,
'sv-SE': /^[0-9A-ZÅÄÖ]+$/i,
'tr-TR': /^[0-9A-ZÇĞİıÖŞÜ]+$/i,
'uk-UA': /^[0-9А-ЩЬЮЯЄIЇҐі]+$/i,
ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/
};
var decimal = exports.decimal = {
'en-US': '.',
ar: '٫'
};
var englishLocales = exports.englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM'];
for (var locale, i = 0; i < englishLocales.length; i++) {
locale = 'en-' + englishLocales[i];
alpha[locale] = alpha['en-US'];
alphanumeric[locale] = alphanumeric['en-US'];
decimal[locale] = decimal['en-US'];
}
// Source: http://www.localeplanet.com/java/
var arabicLocales = exports.arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE'];
for (var _locale, _i = 0; _i < arabicLocales.length; _i++) {
_locale = 'ar-' + arabicLocales[_i];
alpha[_locale] = alpha.ar;
alphanumeric[_locale] = alphanumeric.ar;
decimal[_locale] = decimal.ar;
}
// Source: https://en.wikipedia.org/wiki/Decimal_mark
var dotDecimal = exports.dotDecimal = [];
var commaDecimal = exports.commaDecimal = ['bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'es-ES', 'fr-FR', 'it-IT', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-Pl', 'pt-PT', 'ru-RU', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA'];
for (var _i2 = 0; _i2 < dotDecimal.length; _i2++) {
decimal[dotDecimal[_i2]] = decimal['en-US'];
}
for (var _i3 = 0; _i3 < commaDecimal.length; _i3++) {
decimal[commaDecimal[_i3]] = ',';
}
alpha['pt-BR'] = alpha['pt-PT'];
alphanumeric['pt-BR'] = alphanumeric['pt-PT'];
decimal['pt-BR'] = decimal['pt-PT'];
+18
View File
@@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = blacklist;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function blacklist(str, chars) {
(0, _assertString2.default)(str);
return str.replace(new RegExp('[' + chars + ']+', 'g'), '');
}
module.exports = exports['default'];
+22
View File
@@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = contains;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _toString = require('./util/toString');
var _toString2 = _interopRequireDefault(_toString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function contains(str, elem) {
(0, _assertString2.default)(str);
return str.indexOf((0, _toString2.default)(elem)) >= 0;
}
module.exports = exports['default'];
+18
View File
@@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = equals;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function equals(str, comparison) {
(0, _assertString2.default)(str);
return str === comparison;
}
module.exports = exports['default'];
+18
View File
@@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = escape;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function escape(str) {
(0, _assertString2.default)(str);
return str.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\//g, '&#x2F;').replace(/\\/g, '&#x5C;').replace(/`/g, '&#96;');
}
module.exports = exports['default'];
+26
View File
@@ -0,0 +1,26 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAfter;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _toDate = require('./toDate');
var _toDate2 = _interopRequireDefault(_toDate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isAfter(str) {
var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date());
(0, _assertString2.default)(str);
var comparison = (0, _toDate2.default)(date);
var original = (0, _toDate2.default)(str);
return !!(original && comparison && original > comparison);
}
module.exports = exports['default'];
+25
View File
@@ -0,0 +1,25 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAlpha;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _alpha = require('./alpha');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isAlpha(str) {
var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';
(0, _assertString2.default)(str);
if (locale in _alpha.alpha) {
return _alpha.alpha[locale].test(str);
}
throw new Error('Invalid locale \'' + locale + '\'');
}
module.exports = exports['default'];
@@ -0,0 +1,25 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAlphanumeric;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _alpha = require('./alpha');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isAlphanumeric(str) {
var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';
(0, _assertString2.default)(str);
if (locale in _alpha.alphanumeric) {
return _alpha.alphanumeric[locale].test(str);
}
throw new Error('Invalid locale \'' + locale + '\'');
}
module.exports = exports['default'];
+22
View File
@@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAscii;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-control-regex */
var ascii = /^[\x00-\x7F]+$/;
/* eslint-enable no-control-regex */
function isAscii(str) {
(0, _assertString2.default)(str);
return ascii.test(str);
}
module.exports = exports['default'];
+25
View File
@@ -0,0 +1,25 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isBase64;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var notBase64 = /[^A-Z0-9+\/=]/i;
function isBase64(str) {
(0, _assertString2.default)(str);
var len = str.length;
if (!len || len % 4 !== 0 || notBase64.test(str)) {
return false;
}
var firstPaddingChar = str.indexOf('=');
return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '=';
}
module.exports = exports['default'];
+26
View File
@@ -0,0 +1,26 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isBefore;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _toDate = require('./toDate');
var _toDate2 = _interopRequireDefault(_toDate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isBefore(str) {
var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date());
(0, _assertString2.default)(str);
var comparison = (0, _toDate2.default)(date);
var original = (0, _toDate2.default)(str);
return !!(original && comparison && original < comparison);
}
module.exports = exports['default'];
+18
View File
@@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isBoolean;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isBoolean(str) {
(0, _assertString2.default)(str);
return ['true', 'false', '1', '0'].indexOf(str) >= 0;
}
module.exports = exports['default'];
+33
View File
@@ -0,0 +1,33 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = isByteLength;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable prefer-rest-params */
function isByteLength(str, options) {
(0, _assertString2.default)(str);
var min = void 0;
var max = void 0;
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
min = options.min || 0;
max = options.max;
} else {
// backwards compatibility: isByteLength(str, min [, max])
min = arguments[1];
max = arguments[2];
}
var len = encodeURI(str).split(/%..|./).length - 1;
return len >= min && (typeof max === 'undefined' || len <= max);
}
module.exports = exports['default'];
+45
View File
@@ -0,0 +1,45 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isCreditCard;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable max-len */
var creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|62[0-9]{14})$/;
/* eslint-enable max-len */
function isCreditCard(str) {
(0, _assertString2.default)(str);
var sanitized = str.replace(/[- ]+/g, '');
if (!creditCard.test(sanitized)) {
return false;
}
var sum = 0;
var digit = void 0;
var tmpNum = void 0;
var shouldDouble = void 0;
for (var i = sanitized.length - 1; i >= 0; i--) {
digit = sanitized.substring(i, i + 1);
tmpNum = parseInt(digit, 10);
if (shouldDouble) {
tmpNum *= 2;
if (tmpNum >= 10) {
sum += tmpNum % 10 + 1;
} else {
sum += tmpNum;
}
} else {
sum += tmpNum;
}
shouldDouble = !shouldDouble;
}
return !!(sum % 10 === 0 ? sanitized : false);
}
module.exports = exports['default'];
+92
View File
@@ -0,0 +1,92 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isCurrency;
var _merge = require('./util/merge');
var _merge2 = _interopRequireDefault(_merge);
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function currencyRegex(options) {
var decimal_digits = '\\d{' + options.digits_after_decimal[0] + '}';
options.digits_after_decimal.forEach(function (digit, index) {
if (index !== 0) decimal_digits = decimal_digits + '|\\d{' + digit + '}';
});
var symbol = '(\\' + options.symbol.replace(/\./g, '\\.') + ')' + (options.require_symbol ? '' : '?'),
negative = '-?',
whole_dollar_amount_without_sep = '[1-9]\\d*',
whole_dollar_amount_with_sep = '[1-9]\\d{0,2}(\\' + options.thousands_separator + '\\d{3})*',
valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep],
whole_dollar_amount = '(' + valid_whole_dollar_amounts.join('|') + ')?',
decimal_amount = '(\\' + options.decimal_separator + '(' + decimal_digits + '))' + (options.require_decimal ? '' : '?');
var pattern = whole_dollar_amount + (options.allow_decimal || options.require_decimal ? decimal_amount : '');
// default is negative sign before symbol, but there are two other options (besides parens)
if (options.allow_negatives && !options.parens_for_negatives) {
if (options.negative_sign_after_digits) {
pattern += negative;
} else if (options.negative_sign_before_digits) {
pattern = negative + pattern;
}
}
// South African Rand, for example, uses R 123 (space) and R-123 (no space)
if (options.allow_negative_sign_placeholder) {
pattern = '( (?!\\-))?' + pattern;
} else if (options.allow_space_after_symbol) {
pattern = ' ?' + pattern;
} else if (options.allow_space_after_digits) {
pattern += '( (?!$))?';
}
if (options.symbol_after_digits) {
pattern += symbol;
} else {
pattern = symbol + pattern;
}
if (options.allow_negatives) {
if (options.parens_for_negatives) {
pattern = '(\\(' + pattern + '\\)|' + pattern + ')';
} else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) {
pattern = negative + pattern;
}
}
// ensure there's a dollar and/or decimal amount, and that
// it doesn't start with a space or a negative sign followed by a space
return new RegExp('^(?!-? )(?=.*\\d)' + pattern + '$');
}
var default_currency_options = {
symbol: '$',
require_symbol: false,
allow_space_after_symbol: false,
symbol_after_digits: false,
allow_negatives: true,
parens_for_negatives: false,
negative_sign_before_digits: false,
negative_sign_after_digits: false,
allow_negative_sign_placeholder: false,
thousands_separator: ',',
decimal_separator: '.',
allow_decimal: true,
require_decimal: false,
digits_after_decimal: [2],
allow_space_after_digits: false
};
function isCurrency(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_currency_options);
return currencyRegex(options).test(str);
}
module.exports = exports['default'];
+49
View File
@@ -0,0 +1,49 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isDataURI;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var validMediaType = /^[a-z]+\/[a-z0-9\-\+]+$/i;
var validAttribute = /^[a-z\-]+=[a-z0-9\-]+$/i;
var validData = /^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$/i;
function isDataURI(str) {
(0, _assertString2.default)(str);
var data = str.split(',');
if (data.length < 2) {
return false;
}
var attributes = data.shift().trim().split(';');
var schemeAndMediaType = attributes.shift();
if (schemeAndMediaType.substr(0, 5) !== 'data:') {
return false;
}
var mediaType = schemeAndMediaType.substr(5);
if (mediaType !== '' && !validMediaType.test(mediaType)) {
return false;
}
for (var i = 0; i < attributes.length; i++) {
if (i === attributes.length - 1 && attributes[i].toLowerCase() === 'base64') {
// ok
} else if (!validAttribute.test(attributes[i])) {
return false;
}
}
for (var _i = 0; _i < data.length; _i++) {
if (!validData.test(data[_i])) {
return false;
}
}
return true;
}
module.exports = exports['default'];
+41
View File
@@ -0,0 +1,41 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isDecimal;
var _merge = require('./util/merge');
var _merge2 = _interopRequireDefault(_merge);
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _alpha = require('./alpha');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function decimalRegExp(options) {
var regExp = new RegExp('^[-+]?([0-9]+)?(\\' + _alpha.decimal[options.locale] + '[0-9]{' + options.decimal_digits + '})' + (options.force_decimal ? '' : '?') + '$');
return regExp;
}
var default_decimal_options = {
force_decimal: false,
decimal_digits: '1,',
locale: 'en-US'
};
var blacklist = ['', '-', '+'];
function isDecimal(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_decimal_options);
if (options.locale in _alpha.decimal) {
return !blacklist.includes(str.replace(/ /g, '')) && decimalRegExp(options).test(str);
}
throw new Error('Invalid locale \'' + options.locale + '\'');
}
module.exports = exports['default'];
+22
View File
@@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isDivisibleBy;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _toFloat = require('./toFloat');
var _toFloat2 = _interopRequireDefault(_toFloat);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isDivisibleBy(str, num) {
(0, _assertString2.default)(str);
return (0, _toFloat2.default)(str) % parseInt(num, 10) === 0;
}
module.exports = exports['default'];
+89
View File
@@ -0,0 +1,89 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isEmail;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _merge = require('./util/merge');
var _merge2 = _interopRequireDefault(_merge);
var _isByteLength = require('./isByteLength');
var _isByteLength2 = _interopRequireDefault(_isByteLength);
var _isFQDN = require('./isFQDN');
var _isFQDN2 = _interopRequireDefault(_isFQDN);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var default_email_options = {
allow_display_name: false,
require_display_name: false,
allow_utf8_local_part: true,
require_tld: true
};
/* eslint-disable max-len */
/* eslint-disable no-control-regex */
var displayName = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\,\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\s]*<(.+)>$/i;
var emailUserPart = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i;
var quotedEmailUser = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i;
var emailUserUtf8Part = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i;
var quotedEmailUserUtf8 = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i;
/* eslint-enable max-len */
/* eslint-enable no-control-regex */
function isEmail(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_email_options);
if (options.require_display_name || options.allow_display_name) {
var display_email = str.match(displayName);
if (display_email) {
str = display_email[1];
} else if (options.require_display_name) {
return false;
}
}
var parts = str.split('@');
var domain = parts.pop();
var user = parts.join('@');
var lower_domain = domain.toLowerCase();
if (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com') {
user = user.replace(/\./g, '').toLowerCase();
}
if (!(0, _isByteLength2.default)(user, { max: 64 }) || !(0, _isByteLength2.default)(domain, { max: 254 })) {
return false;
}
if (!(0, _isFQDN2.default)(domain, { require_tld: options.require_tld })) {
return false;
}
if (user[0] === '"') {
user = user.slice(1, user.length - 1);
return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user);
}
var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart;
var user_parts = user.split('.');
for (var i = 0; i < user_parts.length; i++) {
if (!pattern.test(user_parts[i])) {
return false;
}
}
return true;
}
module.exports = exports['default'];
+18
View File
@@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isEmpty;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isEmpty(str) {
(0, _assertString2.default)(str);
return str.length === 0;
}
module.exports = exports['default'];
+61
View File
@@ -0,0 +1,61 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isFQDN;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _merge = require('./util/merge');
var _merge2 = _interopRequireDefault(_merge);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var default_fqdn_options = {
require_tld: true,
allow_underscores: false,
allow_trailing_dot: false
};
function isFQDN(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_fqdn_options);
/* Remove the optional trailing dot before checking validity */
if (options.allow_trailing_dot && str[str.length - 1] === '.') {
str = str.substring(0, str.length - 1);
}
var parts = str.split('.');
if (options.require_tld) {
var tld = parts.pop();
if (!parts.length || !/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) {
return false;
}
// disallow spaces
if (/[\s\u2002-\u200B\u202F\u205F\u3000\uFEFF\uDB40\uDC20]/.test(tld)) {
return false;
}
}
for (var part, i = 0; i < parts.length; i++) {
part = parts[i];
if (options.allow_underscores) {
part = part.replace(/_/g, '');
}
if (!/^[a-z\u00a1-\uffff0-9-]+$/i.test(part)) {
return false;
}
// disallow full-width chars
if (/[\uff01-\uff5e]/.test(part)) {
return false;
}
if (part[0] === '-' || part[part.length - 1] === '-') {
return false;
}
}
return true;
}
module.exports = exports['default'];
+25
View File
@@ -0,0 +1,25 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isFloat;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _alpha = require('./alpha');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isFloat(str, options) {
(0, _assertString2.default)(str);
options = options || {};
var float = new RegExp('^(?:[-+])?(?:[0-9]+)?(?:\\' + (options.locale ? _alpha.decimal[options.locale] : '.') + '[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$');
if (str === '' || str === '.' || str === '-' || str === '+') {
return false;
}
return float.test(str) && (!options.hasOwnProperty('min') || str >= options.min) && (!options.hasOwnProperty('max') || str <= options.max) && (!options.hasOwnProperty('lt') || str < options.lt) && (!options.hasOwnProperty('gt') || str > options.gt);
}
module.exports = exports['default'];
+20
View File
@@ -0,0 +1,20 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fullWidth = undefined;
exports.default = isFullWidth;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var fullWidth = exports.fullWidth = /[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;
function isFullWidth(str) {
(0, _assertString2.default)(str);
return fullWidth.test(str);
}
+20
View File
@@ -0,0 +1,20 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.halfWidth = undefined;
exports.default = isHalfWidth;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var halfWidth = exports.halfWidth = /[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;
function isHalfWidth(str) {
(0, _assertString2.default)(str);
return halfWidth.test(str);
}
+35
View File
@@ -0,0 +1,35 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isHash;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var lengths = {
md5: 32,
md4: 32,
sha1: 40,
sha256: 64,
sha384: 96,
sha512: 128,
ripemd128: 32,
ripemd160: 40,
tiger128: 32,
tiger160: 40,
tiger192: 48,
crc32: 8,
crc32b: 8
};
function isHash(str, algorithm) {
(0, _assertString2.default)(str);
var hash = new RegExp('^[a-f0-9]{' + lengths[algorithm] + '}$');
return hash.test(str);
}
module.exports = exports['default'];
+20
View File
@@ -0,0 +1,20 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isHexColor;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{6})$/i;
function isHexColor(str) {
(0, _assertString2.default)(str);
return hexcolor.test(str);
}
module.exports = exports['default'];
+20
View File
@@ -0,0 +1,20 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isHexadecimal;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var hexadecimal = /^[0-9A-F]+$/i;
function isHexadecimal(str) {
(0, _assertString2.default)(str);
return hexadecimal.test(str);
}
module.exports = exports['default'];
+81
View File
@@ -0,0 +1,81 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isIP;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ipv4Maybe = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
var ipv6Block = /^[0-9A-F]{1,4}$/i;
function isIP(str) {
var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
(0, _assertString2.default)(str);
version = String(version);
if (!version) {
return isIP(str, 4) || isIP(str, 6);
} else if (version === '4') {
if (!ipv4Maybe.test(str)) {
return false;
}
var parts = str.split('.').sort(function (a, b) {
return a - b;
});
return parts[3] <= 255;
} else if (version === '6') {
var blocks = str.split(':');
var foundOmissionBlock = false; // marker to indicate ::
// At least some OS accept the last 32 bits of an IPv6 address
// (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says
// that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses,
// and '::a.b.c.d' is deprecated, but also valid.
var foundIPv4TransitionBlock = isIP(blocks[blocks.length - 1], 4);
var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8;
if (blocks.length > expectedNumberOfBlocks) {
return false;
}
// initial or final ::
if (str === '::') {
return true;
} else if (str.substr(0, 2) === '::') {
blocks.shift();
blocks.shift();
foundOmissionBlock = true;
} else if (str.substr(str.length - 2) === '::') {
blocks.pop();
blocks.pop();
foundOmissionBlock = true;
}
for (var i = 0; i < blocks.length; ++i) {
// test for a :: which can not be at the string start/end
// since those cases have been handled above
if (blocks[i] === '' && i > 0 && i < blocks.length - 1) {
if (foundOmissionBlock) {
return false; // multiple :: in address
}
foundOmissionBlock = true;
} else if (foundIPv4TransitionBlock && i === blocks.length - 1) {
// it has been checked before that the last
// block is a valid IPv4 address
} else if (!ipv6Block.test(blocks[i])) {
return false;
}
}
if (foundOmissionBlock) {
return blocks.length >= 1;
}
return blocks.length === expectedNumberOfBlocks;
}
return false;
}
module.exports = exports['default'];
+57
View File
@@ -0,0 +1,57 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isISBN;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/;
var isbn13Maybe = /^(?:[0-9]{13})$/;
var factor = [1, 3];
function isISBN(str) {
var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
(0, _assertString2.default)(str);
version = String(version);
if (!version) {
return isISBN(str, 10) || isISBN(str, 13);
}
var sanitized = str.replace(/[\s-]+/g, '');
var checksum = 0;
var i = void 0;
if (version === '10') {
if (!isbn10Maybe.test(sanitized)) {
return false;
}
for (i = 0; i < 9; i++) {
checksum += (i + 1) * sanitized.charAt(i);
}
if (sanitized.charAt(9) === 'X') {
checksum += 10 * 10;
} else {
checksum += 10 * sanitized.charAt(9);
}
if (checksum % 11 === 0) {
return !!sanitized;
}
} else if (version === '13') {
if (!isbn13Maybe.test(sanitized)) {
return false;
}
for (i = 0; i < 12; i++) {
checksum += factor[i % 2] * sanitized.charAt(i);
}
if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) {
return !!sanitized;
}
}
return false;
}
module.exports = exports['default'];
Loaded 100 of 732 files, more files were not shown because too many files have changed in this diff. Show more