@microsoft/office-js
Version:
Office JavaScript APIs
943 lines (936 loc) • 784 kB
JavaScript
/*
Copyright (c) Microsoft Corporation. All rights reserved.
*/
/*
Your use of this file is governed by the Microsoft Services Agreement http://go.microsoft.com/fwlink/?LinkId=266419.
*/
/*
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
* @version 2.3.0
*/
// Sources:
// osfweb: none
// runtime: 16.0\15303.10000
// core: 16.0\15303.10000
// host: 16.0.15302.34957
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var OfficeExtension;
(function (OfficeExtension) {
var _Internal;
(function (_Internal) {
_Internal.OfficeRequire = function () {
return null;
}();
})(_Internal = OfficeExtension._Internal || (OfficeExtension._Internal = {}));
(function (_Internal) {
var PromiseImpl;
(function (PromiseImpl) {
function Init() {
return (function () {
"use strict";
function lib$es6$promise$utils$$objectOrFunction(x) {
return typeof x === 'function' || (typeof x === 'object' && x !== null);
}
function lib$es6$promise$utils$$isFunction(x) {
return typeof x === 'function';
}
function lib$es6$promise$utils$$isMaybeThenable(x) {
return typeof x === 'object' && x !== null;
}
var lib$es6$promise$utils$$_isArray;
if (!Array.isArray) {
lib$es6$promise$utils$$_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
}
else {
lib$es6$promise$utils$$_isArray = Array.isArray;
}
var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
var lib$es6$promise$asap$$len = 0;
var lib$es6$promise$asap$$toString = {}.toString;
var lib$es6$promise$asap$$vertxNext;
var lib$es6$promise$asap$$customSchedulerFn;
var lib$es6$promise$asap$$asap = function asap(callback, arg) {
lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
lib$es6$promise$asap$$len += 2;
if (lib$es6$promise$asap$$len === 2) {
if (lib$es6$promise$asap$$customSchedulerFn) {
lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
}
else {
lib$es6$promise$asap$$scheduleFlush();
}
}
};
function lib$es6$promise$asap$$setScheduler(scheduleFn) {
lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
}
function lib$es6$promise$asap$$setAsap(asapFn) {
lib$es6$promise$asap$$asap = asapFn;
}
var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
function lib$es6$promise$asap$$useNextTick() {
var nextTick = process.nextTick;
var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);
if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {
nextTick = window.setImmediate;
}
return function () {
nextTick(lib$es6$promise$asap$$flush);
};
}
function lib$es6$promise$asap$$useVertxTimer() {
return function () {
lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
};
}
function lib$es6$promise$asap$$useMutationObserver() {
var iterations = 0;
var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = (iterations = ++iterations % 2);
};
}
function lib$es6$promise$asap$$useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = lib$es6$promise$asap$$flush;
return function () {
channel.port2.postMessage(0);
};
}
function lib$es6$promise$asap$$useSetTimeout() {
return function () {
setTimeout(lib$es6$promise$asap$$flush, 1);
};
}
var lib$es6$promise$asap$$queue = new Array(1000);
function lib$es6$promise$asap$$flush() {
for (var i = 0; i < lib$es6$promise$asap$$len; i += 2) {
var callback = lib$es6$promise$asap$$queue[i];
var arg = lib$es6$promise$asap$$queue[i + 1];
callback(arg);
lib$es6$promise$asap$$queue[i] = undefined;
lib$es6$promise$asap$$queue[i + 1] = undefined;
}
lib$es6$promise$asap$$len = 0;
}
var lib$es6$promise$asap$$scheduleFlush;
if (lib$es6$promise$asap$$isNode) {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
}
else if (lib$es6$promise$asap$$isWorker) {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
}
else {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
}
function lib$es6$promise$$internal$$noop() { }
var lib$es6$promise$$internal$$PENDING = void 0;
var lib$es6$promise$$internal$$FULFILLED = 1;
var lib$es6$promise$$internal$$REJECTED = 2;
var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
function lib$es6$promise$$internal$$selfFullfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function lib$es6$promise$$internal$$cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function lib$es6$promise$$internal$$getThen(promise) {
try {
return promise.then;
}
catch (error) {
lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
return lib$es6$promise$$internal$$GET_THEN_ERROR;
}
}
function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
}
catch (e) {
return e;
}
}
function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
lib$es6$promise$asap$$asap(function (promise) {
var sealed = false;
var error = lib$es6$promise$$internal$$tryThen(then, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
lib$es6$promise$$internal$$resolve(promise, value);
}
else {
lib$es6$promise$$internal$$fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
lib$es6$promise$$internal$$reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
lib$es6$promise$$internal$$reject(promise, error);
}
}, promise);
}
function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
lib$es6$promise$$internal$$fulfill(promise, thenable._result);
}
else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, thenable._result);
}
else {
lib$es6$promise$$internal$$subscribe(thenable, undefined, function (value) {
lib$es6$promise$$internal$$resolve(promise, value);
}, function (reason) {
lib$es6$promise$$internal$$reject(promise, reason);
});
}
}
function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
if (maybeThenable.constructor === promise.constructor) {
lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
}
else {
var then = lib$es6$promise$$internal$$getThen(maybeThenable);
if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
}
else if (then === undefined) {
lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
}
else if (lib$es6$promise$utils$$isFunction(then)) {
lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
}
else {
lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
}
}
}
function lib$es6$promise$$internal$$resolve(promise, value) {
if (promise === value) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment());
}
else if (lib$es6$promise$utils$$objectOrFunction(value)) {
lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
}
else {
lib$es6$promise$$internal$$fulfill(promise, value);
}
}
function lib$es6$promise$$internal$$publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
lib$es6$promise$$internal$$publish(promise);
}
function lib$es6$promise$$internal$$fulfill(promise, value) {
if (promise._state !== lib$es6$promise$$internal$$PENDING) {
return;
}
promise._result = value;
promise._state = lib$es6$promise$$internal$$FULFILLED;
if (promise._subscribers.length !== 0) {
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
}
}
function lib$es6$promise$$internal$$reject(promise, reason) {
if (promise._state !== lib$es6$promise$$internal$$PENDING) {
return;
}
promise._state = lib$es6$promise$$internal$$REJECTED;
promise._result = reason;
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
}
function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
parent._onerror = null;
subscribers[length] = child;
subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
if (length === 0 && parent._state) {
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
}
}
function lib$es6$promise$$internal$$publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child, callback, detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
}
else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function lib$es6$promise$$internal$$ErrorObject() {
this.error = null;
}
var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
function lib$es6$promise$$internal$$tryCatch(callback, detail) {
try {
return callback(detail);
}
catch (e) {
lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
}
}
function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
var hasCallback = lib$es6$promise$utils$$isFunction(callback), value, error, succeeded, failed;
if (hasCallback) {
value = lib$es6$promise$$internal$$tryCatch(callback, detail);
if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
}
else {
succeeded = true;
}
if (promise === value) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
return;
}
}
else {
value = detail;
succeeded = true;
}
if (promise._state !== lib$es6$promise$$internal$$PENDING) {
}
else if (hasCallback && succeeded) {
lib$es6$promise$$internal$$resolve(promise, value);
}
else if (failed) {
lib$es6$promise$$internal$$reject(promise, error);
}
else if (settled === lib$es6$promise$$internal$$FULFILLED) {
lib$es6$promise$$internal$$fulfill(promise, value);
}
else if (settled === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, value);
}
}
function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
lib$es6$promise$$internal$$resolve(promise, value);
}, function rejectPromise(reason) {
lib$es6$promise$$internal$$reject(promise, reason);
});
}
catch (e) {
lib$es6$promise$$internal$$reject(promise, e);
}
}
function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
var enumerator = this;
enumerator._instanceConstructor = Constructor;
enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
if (enumerator._validateInput(input)) {
enumerator._input = input;
enumerator.length = input.length;
enumerator._remaining = input.length;
enumerator._init();
if (enumerator.length === 0) {
lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
}
else {
enumerator.length = enumerator.length || 0;
enumerator._enumerate();
if (enumerator._remaining === 0) {
lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
}
}
}
else {
lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
}
}
lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function (input) {
return lib$es6$promise$utils$$isArray(input);
};
lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function () {
return new _Internal.Error('Array Methods must be provided an Array');
};
lib$es6$promise$enumerator$$Enumerator.prototype._init = function () {
this._result = new Array(this.length);
};
var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function () {
var enumerator = this;
var length = enumerator.length;
var promise = enumerator.promise;
var input = enumerator._input;
for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
enumerator._eachEntry(input[i], i);
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function (entry, i) {
var enumerator = this;
var c = enumerator._instanceConstructor;
if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
entry._onerror = null;
enumerator._settledAt(entry._state, i, entry._result);
}
else {
enumerator._willSettleAt(c.resolve(entry), i);
}
}
else {
enumerator._remaining--;
enumerator._result[i] = entry;
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function (state, i, value) {
var enumerator = this;
var promise = enumerator.promise;
if (promise._state === lib$es6$promise$$internal$$PENDING) {
enumerator._remaining--;
if (state === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, value);
}
else {
enumerator._result[i] = value;
}
}
if (enumerator._remaining === 0) {
lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function (promise, i) {
var enumerator = this;
lib$es6$promise$$internal$$subscribe(promise, undefined, function (value) {
enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
}, function (reason) {
enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
});
};
function lib$es6$promise$promise$all$$all(entries) {
return new lib$es6$promise$enumerator$$default(this, entries).promise;
}
var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
function lib$es6$promise$promise$race$$race(entries) {
var Constructor = this;
var promise = new Constructor(lib$es6$promise$$internal$$noop);
if (!lib$es6$promise$utils$$isArray(entries)) {
lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
return promise;
}
var length = entries.length;
function onFulfillment(value) {
lib$es6$promise$$internal$$resolve(promise, value);
}
function onRejection(reason) {
lib$es6$promise$$internal$$reject(promise, reason);
}
for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
}
return promise;
}
var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
function lib$es6$promise$promise$resolve$$resolve(object) {
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(lib$es6$promise$$internal$$noop);
lib$es6$promise$$internal$$resolve(promise, object);
return promise;
}
var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
function lib$es6$promise$promise$reject$$reject(reason) {
var Constructor = this;
var promise = new Constructor(lib$es6$promise$$internal$$noop);
lib$es6$promise$$internal$$reject(promise, reason);
return promise;
}
var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
var lib$es6$promise$promise$$counter = 0;
function lib$es6$promise$promise$$needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function lib$es6$promise$promise$$needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
function lib$es6$promise$promise$$Promise(resolver) {
this._id = lib$es6$promise$promise$$counter++;
this._state = undefined;
this._result = undefined;
this._subscribers = [];
if (lib$es6$promise$$internal$$noop !== resolver) {
if (!lib$es6$promise$utils$$isFunction(resolver)) {
lib$es6$promise$promise$$needsResolver();
}
if (!(this instanceof lib$es6$promise$promise$$Promise)) {
lib$es6$promise$promise$$needsNew();
}
lib$es6$promise$$internal$$initializePromise(this, resolver);
}
}
lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
lib$es6$promise$promise$$Promise.prototype = {
constructor: lib$es6$promise$promise$$Promise,
then: function (onFulfillment, onRejection) {
var parent = this;
var state = parent._state;
if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
return this;
}
var child = new this.constructor(lib$es6$promise$$internal$$noop);
var result = parent._result;
if (state) {
var callback = arguments[state - 1];
lib$es6$promise$asap$$asap(function () {
lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
});
}
else {
lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
}
return child;
},
'catch': function (onRejection) {
return this.then(null, onRejection);
}
};
return lib$es6$promise$promise$$default;
}).call(this);
}
PromiseImpl.Init = Init;
})(PromiseImpl = _Internal.PromiseImpl || (_Internal.PromiseImpl = {}));
})(_Internal = OfficeExtension._Internal || (OfficeExtension._Internal = {}));
(function (_Internal) {
function isEdgeLessThan14() {
var userAgent = window.navigator.userAgent;
var versionIdx = userAgent.indexOf("Edge/");
if (versionIdx >= 0) {
userAgent = userAgent.substring(versionIdx + 5, userAgent.length);
if (userAgent < "14.14393")
return true;
else
return false;
}
return false;
}
function determinePromise() {
if (typeof (window) === "undefined" && typeof (Promise) === "function") {
return Promise;
}
if (typeof (window) !== "undefined" && window.Promise) {
if (isEdgeLessThan14()) {
return _Internal.PromiseImpl.Init();
}
else {
return window.Promise;
}
}
else {
return _Internal.PromiseImpl.Init();
}
}
_Internal.OfficePromise = determinePromise();
})(_Internal = OfficeExtension._Internal || (OfficeExtension._Internal = {}));
var OfficePromise = _Internal.OfficePromise;
OfficeExtension.Promise = OfficePromise;
})(OfficeExtension || (OfficeExtension = {}));
var OfficeExtension;
(function (OfficeExtension_1) {
var SessionBase = (function () {
function SessionBase() {
}
SessionBase.prototype._resolveRequestUrlAndHeaderInfo = function () {
return CoreUtility._createPromiseFromResult(null);
};
SessionBase.prototype._createRequestExecutorOrNull = function () {
return null;
};
SessionBase.prototype.getEventRegistration = function (controlId) {
return null;
};
return SessionBase;
}());
OfficeExtension_1.SessionBase = SessionBase;
var HttpUtility = (function () {
function HttpUtility() {
}
HttpUtility.setCustomSendRequestFunc = function (func) {
HttpUtility.s_customSendRequestFunc = func;
};
HttpUtility.xhrSendRequestFunc = function (request) {
return CoreUtility.createPromise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(request.method, request.url);
xhr.onload = function () {
var resp = {
statusCode: xhr.status,
headers: CoreUtility._parseHttpResponseHeaders(xhr.getAllResponseHeaders()),
body: xhr.responseText
};
resolve(resp);
};
xhr.onerror = function () {
reject(new _Internal.RuntimeError({
code: CoreErrorCodes.connectionFailure,
httpStatusCode: xhr.status,
message: CoreUtility._getResourceString(CoreResourceStrings.connectionFailureWithStatus, xhr.statusText)
}));
};
if (request.headers) {
for (var key in request.headers) {
xhr.setRequestHeader(key, request.headers[key]);
}
}
xhr.send(CoreUtility._getRequestBodyText(request));
});
};
HttpUtility.fetchSendRequestFunc = function (request) {
var requestBodyText = CoreUtility._getRequestBodyText(request);
if (requestBodyText === '') {
requestBodyText = undefined;
}
return fetch(request.url, {
method: request.method,
headers: request.headers,
body: requestBodyText
})
.then(function (resp) {
return resp.text()
.then(function (body) {
var statusCode = resp.status;
var headers = {};
resp.headers.forEach(function (value, name) {
headers[name] = value;
});
var ret = { statusCode: statusCode, headers: headers, body: body };
return ret;
});
});
};
HttpUtility.sendRequest = function (request) {
HttpUtility.validateAndNormalizeRequest(request);
var func = HttpUtility.s_customSendRequestFunc;
if (!func) {
if (typeof (fetch) !== 'undefined') {
func = HttpUtility.fetchSendRequestFunc;
}
else {
func = HttpUtility.xhrSendRequestFunc;
}
}
return func(request);
};
HttpUtility.setCustomSendLocalDocumentRequestFunc = function (func) {
HttpUtility.s_customSendLocalDocumentRequestFunc = func;
};
HttpUtility.sendLocalDocumentRequest = function (request) {
HttpUtility.validateAndNormalizeRequest(request);
var func;
func = HttpUtility.s_customSendLocalDocumentRequestFunc || HttpUtility.officeJsSendLocalDocumentRequestFunc;
return func(request);
};
HttpUtility.officeJsSendLocalDocumentRequestFunc = function (request) {
request = CoreUtility._validateLocalDocumentRequest(request);
var requestSafeArray = CoreUtility._buildRequestMessageSafeArray(request);
return CoreUtility.createPromise(function (resolve, reject) {
OSF.DDA.RichApi.executeRichApiRequestAsync(requestSafeArray, function (asyncResult) {
var response;
if (asyncResult.status == 'succeeded') {
response = {
statusCode: RichApiMessageUtility.getResponseStatusCode(asyncResult),
headers: RichApiMessageUtility.getResponseHeaders(asyncResult),
body: RichApiMessageUtility.getResponseBody(asyncResult)
};
}
else {
response = RichApiMessageUtility.buildHttpResponseFromOfficeJsError(asyncResult.error.code, asyncResult.error.message);
}
CoreUtility.log('Response:');
CoreUtility.log(JSON.stringify(response));
resolve(response);
});
});
};
HttpUtility.validateAndNormalizeRequest = function (request) {
if (CoreUtility.isNullOrUndefined(request)) {
throw _Internal.RuntimeError._createInvalidArgError({
argumentName: 'request'
});
}
if (CoreUtility.isNullOrEmptyString(request.method)) {
request.method = 'GET';
}
request.method = request.method.toUpperCase();
var alreadyHasTestName = false;
if (typeof (request.headers) === 'object' && request.headers[CoreConstants.testRequestNameHeader]) {
alreadyHasTestName = true;
}
if (!alreadyHasTestName) {
var currentTestName = TestUtility._getCurrentTestNameWithSequenceId();
if (currentTestName) {
if (!request.headers) {
request.headers = {};
}
request.headers[CoreConstants.testRequestNameHeader] = currentTestName;
}
}
};
HttpUtility.logRequest = function (request) {
if (CoreUtility._logEnabled) {
CoreUtility.log('---HTTP Request---');
CoreUtility.log(request.method + ' ' + request.url);
if (request.headers) {
for (var key in request.headers) {
CoreUtility.log(key + ': ' + request.headers[key]);
}
}
if (HttpUtility._logBodyEnabled) {
CoreUtility.log(CoreUtility._getRequestBodyText(request));
}
}
};
HttpUtility.logResponse = function (response) {
if (CoreUtility._logEnabled) {
CoreUtility.log('---HTTP Response---');
CoreUtility.log('' + response.statusCode);
if (response.headers) {
for (var key in response.headers) {
CoreUtility.log(key + ': ' + response.headers[key]);
}
}
if (HttpUtility._logBodyEnabled) {
CoreUtility.log(response.body);
}
}
};
HttpUtility._logBodyEnabled = false;
return HttpUtility;
}());
OfficeExtension_1.HttpUtility = HttpUtility;
var HostBridge = (function () {
function HostBridge(m_bridge) {
var _this = this;
this.m_bridge = m_bridge;
this.m_promiseResolver = {};
this.m_handlers = [];
this.m_bridge.onMessageFromHost = function (messageText) {
var message = JSON.parse(messageText);
if (message.type == 3) {
var genericMessageBody = message.message;
if (genericMessageBody && genericMessageBody.entries) {
for (var i = 0; i < genericMessageBody.entries.length; i++) {
var entryObjectOrArray = genericMessageBody.entries[i];
if (Array.isArray(entryObjectOrArray)) {
var entry = {
messageCategory: entryObjectOrArray[0],
messageType: entryObjectOrArray[1],
targetId: entryObjectOrArray[2],
message: entryObjectOrArray[3],
id: entryObjectOrArray[4]
};
genericMessageBody.entries[i] = entry;
}
}
}
}
_this.dispatchMessage(message);
};
}
HostBridge.init = function (bridge) {
if (typeof bridge !== 'object' || !bridge) {
return;
}
var instance = new HostBridge(bridge);
HostBridge.s_instance = instance;
HttpUtility.setCustomSendLocalDocumentRequestFunc(function (request) {
request = CoreUtility._validateLocalDocumentRequest(request);
var requestFlags = 0;
if (!CoreUtility.isReadonlyRestRequest(request.method)) {
requestFlags = 1;
}
var index = request.url.indexOf('?');
if (index >= 0) {
var query = request.url.substr(index + 1);
var flagsAndCustomData = CoreUtility._parseRequestFlagsAndCustomDataFromQueryStringIfAny(query);
if (flagsAndCustomData.flags >= 0) {
requestFlags = flagsAndCustomData.flags;
}
}
if (typeof (request.body) === "string") {
request.body = JSON.parse(request.body);
}
var bridgeMessage = {
id: HostBridge.nextId(),
type: 1,
flags: requestFlags,
message: request
};
return instance.sendMessageToHostAndExpectResponse(bridgeMessage).then(function (bridgeResponse) {
var responseInfo = bridgeResponse.message;
return responseInfo;
});
});
for (var i = 0; i < HostBridge.s_onInitedHandlers.length; i++) {
HostBridge.s_onInitedHandlers[i](instance);
}
};
Object.defineProperty(HostBridge, "instance", {
get: function () {
return HostBridge.s_instance;
},
enumerable: true,
configurable: true
});
HostBridge.prototype.sendMessageToHost = function (message) {
this.m_bridge.sendMessageToHost(JSON.stringify(message));
};
HostBridge.prototype.sendMessageToHostAndExpectResponse = function (message) {
var _this = this;
var ret = CoreUtility.createPromise(function (resolve, reject) {
_this.m_promiseResolver[message.id] = resolve;
});
this.m_bridge.sendMessageToHost(JSON.stringify(message));
return ret;
};
HostBridge.prototype.addHostMessageHandler = function (handler) {
this.m_handlers.push(handler);
};
HostBridge.prototype.removeHostMessageHandler = function (handler) {
var index = this.m_handlers.indexOf(handler);
if (index >= 0) {
this.m_handlers.splice(index, 1);
}
};
HostBridge.onInited = function (handler) {
HostBridge.s_onInitedHandlers.push(handler);
if (HostBridge.s_instance) {
handler(HostBridge.s_instance);
}
};
HostBridge.prototype.dispatchMessage = function (message) {
if (typeof message.id === 'number') {
var resolve = this.m_promiseResolver[message.id];
if (resolve) {
resolve(message);
delete this.m_promiseResolver[message.id];
return;
}
}
for (var i = 0; i < this.m_handlers.length; i++) {
this.m_handlers[i](message);
}
};
HostBridge.nextId = function () {
return HostBridge.s_nextId++;
};
HostBridge.s_onInitedHandlers = [];
HostBridge.s_nextId = 1;
return HostBridge;
}());
OfficeExtension_1.HostBridge = HostBridge;
if (typeof _richApiNativeBridge === 'object' && _richApiNativeBridge) {
HostBridge.init(_richApiNativeBridge);
}
var _Internal;
(function (_Internal) {
var RuntimeError = (function (_super) {
__extends(RuntimeError, _super);
function RuntimeError(error) {
var _this = _super.call(this, typeof error === 'string' ? error : error.message) || this;
Object.setPrototypeOf(_this, RuntimeError.prototype);
_this.name = 'RichApi.Error';
if (typeof error === 'string') {
_this.message = error;
}
else {
_this.code = error.code;
_this.message = error.message;
_this.traceMessages = error.traceMessages || [];
_this.innerError = error.innerError || null;
_this.debugInfo = _this._createDebugInfo(error.debugInfo || {});
_this.httpStatusCode = error.httpStatusCode;
_this.data = error.data;
}
if (CoreUtility.isNullOrUndefined(_this.httpStatusCode) || _this.httpStatusCode === 200) {
var mapping = {};
mapping[CoreErrorCodes.accessDenied] = 401;
mapping[CoreErrorCodes.connectionFailure] = 500;
mapping[CoreErrorCodes.generalException] = 500;
mapping[CoreErrorCodes.invalidArgument] = 400;
mapping[CoreErrorCodes.invalidObjectPath] = 400;
mapping[CoreErrorCodes.invalidOrTimedOutSession] = 408;
mapping[CoreErrorCodes.invalidRequestContext] = 400;
mapping[CoreErrorCodes.timeout] = 408;
mapping[CoreErrorCodes.valueNotLoaded] = 400;
_this.httpStatusCode = mapping[_this.code];
}
if (CoreUtility.isNullOrUndefined(_this.httpStatusCode)) {
_this.httpStatusCode = 500;
}
return _this;
}
RuntimeError.prototype.toString = function () {
return this.code + ': ' + this.message;
};
RuntimeError.prototype._createDebugInfo = function (partialDebugInfo) {
var debugInfo = {
code: this.code,
message: this.message
};
debugInfo.toString = function () {
return JSON.stringify(this);
};
for (var key in partialDebugInfo)