Showing preview only (615K chars total). Download the full file or copy to clipboard to get everything.
Repository: cerner/smart-on-fhir-tutorial
Branch: gh-pages
Commit: e8dbcaf869ce
Files: 16
Total size: 597.6 KB
Directory structure:
gitextract_80gh6yd1/
├── example-smart-app/
│ ├── health.html
│ ├── index.html
│ ├── launch-patient.html
│ ├── launch-smart-sandbox.html
│ ├── launch.html
│ ├── lib/
│ │ └── js/
│ │ ├── fhir-client-cerner-additions-1.0.0.js
│ │ └── fhir-client-v0.1.12.js
│ └── src/
│ ├── css/
│ │ └── example-smart-app.css
│ └── js/
│ └── example-smart-app.js
├── images/
│ ├── ehr_launch_seq.txt
│ └── patient_launch_seq.txt
├── index.html
├── javascripts/
│ ├── all.js
│ └── all_nosearch.js
└── stylesheets/
├── print.css
└── screen.css
================================================
FILE CONTENTS
================================================
================================================
FILE: example-smart-app/health.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Example-SMART-App</title>
<!--
Temporarily disable cerner-smart-embeddable-lib
<link rel='stylesheet' type='text/css' href='./lib/css/cerner-smart-embeddable-lib-1.0.0.min.css'>
-->
</head>
<body>
<!-- Required JS files to enable this page to embed within an MPage -->
<!--
Temporarily disable cerner-smart-embeddable-lib
<script src='https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.min.js'></script>
<script src='./lib/js/cerner-smart-embeddable-lib-1.0.0.min.js'></script>
-->
<img src="./src/images/batman.gif" alt="Batman">
<p>Healthy!</p>
</body>
</html>
================================================
FILE: example-smart-app/index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>Example-SMART-App</title>
<link rel='stylesheet' type='text/css' href='./src/css/example-smart-app.css'>
<!--
Temporarily disable cerner-smart-embeddable-lib
<link rel='stylesheet' type='text/css' href='./lib/css/cerner-smart-embeddable-lib-1.0.0.min.css'>
-->
</head>
<body>
<div id='errors'>
</div>
<div id="loading" class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
<div id='holder' >
<h2>Example-SMART-App</h2>
<h2>Patient Resource</h2>
<table>
<tr>
<th>First Name:</th>
<td id='fname'></td>
</tr>
<tr>
<th>Last Name:</th>
<td id='lname'></td>
</tr>
<tr>
<th>Gender:</th>
<td id='gender'></td>
</tr>
<tr>
<th>Date of Birth:</th>
<td id='birthdate'></td>
</tr>
</table>
<h2>Observation Resource</h2>
<table>
<tr>
<th>Height:</th>
<td id='height'></td>
</tr>
<tr>
<th>Systolic Blood Pressure:</th>
<td id='systolicbp'></td>
</tr>
<tr>
<th>Diastolic Blood Pressure:</th>
<td id='diastolicbp'></td>
</tr>
<tr>
<th>LDL:</th>
<td id='ldl'></td>
</tr>
<tr>
<th>HDL:</th>
<td id='hdl'></td>
</tr>
</table>
</div>
<!-- Required JS files to enable this page to embed within an MPage -->
<!--
Temporarily disable cerner-smart-embeddable-lib
<script src='https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.min.js'></script>
<script src='./lib/js/cerner-smart-embeddable-lib-1.0.0.min.js'></script>
-->
<!-- Application-level javascript-->
<script src='./src/js/example-smart-app.js'></script>
<!-- FHIR Client JS Library -->
<script src='./lib/js/fhir-client-v0.1.12.js'></script>
<!-- Prevent session bleed caused by single threaded embedded browser and sessionStorage API -->
<!-- https://github.com/cerner/fhir-client-cerner-additions -->
<script src='./lib/js/fhir-client-cerner-additions-1.0.0.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
extractData().then(
//Display Patient Demographics and Observations if extractData was success
function(p) {
drawVisualization(p);
},
//Display 'Failed to call FHIR Service' if extractData failed
function() {
$('#loading').hide();
$('#errors').html('<p> Failed to call FHIR Service </p>');
}
);
</script>
</body>
</html>
================================================
FILE: example-smart-app/launch-patient.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel='stylesheet' type='text/css' href='./src/css/example-smart-app.css'>
<!--
Temporarily disable cerner-smart-embeddable-lib
<link rel='stylesheet' type='text/css' href='./lib/css/cerner-smart-embeddable-lib-1.0.0.min.css'>
-->
<title>Example-SMART-App</title>
</head>
<body>
<!-- Required JS files to enable this page to embed within an MPage -->
<!--
Temporarily disable cerner-smart-embeddable-lib
<script src='https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.min.js'></script>
<script src='./lib/js/cerner-smart-embeddable-lib-1.0.0.min.js'></script>
-->
<!-- FHIR Client JS Library -->
<script src='./lib/js/fhir-client-v0.1.12.js'></script>
<!-- Prevent session bleed caused by single threaded embedded browser and sessionStorage API -->
<!-- https://github.com/cerner/fhir-client-cerner-additions -->
<script src='./lib/js/fhir-client-cerner-additions-1.0.0.js'></script>
<script>
FHIR.oauth2.authorize({
'client_id': 'CLIENT_ID_HERE',
'scope': 'patient/Patient.read patient/Observation.read launch/patient online_access openid profile'
});
</script>
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</body>
</html>
================================================
FILE: example-smart-app/launch-smart-sandbox.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel='stylesheet' type='text/css' href='./src/css/example-smart-app.css'>
<!--
Temporarily disable cerner-smart-embeddable-lib
<link rel='stylesheet' type='text/css' href='./lib/css/cerner-smart-embeddable-lib-1.0.0.min.css'>
-->
<title>Example-SMART-App</title>
</head>
<body>
<!-- Required JS files to enable this page to embed within an MPage -->
<!--
Temporarily disable cerner-smart-embeddable-lib
<script src='https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.min.js'></script>
<script src='./lib/js/cerner-smart-embeddable-lib-1.0.0.min.js'></script>
-->
<!-- FHIR Client JS Library -->
<script src='./lib/js/fhir-client-v0.1.12.js'></script>
<!-- Prevent session bleed caused by single threaded embedded browser and sessionStorage API -->
<!-- https://github.com/cerner/fhir-client-cerner-additions -->
<script src='./lib/js/fhir-client-cerner-additions-1.0.0.js'></script>
<!-- Currently, the SMART App Launcher (https://launch.smarthealthit.org) does not check/validate the client_id field.
If/when this changes, or when working with other authorization servers, please update the client_id field here. -->
<script>
FHIR.oauth2.authorize({
'client_id': 'YOUR-SMART-HEALTH-IT-CLIENT-ID-HERE',
'scope': 'patient/Patient.read patient/Observation.read launch online_access openid profile'
});
</script>
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</body>
</html>
================================================
FILE: example-smart-app/launch.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel='stylesheet' type='text/css' href='./src/css/example-smart-app.css'>
<!--
Temporarily disable cerner-smart-embeddable-lib
<link rel='stylesheet' type='text/css' href='./lib/css/cerner-smart-embeddable-lib-1.0.0.min.css'>
-->
<title>Example-SMART-App</title>
</head>
<body>
<!-- Required JS files to enable this page to embed within an MPage -->
<!--
Temporarily disable cerner-smart-embeddable-lib
<script src='https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.min.js'></script>
<script src='./lib/js/cerner-smart-embeddable-lib-1.0.0.min.js'></script>
-->
<!-- FHIR Client JS Library -->
<script src='./lib/js/fhir-client-v0.1.12.js'></script>
<!-- Prevent session bleed caused by single threaded embedded browser and sessionStorage API -->
<!-- https://github.com/cerner/fhir-client-cerner-additions -->
<script src='./lib/js/fhir-client-cerner-additions-1.0.0.js'></script>
<script>
FHIR.oauth2.authorize({
'client_id': '<enter your client id here>',
'scope': 'patient/Patient.read patient/Observation.read launch online_access openid profile'
});
</script>
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</body>
</html>
================================================
FILE: example-smart-app/lib/js/fhir-client-cerner-additions-1.0.0.js
================================================
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(1);
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
// This is the entry point for webpack to distribute assets
// Require all JS and output as a single js bundle.
// Note, we are requiring the es6 js.
__webpack_require__(2);
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var _fhirClientCernerAdditions = __webpack_require__(3);
var _fhirClientCernerAdditions2 = _interopRequireDefault(_fhirClientCernerAdditions);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Prereq: This library should be included after fhir-client.js library.
*
* Automatically sets the fullSessionStorageSupport flag
* when this library is included after fhir-client.js.
* The boolean value is computed based on whether the page
* is rendered within PowerChart or elsewhere.
*
* If the page is rendered within PowerChart, the value will
* be set to false. This is done to prevent session data
* to be shared between applications. The reason is the embedded
* IE browser is instantiated on a single thread in PowerChart.
*/
_fhirClientCernerAdditions2.default.setFullSessionStorageSupport();
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = __webpack_require__(4);
var _utils2 = _interopRequireDefault(_utils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Wrapper object containing additional feature or settings
* to the open source version of fhir-client.js file.
*/
var FhirClientCernerAdditions = {
/**
* Override fullSessionStorageSupport flag in fhir-client.js (src/client/bb-client.js) file.
* The value depends on whether the page is loaded in PowerChart or
* a regular browser that supports sessionStorage API without session being shared across tabs.
*/
setFullSessionStorageSupport: function setFullSessionStorageSupport() {
FHIR.oauth2.settings.fullSessionStorageSupport = !_utils2.default.isPowerChart();
}
}; /* globals FHIR */
exports.default = FhirClientCernerAdditions;
/***/ }),
/* 4 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/* globals window */
/**
* This Utils object contains util function(s) needed by this project.
* All the functions in this file can be moved to fhir-client-cerner-additions.js file,
* however having them here make it easier to write tests.
*/
var Utils = {
/**
* Determine if application is rendered in PowerChart.
* @return null or true/false
*/
isPowerChart: function isPowerChart() {
return window.external && typeof window.external.DiscernObjectFactory !== 'undefined';
}
};
exports.default = Utils;
/***/ })
/******/ ]);
//# sourceMappingURL=fhir-client-cerner-additions-1.0.0.min.js.map
================================================
FILE: example-smart-app/lib/js/fhir-client-v0.1.12.js
================================================
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["fhir"] = factory();
else
root["fhir"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
(function() {
var mkFhir = __webpack_require__(1);
var jquery = window['_jQuery'] || window['jQuery'];
var defer = function(){
pr = jquery.Deferred();
pr.promise = pr.promise();
return pr;
};
var adapter = {
defer: defer,
http: function(args) {
var ret = jquery.Deferred();
var opts = {
type: args.method,
url: args.url,
headers: args.headers,
dataType: "json",
contentType: "application/json",
data: args.data || args.params,
withCredentials: args.credentials === 'include',
};
jquery.ajax(opts)
.done(function(data, status, xhr) {ret.resolve({data: data, status: status, headers: xhr.getResponseHeader, config: args});})
.fail(function(err) {ret.reject({error: err, data: err, config: args});});
return ret.promise();
}
};
var fhir = function(config) {
return mkFhir(config, adapter);
};
fhir.defer = defer;
module.exports = fhir;
}).call(this);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
(function() {
var utils = __webpack_require__(2);
var M = __webpack_require__(5);
var query = __webpack_require__(6);
var auth = __webpack_require__(7);
var transport = __webpack_require__(9);
var errors = __webpack_require__(10);
var config = __webpack_require__(11);
var bundle = __webpack_require__(12);
var pt = __webpack_require__(13);
var refs = __webpack_require__(14);
var url = __webpack_require__(15);
var decorate = __webpack_require__(16);
var cache = {};
var fhir = function(cfg, adapter){
var Middleware = M.Middleware;
var $$Attr = M.$$Attr;
var $$Method = function(m){ return $$Attr('method', m);};
var $$Header = function(h,v) {return $$Attr('headers.' + h, v);};
var $Errors = Middleware(errors);
var Defaults = Middleware(config(cfg, adapter))
.and($Errors)
.and(auth.$Basic)
.and(auth.$Bearer)
.and(auth.$Credentials)
.and(transport.$JsonData)
.and($$Header('Accept', 'application/json'))
.and($$Header('Content-Type', 'application/json'));
var GET = Defaults.and($$Method('GET'));
var POST = Defaults.and($$Method('POST'));
var PUT = Defaults.and($$Method('PUT'));
var DELETE = Defaults.and($$Method('DELETE'));
var http = transport.Http(cfg, adapter);
var Path = url.Path;
var BaseUrl = Path(cfg.baseUrl);
var resourceTypePath = BaseUrl.slash(":type || :resource.resourceType");
var searchPath = resourceTypePath;
var resourceTypeHxPath = resourceTypePath.slash("_history");
var resourcePath = resourceTypePath.slash(":id || :resource.id");
var resourceHxPath = resourcePath.slash("_history");
var vreadPath = resourceHxPath.slash(":versionId || :resource.meta.versionId");
var resourceVersionPath = resourceHxPath.slash(":versionId || :resource.meta.versionId");
var ReturnHeader = $$Header('Prefer', 'return=representation');
var $Paging = Middleware(query.$Paging);
return decorate({
conformance: GET.and(BaseUrl.slash("metadata")).end(http),
document: POST.and(BaseUrl.slash("Document")).end(http),
profile: GET.and(BaseUrl.slash("Profile").slash(":type")).end(http),
transaction: POST.and(BaseUrl).end(http),
history: GET.and(BaseUrl.slash("_history")).and($Paging).end(http),
typeHistory: GET.and(resourceTypeHxPath).and($Paging).end(http),
resourceHistory: GET.and(resourceHxPath).and($Paging).end(http),
read: GET.and(pt.$WithPatient).and(resourcePath).end(http),
vread: GET.and(vreadPath).end(http),
"delete": DELETE.and(resourcePath).and(ReturnHeader).end(http),
create: POST.and(resourceTypePath).and(ReturnHeader).end(http),
validate: POST.and(resourceTypePath.slash("_validate")).end(http),
search: GET.and(resourceTypePath).and(pt.$WithPatient).and(query.$SearchParams).and($Paging).end(http),
update: PUT.and(resourcePath).and(ReturnHeader).end(http),
nextPage: GET.and(bundle.$$BundleLinkUrl("next")).end(http),
prevPage: GET.and(bundle.$$BundleLinkUrl("prev")).end(http),
resolve: GET.and(refs.resolve).end(http)
}, adapter);
};
module.exports = fhir;
}).call(this);
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
(function() {
var merge = __webpack_require__(3);
var RTRIM = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
var trim = function(text) {
return text ? text.toString().replace(RTRIM, "") : "";
};
exports.trim = trim;
var addKey = function(acc, str) {
var pair, val;
if (!str) {
return null;
}
pair = str.split("=").map(trim);
val = pair[1].replace(/(^"|"$)/g, '');
if (val) {
acc[pair[0]] = val;
}
return acc;
};
var type = function(obj) {
var classToType;
if (obj == null && obj === undefined) {
return String(obj);
}
classToType = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regexp',
'[object Object]': 'object'
};
return classToType[Object.prototype.toString.call(obj)];
};
exports.type = type;
var assertArray = function(a) {
if (type(a) !== 'array') {
throw 'not array';
}
return a;
};
exports.assertArray = assertArray;
var assertObject = function(a) {
if (type(a) !== 'object') {
throw 'not object';
}
return a;
};
exports.assertObject = assertObject;
var reduceMap = function(m, fn, acc) {
var k, v;
acc || (acc = []);
assertObject(m);
return ((function() {
var results;
results = [];
for (k in m) {
v = m[k];
results.push([k, v]);
}
return results;
})()).reduce(fn, acc);
};
exports.reduceMap = reduceMap;
var identity = function(x) {return x;};
exports.identity = identity;
var argsArray = function() {
return Array.prototype.slice.call(arguments)
};
exports.argsArray = argsArray;
var mergeLists = function() {
var reduce;
reduce = function(merged, nextMap) {
var k, ret, v;
ret = merge(true, merged);
for (k in nextMap) {
v = nextMap[k];
ret[k] = (ret[k] || []).concat(v);
}
return ret;
};
return argsArray.apply(null, arguments).reduce(reduce, {});
};
exports.mergeLists = mergeLists;
var absoluteUrl = function(baseUrl, ref) {
if (!ref.match(/https?:\/\/./)) {
return baseUrl + "/" + ref;
} else {
return ref;
}
};
exports.absoluteUrl = absoluteUrl;
var relativeUrl = function(baseUrl, ref) {
if (ref.slice(ref, baseUrl.length + 1) === baseUrl + "/") {
return ref.slice(baseUrl.length + 1);
} else {
return ref;
}
};
exports.relativeUrl = relativeUrl;
exports.resourceIdToUrl = function(id, baseUrl, type) {
baseUrl = baseUrl.replace(/\/$/, '');
id = id.replace(/^\//, '');
if (id.indexOf('/') < 0) {
return baseUrl + "/" + type + "/" + id;
} else if (id.indexOf(baseUrl) !== 0) {
return baseUrl + "/" + id;
} else {
return id;
}
};
var walk = function(inner, outer, data, context) {
var keysToMap, remapped;
switch (type(data)) {
case 'array':
return outer(data.map(function(item) {
return inner(item, [data, context]);
}), context);
case 'object':
keysToMap = function(acc, arg) {
var k, v;
k = arg[0], v = arg[1];
acc[k] = inner(v, [data].concat(context));
return acc;
};
remapped = reduceMap(data, keysToMap, {});
return outer(remapped, context);
default:
return outer(data, context);
}
};
exports.walk = walk;
var postwalk = function(f, data, context) {
if (!data) {
return function(data, context) {
return postwalk(f, data, context);
};
} else {
return walk(postwalk(f), f, data, context);
}
};
exports.postwalk = postwalk;
}).call(this);
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {/*!
* @name JavaScript/NodeJS Merge v1.1.3
* @author yeikos
* @repository https://github.com/yeikos/js.merge
* Copyright 2014 yeikos - MIT license
* https://raw.github.com/yeikos/js.merge/master/LICENSE
*/
;(function(isNode) {
function merge() {
var items = Array.prototype.slice.call(arguments),
result = items.shift(),
deep = (result === true),
size = items.length,
item, index, key;
if (deep || typeOf(result) !== 'object')
result = {};
for (index=0;index<size;++index)
if (typeOf(item = items[index]) === 'object')
for (key in item)
result[key] = deep ? clone(item[key]) : item[key];
return result;
}
function clone(input) {
var output = input,
type = typeOf(input),
index, size;
if (type === 'array') {
output = [];
size = input.length;
for (index=0;index<size;++index)
output[index] = clone(input[index]);
} else if (type === 'object') {
output = {};
for (index in input)
output[index] = clone(input[index]);
}
return output;
}
function typeOf(input) {
return ({}).toString.call(input).match(/\s([\w]+)/)[1].toLowerCase();
}
if (isNode) {
module.exports = merge;
} else {
window.merge = merge;
}
})(typeof module === 'object' && module && typeof module.exports === 'object' && module.exports);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)(module)))
/***/ },
/* 4 */
/***/ function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
module.children = [];
module.webpackPolyfill = 1;
}
return module;
}
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
(function() {
var utils = __webpack_require__(2);
var id = function(x){return x;};
var constantly = function(x){return function(){return x;};};
var mwComposition = function(mw1, mw2){
return function(h){ return mw1(mw2(h)); };
};
var Middleware = function(mw){
mw.and = function(nmw){
return Middleware(mwComposition(mw, nmw));
};
mw.end = function(h){
return mw(h);
};
return mw;
};
// generate wm from function
exports.$$Simple = function(f){
return function(h){
return function(args){
return h(f(args));
};
};
};
var setAttr = function(args, attr, value){
var path = attr.split('.');
var obj = args;
for(var i = 0; i < (path.length - 1); i++){
var k = path[i];
obj = args[k];
if(!obj){
obj = {};
args[k] = obj;
}
}
obj[path[path.length - 1]] = value;
return args;
};
// generate wm from function
exports.$$Attr = function(attr, fn){
return Middleware(function(h){
return function(args) {
var value = null;
if(utils.type(fn) == 'function'){
value = fn(args);
} else {
value = fn;
}
if(value == null && value == undefined){
return h(args);
}else {
return h(setAttr(args, attr, value));
}
};
});
};
var Attribute = function(attr, fn){
return Middleware(function(h){
return function(args) {
args[attr] = fn(args);
return h(args);
};
});
};
var Method = function(method){
return Attribute('method', constantly(method));
};
exports.Middleware = Middleware;
exports.Attribute = Attribute;
exports.Method = Method;
}).call(this);
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
(function() {
var utils = __webpack_require__(2);
var type = utils.type;
var assertArray = utils.assertArray;
var assertObject = utils.assertObject;
var reduceMap = utils.reduceMap;
var identity = utils.identity;
var OPERATORS = {
$gt: 'gt',
$lt: 'lt',
$lte: 'lte',
$gte: 'gte'
};
var MODIFIERS = {
$asc: ':asc',
$desc: ':desc',
$exact: ':exact',
$missing: ':missing',
$null: ':missing',
$text: ':text'
};
var isOperator = function(v) {
return v.indexOf('$') === 0;
};
var expandParam = function(k, v) {
return reduceMap(v, function(acc, arg) {
var kk, o, res, vv;
kk = arg[0], vv = arg[1];
return acc.concat(kk === '$and' ? assertArray(vv).reduce((function(a, vvv) {
return a.concat(linearizeOne(k, vvv));
}), []) : kk === '$type' ? [] : isOperator(kk) ? (o = {
param: k
}, kk === '$or' ? o.value = vv : (OPERATORS[kk] ? o.operator = OPERATORS[kk] : void 0, MODIFIERS[kk] ? o.modifier = MODIFIERS[kk] : void 0, type(vv) === 'object' && vv.$or ? o.value = vv.$or : o.value = [vv]), [o]) : (v.$type ? res = ":" + v.$type : void 0, linearizeOne("" + k + (res || '') + "." + kk, vv)));
});
};
var handleSort = function(xs) {
var i, len, results, x;
assertArray(xs);
results = [];
for (i = 0, len = xs.length; i < len; i++) {
x = xs[i];
switch (type(x)) {
case 'array':
results.push({
param: '_sort',
value: x[0],
modifier: ":" + x[1]
});
break;
case 'string':
results.push({
param: '_sort',
value: x
});
break;
default:
results.push(void 0);
}
}
return results;
};
var handleInclude = function(includes) {
return reduceMap(includes, function(acc, arg) {
var k, v;
k = arg[0], v = arg[1];
return acc.concat((function() {
switch (type(v)) {
case 'array':
return v.map(function(x) {
return {
param: '_include',
value: k + "." + x
};
});
case 'string':
return [
{
param: '_include',
value: k + "." + v
}
];
}
})());
});
};
var linearizeOne = function(k, v) {
if (k === '$sort') {
return handleSort(v);
} else if (k === '$include') {
return handleInclude(v);
} else {
switch (type(v)) {
case 'object':
return expandParam(k, v);
case 'string':
return [
{
param: k,
value: [v]
}
];
case 'number':
return [
{
param: k,
value: [v]
}
];
case 'array':
return [
{
param: k,
value: [v.join("|")]
}
];
default:
throw "could not linearizeParams " + (type(v));
}
}
};
var linearizeParams = function(query) {
return reduceMap(query, function(acc, arg) {
var k, v;
k = arg[0], v = arg[1];
return acc.concat(linearizeOne(k, v));
});
};
var buildSearchParams = function(query) {
var p, ps;
ps = (function() {
var i, len, ref, results;
ref = linearizeParams(query);
results = [];
for (i = 0, len = ref.length; i < len; i++) {
p = ref[i];
results.push([p.param, p.modifier, '=', p.operator, encodeURIComponent(p.value)].filter(identity).join(''));
}
return results;
})();
return ps.join("&");
};
exports._query = linearizeParams;
exports.query = buildSearchParams;
var mw = __webpack_require__(5);
exports.$SearchParams = mw.$$Attr('url', function(args){
var url = args.url;
if(args.query){
var queryStr = buildSearchParams(args.query);
return url + "?" + queryStr;
}
return url;
});
exports.$Paging = function(h){
return function(args){
var params = args.params || {};
if(args.since){params._since = args.since;}
if(args.count){params._count = args.count;}
args.params = params;
return h(args);
};
};
}).call(this);
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
(function() {
var mw = __webpack_require__(5);
var btoa = __webpack_require__(8).btoa;
exports.$Basic = mw.$$Attr('headers.Authorization', function(args){
if(args.auth && args.auth.user && args.auth.pass){
return "Basic " + btoa(args.auth.user + ":" + args.auth.pass);
}
});
exports.$Bearer = mw.$$Attr('headers.Authorization', function(args){
if(args.auth && args.auth.bearer){
return "Bearer " + args.auth.bearer;
}
});
var credentials;
// this first middleware sets the credentials attribute to empty, so
// adapters cannot use it directly, thus enforcing a valid value to be parsed in.
exports.$Credentials = mw.Middleware(mw.$$Attr('credentials', function(args){
// Assign value for later checking
credentials = args.credentials
// Needs to return non-null and not-undefined
// in order for value to be (un)set
return '';
})).and(mw.$$Attr('credentials', function(args){
// check credentials for valid options, valid for fetch
if(['same-origin', 'include'].indexOf(credentials) > -1 ){
return credentials;
}
}));
}).call(this);
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
;(function () {
var object = true ? exports : this; // #8: web workers
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function InvalidCharacterError(message) {
this.message = message;
}
InvalidCharacterError.prototype = new Error;
InvalidCharacterError.prototype.name = 'InvalidCharacterError';
// encoder
// [https://gist.github.com/999166] by [https://github.com/nignag]
object.btoa || (
object.btoa = function (input) {
var str = String(input);
for (
// initialize result and counter
var block, charCode, idx = 0, map = chars, output = '';
// if the next str index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
str.charAt(idx | 0) || (map = '=', idx % 1);
// "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
output += map.charAt(63 & block >> 8 - idx % 1 * 8)
) {
charCode = str.charCodeAt(idx += 3/4);
if (charCode > 0xFF) {
throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
}
block = block << 8 | charCode;
}
return output;
});
// decoder
// [https://gist.github.com/1020396] by [https://github.com/atk]
object.atob || (
object.atob = function (input) {
var str = String(input).replace(/=+$/, '');
if (str.length % 4 == 1) {
throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
});
}());
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
(function() {
var utils = __webpack_require__(2);
exports.Http = function(cfg, adapter){
return function(args){
if(args.debug){
console.log("\nDEBUG (request):", args.method, args.url, args);
}
var promise = (args.http || adapter.http || cfg.http)(args);
if (args.debug && promise && promise.then){
promise.then(function(x){ console.log("\nDEBUG: (responce)", x);});
}
return promise;
};
};
var toJson = function(x){
return (utils.type(x) == 'object') ? JSON.stringify(x) : x;
};
exports.$JsonData = function(h){
return function(args){
var data = args.bundle || args.data || args.resource;
if(data){
args.data = toJson(data);
}
return h(args);
};
};
}).call(this);
/***/ },
/* 10 */
/***/ function(module, exports) {
module.exports = function(h){
return function(args){
try{
return h(args);
}catch(e){
if(args.debug){
console.log("\nDEBUG: (ERROR in middleware)");
console.log(e.message);
console.log(e.stack);
}
if(!args.defer) {
console.log("\nDEBUG: (ERROR in middleware)");
console.log(e.message);
console.log(e.stack);
throw new Error("I need adapter.defer");
}
var deff = args.defer();
deff.reject(e);
return deff.promise;
}
};
};
/***/ },
/* 11 */
/***/ function(module, exports) {
(function() {
var copyAttr = function(from, to, attr){
var v = from[attr];
if(v && !to[attr]) {to[attr] = v;}
return from;
};
module.exports = function(cfg, adapter){
return function(h){
return function(args){
copyAttr(cfg, args, 'baseUrl');
copyAttr(cfg, args, 'cache');
copyAttr(cfg, args, 'auth');
copyAttr(cfg, args, 'patient');
copyAttr(cfg, args, 'debug');
copyAttr(adapter, args, 'defer');
copyAttr(adapter, args, 'http');
return h(args);
};
};
};
}).call(this);
/***/ },
/* 12 */
/***/ function(module, exports) {
exports.$$BundleLinkUrl = function(rel){
return function(h) {
return function(args){
var matched = function(x){return x.relation && x.relation === rel;};
var res = args.bundle && (args.bundle.link || []).filter(matched)[0];
if(res && res.url){
args.url = res.url;
args.data = null;
return h(args);
}
else{
throw new Error("No " + rel + " link found in bundle");
}
};
};
};
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
(function() {
var mw = __webpack_require__(5);
// List of resources with 'patient' or 'subject' properties (as of FHIR DSTU2 1.0.0)
var targets = [
"Account",
"AllergyIntolerance",
"BodySite",
"CarePlan",
"Claim",
"ClinicalImpression",
"Communication",
"CommunicationRequest",
"Composition",
"Condition",
"Contract",
"DetectedIssue",
"Device",
"DeviceUseRequest",
"DeviceUseStatement",
"DiagnosticOrder",
"DiagnosticReport",
"DocumentManifest",
"DocumentReference",
"Encounter",
"EnrollmentRequest",
"EpisodeOfCare",
"FamilyMemberHistory",
"Flag",
"Goal",
"ImagingObjectSelection",
"ImagingStudy",
"Immunization",
"ImmunizationRecommendation",
"List",
"Media",
"MedicationAdministration",
"MedicationDispense",
"MedicationOrder",
"MedicationStatement",
"NutritionOrder",
"Observation",
"Order",
"Procedure",
"ProcedureRequest",
"QuestionnaireResponse",
"ReferralRequest",
"RelatedPerson",
"RiskAssessment",
"Specimen",
"SupplyDelivery",
"SupplyRequest",
"VisionPrescription"
];
exports.$WithPatient = mw.$$Simple(function(args){
var type = args.type;
if (args.patient) {
if (type === "Patient") {
args.query = args.query || {};
args.query["_id"] = args.patient;
args["id"] = args.patient;
} else if (targets.indexOf(type) >= 0){
args.query = args.query || {};
args.query["patient"] = args.patient;
}
}
return args;
});
}).call(this);
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
(function() {
var utils = __webpack_require__(2);
var CONTAINED = /^#(.*)/;
var resolveContained = function(ref, resource) {
var cid = ref.match(CONTAINED)[1];
var ret = (resource.contained || []).filter(function(r){
return (r.id || r._id) == cid;
})[0];
return (ret && {content: ret}) || null;
};
var sync = function(arg) {
var cache = arg.cache;
var reference = arg.reference;
var bundle = arg.bundle;
var ref = reference;
if (!ref.reference) {return null;}
if (ref.reference.match(CONTAINED)) {return resolveContained(ref.reference, arg.resource);}
var abs = utils.absoluteUrl(arg.baseUrl, ref.reference);
var bundled = ((bundle && bundle.entry) || []).filter( function(e){
return e.id === abs;
})[0];
return bundled || (cache != null ? cache[abs] : void 0) || null;
};
var resolve = function(h){
return function(args) {
var cacheMatched = sync(args);
var ref = args.reference;
var def = args.defer();
if (cacheMatched) {
if(!args.defer){ throw new Error("I need promise constructor 'adapter.defer' in adapter"); }
def.resolve(cacheMatched);
return def.promise;
}
if (!ref) {
throw new Error("No reference found");
}
if (ref && ref.reference.match(CONTAINED)) {
throw new Error("Contained resource not found");
}
args.url = utils.absoluteUrl(args.baseUrl, ref.reference);
args.data = null;
return h(args);
};
};
module.exports.sync = sync;
module.exports.resolve = resolve;
}).call(this);
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
(function() {
var utils = __webpack_require__(2);
var core = __webpack_require__(5);
var id = function(x){return x;};
var constantly = function(x){return function(){return x;};};
var get_in = function(obj, path){
return path.split('.').reduce(function(acc,x){
if(acc == null || acc == undefined) { return null; }
return acc[x];
}, obj);
};
var evalPropsExpr = function(exp, args){
var exps = exp.split('||').map(function(x){return x.trim().substring(1);});
for(var i = 0; i < exps.length; i++){
var res = get_in(args, exps[i]);
if(res){ return res; }
}
return null;
};
var evalExpr = function(exp, args){
if (exp.indexOf(":") == 0){
return evalPropsExpr(exp, args);
} else {
return exp;
}
};
var buildPathPart = function(pth, args){
var k = evalExpr(pth.trim(), args);
if(k==null || k === undefined){ throw new Error("Parameter "+pth+" is required: " + JSON.stringify(args)); }
return k;
};
// path chaining function
// which return haldler wrapper: (h, cfg)->(args -> promise)
// it's chainable Path("baseUrl").slash(":type").slash(":id").slash("_history")(id, {})({id: 5, type: 'Patient'})
// and composable p0 = Path("baseUrl); p1 = p0.slash("path)
var Path = function(tkn, chain){
//Chainable
var new_chain = function(args){
return ((chain && (chain(args) + "/")) || "") + buildPathPart(tkn, args);
};
var ch = core.Attribute('url', new_chain);
ch.slash = function(tkn){
return Path(tkn, new_chain);
};
return ch;
};
exports.Path = Path;
}).call(this);
/***/ },
/* 16 */
/***/ function(module, exports) {
(function() {
var fhirAPI;
var adapter;
function getNext (bundle, process) {
var i;
var d = bundle.data.entry || [];
var entries = [];
for (i = 0; i < d.length; i++) {
entries.push(d[i].resource);
}
process(entries);
var def = adapter.defer();
fhirAPI.nextPage({bundle:bundle.data}).then(function (r) {
getNext(r, process).then(function (t) {
def.resolve();
});
}, function(err) {def.resolve()});
return def.promise;
}
function drain (searchParams, process, done, fail) {
var ret = adapter.defer();
fhirAPI.search(searchParams).then(function(data){
getNext(data, process).then(function() {
done();
}, function(err) {
fail(err);
});
}, function(err) {
fail(err);
});
};
function fetchAll (searchParams){
var ret = adapter.defer();
var results = [];
drain(
searchParams,
function(entries) {
entries.forEach(function(entry) {
results.push(entry);
});
},
function () {
ret.resolve(results);
},
function (err) {
ret.reject(err);
}
);
return ret.promise;
};
function fetchAllWithReferences (searchParams, resolveParams) {
var ret = adapter.defer();
fhirAPI.search(searchParams) // TODO: THIS IS NOT CORRECT (need fetchAll, but it does not return a bundle yet)
.then(function(results){
var resolvedReferences = {};
var queue = [function() {
var entries = results.data.entry || [];
var res = entries.map(function(r){
return r.resource;
});
var refs = function (resource, reference) {
var refID = normalizeRefID(resource,reference);
return resolvedReferences[refID];
};
ret.resolve(res,refs);
}];
function normalizeRefID (resource, reference) {
var refID = reference.reference;
if (refID.startsWith('#')) {
var resourceID = resource.resourceType + "/" + resource.id;
return resourceID + refID;
} else {
return refID;
}
}
function enqueue (bundle,resource,reference) {
queue.push(function() {
resolveReference(bundle,resource,reference);
});
}
function next() {
(queue.pop())();
}
function resolveReference (bundle,resource,reference) {
var refID = normalizeRefID(resource,reference);
fhirAPI.resolve({'bundle': bundle, 'resource': resource, 'reference':reference}).then(function(res){
var referencedObject = res.data || res.content;
resolvedReferences[refID] = referencedObject;
next();
});
}
var bundle = results.data;
bundle.entry && bundle.entry.forEach(function(element){
var resource = element.resource;
var type = resource.resourceType;
resolveParams && resolveParams.forEach(function(resolveParam){
var param = resolveParam.split('.');
var targetType = param[0];
var targetElement = param[1];
var reference = resource[targetElement];
if (type === targetType && reference) {
var referenceID = reference.reference;
if (!resolvedReferences[referenceID]) {
enqueue(bundle,resource,reference);
}
}
});
});
next();
}, function(){
ret.reject("Could not fetch search results");
});
return ret.promise;
};
function decorate (client, newAdapter) {
fhirAPI = client;
adapter = newAdapter;
client["drain"] = drain;
client["fetchAll"] = fetchAll;
client["fetchAllWithReferences"] = fetchAllWithReferences;
return client;
}
module.exports = decorate;
}).call(this);
/***/ }
/******/ ])
});
;
},{}],2:[function(require,module,exports){
},{}],3:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = Buffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192
/**
* If `TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Note:
*
* - Implementation must support adding new properties to `Uint8Array` instances.
* Firefox 4-29 lacked support, fixed in Firefox 30+.
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
*
* We detect these buggy browsers and set `TYPED_ARRAY_SUPPORT` to `false` so they will
* get the Object implementation, which is slower but will work correctly.
*/
var TYPED_ARRAY_SUPPORT = (function () {
try {
var buf = new ArrayBuffer(0)
var arr = new Uint8Array(buf)
arr.foo = function () { return 42 }
return 42 === arr.foo() && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (subject, encoding, noZero) {
if (!(this instanceof Buffer))
return new Buffer(subject, encoding, noZero)
var type = typeof subject
// Find the length
var length
if (type === 'number')
length = subject > 0 ? subject >>> 0 : 0
else if (type === 'string') {
if (encoding === 'base64')
subject = base64clean(subject)
length = Buffer.byteLength(subject, encoding)
} else if (type === 'object' && subject !== null) { // assume object is array-like
if (subject.type === 'Buffer' && isArray(subject.data))
subject = subject.data
length = +subject.length > 0 ? Math.floor(+subject.length) : 0
} else
throw new Error('First argument needs to be a number, array or string.')
var buf
if (TYPED_ARRAY_SUPPORT) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
buf = Buffer._augment(new Uint8Array(length))
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
buf = this
buf.length = length
buf._isBuffer = true
}
var i
if (TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
// Speed optimization -- use set if we're copying from a typed array
buf._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
if (Buffer.isBuffer(subject)) {
for (i = 0; i < length; i++)
buf[i] = subject.readUInt8(i)
} else {
for (i = 0; i < length; i++)
buf[i] = ((subject[i] % 256) + 256) % 256
}
} else if (type === 'string') {
buf.write(subject, 0, encoding)
} else if (type === 'number' && !TYPED_ARRAY_SUPPORT && !noZero) {
for (i = 0; i < length; i++) {
buf[i] = 0
}
}
return buf
}
// STATIC METHODS
// ==============
Buffer.isEncoding = function (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.isBuffer = function (b) {
return !!(b != null && b._isBuffer)
}
Buffer.byteLength = function (str, encoding) {
var ret
str = str.toString()
switch (encoding || 'utf8') {
case 'hex':
ret = str.length / 2
break
case 'utf8':
case 'utf-8':
ret = utf8ToBytes(str).length
break
case 'ascii':
case 'binary':
case 'raw':
ret = str.length
break
case 'base64':
ret = base64ToBytes(str).length
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = str.length * 2
break
default:
throw new Error('Unknown encoding')
}
return ret
}
Buffer.concat = function (list, totalLength) {
assert(isArray(list), 'Usage: Buffer.concat(list[, length])')
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
return list[0]
}
var i
if (totalLength === undefined) {
totalLength = 0
for (i = 0; i < list.length; i++) {
totalLength += list[i].length
}
}
var buf = new Buffer(totalLength)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
Buffer.compare = function (a, b) {
assert(Buffer.isBuffer(a) && Buffer.isBuffer(b), 'Arguments must be Buffers')
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
if (i !== len) {
x = a[i]
y = b[i]
}
if (x < y) {
return -1
}
if (y < x) {
return 1
}
return 0
}
// BUFFER INSTANCE METHODS
// =======================
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
assert(strLen % 2 === 0, 'Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var byte = parseInt(string.substr(i * 2, 2), 16)
assert(!isNaN(byte), 'Invalid hex string')
buf[offset + i] = byte
}
return i
}
function utf8Write (buf, string, offset, length) {
var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
return charsWritten
}
function asciiWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
return charsWritten
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
return charsWritten
}
function utf16leWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length)
return charsWritten
}
Buffer.prototype.write = function (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
encoding = String(encoding || 'utf8').toLowerCase()
var ret
switch (encoding) {
case 'hex':
ret = hexWrite(this, string, offset, length)
break
case 'utf8':
case 'utf-8':
ret = utf8Write(this, string, offset, length)
break
case 'ascii':
ret = asciiWrite(this, string, offset, length)
break
case 'binary':
ret = binaryWrite(this, string, offset, length)
break
case 'base64':
ret = base64Write(this, string, offset, length)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = utf16leWrite(this, string, offset, length)
break
default:
throw new Error('Unknown encoding')
}
return ret
}
Buffer.prototype.toString = function (encoding, start, end) {
var self = this
encoding = String(encoding || 'utf8').toLowerCase()
start = Number(start) || 0
end = (end === undefined) ? self.length : Number(end)
// Fastpath empty strings
if (end === start)
return ''
var ret
switch (encoding) {
case 'hex':
ret = hexSlice(self, start, end)
break
case 'utf8':
case 'utf-8':
ret = utf8Slice(self, start, end)
break
case 'ascii':
ret = asciiSlice(self, start, end)
break
case 'binary':
ret = binarySlice(self, start, end)
break
case 'base64':
ret = base64Slice(self, start, end)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = utf16leSlice(self, start, end)
break
default:
throw new Error('Unknown encoding')
}
return ret
}
Buffer.prototype.toJSON = function () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
Buffer.prototype.equals = function (b) {
assert(Buffer.isBuffer(b), 'Argument must be a Buffer')
return Buffer.compare(this, b) === 0
}
Buffer.prototype.compare = function (b) {
assert(Buffer.isBuffer(b), 'Argument must be a Buffer')
return Buffer.compare(this, b)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function (target, target_start, start, end) {
var source = this
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (!target_start) target_start = 0
// Copy 0 bytes; we're done
if (end === start) return
if (target.length === 0 || source.length === 0) return
// Fatal error conditions
assert(end >= start, 'sourceEnd < sourceStart')
assert(target_start >= 0 && target_start < target.length,
'targetStart out of bounds')
assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
// Are we oob?
if (end > this.length)
end = this.length
if (target.length - target_start < end - start)
end = target.length - target_start + start
var len = end - start
if (len < 100 || !TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < len; i++) {
target[i + target_start] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), target_start)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
var res = ''
var tmp = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
if (buf[i] <= 0x7F) {
res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
tmp = ''
} else {
tmp += '%' + buf[i].toString(16)
}
}
return res + decodeUtf8Char(tmp)
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function binarySlice (buf, start, end) {
return asciiSlice(buf, start, end)
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len;
if (start < 0)
start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0)
end = 0
} else if (end > len) {
end = len
}
if (end < start)
end = start
if (TYPED_ARRAY_SUPPORT) {
return Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
var newBuf = new Buffer(sliceLen, undefined, true)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
return newBuf
}
}
// `get` will be removed in Node 0.13+
Buffer.prototype.get = function (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
Buffer.prototype.set = function (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
Buffer.prototype.readUInt8 = function (offset, noAssert) {
if (!noAssert) {
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < this.length, 'Trying to read beyond buffer length')
}
if (offset >= this.length)
return
return this[offset]
}
function readUInt16 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val
if (littleEndian) {
val = buf[offset]
if (offset + 1 < len)
val |= buf[offset + 1] << 8
} else {
val = buf[offset] << 8
if (offset + 1 < len)
val |= buf[offset + 1]
}
return val
}
Buffer.prototype.readUInt16LE = function (offset, noAssert) {
return readUInt16(this, offset, true, noAssert)
}
Buffer.prototype.readUInt16BE = function (offset, noAssert) {
return readUInt16(this, offset, false, noAssert)
}
function readUInt32 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val
if (littleEndian) {
if (offset + 2 < len)
val = buf[offset + 2] << 16
if (offset + 1 < len)
val |= buf[offset + 1] << 8
val |= buf[offset]
if (offset + 3 < len)
val = val + (buf[offset + 3] << 24 >>> 0)
} else {
if (offset + 1 < len)
val = buf[offset + 1] << 16
if (offset + 2 < len)
val |= buf[offset + 2] << 8
if (offset + 3 < len)
val |= buf[offset + 3]
val = val + (buf[offset] << 24 >>> 0)
}
return val
}
Buffer.prototype.readUInt32LE = function (offset, noAssert) {
return readUInt32(this, offset, true, noAssert)
}
Buffer.prototype.readUInt32BE = function (offset, noAssert) {
return readUInt32(this, offset, false, noAssert)
}
Buffer.prototype.readInt8 = function (offset, noAssert) {
if (!noAssert) {
assert(offset !== undefined && offset !== null,
'missing offset')
assert(offset < this.length, 'Trying to read beyond buffer length')
}
if (offset >= this.length)
return
var neg = this[offset] & 0x80
if (neg)
return (0xff - this[offset] + 1) * -1
else
return this[offset]
}
function readInt16 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val = readUInt16(buf, offset, littleEndian, true)
var neg = val & 0x8000
if (neg)
return (0xffff - val + 1) * -1
else
return val
}
Buffer.prototype.readInt16LE = function (offset, noAssert) {
return readInt16(this, offset, true, noAssert)
}
Buffer.prototype.readInt16BE = function (offset, noAssert) {
return readInt16(this, offset, false, noAssert)
}
function readInt32 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val = readUInt32(buf, offset, littleEndian, true)
var neg = val & 0x80000000
if (neg)
return (0xffffffff - val + 1) * -1
else
return val
}
Buffer.prototype.readInt32LE = function (offset, noAssert) {
return readInt32(this, offset, true, noAssert)
}
Buffer.prototype.readInt32BE = function (offset, noAssert) {
return readInt32(this, offset, false, noAssert)
}
function readFloat (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
}
return ieee754.read(buf, offset, littleEndian, 23, 4)
}
Buffer.prototype.readFloatLE = function (offset, noAssert) {
return readFloat(this, offset, true, noAssert)
}
Buffer.prototype.readFloatBE = function (offset, noAssert) {
return readFloat(this, offset, false, noAssert)
}
function readDouble (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
}
return ieee754.read(buf, offset, littleEndian, 52, 8)
}
Buffer.prototype.readDoubleLE = function (offset, noAssert) {
return readDouble(this, offset, true, noAssert)
}
Buffer.prototype.readDoubleBE = function (offset, noAssert) {
return readDouble(this, offset, false, noAssert)
}
Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < this.length, 'trying to write beyond buffer length')
verifuint(value, 0xff)
}
if (offset >= this.length) return
this[offset] = value
return offset + 1
}
function writeUInt16 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
verifuint(value, 0xffff)
}
var len = buf.length
if (offset >= len)
return
for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
buf[offset + i] =
(value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
return offset + 2
}
Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
return writeUInt16(this, value, offset, true, noAssert)
}
Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
return writeUInt16(this, value, offset, false, noAssert)
}
function writeUInt32 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
verifuint(value, 0xffffffff)
}
var len = buf.length
if (offset >= len)
return
for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
buf[offset + i] =
(value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
return offset + 4
}
Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
return writeUInt32(this, value, offset, true, noAssert)
}
Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
return writeUInt32(this, value, offset, false, noAssert)
}
Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < this.length, 'Trying to write beyond buffer length')
verifsint(value, 0x7f, -0x80)
}
if (offset >= this.length)
return
if (value >= 0)
this.writeUInt8(value, offset, noAssert)
else
this.writeUInt8(0xff + value + 1, offset, noAssert)
return offset + 1
}
function writeInt16 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
verifsint(value, 0x7fff, -0x8000)
}
var len = buf.length
if (offset >= len)
return
if (value >= 0)
writeUInt16(buf, value, offset, littleEndian, noAssert)
else
writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
return offset + 2
}
Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
return writeInt16(this, value, offset, true, noAssert)
}
Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
return writeInt16(this, value, offset, false, noAssert)
}
function writeInt32 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
verifsint(value, 0x7fffffff, -0x80000000)
}
var len = buf.length
if (offset >= len)
return
if (value >= 0)
writeUInt32(buf, value, offset, littleEndian, noAssert)
else
writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
return offset + 4
}
Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
return writeInt32(this, value, offset, true, noAssert)
}
Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
return writeInt32(this, value, offset, false, noAssert)
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
var len = buf.length
if (offset >= len)
return
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 7 < buf.length,
'Trying to write beyond buffer length')
verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
var len = buf.length
if (offset >= len)
return
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
assert(end >= start, 'end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
assert(start >= 0 && start < this.length, 'start out of bounds')
assert(end >= 0 && end <= this.length, 'end out of bounds')
var i
if (typeof value === 'number') {
for (i = start; i < end; i++) {
this[i] = value
}
} else {
var bytes = utf8ToBytes(value.toString())
var len = bytes.length
for (i = start; i < end; i++) {
this[i] = bytes[i % len]
}
}
return this
}
Buffer.prototype.inspect = function () {
var out = []
var len = this.length
for (var i = 0; i < len; i++) {
out[i] = toHex(this[i])
if (i === exports.INSPECT_MAX_BYTES) {
out[i + 1] = '...'
break
}
}
return '<Buffer ' + out.join(' ') + '>'
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
Buffer.prototype.toArrayBuffer = function () {
if (typeof Uint8Array !== 'undefined') {
if (TYPED_ARRAY_SUPPORT) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1) {
buf[i] = this[i]
}
return buf.buffer
}
} else {
throw new Error('Buffer.toArrayBuffer not supported in this browser')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function (arr) {
arr._isBuffer = true
// save reference to original Uint8Array get/set methods before overwriting
arr._get = arr.get
arr._set = arr.set
// deprecated, will be removed in node 0.13+
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.equals = BP.equals
arr.compare = BP.compare
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function isArray (subject) {
return (Array.isArray || function (subject) {
return Object.prototype.toString.call(subject) === '[object Array]'
})(subject)
}
function isArrayish (subject) {
return isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number'
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
var b = str.charCodeAt(i)
if (b <= 0x7F) {
byteArray.push(b)
} else {
var start = i
if (b >= 0xD800 && b <= 0xDFFF) i++
var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
for (var j = 0; j < h.length; j++) {
byteArray.push(parseInt(h[j], 16))
}
}
}
return byteArray
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(str)
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length))
break
dst[i + offset] = src[i]
}
return i
}
function decodeUtf8Char (str) {
try {
return decodeURIComponent(str)
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
/*
* We have to make sure that the value is a valid integer. This means that it
* is non-negative. It has no fractional component and that it does not
* exceed the maximum allowed value.
*/
function verifuint (value, max) {
assert(typeof value === 'number', 'cannot write a non-number as a number')
assert(value >= 0, 'specified a negative value for writing an unsigned value')
assert(value <= max, 'value is larger than maximum value for type')
assert(Math.floor(value) === value, 'value has a fractional component')
}
function verifsint (value, max, min) {
assert(typeof value === 'number', 'cannot write a non-number as a number')
assert(value <= max, 'value larger than maximum allowed value')
assert(value >= min, 'value smaller than minimum allowed value')
assert(Math.floor(value) === value, 'value has a fractional component')
}
function verifIEEE754 (value, max, min) {
assert(typeof value === 'number', 'cannot write a non-number as a number')
assert(value <= max, 'value larger than maximum allowed value')
assert(value >= min, 'value smaller than minimum allowed value')
}
function assert (test, message) {
if (!test) throw new Error(message || 'Failed assertion')
}
},{"base64-js":4,"ieee754":5}],4:[function(require,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS)
return 62 // '+'
if (code === SLASH)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],5:[function(require,module,exports){
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
nBits = -7,
i = isLE ? (nBytes - 1) : 0,
d = isLE ? -1 : 1,
s = buffer[offset + i];
i += d;
e = s & ((1 << (-nBits)) - 1);
s >>= (-nBits);
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
m = e & ((1 << (-nBits)) - 1);
e >>= (-nBits);
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity);
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
i = isLE ? 0 : (nBytes - 1),
d = isLE ? 1 : -1,
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
};
},{}],6:[function(require,module,exports){
(function (Buffer){
var createHash = require('sha.js')
var md5 = toConstructor(require('./md5'))
var rmd160 = toConstructor(require('ripemd160'))
function toConstructor (fn) {
return function () {
var buffers = []
var m= {
update: function (data, enc) {
if(!Buffer.isBuffer(data)) data = new Buffer(data, enc)
buffers.push(data)
return this
},
digest: function (enc) {
var buf = Buffer.concat(buffers)
var r = fn(buf)
buffers = null
return enc ? r.toString(enc) : r
}
}
return m
}
}
module.exports = function (alg) {
if('md5' === alg) return new md5()
if('rmd160' === alg) return new rmd160()
return createHash(alg)
}
}).call(this,require("buffer").Buffer)
},{"./md5":10,"buffer":3,"ripemd160":11,"sha.js":13}],7:[function(require,module,exports){
(function (Buffer){
var createHash = require('./create-hash')
var blocksize = 64
var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0)
module.exports = Hmac
function Hmac (alg, key) {
if(!(this instanceof Hmac)) return new Hmac(alg, key)
this._opad = opad
this._alg = alg
key = this._key = !Buffer.isBuffer(key) ? new Buffer(key) : key
if(key.length > blocksize) {
key = createHash(alg).update(key).digest()
} else if(key.length < blocksize) {
key = Buffer.concat([key, zeroBuffer], blocksize)
}
var ipad = this._ipad = new Buffer(blocksize)
var opad = this._opad = new Buffer(blocksize)
for(var i = 0; i < blocksize; i++) {
ipad[i] = key[i] ^ 0x36
opad[i] = key[i] ^ 0x5C
}
this._hash = createHash(alg).update(ipad)
}
Hmac.prototype.update = function (data, enc) {
this._hash.update(data, enc)
return this
}
Hmac.prototype.digest = function (enc) {
var h = this._hash.digest()
return createHash(this._alg).update(this._opad).update(h).digest(enc)
}
}).call(this,require("buffer").Buffer)
},{"./create-hash":6,"buffer":3}],8:[function(require,module,exports){
(function (Buffer){
var intSize = 4;
var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0);
var chrsz = 8;
function toArray(buf, bigEndian) {
if ((buf.length % intSize) !== 0) {
var len = buf.length + (intSize - (buf.length % intSize));
buf = Buffer.concat([buf, zeroBuffer], len);
}
var arr = [];
var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
for (var i = 0; i < buf.length; i += intSize) {
arr.push(fn.call(buf, i));
}
return arr;
}
function toBuffer(arr, size, bigEndian) {
var buf = new Buffer(size);
var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
for (var i = 0; i < arr.length; i++) {
fn.call(buf, arr[i], i * 4, true);
}
return buf;
}
function hash(buf, fn, hashSize, bigEndian) {
if (!Buffer.isBuffer(buf)) buf = new Buffer(buf);
var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
return toBuffer(arr, hashSize, bigEndian);
}
module.exports = { hash: hash };
}).call(this,require("buffer").Buffer)
},{"buffer":3}],9:[function(require,module,exports){
(function (Buffer){
var rng = require('./rng')
function error () {
var m = [].slice.call(arguments).join(' ')
throw new Error([
m,
'we accept pull requests',
'http://github.com/dominictarr/crypto-browserify'
].join('\n'))
}
exports.createHash = require('./create-hash')
exports.createHmac = require('./create-hmac')
exports.randomBytes = function(size, callback) {
if (callback && callback.call) {
try {
callback.call(this, undefined, new Buffer(rng(size)))
} catch (err) { callback(err) }
} else {
return new Buffer(rng(size))
}
}
function each(a, f) {
for(var i in a)
f(a[i], i)
}
exports.getHashes = function () {
return ['sha1', 'sha256', 'md5', 'rmd160']
}
var p = require('./pbkdf2')(exports.createHmac)
exports.pbkdf2 = p.pbkdf2
exports.pbkdf2Sync = p.pbkdf2Sync
// the least I can do is make error messages for the rest of the node.js/crypto api.
each(['createCredentials'
, 'createCipher'
, 'createCipheriv'
, 'createDecipher'
, 'createDecipheriv'
, 'createSign'
, 'createVerify'
, 'createDiffieHellman'
], function (name) {
exports[name] = function () {
error('sorry,', name, 'is not implemented yet')
}
})
}).call(this,require("buffer").Buffer)
},{"./create-hash":6,"./create-hmac":7,"./pbkdf2":17,"./rng":18,"buffer":3}],10:[function(require,module,exports){
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
var helpers = require('./helpers');
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(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 bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
module.exports = function md5(buf) {
return helpers.hash(buf, core_md5, 16);
};
},{"./helpers":8}],11:[function(require,module,exports){
(function (Buffer){
module.exports = ripemd160
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Constants table
var zl = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13];
var zr = [
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11];
var sl = [
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ];
var sr = [
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ];
var hl = [ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E];
var hr = [ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000];
var bytesToWords = function (bytes) {
var words = [];
for (var i = 0, b = 0; i < bytes.length; i++, b += 8) {
words[b >>> 5] |= bytes[i] << (24 - b % 32);
}
return words;
};
var wordsToBytes = function (words) {
var bytes = [];
for (var b = 0; b < words.length * 32; b += 8) {
bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
}
return bytes;
};
var processBlock = function (H, M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
};
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
function ripemd160(message) {
var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
if (typeof message == 'string')
message = new Buffer(message, 'utf8');
var m = bytesToWords(message);
var nBitsLeft = message.length * 8;
var nBitsTotal = message.length * 8;
// Add padding
m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
for (var i=0 ; i<m.length; i += 16) {
processBlock(H, m, i);
}
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
var digestbytes = wordsToBytes(H);
return new Buffer(digestbytes);
}
}).call(this,require("buffer").Buffer)
},{"buffer":3}],12:[function(require,module,exports){
var u = require('./util')
var write = u.write
var fill = u.zeroFill
module.exports = function (Buffer) {
//prototype class for hash functions
function Hash (blockSize, finalSize) {
this._block = new Buffer(blockSize) //new Uint32Array(blockSize/4)
this._finalSize = finalSize
this._blockSize = blockSize
this._len = 0
this._s = 0
}
Hash.prototype.init = function () {
this._s = 0
this._len = 0
}
function lengthOf(data, enc) {
if(enc == null) return data.byteLength || data.length
if(enc == 'ascii' || enc == 'binary') return data.length
if(enc == 'hex') return data.length/2
if(enc == 'base64') return data.length/3
}
Hash.prototype.update = function (data, enc) {
var bl = this._blockSize
//I'd rather do this with a streaming encoder, like the opposite of
//http://nodejs.org/api/string_decoder.html
var length
if(!enc && 'string' === typeof data)
enc = 'utf8'
if(enc) {
if(enc === 'utf-8')
enc = 'utf8'
if(enc === 'base64' || enc === 'utf8')
data = new Buffer(data, enc), enc = null
length = lengthOf(data, enc)
} else
length = data.byteLength || data.length
var l = this._len += length
var s = this._s = (this._s || 0)
var f = 0
var buffer = this._block
while(s < l) {
var t = Math.min(length, f + bl - s%bl)
write(buffer, data, enc, s%bl, f, t)
var ch = (t - f);
s += ch; f += ch
if(!(s%bl))
this._update(buffer)
}
this._s = s
return this
}
Hash.prototype.digest = function (enc) {
var bl = this._blockSize
var fl = this._finalSize
var len = this._len*8
var x = this._block
var bits = len % (bl*8)
//add end marker, so that appending 0's creats a different hash.
x[this._len % bl] = 0x80
fill(this._block, this._len % bl + 1)
if(bits >= fl*8) {
this._update(this._block)
u.zeroFill(this._block, 0)
}
//TODO: handle case where the bit length is > Math.pow(2, 29)
x.writeInt32BE(len, fl + 4) //big endian
var hash = this._update(this._block) || this._hash()
if(enc == null) return hash
return hash.toString(enc)
}
Hash.prototype._update = function () {
throw new Error('_update must be implemented by subclass')
}
return Hash
}
},{"./util":16}],13:[function(require,module,exports){
var exports = module.exports = function (alg) {
var Alg = exports[alg]
if(!Alg) throw new Error(alg + ' is not supported (we accept pull requests)')
return new Alg()
}
var Buffer = require('buffer').Buffer
var Hash = require('./hash')(Buffer)
exports.sha =
exports.sha1 = require('./sha1')(Buffer, Hash)
exports.sha256 = require('./sha256')(Buffer, Hash)
},{"./hash":12,"./sha1":14,"./sha256":15,"buffer":3}],14:[function(require,module,exports){
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1a Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
module.exports = function (Buffer, Hash) {
var inherits = require('util').inherits
inherits(Sha1, Hash)
var A = 0|0
var B = 4|0
var C = 8|0
var D = 12|0
var E = 16|0
var BE = false
var LE = true
var W = new Int32Array(80)
var POOL = []
function Sha1 () {
if(POOL.length)
return POOL.pop().init()
if(!(this instanceof Sha1)) return new Sha1()
this._w = W
Hash.call(this, 16*4, 14*4)
this._h = null
this.init()
}
Sha1.prototype.init = function () {
this._a = 0x67452301
this._b = 0xefcdab89
this._c = 0x98badcfe
this._d = 0x10325476
this._e = 0xc3d2e1f0
Hash.prototype.init.call(this)
return this
}
Sha1.prototype._POOL = POOL
// assume that array is a Uint32Array with length=16,
// and that if it is the last block, it already has the length and the 1 bit appended.
var isDV = new Buffer(1) instanceof DataView
function readInt32BE (X, i) {
return isDV
? X.getInt32(i, false)
: X.readInt32BE(i)
}
Sha1.prototype._update = function (array) {
var X = this._block
var h = this._h
var a, b, c, d, e, _a, _b, _c, _d, _e
a = _a = this._a
b = _b = this._b
c = _c = this._c
d = _d = this._d
e = _e = this._e
var w = this._w
for(var j = 0; j < 80; j++) {
var W = w[j]
= j < 16
//? X.getInt32(j*4, false)
//? readInt32BE(X, j*4) //*/ X.readInt32BE(j*4) //*/
? X.readInt32BE(j*4)
: rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)
var t =
add(
add(rol(a, 5), sha1_ft(j, b, c, d)),
add(add(e, W), sha1_kt(j))
);
e = d
d = c
c = rol(b, 30)
b = a
a = t
}
this._a = add(a, _a)
this._b = add(b, _b)
this._c = add(c, _c)
this._d = add(d, _d)
this._e = add(e, _e)
}
Sha1.prototype._hash = function () {
if(POOL.length < 100) POOL.push(this)
var H = new Buffer(20)
//console.log(this._a|0, this._b|0, this._c|0, this._d|0, this._e|0)
H.writeInt32BE(this._a|0, A)
H.writeInt32BE(this._b|0, B)
H.writeInt32BE(this._c|0, C)
H.writeInt32BE(this._d|0, D)
H.writeInt32BE(this._e|0, E)
return H
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t, b, c, d) {
if(t < 20) return (b & c) | ((~b) & d);
if(t < 40) return b ^ c ^ d;
if(t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t) {
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
(t < 60) ? -1894007588 : -899497514;
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
* //dominictarr: this is 10 years old, so maybe this can be dropped?)
*
*/
function add(x, y) {
return (x + y ) | 0
//lets see how this goes on testling.
// 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 rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
return Sha1
}
},{"util":37}],15:[function(require,module,exports){
/**
* A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
* in FIPS 180-2
* Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
*
*/
var inherits = require('util').inherits
var BE = false
var LE = true
var u = require('./util')
module.exports = function (Buffer, Hash) {
var K = [
0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
]
inherits(Sha256, Hash)
var W = new Array(64)
var POOL = []
function Sha256() {
if(POOL.length) {
//return POOL.shift().init()
}
//this._data = new Buffer(32)
this.init()
this._w = W //new Array(64)
Hash.call(this, 16*4, 14*4)
};
Sha256.prototype.init = function () {
this._a = 0x6a09e667|0
this._b = 0xbb67ae85|0
this._c = 0x3c6ef372|0
this._d = 0xa54ff53a|0
this._e = 0x510e527f|0
this._f = 0x9b05688c|0
this._g = 0x1f83d9ab|0
this._h = 0x5be0cd19|0
this._len = this._s = 0
return this
}
var safe_add = function(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function S (X, n) {
return (X >>> n) | (X << (32 - n));
}
function R (X, n) {
return (X >>> n);
}
function Ch (x, y, z) {
return ((x & y) ^ ((~x) & z));
}
function Maj (x, y, z) {
return ((x & y) ^ (x & z) ^ (y & z));
}
function Sigma0256 (x) {
return (S(x, 2) ^ S(x, 13) ^ S(x, 22));
}
function Sigma1256 (x) {
return (S(x, 6) ^ S(x, 11) ^ S(x, 25));
}
function Gamma0256 (x) {
return (S(x, 7) ^ S(x, 18) ^ R(x, 3));
}
function Gamma1256 (x) {
return (S(x, 17) ^ S(x, 19) ^ R(x, 10));
}
Sha256.prototype._update = function(m) {
var M = this._block
var W = this._w
var a, b, c, d, e, f, g, h
var T1, T2
a = this._a | 0
b = this._b | 0
c = this._c | 0
d = this._d | 0
e = this._e | 0
f = this._f | 0
g = this._g | 0
h = this._h | 0
for (var j = 0; j < 64; j++) {
var w = W[j] = j < 16
? M.readInt32BE(j * 4)
: Gamma1256(W[j - 2]) + W[j - 7] + Gamma0256(W[j - 15]) + W[j - 16]
T1 = h + Sigma1256(e) + Ch(e, f, g) + K[j] + w
T2 = Sigma0256(a) + Maj(a, b, c);
h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2;
}
this._a = (a + this._a) | 0
this._b = (b + this._b) | 0
this._c = (c + this._c) | 0
this._d = (d + this._d) | 0
this._e = (e + this._e) | 0
this._f = (f + this._f) | 0
this._g = (g + this._g) | 0
this._h = (h + this._h) | 0
};
Sha256.prototype._hash = function () {
if(POOL.length < 10)
POOL.push(this)
var H = new Buffer(32)
H.writeInt32BE(this._a, 0)
H.writeInt32BE(this._b, 4)
H.writeInt32BE(this._c, 8)
H.writeInt32BE(this._d, 12)
H.writeInt32BE(this._e, 16)
H.writeInt32BE(this._f, 20)
H.writeInt32BE(this._g, 24)
H.writeInt32BE(this._h, 28)
return H
}
return Sha256
}
},{"./util":16,"util":37}],16:[function(require,module,exports){
exports.write = write
exports.zeroFill = zeroFill
exports.toString = toString
function write (buffer, string, enc, start, from, to, LE) {
var l = (to - from)
if(enc === 'ascii' || enc === 'binary') {
for( var i = 0; i < l; i++) {
buffer[start + i] = string.charCodeAt(i + from)
}
}
else if(enc == null) {
for( var i = 0; i < l; i++) {
buffer[start + i] = string[i + from]
}
}
else if(enc === 'hex') {
for(var i = 0; i < l; i++) {
var j = from + i
buffer[start + i] = parseInt(string[j*2] + string[(j*2)+1], 16)
}
}
else if(enc === 'base64') {
throw new Error('base64 encoding not yet supported')
}
else
throw new Error(enc +' encoding not yet supported')
}
//always fill to the end!
function zeroFill(buf, from) {
for(var i = from; i < buf.length; i++)
buf[i] = 0
}
},{}],17:[function(require,module,exports){
(function (Buffer){
// JavaScript PBKDF2 Implementation
// Based on http://git.io/qsv2zw
// Licensed under LGPL v3
// Copyright (c) 2013 jduncanator
var blocksize = 64
var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0)
module.exports = function (createHmac, exports) {
exports = exports || {}
exports.pbkdf2 = function(password, salt, iterations, keylen, cb) {
if('function' !== typeof cb)
throw new Error('No callback provided to pbkdf2');
setTimeout(function () {
cb(null, exports.pbkdf2Sync(password, salt, iterations, keylen))
})
}
exports.pbkdf2Sync = function(key, salt, iterations, keylen) {
if('number' !== typeof iterations)
throw new TypeError('Iterations not a number')
if(iterations < 0)
throw new TypeError('Bad iterations')
if('number' !== typeof keylen)
throw new TypeError('Key length not a number')
if(keylen < 0)
throw new TypeError('Bad key length')
//stretch key to the correct length that hmac wants it,
//otherwise this will happen every time hmac is called
//twice per iteration.
var key = !Buffer.isBuffer(key) ? new Buffer(key) : key
if(key.length > blocksize) {
key = createHash(alg).update(key).digest()
} else if(key.length < blocksize) {
key = Buffer.concat([key, zeroBuffer], blocksize)
}
var HMAC;
var cplen, p = 0, i = 1, itmp = new Buffer(4), digtmp;
var out = new Buffer(keylen);
out.fill(0);
while(keylen) {
if(keylen > 20)
cplen = 20;
else
cplen = keylen;
/* We are unlikely to ever use more than 256 blocks (5120 bits!)
* but just in case...
*/
itmp[0] = (i >> 24) & 0xff;
itmp[1] = (i >> 16) & 0xff;
itmp[2] = (i >> 8) & 0xff;
itmp[3] = i & 0xff;
HMAC = createHmac('sha1', key);
HMAC.update(salt)
HMAC.update(itmp);
digtmp = HMAC.digest();
digtmp.copy(out, p, 0, cplen);
for(var j = 1; j < iterations; j++) {
HMAC = createHmac('sha1', key);
HMAC.update(digtmp);
digtmp = HMAC.digest();
for(var k = 0; k < cplen; k++) {
out[k] ^= digtmp[k];
}
}
keylen -= cplen;
i++;
p += cplen;
}
return out;
}
return exports
}
}).call(this,require("buffer").Buffer)
},{"buffer":3}],18:[function(require,module,exports){
(function (Buffer){
(function() {
module.exports = function(size) {
var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array
/* This will not work in older browsers.
* See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
*/
crypto.getRandomValues(bytes);
return bytes;
}
}())
}).call(this,require("buffer").Buffer)
},{"buffer":3}],19:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
throw TypeError('Uncaught, unspecified "error" event.');
}
return false;
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],20:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],21:[function(require,module,exports){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
},{}],22:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],23:[function(require,module,exports){
module.exports = require("./lib/_stream_duplex.js")
},{"./lib/_stream_duplex.js":24}],24:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
module.exports = Duplex;
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
forEach(objectKeys(Writable.prototype), function(method) {
if (!Duplex.prototype[method])
Duplex.prototype[method] = Writable.prototype[method];
});
function Duplex(options) {
if (!(this instanceof Duplex))
return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false)
this.readable = false;
if (options && options.writable === false)
this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false)
this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended)
return;
// no more data can be written.
// But allow more writes to happen in this tick.
process.nextTick(this.end.bind(this));
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
}).call(this,require('_process'))
},{"./_stream_readable":26,"./_stream_writable":28,"_process":22,"core-util-is":29,"inherits":20}],25:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough))
return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function(chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":27,"core-util-is":29,"inherits":20}],26:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
module.exports = Readable;
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Readable.ReadableState = ReadableState;
var EE = require('events').EventEmitter;
/*<replacement>*/
if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
var Stream = require('stream');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var StringDecoder;
util.inherits(Readable, Stream);
function ReadableState(options, stream) {
options = options || {};
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.buffer = [];
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = false;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// In streams that never have any data, and do push(null) right away,
// the consumer can miss the 'end' event if they do some I/O before
// consuming the stream. So, we don't emit('end') until some reading
// happens.
this.calledRead = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, becuase any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
if (!(this instanceof Readable))
return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState;
if (typeof chunk === 'string' && !state.objectMode) {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (chunk === null || chunk === undefined) {
state.reading = false;
if (!state.ended)
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var e = new Error('stream.unshift() after end event');
stream.emit('error', e);
} else {
if (state.decoder && !addToFront && !encoding)
chunk = state.decoder.write(chunk);
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) {
state.buffer.unshift(chunk);
} else {
state.reading = false;
state.buffer.push(chunk);
}
if (state.needReadable)
emitReadable(stream);
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended &&
(state.needReadable ||
state.length < state.highWaterMark ||
state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
};
// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2
n--;
for (var p = 1; p < 32; p <<= 1) n |= n >> p;
n++;
}
return n;
}
function howMuchToRead(n, state) {
if (state.length === 0 && state.ended)
return 0;
if (state.objectMode)
return n === 0 ? 0 : 1;
if (n === null || isNaN(n)) {
// only flow one buffer at a time
if (state.flowing && state.buffer.length)
return state.buffer[0].length;
else
return state.length;
}
if (n <= 0)
return 0;
// If we're asking for more than the target buffer level,
// then raise the water mark. Bump up to the next highest
// power of 2, to prevent increasing it excessively in tiny
// amounts.
if (n > state.highWaterMark)
state.highWaterMark = roundUpToNextPowerOf2(n);
// don't have that much. return null, unless we've ended.
if (n > state.length) {
if (!state.ended) {
state.needReadable = true;
return 0;
} else
return state.length;
}
return n;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
var state = this._readableState;
state.calledRead = true;
var nOrig = n;
var ret;
if (typeof n !== 'number' || n > 0)
state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 &&
state.needReadable &&
(state.length >= state.highWaterMark || state.ended)) {
emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
ret = null;
// In cases where the decoder did not receive enough data
// to produce a full chunk, then immediately received an
// EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
// howMuchToRead will see this and coerce the amount to
// read to zero (because it's looking at the length of the
// first <Buffer > in state.buffer), and we'll end up here.
//
// This can only happen via state.decoder -- no other venue
// exists for pushing a zero-length chunk into state.buffer
// and triggering this behavior. In this case, we return our
// remaining data and end the stream, if appropriate.
if (state.length > 0 && state.decoder) {
ret = fromList(n, state);
state.length -= ret.length;
}
if (state.length === 0)
endReadable(this);
return ret;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
// if we currently have less than the highWaterMark, then also read some
if (state.length - n <= state.highWaterMark)
doRead = true;
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading)
doRead = false;
if (doRead) {
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0)
state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
}
// If _read called its callback synchronously, then `reading`
// will be false, and we need to re-evaluate how much data we
// can return to the user.
if (doRead && !state.reading)
n = howMuchToRead(nOrig, state);
if (n > 0)
ret = fromList(n, state);
else
ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
}
state.length -= n;
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (state.length === 0 && !state.ended)
state.needReadable = true;
// If we happened to read() exactly the remaining amount in the
// buffer, and the EOF has been seen at this point, then make sure
// that we emit 'end' on the very next tick.
if (state.ended && !state.endEmitted && state.length === 0)
endReadable(this);
return ret;
};
function chunkInvalid(state, chunk) {
var er = null;
if (!Buffer.isBuffer(chunk) &&
'string' !== typeof chunk &&
chunk !== null &&
chunk !== undefined &&
!state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
function onEofChunk(stream, state) {
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// if we've ended and we have some data left, then emit
// 'readable' now to make sure it gets picked up.
if (state.length > 0)
emitReadable(stream);
else
endReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (state.emittedReadable)
return;
state.emittedReadable = true;
if (state.sync)
process.nextTick(function() {
emitReadable_(stream);
});
else
emitReadable_(stream);
}
function emitReadable_(stream) {
stream.emit('readable');
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
process.nextTick(function() {
maybeReadMore_(stream, state);
});
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended &&
state.length < state.highWaterMark) {
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;
else
len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function(n) {
this.emit('error', new Error('not implemented'));
};
Readable.prototype.pipe = function(dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
dest !== process.stdout &&
dest !== process.stderr;
var endFn = doEnd ? onend : cleanup;
if (state.endEmitted)
process.nextTick(endFn);
else
src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable) {
if (readable !== src) return;
cleanup();
}
function onend() {
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
function cleanup() {
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', cleanup);
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (!dest._writableState || dest._writableState.needDrain)
ondrain();
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
unpipe();
dest.removeListener('error', onerror);
if (EE.listenerCount(dest, 'error') === 0)
dest.emit('error', er);
}
// This is a brutally ugly hack to make sure that our error handler
// is attached before any userland ones. NEVER DO THIS.
if (!dest._events || !dest._events.error)
dest.on('error', onerror);
else if (isArray(dest._events.error))
dest._events.error.unshift(onerror);
else
dest._events.error = [onerror, dest._events.error];
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
// the handler that waits for readable events after all
// the data gets sucked out in flow.
// This would be easier to follow with a .once() handler
// in flow(), but that is too slow.
this.on('readable', pipeOnReadable);
state.flowing = true;
process.nextTick(function() {
flow(src);
});
}
return dest;
};
function pipeOnDrain(src) {
return function() {
var dest = this;
var state = src._readableState;
state.awaitDrain--;
if (state.awaitDrain === 0)
flow(src);
};
}
function flow(src) {
var state = src._readableState;
var chunk;
state.awaitDrain = 0;
function write(dest, i, list) {
var written = dest.write(chunk);
if (false === written) {
state.awaitDrain++;
}
}
while (state.pipesCount && null !== (chunk = src.read())) {
if (state.pipesCount === 1)
write(state.pipes, 0, null);
else
forEach(state.pipes, write);
src.emit('data', chunk);
// if anyone needs a drain, then we have to wait for that.
if (state.awaitDrain > 0)
return;
}
// if every destination was unpiped, either before entering this
// function, or in the while loop, then stop flowing.
//
// NB: This is a pretty rare edge case.
if (state.pipesCount === 0) {
state.flowing = false;
// if there were data event listeners added, then switch to old mode.
if (EE.listenerCount(src, 'data') > 0)
emitDataEvents(src);
return;
}
// at this point, no one needed a drain, so we just ran out of data
// on the next readable event, start it over again.
state.ranOut = true;
}
function pipeOnReadable() {
if (this._readableState.ranOut) {
this._readableState.ranOut = false;
flow(this);
}
}
Readable.prototype.unpipe = function(dest) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0)
return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes)
return this;
if (!dest)
dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
this.removeListener('readable', pipeOnReadable);
state.flowing = false;
if (dest)
dest.emit('unpipe', this);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
this.removeListener('readable', pipeOnReadable);
state.flowing = false;
for (var i = 0; i < len; i++)
dests[i].emit('unpipe', this);
return this;
}
// try to find the right one.
var i = indexOf(state.pipes, dest);
if (i === -1)
return this;
state.pipes.splice(i, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1)
state.pipes = state.pipes[0];
dest.emit('unpipe', this);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function(ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data' && !this._readableState.flowing)
emitDataEvents(this);
if (ev === 'readable' && this.readable) {
var state = this._readableState;
if (!state.readableListening) {
state.readableListening = true;
state.emittedReadable = false;
state.needReadable = true;
if (!state.reading) {
this.read(0);
} else if (state.length) {
emitReadable(this, state);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function() {
emitDataEvents(this);
this.read(0);
this.emit('resume');
};
Readable.prototype.pause = function() {
emitDataEvents(this, true);
this.emit('pause');
};
function emitDataEvents(stream, startPaused) {
var state = stream._readableState;
if (state.flowing) {
// https://github.com/isaacs/readable-stream/issues/16
throw new Error('Cannot switch to old mode now.');
}
var paused = startPaused || false;
var readable = false;
// convert to an old-style stream.
stream.readable = true;
stream.pipe = Stream.prototype.pipe;
stream.on = stream.addListener = Stream.prototype.on;
stream.on('readable', function() {
readable = true;
var c;
while (!paused && (null !== (c = stream.read())))
stream.emit('data', c);
if (c === null) {
readable = false;
stream._readableState.needReadable = true;
}
});
stream.pause = function() {
paused = true;
this.emit('pause');
};
stream.resume = function() {
paused = false;
if (readable)
process.nextTick(function() {
stream.emit('readable');
});
else
this.read(0);
this.emit('resume');
};
// now make it start, just in case it hadn't already.
stream.emit('readable');
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function(stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function() {
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length)
self.push(chunk);
}
self.push(null);
});
stream.on('data', function(chunk) {
if (state.decoder)
chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
//if (state.objectMode && util.isNullOrUndefined(chunk))
if (state.objectMode && (chunk === null || chunk === undefined))
return;
else if (!state.objectMode && (!chunk || !chunk.length))
return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (typeof stream[i] === 'function' &&
typeof this[i] === 'undefined') {
this[i] = function(method) { return function() {
return stream[method].apply(stream, arguments);
}}(i);
}
}
// proxy certain important events.
var events = ['error', 'close', 'destroy', 'pause', 'resume'];
forEach(events, function(ev) {
stream.on(ev, self.emit.bind(self, ev));
});
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function(n) {
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
var list = state.buffer;
var length = state.length;
var stringMode = !!state.decoder;
var objectMode = !!state.objectMode;
var ret;
// nothing in the list, definitely empty.
if (list.length === 0)
return null;
if (length === 0)
ret = null;
else if (objectMode)
ret = list.shift();
else if (!n || n >= length) {
// read it all, truncate the array.
if (stringMode)
ret = list.join('');
else
ret = Buffer.concat(list, length);
list.length = 0;
} else {
// read just some of it.
if (n < list[0].length) {
// just take a part of the first list item.
// slice is the same for buffers and strings.
var buf = list[0];
ret = buf.slice(0, n);
list[0] = buf.slice(n);
} else if (n === list[0].length) {
// first list is a perfect match
ret = list.shift();
} else {
// complex case.
// we have enough to cover it, but it spans past the first buffer.
if (stringMode)
ret = '';
else
ret = new Buffer(n);
var c = 0;
for (var i = 0, l = list.length; i < l && c < n; i++) {
var buf = list[0];
var cpy = Math.min(n - c, buf.length);
if (stringMode)
ret += buf.slice(0, cpy);
else
buf.copy(ret, c, 0, cpy);
if (cpy < buf.length)
list[0] = buf.slice(cpy);
else
list.shift();
c += cpy;
}
}
}
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0)
throw new Error('endReadable called on non-empty stream');
if (!state.endEmitted && state.calledRead) {
state.ended = true;
process.nextTick(function() {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
});
}
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf (xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this,require('_process'))
},{"_process":22,"buffer":3,"core-util-is":29,"events":19,"inherits":20,"isarray":21,"stream":35,"string_decoder/":30}],27:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function TransformState(options, stream) {
this.afterTransform = function(er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb)
return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined)
stream.push(data);
if (cb)
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform))
return new Transform(options);
Duplex.call(this, options);
var ts = this._transformState = new TransformState(options, this);
// when the writable side finishes, then flush out anything remaining.
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
this.once('finish', function() {
if ('function' === typeof this._flush)
this._flush(function(er) {
done(stream, er);
});
else
done(stream);
});
}
Transform.prototype.push = function(chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function(chunk, encoding, cb) {
throw new Error('not implemented');
};
Transform.prototype._write = function(chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform ||
rs.needReadable ||
rs.length < rs.highWaterMark)
this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function(n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er) {
if (er)
return stream.emit('error', er);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var rs = stream._readableState;
var ts = stream._transformState;
if (ws.length)
throw new Error('calling transform done when ws.length != 0');
if (ts.transforming)
throw new Error('calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":24,"core-util-is":29,"inherits":20}],28:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
module.exports = Writable;
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Stream = require('stream');
util.inherits(Writable, Stream);
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
}
function WritableState(options, stream) {
options = options || {};
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, becuase any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function(er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.buffer = [];
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
}
function Writable(options) {
var Duplex = require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
this.emit('error', new Error('Cannot pipe. Not readable.'));
};
function writeAfterEnd(stream, state, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!Buffer.isBuffer(chunk) &&
'string' !== typeof chunk &&
chunk !== null &&
chunk !== undefined &&
!state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
valid = false;
}
return valid;
}
Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (Buffer.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (typeof cb !== 'function')
cb = function() {};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb))
ret = writeOrBuffer(this, state, chunk, encoding, cb);
return ret;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode &&
state.decodeStrings !== false &&
typeof chunk === 'string') {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (Buffer.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret)
state.needDrain = true;
if (state.writing)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
process.nextTick(function() {
cb(er);
});
else
cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er)
onwriteError(stream, state, sync, er, cb);
else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(stream, state);
if (!finished && !state.bufferProcessing && state.buffer.length)
clearBuffer(stream, state);
if (sync) {
process.nextTick(function() {
afterWrite(stream, state, finished, cb);
});
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished)
onwriteDrain(stream, state);
cb();
if (finished)
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
for (var c = 0; c < state.buffer.length; c++) {
var entry = state.buffer[c];
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, len, chunk, encoding, cb);
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
c++;
break;
}
}
state.bufferProcessing = false;
if (c < state.buffer.length)
state.buffer = state.buffer.slice(c);
else
state.buffer.length = 0;
}
Writable.prototype._write = function(chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (typeof chunk !== 'undefined' && chunk !== null)
this.write(chunk, encoding);
// ignore unnecessary end() calls.
if (!state.ending && !state.finished)
endWritable(this, state, cb);
};
function needFinish(stream, state) {
return (state.ending &&
state.length === 0 &&
!state.finished &&
!state.writing);
}
function finishMaybe(stream, state) {
var need = needFinish(stream, state);
if (need) {
state.finished = true;
stream.emit('finish');
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished)
process.nextTick(cb);
else
stream.once('finish', cb);
}
state.ended = true;
}
}).call(this,require('_process'))
},{"./_stream_duplex":24,"_process":22,"buffer":3,"core-util-is":29,"inherits":20,"stream":35}],29:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,require("buffer").Buffer)
},{"buffer":3}],30:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var Buffer = require('buffer').Buffer;
var isBufferEncoding = Buffer.isEncoding
|| function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
default: return false;
}
}
function assertEncoding(encoding) {
if (encoding && !isBufferEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
end -= this.charReceived;
}
charStr += buffer.toString(this.encoding, 0, end);
var end = charStr.length - 1;
var charCode = charStr.charCodeAt(end);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
var size = this.surrogateSize;
this.charLength += size;
this.charReceived += size;
this.charBuffer.copy(this.charBuffer, size, 0, size);
buffer.copy(this.charBuffer, 0, 0, size);
return charStr.substring(0, end);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
this.charLength = 4;
break;
}
}
this.charReceived = i;
};
StringDecoder.prototype.end = function(buffer) {
var res = '';
if (buffer && buffer.length)
res = this.write(buffer);
if (this.charReceived) {
var cr = this.charReceived;
var buf = this.charBuffer;
var enc = this.encoding;
res += buf.slice(0, cr).toString(enc);
}
return res;
};
function passThroughWrite(buffer) {
return buffer.toString(this.encoding);
}
function utf16DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 2;
this.charLength = this.charReceived ? 2 : 0;
}
function base64DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 3;
this.charLength = this.charReceived ? 3 : 0;
}
},{"buffer":3}],31:[function(require,module,exports){
module.exports = require("./lib/_stream_passthrough.js")
},{"./lib/_stream_passthrough.js":25}],32:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":24,"./lib/_stream_passthrough.js":25,"./lib/_stream_readable.js":26,"./lib/_stream_transform.js":27,"./lib/_stream_writable.js":28}],33:[function(require,module,exports){
module.exports = require("./lib/_stream_transform.js")
},{"./lib/_stream_transform.js":27}],34:[function(require,module,exports){
module.exports = require("./lib/_stream_writable.js")
},{"./lib/_stream_writable.js":28}],35:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
module.exports = Stream;
var EE = require('events').EventEmitter;
var inherits = require('inherits');
inherits(Stream, EE);
Stream.Readable = require('readable-stream/readable.js');
Stream.Writable = require('readable-stream/writable.js');
Stream.Duplex = require('readable-stream/duplex.js');
Stream.Transform = require('readable-stream/transform.js');
Stream.PassThrough = require('readable-stream/passthrough.js');
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
function Stream() {
EE.call(this);
}
Stream.prototype.pipe = function(dest, options) {
var source = this;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
// If the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd) return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd) return;
didOnEnd = true;
if (typeof dest.destroy === 'function') dest.destroy();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
},{"events":19,"inherits":20,"readable-stream/duplex.js":23,"readable-stream/passthrough.js":31,"readable-stream/readable.js":32,"readable-stream/transform.js":33,"readable-stream/writable.js":34}],36:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],37:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return
gitextract_80gh6yd1/
├── example-smart-app/
│ ├── health.html
│ ├── index.html
│ ├── launch-patient.html
│ ├── launch-smart-sandbox.html
│ ├── launch.html
│ ├── lib/
│ │ └── js/
│ │ ├── fhir-client-cerner-additions-1.0.0.js
│ │ └── fhir-client-v0.1.12.js
│ └── src/
│ ├── css/
│ │ └── example-smart-app.css
│ └── js/
│ └── example-smart-app.js
├── images/
│ ├── ehr_launch_seq.txt
│ └── patient_launch_seq.txt
├── index.html
├── javascripts/
│ ├── all.js
│ └── all_nosearch.js
└── stylesheets/
├── print.css
└── screen.css
SYMBOL INDEX (329 symbols across 3 files)
FILE: example-smart-app/lib/js/fhir-client-cerner-additions-1.0.0.js
function __webpack_require__ (line 6) | function __webpack_require__(moduleId) {
function _interopRequireDefault (line 71) | function _interopRequireDefault(obj) { return obj && obj.__esModule ? ob...
function _interopRequireDefault (line 102) | function _interopRequireDefault(obj) { return obj && obj.__esModule ? ob...
FILE: example-smart-app/lib/js/fhir-client-v0.1.12.js
function s (line 1) | function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&re...
function __webpack_require__ (line 17) | function __webpack_require__(moduleId) {
function merge (line 374) | function merge() {
function clone (line 398) | function clone(input) {
function typeOf (line 427) | function typeOf(input) {
function InvalidCharacterError (line 789) | function InvalidCharacterError(message) {
function getNext (line 1165) | function getNext (bundle, process) {
function drain (line 1182) | function drain (searchParams, process, done, fail) {
function fetchAll (line 1196) | function fetchAll (searchParams){
function fetchAllWithReferences (line 1218) | function fetchAllWithReferences (searchParams, resolveParams) {
function decorate (line 1295) | function decorate (client, newAdapter) {
function Buffer (line 1376) | function Buffer (subject, encoding, noZero) {
function hexWrite (line 1537) | function hexWrite (buf, string, offset, length) {
function utf8Write (line 1564) | function utf8Write (buf, string, offset, length) {
function asciiWrite (line 1569) | function asciiWrite (buf, string, offset, length) {
function binaryWrite (line 1574) | function binaryWrite (buf, string, offset, length) {
function base64Write (line 1578) | function base64Write (buf, string, offset, length) {
function utf16leWrite (line 1583) | function utf16leWrite (buf, string, offset, length) {
function base64Slice (line 1739) | function base64Slice (buf, start, end) {
function utf8Slice (line 1747) | function utf8Slice (buf, start, end) {
function asciiSlice (line 1764) | function asciiSlice (buf, start, end) {
function binarySlice (line 1774) | function binarySlice (buf, start, end) {
function hexSlice (line 1778) | function hexSlice (buf, start, end) {
function utf16leSlice (line 1791) | function utf16leSlice (buf, start, end) {
function readUInt16 (line 1860) | function readUInt16 (buf, offset, littleEndian, noAssert) {
function readUInt32 (line 1892) | function readUInt32 (buf, offset, littleEndian, noAssert) {
function readInt16 (line 1949) | function readInt16 (buf, offset, littleEndian, noAssert) {
function readInt32 (line 1976) | function readInt32 (buf, offset, littleEndian, noAssert) {
function readFloat (line 2003) | function readFloat (buf, offset, littleEndian, noAssert) {
function readDouble (line 2020) | function readDouble (buf, offset, littleEndian, noAssert) {
function writeUInt16 (line 2051) | function writeUInt16 (buf, value, offset, littleEndian, noAssert) {
function writeUInt32 (line 2080) | function writeUInt32 (buf, value, offset, littleEndian, noAssert) {
function writeInt16 (line 2126) | function writeInt16 (buf, value, offset, littleEndian, noAssert) {
function writeInt32 (line 2154) | function writeInt32 (buf, value, offset, littleEndian, noAssert) {
function writeFloat (line 2182) | function writeFloat (buf, value, offset, littleEndian, noAssert) {
function writeDouble (line 2207) | function writeDouble (buf, value, offset, littleEndian, noAssert) {
function base64clean (line 2361) | function base64clean (str) {
function stringtrim (line 2371) | function stringtrim (str) {
function isArray (line 2376) | function isArray (subject) {
function isArrayish (line 2382) | function isArrayish (subject) {
function toHex (line 2388) | function toHex (n) {
function utf8ToBytes (line 2393) | function utf8ToBytes (str) {
function asciiToBytes (line 2411) | function asciiToBytes (str) {
function utf16leToBytes (line 2420) | function utf16leToBytes (str) {
function base64ToBytes (line 2434) | function base64ToBytes (str) {
function blitBuffer (line 2438) | function blitBuffer (src, dst, offset, length) {
function decodeUtf8Char (line 2447) | function decodeUtf8Char (str) {
function verifuint (line 2460) | function verifuint (value, max) {
function verifsint (line 2467) | function verifsint (value, max, min) {
function verifIEEE754 (line 2474) | function verifIEEE754 (value, max, min) {
function assert (line 2480) | function assert (test, message) {
function decode (line 2500) | function decode (elt) {
function b64ToByteArray (line 2516) | function b64ToByteArray (b64) {
function uint8ToBase64 (line 2562) | function uint8ToBase64 (uint8) {
function toConstructor (line 2699) | function toConstructor (fn) {
function Hmac (line 2735) | function Hmac (alg, key) {
function toArray (line 2777) | function toArray(buf, bigEndian) {
function toBuffer (line 2791) | function toBuffer(arr, size, bigEndian) {
function hash (line 2800) | function hash(buf, fn, hashSize, bigEndian) {
function error (line 2813) | function error () {
function each (line 2836) | function each(a, f) {
function core_md5 (line 2882) | function core_md5(x, len)
function md5_cmn (line 2980) | function md5_cmn(q, a, b, x, s, t)
function md5_ff (line 2984) | function md5_ff(a, b, c, d, x, s, t)
function md5_gg (line 2988) | function md5_gg(a, b, c, d, x, s, t)
function md5_hh (line 2992) | function md5_hh(a, b, c, d, x, s, t)
function md5_ii (line 2996) | function md5_ii(a, b, c, d, x, s, t)
function safe_add (line 3005) | function safe_add(x, y)
function bit_rol (line 3015) | function bit_rol(num, cnt)
function f1 (line 3170) | function f1(x, y, z) {
function f2 (line 3174) | function f2(x, y, z) {
function f3 (line 3178) | function f3(x, y, z) {
function f4 (line 3182) | function f4(x, y, z) {
function f5 (line 3186) | function f5(x, y, z) {
function rotl (line 3190) | function rotl(x,n) {
function ripemd160 (line 3194) | function ripemd160(message) {
function Hash (line 3241) | function Hash (blockSize, finalSize) {
function lengthOf (line 3254) | function lengthOf(data, enc) {
function Sha1 (line 3375) | function Sha1 () {
function readInt32BE (line 3405) | function readInt32BE (X, i) {
function sha1_ft (line 3469) | function sha1_ft(t, b, c, d) {
function sha1_kt (line 3479) | function sha1_kt(t) {
function add (line 3490) | function add(x, y) {
function rol (line 3501) | function rol(num, cnt) {
function Sha256 (line 3547) | function Sha256() {
function S (line 3582) | function S (X, n) {
function R (line 3586) | function R (X, n) {
function Ch (line 3590) | function Ch (x, y, z) {
function Maj (line 3594) | function Maj (x, y, z) {
function Sigma0256 (line 3598) | function Sigma0256 (x) {
function Sigma1256 (line 3602) | function Sigma1256 (x) {
function Gamma0256 (line 3606) | function Gamma0256 (x) {
function Gamma1256 (line 3610) | function Gamma1256 (x) {
function write (line 3679) | function write (buffer, string, enc, start, from, to, LE) {
function zeroFill (line 3705) | function zeroFill(buf, from) {
function EventEmitter (line 3833) | function EventEmitter() {
function g (line 3977) | function g() {
function isFunction (line 4100) | function isFunction(arg) {
function isNumber (line 4104) | function isNumber(arg) {
function isObject (line 4108) | function isObject(arg) {
function isUndefined (line 4112) | function isUndefined(arg) {
function noop (line 4191) | function noop() {}
function Duplex (line 4268) | function Duplex(options) {
function onend (line 4289) | function onend() {
function forEach (line 4300) | function forEach (xs, f) {
function PassThrough (line 4344) | function PassThrough(options) {
function ReadableState (line 4410) | function ReadableState(options, stream) {
function Readable (line 4478) | function Readable(options) {
function readableAddChunk (line 4514) | function readableAddChunk(stream, state, chunk, encoding, addToFront) {
function needMoreData (line 4563) | function needMoreData(state) {
function roundUpToNextPowerOf2 (line 4580) | function roundUpToNextPowerOf2(n) {
function howMuchToRead (line 4592) | function howMuchToRead(n, state) {
function chunkInvalid (line 4754) | function chunkInvalid(state, chunk) {
function onEofChunk (line 4767) | function onEofChunk(stream, state) {
function emitReadable (line 4788) | function emitReadable(stream) {
function emitReadable_ (line 4803) | function emitReadable_(stream) {
function maybeReadMore (line 4814) | function maybeReadMore(stream, state) {
function maybeReadMore_ (line 4823) | function maybeReadMore_(stream, state) {
function onunpipe (line 4873) | function onunpipe(readable) {
function onend (line 4878) | function onend() {
function cleanup (line 4889) | function cleanup() {
function onerror (line 4910) | function onerror(er) {
function onclose (line 4928) | function onclose() {
function onfinish (line 4933) | function onfinish() {
function unpipe (line 4939) | function unpipe() {
function pipeOnDrain (line 4963) | function pipeOnDrain(src) {
function flow (line 4973) | function flow(src) {
function pipeOnReadable (line 5017) | function pipeOnReadable() {
function emitDataEvents (line 5121) | function emitDataEvents(stream, startPaused) {
function fromList (line 5242) | function fromList(n, state) {
function endReadable (line 5306) | function endReadable(stream) {
function forEach (line 5327) | function forEach (xs, f) {
function indexOf (line 5333) | function indexOf (xs, x) {
function TransformState (line 5418) | function TransformState(options, stream) {
function afterTransform (line 5429) | function afterTransform(stream, er, data) {
function Transform (line 5455) | function Transform(options) {
function done (line 5534) | function done(stream, er) {
function WriteReq (line 5598) | function WriteReq(chunk, encoding, cb) {
function WritableState (line 5604) | function WritableState(options, stream) {
function Writable (line 5675) | function Writable(options) {
function writeAfterEnd (line 5697) | function writeAfterEnd(stream, state, cb) {
function validChunk (line 5711) | function validChunk(stream, state, chunk, cb) {
function decodeChunk (line 5753) | function decodeChunk(state, chunk, encoding) {
function writeOrBuffer (line 5765) | function writeOrBuffer(stream, state, chunk, encoding, cb) {
function doWrite (line 5786) | function doWrite(stream, state, len, chunk, encoding, cb) {
function onwriteError (line 5795) | function onwriteError(stream, state, sync, er, cb) {
function onwriteStateUpdate (line 5807) | function onwriteStateUpdate(state) {
function onwrite (line 5814) | function onwrite(stream, er) {
function afterWrite (line 5840) | function afterWrite(stream, state, finished, cb) {
function onwriteDrain (line 5851) | function onwriteDrain(stream, state) {
function clearBuffer (line 5860) | function clearBuffer(stream, state) {
function needFinish (line 5914) | function needFinish(stream, state) {
function finishMaybe (line 5921) | function finishMaybe(stream, state) {
function endWritable (line 5930) | function endWritable(stream, state, cb) {
function isArray (line 5968) | function isArray(ar) {
function isBoolean (line 5973) | function isBoolean(arg) {
function isNull (line 5978) | function isNull(arg) {
function isNullOrUndefined (line 5983) | function isNullOrUndefined(arg) {
function isNumber (line 5988) | function isNumber(arg) {
function isString (line 5993) | function isString(arg) {
function isSymbol (line 5998) | function isSymbol(arg) {
function isUndefined (line 6003) | function isUndefined(arg) {
function isRegExp (line 6008) | function isRegExp(re) {
function isObject (line 6013) | function isObject(arg) {
function isDate (line 6018) | function isDate(d) {
function isError (line 6023) | function isError(e) {
function isFunction (line 6029) | function isFunction(arg) {
function isPrimitive (line 6034) | function isPrimitive(arg) {
function isBuffer (line 6044) | function isBuffer(arg) {
function objectToString (line 6049) | function objectToString(o) {
function assertEncoding (line 6086) | function assertEncoding(encoding) {
function passThroughWrite (line 6262) | function passThroughWrite(buffer) {
function utf16DetectIncompleteChar (line 6266) | function utf16DetectIncompleteChar(buffer) {
function base64DetectIncompleteChar (line 6271) | function base64DetectIncompleteChar(buffer) {
function Stream (line 6335) | function Stream() {
function ondata (line 6342) | function ondata(chunk) {
function ondrain (line 6352) | function ondrain() {
function onend (line 6368) | function onend() {
function onclose (line 6376) | function onclose() {
function onerror (line 6384) | function onerror(er) {
function cleanup (line 6395) | function cleanup() {
function deprecated (line 6508) | function deprecated() {
function inspect (line 6555) | function inspect(obj, opts) {
function stylizeWithColor (line 6613) | function stylizeWithColor(str, styleType) {
function stylizeNoColor (line 6625) | function stylizeNoColor(str, styleType) {
function arrayToHash (line 6630) | function arrayToHash(array) {
function formatValue (line 6641) | function formatValue(ctx, value, recurseTimes) {
function formatPrimitive (line 6754) | function formatPrimitive(ctx, value) {
function formatError (line 6773) | function formatError(value) {
function formatArray (line 6778) | function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
function formatProperty (line 6798) | function formatProperty(ctx, value, recurseTimes, visibleKeys, key, arra...
function reduceToSingleString (line 6857) | function reduceToSingleString(output, base, braces) {
function isArray (line 6880) | function isArray(ar) {
function isBoolean (line 6885) | function isBoolean(arg) {
function isNull (line 6890) | function isNull(arg) {
function isNullOrUndefined (line 6895) | function isNullOrUndefined(arg) {
function isNumber (line 6900) | function isNumber(arg) {
function isString (line 6905) | function isString(arg) {
function isSymbol (line 6910) | function isSymbol(arg) {
function isUndefined (line 6915) | function isUndefined(arg) {
function isRegExp (line 6920) | function isRegExp(re) {
function isObject (line 6925) | function isObject(arg) {
function isDate (line 6930) | function isDate(d) {
function isError (line 6935) | function isError(e) {
function isFunction (line 6941) | function isFunction(arg) {
function isPrimitive (line 6946) | function isPrimitive(arg) {
function objectToString (line 6958) | function objectToString(o) {
function pad (line 6963) | function pad(n) {
function timestamp (line 6972) | function timestamp() {
function hasOwnProperty (line 7014) | function hasOwnProperty(obj, prop) {
function btoa (line 7024) | function btoa(str) {
function isArraylike (line 7575) | function isArraylike( obj ) {
function Sizzle (line 7778) | function Sizzle( selector, context, results, seed ) {
function createCache (line 7893) | function createCache() {
function markFunction (line 7911) | function markFunction( fn ) {
function assert (line 7920) | function assert( fn ) {
function addHandle (line 7942) | function addHandle( attrs, handler ) {
function siblingCheck (line 7957) | function siblingCheck( a, b ) {
function createInputPseudo (line 7984) | function createInputPseudo( type ) {
function createButtonPseudo (line 7995) | function createButtonPseudo( type ) {
function createPositionalPseudo (line 8006) | function createPositionalPseudo( fn ) {
function testContext (line 8029) | function testContext( context ) {
function setFilters (line 9026) | function setFilters() {}
function toSelector (line 9097) | function toSelector( tokens ) {
function addCombinator (line 9107) | function addCombinator( matcher, combinator, base ) {
function elementMatcher (line 9160) | function elementMatcher( matchers ) {
function multipleContexts (line 9174) | function multipleContexts( selector, contexts, results ) {
function condense (line 9183) | function condense( unmatched, map, filter, context, xml ) {
function setMatcher (line 9204) | function setMatcher( preFilter, selector, matcher, postFilter, postFinde...
function matcherFromTokens (line 9297) | function matcherFromTokens( tokens ) {
function matcherFromGroupMatchers (line 9352) | function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
function winnow (line 9648) | function winnow( elements, qualifier, not ) {
function sibling (line 9973) | function sibling( cur, dir ) {
function createOptions (line 10051) | function createOptions( options ) {
function completed (line 10445) | function completed() {
function Data (line 10550) | function Data() {
function dataAttr (line 10742) | function dataAttr( elem, key, data ) {
function returnTrue (line 11081) | function returnTrue() {
function returnFalse (line 11085) | function returnFalse() {
function safeActiveElement (line 11089) | function safeActiveElement() {
function manipulationTarget (line 11961) | function manipulationTarget( elem, content ) {
function disableScript (line 11971) | function disableScript( elem ) {
function restoreScript (line 11975) | function restoreScript( elem ) {
function setGlobalEval (line 11988) | function setGlobalEval( elems, refElements ) {
function cloneCopyEvent (line 11999) | function cloneCopyEvent( src, dest ) {
function getAll (line 12033) | function getAll( context, tag ) {
function fixInput (line 12044) | function fixInput( src, dest ) {
function actualDisplay (line 12501) | function actualDisplay( name, doc ) {
function defaultDisplay (line 12523) | function defaultDisplay( nodeName ) {
function curCSS (line 12563) | function curCSS( elem, name, computed ) {
function addGetHookIf (line 12611) | function addGetHookIf( conditionFn, hookFn ) {
function computePixelPositionAndBoxSizingReliable (line 12651) | function computePixelPositionAndBoxSizingReliable() {
function vendorPropName (line 12753) | function vendorPropName( style, name ) {
function setPositiveNumber (line 12775) | function setPositiveNumber( elem, value, subtract ) {
function augmentWidthOrHeight (line 12783) | function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
function getWidthOrHeight (line 12822) | function getWidthOrHeight( elem, name, extra ) {
function showHide (line 12866) | function showHide( elements, show ) {
function Tween (line 13165) | function Tween( elem, options, prop, end, easing ) {
function createFxNow (line 13334) | function createFxNow() {
function genFx (line 13342) | function genFx( type, includeWidth ) {
function createTween (line 13362) | function createTween( value, prop, animation ) {
function defaultPrefilter (line 13376) | function defaultPrefilter( elem, props, opts ) {
function propFilter (line 13510) | function propFilter( props, specialEasing ) {
function Animation (line 13547) | function Animation( elem, properties, options ) {
function addToPrefiltersOrTransports (line 14614) | function addToPrefiltersOrTransports( structure ) {
function inspectPrefiltersOrTransports (line 14646) | function inspectPrefiltersOrTransports( structure, options, originalOpti...
function ajaxExtend (line 14673) | function ajaxExtend( target, src ) {
function ajaxHandleResponses (line 14693) | function ajaxHandleResponses( s, jqXHR, responses ) {
function ajaxConvert (line 14749) | function ajaxConvert( s, response, jqXHR, isSuccess ) {
function done (line 15206) | function done( status, nativeStatusText, responses, headers ) {
function buildParams (line 15458) | function buildParams( prefix, obj, traditional, add ) {
function getWindow (line 15941) | function getWindow( elem ) {
function toString (line 16386) | function toString(obj) {
function jwsSecuredInput (line 16394) | function jwsSecuredInput(header, payload) {
function jwsSign (line 16400) | function jwsSign(opts) {
function isObject (line 16410) | function isObject(thing) {
function safeJsonParse (line 16414) | function safeJsonParse(thing) {
function headerFromJWS (line 16421) | function headerFromJWS(jwsSig) {
function securedInputFromJWS (line 16426) | function securedInputFromJWS(jwsSig) {
function algoFromJWS (line 16430) | function algoFromJWS(jwsSig) {
function signatureFromJWS (line 16449) | function signatureFromJWS(jwsSig) {
function payloadFromJWS (line 16453) | function payloadFromJWS(jwsSig) {
function isValidJws (line 16459) | function isValidJws(string) {
function jwsVerify (line 16467) | function jwsVerify(jwsSig, secretOrKey) {
function jwsDecode (line 16475) | function jwsDecode(jwsSig, opts) {
function SignStream (line 16493) | function SignStream(opts) {
function VerifyStream (line 16524) | function VerifyStream(opts) {
function DataStream (line 16552) | function DataStream(data) {
function fromBase64 (line 16601) | function fromBase64(base64string) {
function toBase64 (line 16610) | function toBase64(base64UrlString) {
function padString (line 16620) | function padString(string) {
function decodeBase64Url (line 16636) | function decodeBase64Url(base64UrlString, encoding) {
function base64url (line 16640) | function base64url(stringOrBuffer) {
function toBuffer (line 16644) | function toBuffer(base64string) {
function typeError (line 16666) | function typeError(template) {
function bufferOrString (line 16672) | function bufferOrString(obj) {
function normalizeInput (line 16676) | function normalizeInput(thing) {
function createHmacSigner (line 16682) | function createHmacSigner(bits) {
function createHmacVerifier (line 16693) | function createHmacVerifier(bits) {
function createKeySigner (line 16700) | function createKeySigner(bits) {
function createKeyVerifier (line 16711) | function createKeyVerifier(bits) {
function createNoneSigner (line 16723) | function createNoneSigner() {
function createNoneVerifier (line 16729) | function createNoneVerifier() {
function urlParam (line 16897) | function urlParam(p, forceArray) {
function stripTrailingSlash (line 16923) | function stripTrailingSlash(str) {
function getPreviousToken (line 16935) | function getPreviousToken(){
function completeTokenFlow (line 16947) | function completeTokenFlow(hash){
function completeCodeFlow (line 16970) | function completeCodeFlow(params){
function completeTokenRefreshFlow (line 17048) | function completeTokenRefreshFlow() {
function completePageReload (line 17073) | function completePageReload(){
function readyArgs (line 17081) | function readyArgs(){
function validTokenResponse (line 17142) | function validTokenResponse() {
function isFakeOAuthToken (line 17154) | function isFakeOAuthToken(){
function providers (line 17257) | function providers(fhirServiceUrl, provider, callback, errback){
function relative (line 17325) | function relative(url){
function isBypassOAuth (line 17329) | function isBypassOAuth(){
function bypassOAuth (line 17333) | function bypassOAuth(fhirServiceUrl, callback){
function ClientPrototype (line 17460) | function ClientPrototype(){}
function FhirClient (line 17466) | function FhirClient(p) {
function byCodes (line 17662) | function byCodes(){
function ensureNumerical (line 17692) | function ensureNumerical(pq) {
FILE: example-smart-app/src/js/example-smart-app.js
function onError (line 5) | function onError() {
function onReady (line 10) | function onReady(smart) {
function defaultPatient (line 75) | function defaultPatient(){
function getBloodPressureValue (line 89) | function getBloodPressureValue(BPObservations, typeOfPressure) {
function getQuantityValueAndUnit (line 106) | function getQuantityValueAndUnit(ob) {
Condensed preview — 16 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (660K chars).
[
{
"path": "example-smart-app/health.html",
"chars": 835,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n "
},
{
"path": "example-smart-app/index.html",
"chars": 2994,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta http-equiv='X-UA-Compatible' content='IE=edge' />\n <meta http-equ"
},
{
"path": "example-smart-app/launch-patient.html",
"chars": 1540,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n "
},
{
"path": "example-smart-app/launch-smart-sandbox.html",
"chars": 1801,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n "
},
{
"path": "example-smart-app/launch.html",
"chars": 1545,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n "
},
{
"path": "example-smart-app/lib/js/fhir-client-cerner-additions-1.0.0.js",
"chars": 4603,
"preview": "/******/ (function(modules) { // webpackBootstrap\n/******/ // The module cache\n/******/ var installedModules = {};\n/**"
},
{
"path": "example-smart-app/lib/js/fhir-client-v0.1.12.js",
"chars": 491606,
"preview": "(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0)"
},
{
"path": "example-smart-app/src/css/example-smart-app.css",
"chars": 909,
"preview": "th, td {\n padding: 5px;\n text-align: left;\n}\n\nbody {\n margin: 0;\n}\n\n#holder {\n display: none;\n}\n\n.spinner {\n margin"
},
{
"path": "example-smart-app/src/js/example-smart-app.js",
"chars": 3816,
"preview": "(function(window){\n window.extractData = function() {\n var ret = $.Deferred();\n\n function onError() {\n conso"
},
{
"path": "images/ehr_launch_seq.txt",
"chars": 781,
"preview": "title EHR App Launch Flow\n\nEHR->App/launch.html: Provider launches the app\nApp/launch.html->+FHIR Server: App gets {iss}"
},
{
"path": "images/patient_launch_seq.txt",
"chars": 834,
"preview": "title Patient App Launch Flow\n\nPatient->App/launch.html: Patient launches the app w/ iss as query param\nApp/launch.html-"
},
{
"path": "index.html",
"chars": 65995,
"preview": "<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta content=\"IE=edge,chrome=1\" http-equiv=\"X-UA-Compati"
},
{
"path": "javascripts/all.js",
"chars": 101,
"preview": "//= require ./lib/_energize\n//= require ./app/_lang\n//= require ./app/_search\n//= require ./app/_toc\n"
},
{
"path": "javascripts/all_nosearch.js",
"chars": 75,
"preview": "//= require ./lib/_energize\n//= require ./app/_lang\n//= require ./app/_toc\n"
},
{
"path": "stylesheets/print.css",
"chars": 11999,
"preview": "@charset \"UTF-8\";\n/*! normalize.css v3.0.2 | MIT License | git.io/normalize */\n/**\n * 1. Set default font family to sans"
},
{
"path": "stylesheets/screen.css",
"chars": 22529,
"preview": "@charset \"UTF-8\";\n/*! normalize.css v3.0.2 | MIT License | git.io/normalize */\n/**\n * 1. Set default font family to sans"
}
]
About this extraction
This page contains the full source code of the cerner/smart-on-fhir-tutorial GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 16 files (597.6 KB), approximately 169.6k tokens, and a symbol index with 329 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.