fhirclient
Version:
JavaScript client for Fast Healthcare Interoperability Resources
1,337 lines (1,218 loc) • 796 kB
JavaScript
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ "./node_modules/abortcontroller-polyfill/dist/abortcontroller-polyfill-only.js":
/*!*************************************************************************************!*\
!*** ./node_modules/abortcontroller-polyfill/dist/abortcontroller-polyfill-only.js ***!
\*************************************************************************************/
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (factory) {
true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) :
0;
})((function () { 'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _get() {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get.bind();
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(arguments.length < 3 ? target : receiver);
}
return desc.value;
};
}
return _get.apply(this, arguments);
}
var Emitter = /*#__PURE__*/function () {
function Emitter() {
_classCallCheck(this, Emitter);
Object.defineProperty(this, 'listeners', {
value: {},
writable: true,
configurable: true
});
}
_createClass(Emitter, [{
key: "addEventListener",
value: function addEventListener(type, callback, options) {
if (!(type in this.listeners)) {
this.listeners[type] = [];
}
this.listeners[type].push({
callback: callback,
options: options
});
}
}, {
key: "removeEventListener",
value: function removeEventListener(type, callback) {
if (!(type in this.listeners)) {
return;
}
var stack = this.listeners[type];
for (var i = 0, l = stack.length; i < l; i++) {
if (stack[i].callback === callback) {
stack.splice(i, 1);
return;
}
}
}
}, {
key: "dispatchEvent",
value: function dispatchEvent(event) {
if (!(event.type in this.listeners)) {
return;
}
var stack = this.listeners[event.type];
var stackToCall = stack.slice();
for (var i = 0, l = stackToCall.length; i < l; i++) {
var listener = stackToCall[i];
try {
listener.callback.call(this, event);
} catch (e) {
Promise.resolve().then(function () {
throw e;
});
}
if (listener.options && listener.options.once) {
this.removeEventListener(event.type, listener.callback);
}
}
return !event.defaultPrevented;
}
}]);
return Emitter;
}();
var AbortSignal = /*#__PURE__*/function (_Emitter) {
_inherits(AbortSignal, _Emitter);
var _super = _createSuper(AbortSignal);
function AbortSignal() {
var _this;
_classCallCheck(this, AbortSignal);
_this = _super.call(this); // Some versions of babel does not transpile super() correctly for IE <= 10, if the parent
// constructor has failed to run, then "this.listeners" will still be undefined and then we call
// the parent constructor directly instead as a workaround. For general details, see babel bug:
// https://github.com/babel/babel/issues/3041
// This hack was added as a fix for the issue described here:
// https://github.com/Financial-Times/polyfill-library/pull/59#issuecomment-477558042
if (!_this.listeners) {
Emitter.call(_assertThisInitialized(_this));
} // Compared to assignment, Object.defineProperty makes properties non-enumerable by default and
// we want Object.keys(new AbortController().signal) to be [] for compat with the native impl
Object.defineProperty(_assertThisInitialized(_this), 'aborted', {
value: false,
writable: true,
configurable: true
});
Object.defineProperty(_assertThisInitialized(_this), 'onabort', {
value: null,
writable: true,
configurable: true
});
Object.defineProperty(_assertThisInitialized(_this), 'reason', {
value: undefined,
writable: true,
configurable: true
});
return _this;
}
_createClass(AbortSignal, [{
key: "toString",
value: function toString() {
return '[object AbortSignal]';
}
}, {
key: "dispatchEvent",
value: function dispatchEvent(event) {
if (event.type === 'abort') {
this.aborted = true;
if (typeof this.onabort === 'function') {
this.onabort.call(this, event);
}
}
_get(_getPrototypeOf(AbortSignal.prototype), "dispatchEvent", this).call(this, event);
}
}]);
return AbortSignal;
}(Emitter);
var AbortController = /*#__PURE__*/function () {
function AbortController() {
_classCallCheck(this, AbortController);
// Compared to assignment, Object.defineProperty makes properties non-enumerable by default and
// we want Object.keys(new AbortController()) to be [] for compat with the native impl
Object.defineProperty(this, 'signal', {
value: new AbortSignal(),
writable: true,
configurable: true
});
}
_createClass(AbortController, [{
key: "abort",
value: function abort(reason) {
var event;
try {
event = new Event('abort');
} catch (e) {
if (typeof document !== 'undefined') {
if (!document.createEvent) {
// For Internet Explorer 8:
event = document.createEventObject();
event.type = 'abort';
} else {
// For Internet Explorer 11:
event = document.createEvent('Event');
event.initEvent('abort', false, false);
}
} else {
// Fallback where document isn't available:
event = {
type: 'abort',
bubbles: false,
cancelable: false
};
}
}
var signalReason = reason;
if (signalReason === undefined) {
if (typeof document === 'undefined') {
signalReason = new Error('This operation was aborted');
signalReason.name = 'AbortError';
} else {
try {
signalReason = new DOMException('signal is aborted without reason');
} catch (err) {
// IE 11 does not support calling the DOMException constructor, use a
// regular error object on it instead.
signalReason = new Error('This operation was aborted');
signalReason.name = 'AbortError';
}
}
}
this.signal.reason = signalReason;
this.signal.dispatchEvent(event);
}
}, {
key: "toString",
value: function toString() {
return '[object AbortController]';
}
}]);
return AbortController;
}();
if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
// These are necessary to make sure that we get correct output for:
// Object.prototype.toString.call(new AbortController())
AbortController.prototype[Symbol.toStringTag] = 'AbortController';
AbortSignal.prototype[Symbol.toStringTag] = 'AbortSignal';
}
function polyfillNeeded(self) {
if (self.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill');
return true;
} // Note that the "unfetch" minimal fetch polyfill defines fetch() without
// defining window.Request, and this polyfill need to work on top of unfetch
// so the below feature detection needs the !self.AbortController part.
// The Request.prototype check is also needed because Safari versions 11.1.2
// up to and including 12.1.x has a window.AbortController present but still
// does NOT correctly implement abortable fetch:
// https://bugs.webkit.org/show_bug.cgi?id=174980#c2
return typeof self.Request === 'function' && !self.Request.prototype.hasOwnProperty('signal') || !self.AbortController;
}
(function (self) {
if (!polyfillNeeded(self)) {
return;
}
self.AbortController = AbortController;
self.AbortSignal = AbortSignal;
})(typeof self !== 'undefined' ? self : __webpack_require__.g);
}));
/***/ }),
/***/ "./node_modules/debug/src/browser.js":
/*!*******************************************!*\
!*** ./node_modules/debug/src/browser.js ***!
\*******************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
__webpack_require__(/*! core-js/modules/es.array.splice.js */ "./node_modules/core-js/modules/es.array.splice.js");
__webpack_require__(/*! core-js/modules/es.regexp.exec.js */ "./node_modules/core-js/modules/es.regexp.exec.js");
__webpack_require__(/*! core-js/modules/es.string.match.js */ "./node_modules/core-js/modules/es.string.match.js");
__webpack_require__(/*! core-js/modules/es.string.replace.js */ "./node_modules/core-js/modules/es.string.replace.js");
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = function () {
var warned = false;
return function () {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
}();
/**
* Colors.
*/
exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
var m;
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance ||
// Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 ||
// Double check webkit in userAgent just in case we are in a worker
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function (match) {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || function () {};
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.getItem('debug');
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = __webpack_require__(/*! ./common */ "./node_modules/debug/src/common.js")(exports);
var formatters = module.exports.formatters;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};
/***/ }),
/***/ "./node_modules/debug/src/common.js":
/*!******************************************!*\
!*** ./node_modules/debug/src/common.js ***!
\******************************************/
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js");
var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/toConsumableArray */ "./node_modules/@babel/runtime/helpers/toConsumableArray.js"));
__webpack_require__(/*! core-js/modules/es.array.concat.js */ "./node_modules/core-js/modules/es.array.concat.js");
__webpack_require__(/*! core-js/modules/es.array.join.js */ "./node_modules/core-js/modules/es.array.join.js");
__webpack_require__(/*! core-js/modules/es.array.map.js */ "./node_modules/core-js/modules/es.array.map.js");
__webpack_require__(/*! core-js/modules/es.array.slice.js */ "./node_modules/core-js/modules/es.array.slice.js");
__webpack_require__(/*! core-js/modules/es.array.splice.js */ "./node_modules/core-js/modules/es.array.splice.js");
__webpack_require__(/*! core-js/modules/es.number.constructor.js */ "./node_modules/core-js/modules/es.number.constructor.js");
__webpack_require__(/*! core-js/modules/es.object.keys.js */ "./node_modules/core-js/modules/es.object.keys.js");
__webpack_require__(/*! core-js/modules/es.object.to-string.js */ "./node_modules/core-js/modules/es.object.to-string.js");
__webpack_require__(/*! core-js/modules/es.regexp.constructor.js */ "./node_modules/core-js/modules/es.regexp.constructor.js");
__webpack_require__(/*! core-js/modules/es.regexp.exec.js */ "./node_modules/core-js/modules/es.regexp.exec.js");
__webpack_require__(/*! core-js/modules/es.regexp.to-string.js */ "./node_modules/core-js/modules/es.regexp.to-string.js");
__webpack_require__(/*! core-js/modules/es.string.replace.js */ "./node_modules/core-js/modules/es.string.replace.js");
__webpack_require__(/*! core-js/modules/es.string.split.js */ "./node_modules/core-js/modules/es.string.split.js");
__webpack_require__(/*! core-js/modules/web.dom-collections.for-each.js */ "./node_modules/core-js/modules/web.dom-collections.for-each.js");
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = __webpack_require__(/*! ms */ "./node_modules/ms/index.js");
createDebug.destroy = destroy;
Object.keys(env).forEach(function (key) {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
var hash = 0;
for (var i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
var prevTime;
var enableOverride = null;
var namespacesCache;
var enabledCache;
function debug() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// Disabled?
if (!debug.enabled) {
return;
}
var self = debug;
// Set `diff` timestamp
var curr = Number(new Date());
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return '%';
}
index++;
var formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
var val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
var logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: function get() {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: function set(v) {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
var i;
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
var namespaces = [].concat((0, _toConsumableArray2.default)(createDebug.names.map(toNamespace)), (0, _toConsumableArray2.default)(createDebug.skips.map(toNamespace).map(function (namespace) {
return '-' + namespace;
}))).join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
var i;
var len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Convert regexp to namespace
*
* @param {RegExp} regxep
* @return {String} namespace
* @api private
*/
function toNamespace(regexp) {
return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*');
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
/***/ }),
/***/ "./src/Client.ts":
/*!***********************!*\
!*** ./src/Client.ts ***!
\***********************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
__webpack_require__(/*! core-js/modules/es.symbol.js */ "./node_modules/core-js/modules/es.symbol.js");
__webpack_require__(/*! core-js/modules/es.object.get-own-property-descriptor.js */ "./node_modules/core-js/modules/es.object.get-own-property-descriptor.js");
__webpack_require__(/*! core-js/modules/es.object.get-own-property-descriptors.js */ "./node_modules/core-js/modules/es.object.get-own-property-descriptors.js");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js");
var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"));
__webpack_require__(/*! core-js/modules/es.array.concat.js */ "./node_modules/core-js/modules/es.array.concat.js");
__webpack_require__(/*! core-js/modules/es.array.filter.js */ "./node_modules/core-js/modules/es.array.filter.js");
__webpack_require__(/*! core-js/modules/es.array.find.js */ "./node_modules/core-js/modules/es.array.find.js");
__webpack_require__(/*! core-js/modules/es.array.flat.js */ "./node_modules/core-js/modules/es.array.flat.js");
__webpack_require__(/*! core-js/modules/es.array.iterator.js */ "./node_modules/core-js/modules/es.array.iterator.js");
__webpack_require__(/*! core-js/modules/es.array.join.js */ "./node_modules/core-js/modules/es.array.join.js");
__webpack_require__(/*! core-js/modules/es.array.map.js */ "./node_modules/core-js/modules/es.array.map.js");
__webpack_require__(/*! core-js/modules/es.array.slice.js */ "./node_modules/core-js/modules/es.array.slice.js");
__webpack_require__(/*! core-js/modules/es.array.sort.js */ "./node_modules/core-js/modules/es.array.sort.js");
__webpack_require__(/*! core-js/modules/es.array.unscopables.flat.js */ "./node_modules/core-js/modules/es.array.unscopables.flat.js");
__webpack_require__(/*! core-js/modules/es.object.assign.js */ "./node_modules/core-js/modules/es.object.assign.js");
__webpack_require__(/*! core-js/modules/es.object.keys.js */ "./node_modules/core-js/modules/es.object.keys.js");
__webpack_require__(/*! core-js/modules/es.object.to-string.js */ "./node_modules/core-js/modules/es.object.to-string.js");
__webpack_require__(/*! core-js/modules/es.promise.js */ "./node_modules/core-js/modules/es.promise.js");
__webpack_require__(/*! core-js/modules/es.promise.finally.js */ "./node_modules/core-js/modules/es.promise.finally.js");
__webpack_require__(/*! core-js/modules/es.regexp.exec.js */ "./node_modules/core-js/modules/es.regexp.exec.js");
__webpack_require__(/*! core-js/modules/es.string.iterator.js */ "./node_modules/core-js/modules/es.string.iterator.js");
__webpack_require__(/*! core-js/modules/es.string.match.js */ "./node_modules/core-js/modules/es.string.match.js");
__webpack_require__(/*! core-js/modules/es.string.replace.js */ "./node_modules/core-js/modules/es.string.replace.js");
__webpack_require__(/*! core-js/modules/es.string.search.js */ "./node_modules/core-js/modules/es.string.search.js");
__webpack_require__(/*! core-js/modules/es.string.trim.js */ "./node_modules/core-js/modules/es.string.trim.js");
__webpack_require__(/*! core-js/modules/es.string.link.js */ "./node_modules/core-js/modules/es.string.link.js");
__webpack_require__(/*! core-js/modules/web.dom-collections.for-each.js */ "./node_modules/core-js/modules/web.dom-collections.for-each.js");
__webpack_require__(/*! core-js/modules/web.dom-collections.iterator.js */ "./node_modules/core-js/modules/web.dom-collections.iterator.js");
__webpack_require__(/*! core-js/modules/web.url.js */ "./node_modules/core-js/modules/web.url.js");
__webpack_require__(/*! core-js/modules/web.url.to-json.js */ "./node_modules/core-js/modules/web.url.to-json.js");
__webpack_require__(/*! core-js/modules/web.url-search-params.js */ "./node_modules/core-js/modules/web.url-search-params.js");
var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"));
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"));
var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"));
var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
Object.defineProperty(exports, "__esModule", ({
value: true
}));
var lib_1 = __webpack_require__(/*! ./lib */ "./src/lib.ts");
var strings_1 = __webpack_require__(/*! ./strings */ "./src/strings.ts");
var settings_1 = __webpack_require__(/*! ./settings */ "./src/settings.ts");
// $lab:coverage:off$
// @ts-ignore
var _ref = typeof FHIRCLIENT_PURE !== "undefined" ? window : __webpack_require__(/*! cross-fetch */ "./node_modules/cross-fetch/dist/browser-ponyfill.js"),
Response = _ref.Response;
// $lab:coverage:on$
var debug = lib_1.debug.extend("client");
/**
* Adds patient context to requestOptions object to be used with [[Client.request]]
* @param requestOptions Can be a string URL (relative to the serviceUrl), or an
* object which will be passed to fetch()
* @param client Current FHIR client object containing patient context
* @return requestOptions object contextualized to current patient
*/
function contextualize(_x, _x2) {
return _contextualize.apply(this, arguments);
}
/**
* Gets single reference by id. Caches the result.
* @param refId
* @param cache A map to store the resolved refs
* @param client The client instance
* @param requestOptions Only signal and headers are currently used if provided
* @returns The resolved reference
* @private
*/
function _contextualize() {
_contextualize = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee9(requestOptions, client) {
var base, contextualURL, _contextualURL;
return _regenerator.default.wrap(function _callee9$(_context9) {
while (1) switch (_context9.prev = _context9.next) {
case 0:
_contextualURL = function _contextualURL3() {
_contextualURL = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee8(_url) {
var resourceType, conformance, searchParam;
return _regenerator.default.wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
resourceType = _url.pathname.split("/").pop();
(0, lib_1.assert)(resourceType, "Invalid url \"".concat(_url, "\""));
(0, lib_1.assert)(settings_1.patientCompartment.indexOf(resourceType) > -1, "Cannot filter \"".concat(resourceType, "\" resources by patient"));
_context8.next = 5;
return (0, lib_1.fetchConformanceStatement)(client.state.serverUrl);
case 5:
conformance = _context8.sent;
searchParam = (0, lib_1.getPatientParam)(conformance, resourceType);
_url.searchParams.set(searchParam, client.patient.id);
return _context8.abrupt("return", _url.href);
case 9:
case "end":
return _context8.stop();
}
}, _callee8);
}));
return _contextualURL.apply(this, arguments);
};
contextualURL = function _contextualURL2(_x9) {
return _contextualURL.apply(this, arguments);
};
base = (0, lib_1.absolute)("/", client.state.serverUrl);
if (!(typeof requestOptions == "string" || requestOptions instanceof URL)) {
_context9.next = 8;
break;
}
_context9.next = 6;
return contextualURL(new URL(requestOptions + "", base));
case 6:
_context9.t0 = _context9.sent;
return _context9.abrupt("return", {
url: _context9.t0
});
case 8:
_context9.next = 10;
return contextualURL(new URL(requestOptions.url + "", base));
case 10:
requestOptions.url = _context9.sent;
return _context9.abrupt("return", requestOptions);
case 12:
case "end":
return _context9.stop();
}
}, _callee9);
}));
return _contextualize.apply(this, arguments);
}
function getRef(refId, cache, client, requestOptions) {
if (!cache[refId]) {
var signal = requestOptions.signal,
headers = requestOptions.headers;
// Note that we set cache[refId] immediately! When the promise is
// settled it will be updated. This is to avoid a ref being fetched
// twice because some of these requests are executed in parallel.
cache[refId] = client.request({
url: refId,
headers: headers,
signal: signal
}).then(function (res) {
cache[refId] = res;
return res;
}, function (error) {
delete cache[refId];
throw error;
});
}
return Promise.resolve(cache[refId]);
}
/**
* Resolves a reference in the given resource.
* @param obj FHIR Resource
*/
function resolveRef(obj, path, graph, cache, client, requestOptions) {
var node = (0, lib_1.getPath)(obj, path);
if (node) {
var isArray = Array.isArray(node);
return Promise.all((0, lib_1.makeArray)(node).filter(Boolean).map(function (item, i) {
var ref = item.reference;
if (ref) {
return getRef(ref, cache, client, requestOptions).then(function (sub) {
if (graph) {
if (isArray) {
if (path.indexOf("..") > -1) {
(0, lib_1.setPath)(obj, "".concat(path.replace("..", ".".concat(i, "."))), sub);
} else {
(0, lib_1.setPath)(obj, "".concat(path, ".").concat(i), sub);
}
} else {
(0, lib_1.setPath)(obj, path, sub);
}
}
}).catch(function (ex) {
/* ignore missing references */
if (ex.status !== 404) {
throw ex;
}
});
}
}));
}
}
/**
* Given a resource and a list of ref paths - resolves them all
* @param obj FHIR Resource
* @param fhirOptions The fhir options of the initiating request call
* @param cache A map to store fetched refs
* @param client The client instance
* @private
*/
function resolveRefs(obj, fhirOptions, cache, client, requestOptions) {
// 1. Sanitize paths, remove any invalid ones
var paths = (0, lib_1.makeArray)(fhirOptions.resolveReferences).filter(Boolean) // No false, 0, null, undefined or ""
.map(function (path) {
return String(path).trim();
}).filter(Boolean); // No space-only strings
// 2. Remove duplicates
paths = paths.filter(function (p, i) {
var index = paths.indexOf(p, i + 1);
if (index > -1) {
debug("Duplicated reference path \"%s\"", p);
return false;
}
return true;
});
// 3. Early exit if no valid paths are found
if (!paths.length) {
return Promise.resolve();
}
// 4. Group the paths by depth so that child refs are looked up
// after their parents!
var groups = {};
paths.forEach(function (path) {
var len = path.split(".").length;
if (!groups[len]) {
groups[len] = [];
}
groups[len].push(path);
});
// 5. Execute groups sequentially! Paths within same group are
// fetched in parallel!
var task = Promise.resolve();
Object.keys(groups).sort().forEach(function (len) {
var group = groups[len];
task = task.then(function () {
return Promise.all(group.map(function (path) {
return resolveRef(obj, path, !!fhirOptions.graph, cache, client, requestOptions);
}));
});
});
return task;
}
/**
* This is a FHIR client that is returned to you from the `ready()` call of the
* **SMART API**. You can also create it yourself if needed:
*
* ```js
* // BROWSER
* const client = FHIR.client("https://r4.smarthealthit.org");
*
* // SERVER
* const client = smart(req, res).client("https://r4.smarthealthit.org");
* ```
*/
var Client = /*#__PURE__*/function () {
/**
* Validates the parameters, creates an instance and tries to connect it to
* FhirJS, if one is available globally.
*/
function Client(environment, state) {
var _this = this;
(0, _classCallCheck2.default)(this, Client);
/**
* @category Utility
*/
this.units = lib_1.units;
var _state = typeof state == "string" ? {
serverUrl: state
} : state;
// Valid serverUrl is required!
(0, lib_1.assert)(_state.serverUrl && _state.serverUrl.match(/https?:\/\/.+/), "A \"serverUrl\" option is required and must begin with \"http(s)\"");
this.state = _state;
this.environment = environment;
this._refreshTask = null;
var client = this;
// patient api ---------------------------------------------------------
this.patient = {
get id() {
return client.getPatientId();
},
read: function read(requestOptions) {
var id = _this.patient.id;
return id ? _this.request(_objectSpread(_objectSpread({}, requestOptions), {}, {
url: "Patient/".concat(id)
})) : Promise.reject(new Error("Patient is not available"));
},
request: function request(requestOptions) {
var fhirOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (_this.patient.id) {
return (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee() {
var options;
return _regenerator.default.wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return contextualize(requestOptions, _this);
case 2:
options = _context.sent;
return _context.abrupt("return", _this.request(options, fhirOptions));
case 4:
case "end":
return _context.stop();
}
}, _callee);
}))();
} else {
return Promise.reject(new Error("Patient is not available"));
}
}
};
// encounter api -------------------------------------------------------
this.encounter = {
get id() {
return client.getEncounterId();
},
read: function read(requestOptions) {
var id = _this.encounter.id;
return id ? _this.request(_objectSpread(_objectSpread({}, requestOptions), {}, {
url: "Encounter/".concat(id)
})) : Promise.reject(new Error("Encounter is not available"));
}
};
// user api ------------------------------------------------------------
this.user = {
get fhirUser() {
return client.getFhirUser();
},
get id() {
return client.getUserId();
},
get resourceType() {
return client.getUserType();
},
read: function read(requestOptions) {
var fhirUser = _this.user.fhirUser;
return fhirUser ? _this.request(_objectSpread(_objectSpread({}, requestOptions), {}, {
url: fhirUser
})) : Promise.reject(new Error("User is not available"));
}
};
// fhir.js api (attached automatically in browser)
// ---------------------------------------------------------------------
this.connect(environment.fhir);
}
/**
* This method is used to make the "link" between the `fhirclient` and the
* `fhir.js`, if one is available.
* **Note:** This is called by the constructor. If fhir.js is available in
* the global scope as `fhir`, it will automatically be linked to any [[Client]]
* instance. You should only use this method to connect to `fhir.js` which
* is not global.
*/
return (0, _createClass2.default)(Client, [{
key: "connect",
value: function connect(fhirJs) {
if (typeof fhirJs == "function") {
var options = {
baseUrl: this.state.serverUrl.replace(/\/$/, "")
};
var accessToken = this.getState("tokenResponse.access_token");
if (accessToken) {
options.auth = {
token: accessToken
};
} else {
var _this$state = this.state,
username = _this$state.username,
password = _this$state.password;
if (username && password) {
options.auth = {
user: username,
pass: password
};
}
}
this.api = fhirJs(options);
var patientId = this.getState("tokenResponse.patient");
if (patientId) {
this.patient.api = fhirJs(_objectSpread(_objectSpread({}, options), {}, {
patient: patientId
}));
}
}
return this;
}
/**
* Returns the ID of the selected patient or null. You should have requested
* "launch/patient" scope. Otherwise this will return null.
*/
}, {
key: "getPatientId",
value: function getPatientId() {
var tokenResponse = this.state.tokenResponse;
if (tokenResponse) {
// We have been authorized against this server but we don't know
// the patient. This should be a scope issue.
if (!tokenResponse.patient) {
if (!(this.state.scope || "").match(/\blaunch(\/patient)?\b/)) {
debug(strings_1.default.noScopeForId, "patient", "patient");
} else {
// The server should have returned the patient!
debug("The ID of the selected patient is not available. Please check if your server supports that.");
}
return null;
}
return tokenResponse.patient;
}
if (this.state.authorizeUri) {
debug(strings_1.default.noIfNoAuth, "the ID of the selected patient");
} else {
debug(strings_1.default.noFreeContext, "selected patient");
}
return null;
}
/**
* Returns the ID of the selected encounter or null. You should have
* requested "launch/encounter" scope. Otherwise this will return null.
* Note that not all servers support the "launch/encounter" scope so this
* will be null if they don't.
*/
}, {
key: "getEncounterId",
value: function getEncounterId() {
var tokenResponse = this.state.tokenResponse;
if (tokenResponse) {
// We have been authorized against this server but we don't know
// the encounter. This should be a scope issue.
if (!tokenResponse.encounter) {
if (!(this.state.scope || "").match(/\blaunch(\/encounter)?\b/)) {
debug(strings_1.default.noScopeForId, "encounter", "encounter");
} else {
// The server should have returned the encounter!
debug("The ID of the selected encounter is not available. Please check if your server supports that, and that the selected patient has any recorded encounters.");
}
return null;
}
return tokenResponse.encounter;
}
if (this.state.authorizeUri) {
debug(strings_1.default.noIfNoAuth, "the ID of the selected encounter");
} else {
debug(strings_1.default.noFreeContext, "selected encounter");
}
return null;
}
/**
* Returns the (decoded) id_token if any. You need to request "openid" and
* "profile" scopes if you need to receive an id_token (if you need to know
* who the logged-in user is).
*/
}, {
key: "getIdToken",
value: function getIdToken() {
var tokenResponse = this.state.tokenResponse;
if (tokenResponse) {
var idToken = tokenResponse.id_token;
var scope = this.state.scope || "";
// We have been authorized against this server but we don't have
// the id_token. This should be a scope issue.
if (!idToken) {
var hasOpenid = scope.match(/\bopenid\b/);
var hasProfile = scope.match(/\bprofile\b/);
var hasFhirUser = scope.match(/\bfhirU