@acrolinx/sdk
Advanced tools
Comparing version 1.2.0 to 1.3.0-dev.1
@@ -17,13 +17,2 @@ "use strict"; | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -38,88 +27,44 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/* tslint:disable:no-console */ | ||
require("cross-fetch/polyfill"); | ||
var index_1 = require("../src/index"); | ||
var common_1 = require("./common"); | ||
const index_1 = require("../src/index"); | ||
const common_1 = require("./common"); | ||
function waitMs(ms) { | ||
return new Promise(function (resolve) { return setTimeout(resolve, ms); }); | ||
return new Promise(resolve => setTimeout(resolve, ms)); | ||
} | ||
function checkExample() { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var acrolinxAddress, accessToken, acrolinxEndpoint, capabilities, check, checkResultOrProgress; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
acrolinxAddress = process.argv[2]; | ||
accessToken = process.argv[3]; | ||
if (!accessToken) { | ||
console.error('Missing AccessToken'); | ||
} | ||
acrolinxEndpoint = new index_1.AcrolinxEndpoint(__assign(__assign({}, common_1.EXAMPLE_ACROLINX_ENDPOINT_PROPS), { acrolinxUrl: acrolinxAddress })); | ||
return [4 /*yield*/, acrolinxEndpoint.getCheckingCapabilities(accessToken)]; | ||
case 1: | ||
capabilities = _a.sent(); | ||
console.log(capabilities); | ||
return [4 /*yield*/, acrolinxEndpoint.check(accessToken, { | ||
checkOptions: { | ||
guidanceProfileId: capabilities.guidanceProfiles[0].id, | ||
}, | ||
document: { | ||
reference: 'filename.txt' | ||
}, | ||
content: 'Testt Textt' | ||
})]; | ||
case 2: | ||
check = _a.sent(); | ||
console.log('check', check); | ||
_a.label = 3; | ||
case 3: return [4 /*yield*/, acrolinxEndpoint.pollForCheckResult(accessToken, check)]; | ||
case 4: | ||
checkResultOrProgress = _a.sent(); | ||
console.log('checkResultOrProgress:', JSON.stringify(checkResultOrProgress, null, 2)); | ||
if (!('progress' in checkResultOrProgress)) return [3 /*break*/, 6]; | ||
return [4 /*yield*/, waitMs(checkResultOrProgress.progress.retryAfter * 1000)]; | ||
case 5: | ||
_a.sent(); | ||
_a.label = 6; | ||
case 6: | ||
if ('progress' in checkResultOrProgress) return [3 /*break*/, 3]; | ||
_a.label = 7; | ||
case 7: | ||
console.log('checkResult:', JSON.stringify(checkResultOrProgress, null, 2)); | ||
return [2 /*return*/]; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const acrolinxAddress = process.argv[2]; | ||
const accessToken = process.argv[3]; | ||
if (!accessToken) { | ||
console.error('Missing AccessToken'); | ||
} | ||
const acrolinxEndpoint = new index_1.AcrolinxEndpoint(Object.assign(Object.assign({}, common_1.EXAMPLE_ACROLINX_ENDPOINT_PROPS), { acrolinxUrl: acrolinxAddress })); | ||
const capabilities = yield acrolinxEndpoint.getCheckingCapabilities(accessToken); | ||
console.log(capabilities); | ||
const check = yield acrolinxEndpoint.check(accessToken, { | ||
checkOptions: { | ||
guidanceProfileId: capabilities.guidanceProfiles[0].id, | ||
}, | ||
document: { | ||
reference: 'filename.txt' | ||
}, | ||
content: 'Testt Textt' | ||
}); | ||
console.log('check', check); | ||
let checkResultOrProgress; | ||
do { | ||
checkResultOrProgress = yield acrolinxEndpoint.pollForCheckResult(accessToken, check); | ||
console.log('checkResultOrProgress:', JSON.stringify(checkResultOrProgress, null, 2)); | ||
if ('progress' in checkResultOrProgress) { | ||
yield waitMs(checkResultOrProgress.progress.retryAfter * 1000); | ||
} | ||
}); | ||
} while ('progress' in checkResultOrProgress); | ||
console.log('checkResult:', JSON.stringify(checkResultOrProgress, null, 2)); | ||
}); | ||
} | ||
checkExample().catch(function (error) { | ||
checkExample().catch(error => { | ||
console.error(error); | ||
}); | ||
//# sourceMappingURL=check.js.map |
@@ -19,3 +19,3 @@ "use strict"; | ||
exports.EXAMPLE_ACROLINX_ENDPOINT_PROPS = void 0; | ||
var src_1 = require("../src"); | ||
const src_1 = require("../src"); | ||
exports.EXAMPLE_ACROLINX_ENDPOINT_PROPS = { | ||
@@ -22,0 +22,0 @@ client: { |
@@ -17,13 +17,2 @@ "use strict"; | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -38,57 +27,21 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/* tslint:disable:no-console */ | ||
require("cross-fetch/polyfill"); | ||
var index_1 = require("../src/index"); | ||
var common_1 = require("./common"); | ||
const index_1 = require("../src/index"); | ||
const common_1 = require("./common"); | ||
function getCheckingCapabilitiesExample() { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var accessToken, acrolinxEndpoint, capabilities; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
accessToken = process.argv[2]; | ||
if (!accessToken) { | ||
console.error('Missing AccessToken'); | ||
} | ||
acrolinxEndpoint = new index_1.AcrolinxEndpoint(__assign({}, common_1.EXAMPLE_ACROLINX_ENDPOINT_PROPS)); | ||
return [4 /*yield*/, acrolinxEndpoint.getCheckingCapabilities(accessToken)]; | ||
case 1: | ||
capabilities = _a.sent(); | ||
console.log(JSON.stringify(capabilities, null, 2)); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const accessToken = process.argv[2]; | ||
if (!accessToken) { | ||
console.error('Missing AccessToken'); | ||
} | ||
const acrolinxEndpoint = new index_1.AcrolinxEndpoint(Object.assign({}, common_1.EXAMPLE_ACROLINX_ENDPOINT_PROPS)); | ||
const capabilities = yield acrolinxEndpoint.getCheckingCapabilities(accessToken); | ||
console.log(JSON.stringify(capabilities, null, 2)); | ||
}); | ||
} | ||
getCheckingCapabilitiesExample().catch(function (error) { | ||
getCheckingCapabilitiesExample().catch(error => { | ||
console.error(error); | ||
}); | ||
//# sourceMappingURL=get-checking-capabilities.js.map |
@@ -26,79 +26,37 @@ "use strict"; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/* tslint:disable:no-console */ | ||
require("cross-fetch/polyfill"); | ||
var index_1 = require("../src/index"); | ||
var signin_1 = require("../src/signin"); | ||
var common_1 = require("./common"); | ||
const index_1 = require("../src/index"); | ||
const signin_1 = require("../src/signin"); | ||
const common_1 = require("./common"); | ||
function signInExample() { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var accessToken, acrolinxEndpoint, loginResult, pollResult; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
accessToken = process.argv[2]; | ||
acrolinxEndpoint = new index_1.AcrolinxEndpoint(common_1.EXAMPLE_ACROLINX_ENDPOINT_PROPS); | ||
return [4 /*yield*/, acrolinxEndpoint.signin({ accessToken: accessToken })]; | ||
case 1: | ||
loginResult = _a.sent(); | ||
if (!(0, signin_1.isSigninLinksResult)(loginResult)) return [3 /*break*/, 6]; | ||
if (accessToken) { | ||
console.log('AccessToken was invalid'); | ||
} | ||
console.log("Please signin at \"".concat(loginResult.links.interactive, "\"\n within ").concat(loginResult.data.interactiveLinkTimeout, " seconds!")); | ||
return [4 /*yield*/, acrolinxEndpoint.pollForSignin(loginResult)]; | ||
case 2: | ||
pollResult = _a.sent(); | ||
_a.label = 3; | ||
case 3: | ||
if (!!(0, index_1.isSigninSuccessResult)(pollResult)) return [3 /*break*/, 5]; | ||
console.log('Polling...', pollResult.progress.retryAfter); | ||
return [4 /*yield*/, acrolinxEndpoint.pollForSignin(loginResult, pollResult)]; | ||
case 4: | ||
pollResult = _a.sent(); | ||
return [3 /*break*/, 3]; | ||
case 5: | ||
console.log('Success:', pollResult); | ||
console.log('accessToken:', pollResult.data.accessToken); | ||
console.log('User:', pollResult.data.user.id); | ||
return [3 /*break*/, 7]; | ||
case 6: | ||
console.log('loginResult', loginResult); | ||
console.log("Your are already signed as \"".concat(loginResult.data.user.id, "\"")); | ||
_a.label = 7; | ||
case 7: return [2 /*return*/]; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const accessToken = process.argv[2]; | ||
const acrolinxEndpoint = new index_1.AcrolinxEndpoint(common_1.EXAMPLE_ACROLINX_ENDPOINT_PROPS); | ||
const loginResult = yield acrolinxEndpoint.signin({ accessToken }); | ||
if ((0, signin_1.isSigninLinksResult)(loginResult)) { | ||
if (accessToken) { | ||
console.log('AccessToken was invalid'); | ||
} | ||
}); | ||
console.log(`Please signin at "${loginResult.links.interactive}" | ||
within ${loginResult.data.interactiveLinkTimeout} seconds!`); | ||
let pollResult = yield acrolinxEndpoint.pollForSignin(loginResult); | ||
while (!(0, index_1.isSigninSuccessResult)(pollResult)) { | ||
console.log('Polling...', pollResult.progress.retryAfter); | ||
pollResult = yield acrolinxEndpoint.pollForSignin(loginResult, pollResult); | ||
} | ||
console.log('Success:', pollResult); | ||
console.log('accessToken:', pollResult.data.accessToken); | ||
console.log('User:', pollResult.data.user.id); | ||
} | ||
else { | ||
console.log('loginResult', loginResult); | ||
console.log(`Your are already signed as "${loginResult.data.user.id}"`); | ||
} | ||
}); | ||
} | ||
signInExample().catch(function (error) { | ||
signInExample().catch(error => { | ||
console.error(error); | ||
}); | ||
//# sourceMappingURL=signin.js.map |
@@ -17,13 +17,2 @@ "use strict"; | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -38,109 +27,65 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/* tslint:disable:no-console */ | ||
require("cross-fetch/polyfill"); | ||
var index_1 = require("../src/index"); | ||
var common_1 = require("./common"); | ||
var fs_1 = require("fs"); | ||
const index_1 = require("../src/index"); | ||
const common_1 = require("./common"); | ||
const fs_1 = require("fs"); | ||
function waitMs(ms) { | ||
return new Promise(function (resolve) { return setTimeout(resolve, ms); }); | ||
return new Promise(resolve => setTimeout(resolve, ms)); | ||
} | ||
function xliffExample() { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var acrolinxAddress, accessToken, xliffDocument, xliffDoc, acrolinxEndpoint, capabilities, check, checkResultOrProgress; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
acrolinxAddress = process.argv[2]; | ||
accessToken = process.argv[3]; | ||
xliffDocument = process.argv[4]; | ||
if (!accessToken) { | ||
console.error('Missing AccessToken'); | ||
} | ||
if (!xliffDocument) { | ||
console.error('Missing xliff document'); | ||
} | ||
xliffDoc = (0, fs_1.readFileSync)(xliffDocument).toString(); | ||
acrolinxEndpoint = new index_1.AcrolinxEndpoint(__assign(__assign({}, common_1.EXAMPLE_ACROLINX_ENDPOINT_PROPS), { acrolinxUrl: acrolinxAddress })); | ||
return [4 /*yield*/, acrolinxEndpoint.getCheckingCapabilities(accessToken)]; | ||
case 1: | ||
capabilities = _a.sent(); | ||
console.log(capabilities); | ||
return [4 /*yield*/, acrolinxEndpoint.check(accessToken, { | ||
checkOptions: { | ||
guidanceProfileId: capabilities.guidanceProfiles[0].id, | ||
contentFormat: 'XML', | ||
}, | ||
document: { | ||
reference: 'filename.xlf' | ||
}, | ||
content: xliffDoc | ||
})]; | ||
case 2: | ||
check = _a.sent(); | ||
console.log('check', check); | ||
_a.label = 3; | ||
case 3: return [4 /*yield*/, acrolinxEndpoint.pollForCheckResult(accessToken, check)]; | ||
case 4: | ||
checkResultOrProgress = _a.sent(); | ||
if (!('progress' in checkResultOrProgress)) return [3 /*break*/, 6]; | ||
console.log('checkResultOrProgress:', JSON.stringify(checkResultOrProgress, null, 2)); | ||
return [4 /*yield*/, waitMs(checkResultOrProgress.progress.retryAfter * 1000)]; | ||
case 5: | ||
_a.sent(); | ||
_a.label = 6; | ||
case 6: | ||
if ('progress' in checkResultOrProgress) return [3 /*break*/, 3]; | ||
_a.label = 7; | ||
case 7: | ||
checkResultOrProgress.data.issues.forEach(function (issue) { | ||
var matches = issue.positionalInformation.matches; | ||
var docUptoMatch = xliffDoc.substring(0, matches[matches.length - 1].originalEnd); | ||
// trans-unit is from xliff spec http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#trans-unit | ||
var transationalUnitStart = docUptoMatch.lastIndexOf('<trans-unit'); | ||
var transationalUnitEnd = docUptoMatch.indexOf('>', transationalUnitStart); | ||
var transationalUnitTag = docUptoMatch.substring(transationalUnitStart, transationalUnitEnd); | ||
var idRegex = new RegExp(/id="(.*?)"/g); | ||
var m = idRegex.exec(transationalUnitTag); | ||
if (!m) | ||
throw new Error('Id not found'); | ||
// Get first group from match | ||
var id = m[1]; | ||
console.log('Id for issue ' + issue.displaySurface + ' is: ' + id); | ||
}); | ||
return [2 /*return*/]; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const acrolinxAddress = process.argv[2]; | ||
const accessToken = process.argv[3]; | ||
const xliffDocument = process.argv[4]; | ||
if (!accessToken) { | ||
console.error('Missing AccessToken'); | ||
} | ||
if (!xliffDocument) { | ||
console.error('Missing xliff document'); | ||
} | ||
const xliffDoc = (0, fs_1.readFileSync)(xliffDocument).toString(); | ||
const acrolinxEndpoint = new index_1.AcrolinxEndpoint(Object.assign(Object.assign({}, common_1.EXAMPLE_ACROLINX_ENDPOINT_PROPS), { acrolinxUrl: acrolinxAddress })); | ||
const capabilities = yield acrolinxEndpoint.getCheckingCapabilities(accessToken); | ||
console.log(capabilities); | ||
const check = yield acrolinxEndpoint.check(accessToken, { | ||
checkOptions: { | ||
guidanceProfileId: capabilities.guidanceProfiles[0].id, | ||
contentFormat: 'XML', | ||
}, | ||
document: { | ||
reference: 'filename.xlf' | ||
}, | ||
content: xliffDoc | ||
}); | ||
console.log('check', check); | ||
let checkResultOrProgress; | ||
do { | ||
checkResultOrProgress = yield acrolinxEndpoint.pollForCheckResult(accessToken, check); | ||
if ('progress' in checkResultOrProgress) { | ||
console.log('checkResultOrProgress:', JSON.stringify(checkResultOrProgress, null, 2)); | ||
yield waitMs(checkResultOrProgress.progress.retryAfter * 1000); | ||
} | ||
} while ('progress' in checkResultOrProgress); | ||
checkResultOrProgress.data.issues.forEach(issue => { | ||
const matches = issue.positionalInformation.matches; | ||
const docUptoMatch = xliffDoc.substring(0, matches[matches.length - 1].originalEnd); | ||
// trans-unit is from xliff spec http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#trans-unit | ||
const transationalUnitStart = docUptoMatch.lastIndexOf('<trans-unit'); | ||
const transationalUnitEnd = docUptoMatch.indexOf('>', transationalUnitStart); | ||
const transationalUnitTag = docUptoMatch.substring(transationalUnitStart, transationalUnitEnd); | ||
const idRegex = new RegExp(/id="(.*?)"/g); | ||
const m = idRegex.exec(transationalUnitTag); | ||
if (!m) | ||
throw new Error('Id not found'); | ||
// Get first group from match | ||
const id = m[1]; | ||
console.log('Id for issue ' + issue.displaySurface + ' is: ' + id); | ||
}); | ||
}); | ||
} | ||
xliffExample().catch(function (error) { | ||
xliffExample().catch(error => { | ||
console.error(error); | ||
}); | ||
//# sourceMappingURL=xliff-usecase.js.map |
@@ -19,3 +19,3 @@ "use strict"; | ||
exports.DocumentQualityStatus = exports.IssueType = exports.SuggestionIconId = exports.KeywordWarningType = exports.hasTermHarvestingReport = void 0; | ||
var capabilities_1 = require("./capabilities"); | ||
const capabilities_1 = require("./capabilities"); | ||
function hasTermHarvestingReport(reports) { | ||
@@ -22,0 +22,0 @@ return !!reports.termHarvesting; |
@@ -17,13 +17,2 @@ "use strict"; | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -33,5 +22,5 @@ exports.sanitizeDocumentDescriptor = void 0; | ||
function sanitizeDocumentDescriptor(d) { | ||
return __assign(__assign({}, d), { customFields: d.customFields || [] }); | ||
return Object.assign(Object.assign({}, d), { customFields: d.customFields || [] }); | ||
} | ||
exports.sanitizeDocumentDescriptor = sanitizeDocumentDescriptor; | ||
//# sourceMappingURL=document-descriptor.js.map |
@@ -17,20 +17,5 @@ "use strict"; | ||
*/ | ||
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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; | ||
return extendStatics(d, b); | ||
}; | ||
return function (d, b) { | ||
if (typeof b !== "function" && b !== null) | ||
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); | ||
extendStatics(d, b); | ||
function __() { this.constructor = d; } | ||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); | ||
}; | ||
})(); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.CheckCanceledByClientError = exports.wrapFetchError = exports.createErrorFromFetchResponse = exports.AcrolinxError = exports.ErrorType = void 0; | ||
var ai_service_utils_1 = require("./services/ai-service/ai-service.utils"); | ||
const ai_service_utils_1 = require("./services/ai-service/ai-service.utils"); | ||
/** | ||
@@ -64,11 +49,10 @@ * See also https://github.com/acrolinx/server-api-spec/blob/master/apiary.apib | ||
})(ErrorType || (exports.ErrorType = ErrorType = {})); | ||
var AcrolinxError = /** @class */ (function (_super) { | ||
__extends(AcrolinxError, _super); | ||
function AcrolinxError(props) { | ||
var _this = _super.call(this, props.title) || this; | ||
_this.type = props.type; | ||
_this.status = props.status; | ||
_this.responseHeaders = props.responseHeaders; | ||
class AcrolinxError extends Error { | ||
constructor(props) { | ||
super(props.title); | ||
this.type = props.type; | ||
this.status = props.status; | ||
this.responseHeaders = props.responseHeaders; | ||
// Copy only known props, to avoid accidental leaking of stuff. | ||
_this.httpRequest = props.httpRequest | ||
this.httpRequest = props.httpRequest | ||
? { | ||
@@ -79,12 +63,10 @@ url: props.httpRequest.url, | ||
: undefined; | ||
_this.title = props.title; | ||
_this.detail = props.detail; | ||
_this.reference = props.reference; | ||
_this.validationDetails = props.validationDetails; | ||
_this.cause = props.cause; | ||
_this.documentId = props.documentId; | ||
return _this; | ||
this.title = props.title; | ||
this.detail = props.detail; | ||
this.reference = props.reference; | ||
this.validationDetails = props.validationDetails; | ||
this.cause = props.cause; | ||
this.documentId = props.documentId; | ||
} | ||
return AcrolinxError; | ||
}(Error)); | ||
} | ||
exports.AcrolinxError = AcrolinxError; | ||
@@ -116,3 +98,3 @@ function createErrorFromFetchResponse(req, res, jsonBody) { | ||
return new AcrolinxError({ | ||
detail: "".concat(res.statusText, ":").concat(JSON.stringify(jsonBody)), | ||
detail: `${res.statusText}:${JSON.stringify(jsonBody)}`, | ||
status: res.status, | ||
@@ -128,5 +110,5 @@ httpRequest: req, | ||
throw new AcrolinxError({ | ||
detail: "".concat(error.message, " (").concat(error.name, ", URL: ").concat(httpRequest.url, ", Method: ").concat(httpRequest.method, ")"), | ||
detail: `${error.message} (${error.name}, URL: ${httpRequest.url}, Method: ${httpRequest.method})`, | ||
title: 'Http Connection Problem', | ||
httpRequest: httpRequest, | ||
httpRequest, | ||
type: ErrorType.HttpConnectionProblem, | ||
@@ -137,11 +119,8 @@ cause: error, | ||
exports.wrapFetchError = wrapFetchError; | ||
var CheckCanceledByClientError = /** @class */ (function (_super) { | ||
__extends(CheckCanceledByClientError, _super); | ||
function CheckCanceledByClientError(props) { | ||
var _this = _super.call(this, props) || this; | ||
setCorrectErrorPrototype(_this, CheckCanceledByClientError); | ||
return _this; | ||
class CheckCanceledByClientError extends AcrolinxError { | ||
constructor(props) { | ||
super(props); | ||
setCorrectErrorPrototype(this, CheckCanceledByClientError); | ||
} | ||
return CheckCanceledByClientError; | ||
}(AcrolinxError)); | ||
} | ||
exports.CheckCanceledByClientError = CheckCanceledByClientError; | ||
@@ -148,0 +127,0 @@ function setCorrectErrorPrototype(self, clazz) { |
@@ -17,16 +17,5 @@ "use strict"; | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getAcrolinxClientHttpHeader = exports.getHeadersLegacy = exports.getHeaders = exports.getCommonHeaders = exports.HEADER_ACROLINX_ONE_AUTH = exports.HEADER_X_ACROLINX_APP_SIGNATURE = exports.HEADER_X_ACROLINX_CLIENT_LOCALE = exports.HEADER_X_ACROLINX_BASE_URL = exports.HEADER_X_ACROLINX_AUTH = exports.HEADER_X_ACROLINX_CLIENT = void 0; | ||
var common_types_1 = require("./common-types"); | ||
const common_types_1 = require("./common-types"); | ||
exports.HEADER_X_ACROLINX_CLIENT = 'X-Acrolinx-Client'; | ||
@@ -38,17 +27,16 @@ exports.HEADER_X_ACROLINX_AUTH = 'X-Acrolinx-Auth'; | ||
exports.HEADER_ACROLINX_ONE_AUTH = 'Authorization'; | ||
function getCommonHeaders(props, accessToken, serviceType) { | ||
if (serviceType === void 0) { serviceType = common_types_1.ServiceType.ACROLINX_CORE; } | ||
var headers = { | ||
function getCommonHeaders(props, accessToken, serviceType = common_types_1.ServiceType.ACROLINX_CORE) { | ||
const headers = { | ||
'Content-Type': 'application/json', | ||
}; | ||
if (serviceType === common_types_1.ServiceType.ACROLINX_CORE) { | ||
return __assign(__assign({}, headers), getHeadersLegacy(props, accessToken)); | ||
return Object.assign(Object.assign({}, headers), getHeadersLegacy(props, accessToken)); | ||
} | ||
return __assign(__assign({}, headers), getHeaders(props, accessToken)); | ||
return Object.assign(Object.assign({}, headers), getHeaders(props, accessToken)); | ||
} | ||
exports.getCommonHeaders = getCommonHeaders; | ||
function getHeaders(props, accessToken) { | ||
var headers = {}; | ||
const headers = {}; | ||
if (accessToken) { | ||
headers[exports.HEADER_ACROLINX_ONE_AUTH] = "Bearer ".concat(accessToken); | ||
headers[exports.HEADER_ACROLINX_ONE_AUTH] = `Bearer ${accessToken}`; | ||
headers[exports.HEADER_X_ACROLINX_CLIENT] = getAcrolinxClientHttpHeader(props); | ||
@@ -60,3 +48,3 @@ } | ||
function getHeadersLegacy(props, accessToken) { | ||
var headers = {}; | ||
const headers = {}; | ||
headers[exports.HEADER_X_ACROLINX_BASE_URL] = props.acrolinxUrl; | ||
@@ -74,5 +62,5 @@ headers[exports.HEADER_X_ACROLINX_CLIENT] = getAcrolinxClientHttpHeader(props); | ||
function getAcrolinxClientHttpHeader(props) { | ||
return "".concat(props.client.signature, "; ").concat(props.client.version); | ||
return `${props.client.signature}; ${props.client.version}`; | ||
} | ||
exports.getAcrolinxClientHttpHeader = getAcrolinxClientHttpHeader; | ||
//# sourceMappingURL=headers.js.map |
@@ -17,13 +17,2 @@ "use strict"; | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
@@ -52,49 +41,22 @@ if (k2 === undefined) k2 = k; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.AcrolinxEndpoint = exports.DEVELOPMENT_APP_SIGNATURE = exports.DEVELOPMENT_SIGNATURE = exports.HEADER_X_ACROLINX_APP_SIGNATURE = exports.ReportType = exports.CheckType = exports.ContentEncoding = exports.ErrorType = exports.CheckCanceledByClientError = exports.AcrolinxError = exports.isSigninLinksResult = exports.setLoggingEnabled = exports.AuthorizationType = exports.isSigninSuccessResult = void 0; | ||
var capabilities_1 = require("./capabilities"); | ||
const capabilities_1 = require("./capabilities"); | ||
Object.defineProperty(exports, "CheckType", { enumerable: true, get: function () { return capabilities_1.CheckType; } }); | ||
Object.defineProperty(exports, "ContentEncoding", { enumerable: true, get: function () { return capabilities_1.ContentEncoding; } }); | ||
Object.defineProperty(exports, "ReportType", { enumerable: true, get: function () { return capabilities_1.ReportType; } }); | ||
var common_types_1 = require("./common-types"); | ||
var document_descriptor_1 = require("./document-descriptor"); | ||
var errors_1 = require("./errors"); | ||
const common_types_1 = require("./common-types"); | ||
const document_descriptor_1 = require("./document-descriptor"); | ||
const errors_1 = require("./errors"); | ||
Object.defineProperty(exports, "AcrolinxError", { enumerable: true, get: function () { return errors_1.AcrolinxError; } }); | ||
Object.defineProperty(exports, "CheckCanceledByClientError", { enumerable: true, get: function () { return errors_1.CheckCanceledByClientError; } }); | ||
Object.defineProperty(exports, "ErrorType", { enumerable: true, get: function () { return errors_1.ErrorType; } }); | ||
var headers_1 = require("./headers"); | ||
const headers_1 = require("./headers"); | ||
Object.defineProperty(exports, "HEADER_X_ACROLINX_APP_SIGNATURE", { enumerable: true, get: function () { return headers_1.HEADER_X_ACROLINX_APP_SIGNATURE; } }); | ||
var signin_1 = require("./signin"); | ||
const signin_1 = require("./signin"); | ||
Object.defineProperty(exports, "isSigninLinksResult", { enumerable: true, get: function () { return signin_1.isSigninLinksResult; } }); | ||
var fetch_1 = require("./utils/fetch"); | ||
var logging = require("./utils/logging"); | ||
var logging_buffer_1 = require("./utils/logging-buffer"); | ||
var mixed_utils_1 = require("./utils/mixed-utils"); | ||
const fetch_1 = require("./utils/fetch"); | ||
const logging = require("./utils/logging"); | ||
const logging_buffer_1 = require("./utils/logging-buffer"); | ||
const mixed_utils_1 = require("./utils/mixed-utils"); | ||
__exportStar(require("./dictionary"), exports); | ||
@@ -124,7 +86,7 @@ __exportStar(require("./extraction"), exports); | ||
exports.DEVELOPMENT_APP_SIGNATURE = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiS2lsbGVyIEFwcCIsImlkIjoiNGVlZDM3NjctMGYzMS00ZDVmLWI2MjktYzg2MWFiM2VkODUyIiwidHlwZSI6IkFQUCIsImlhdCI6MTU2MTE4ODI5M30.zlVJuGITMjAJ2p4nl-qtpj4N0p_8e4tenr-4dkrGdXg'; | ||
var VALIDATE_APP_ACCESS_TOKEN_PATH = '/api/v1/apps/whoami'; | ||
var AcrolinxEndpoint = /** @class */ (function () { | ||
function AcrolinxEndpoint(props) { | ||
const VALIDATE_APP_ACCESS_TOKEN_PATH = '/api/v1/apps/whoami'; | ||
class AcrolinxEndpoint { | ||
constructor(props) { | ||
this.loggingBuffer = null; | ||
this.props = __assign(__assign({}, props), { acrolinxUrl: props.acrolinxUrl.trim().replace(/\/$/, '') }); | ||
this.props = Object.assign(Object.assign({}, props), { acrolinxUrl: props.acrolinxUrl.trim().replace(/\/$/, '') }); | ||
if (this.props.enableCloudLogging) { | ||
@@ -134,292 +96,201 @@ this.loggingBuffer = new logging_buffer_1.LogBuffer(this.props.acrolinxUrl, this.props.loggingConfig); | ||
} | ||
AcrolinxEndpoint.prototype.setClientLocale = function (clientLocale) { | ||
setClientLocale(clientLocale) { | ||
this.props.clientLocale = clientLocale; | ||
}; | ||
AcrolinxEndpoint.prototype.getPlatformInformation = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, getData(this.getJsonFromPath('/api/v1/'))]; | ||
}); | ||
} | ||
getPlatformInformation() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return getData(this.getJsonFromPath('/api/v1/')); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.signInWithSSO = function (genericToken, username) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var signinResult; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.signin({ genericToken: genericToken, username: username })]; | ||
case 1: | ||
signinResult = _a.sent(); | ||
if ((0, signin_1.isSigninSuccessResult)(signinResult)) { | ||
return [2 /*return*/, signinResult]; | ||
} | ||
else { | ||
throw new errors_1.AcrolinxError({ | ||
type: errors_1.ErrorType.SSO, | ||
title: 'SSO Error', | ||
detail: 'Sign-In by SSO failed.', | ||
}); | ||
} | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
} | ||
signInWithSSO(genericToken, username) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const signinResult = yield this.signin({ genericToken, username }); | ||
if ((0, signin_1.isSigninSuccessResult)(signinResult)) { | ||
return signinResult; | ||
} | ||
else { | ||
throw new errors_1.AcrolinxError({ | ||
type: errors_1.ErrorType.SSO, | ||
title: 'SSO Error', | ||
detail: 'Sign-In by SSO failed.', | ||
}); | ||
} | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.singInInteractive = function (opts) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var signinResult; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.signin({ accessToken: opts.accessToken })]; | ||
case 1: | ||
signinResult = _a.sent(); | ||
if ((0, signin_1.isSigninSuccessResult)(signinResult)) { | ||
return [2 /*return*/, signinResult.data]; | ||
} | ||
opts.onSignInUrl(signinResult.links.interactive); | ||
return [2 /*return*/, this.pollForInteractiveSignIn(signinResult, opts.timeoutMs || 60 * 60 * 1000)]; | ||
} | ||
}); | ||
} | ||
singInInteractive(opts) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const signinResult = yield this.signin({ accessToken: opts.accessToken }); | ||
if ((0, signin_1.isSigninSuccessResult)(signinResult)) { | ||
return signinResult.data; | ||
} | ||
opts.onSignInUrl(signinResult.links.interactive); | ||
return this.pollForInteractiveSignIn(signinResult, opts.timeoutMs || 60 * 60 * 1000); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.signin = function () { | ||
return __awaiter(this, arguments, void 0, function (options) { | ||
if (options === void 0) { options = {}; } | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, (0, fetch_1.post)('/api/v1/auth/sign-ins', {}, (0, signin_1.getSigninRequestHeaders)(options), this.props)]; | ||
}); | ||
} | ||
signin() { | ||
return __awaiter(this, arguments, void 0, function* (options = {}) { | ||
return (0, fetch_1.post)('/api/v1/auth/sign-ins', {}, (0, signin_1.getSigninRequestHeaders)(options), this.props); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.pollForSignin = function (signinLinks, lastPollResult) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!(lastPollResult && lastPollResult.progress.retryAfter)) return [3 /*break*/, 2]; | ||
logging.log('Waiting before retry', lastPollResult.progress.retryAfter); | ||
return [4 /*yield*/, (0, mixed_utils_1.waitMs)(lastPollResult.progress.retryAfter * 1000)]; | ||
case 1: | ||
_a.sent(); | ||
_a.label = 2; | ||
case 2: return [2 /*return*/, this.getJsonFromUrl(signinLinks.links.poll)]; | ||
} | ||
}); | ||
} | ||
pollForSignin(signinLinks, lastPollResult) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (lastPollResult && lastPollResult.progress.retryAfter) { | ||
logging.log('Waiting before retry', lastPollResult.progress.retryAfter); | ||
yield (0, mixed_utils_1.waitMs)(lastPollResult.progress.retryAfter * 1000); | ||
} | ||
return this.getJsonFromUrl(signinLinks.links.poll); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.getAppAccessToken = function (accessToken, appId) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var tokenApiResult; | ||
var _a; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: return [4 /*yield*/, getData((0, fetch_1.post)('/api/v1/apps/accessToken/' + appId, {}, undefined, this.props, accessToken))]; | ||
case 1: | ||
tokenApiResult = _b.sent(); | ||
return [2 /*return*/, __assign(__assign({}, tokenApiResult), { validationRequest: { | ||
url: (0, fetch_1.getUrlOfPath)(this.props, VALIDATE_APP_ACCESS_TOKEN_PATH), | ||
headers: (_a = { | ||
'Content-Type': 'application/json' | ||
}, | ||
_a[headers_1.HEADER_X_ACROLINX_CLIENT] = (0, headers_1.getAcrolinxClientHttpHeader)(this.props), | ||
_a[headers_1.HEADER_X_ACROLINX_AUTH] = tokenApiResult.appAccessToken, | ||
_a), | ||
} })]; | ||
} | ||
}); | ||
} | ||
getAppAccessToken(accessToken, appId) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const tokenApiResult = yield getData((0, fetch_1.post)('/api/v1/apps/accessToken/' + appId, {}, undefined, this.props, accessToken)); | ||
return Object.assign(Object.assign({}, tokenApiResult), { validationRequest: { | ||
url: (0, fetch_1.getUrlOfPath)(this.props, VALIDATE_APP_ACCESS_TOKEN_PATH), | ||
headers: { | ||
'Content-Type': 'application/json', | ||
[headers_1.HEADER_X_ACROLINX_CLIENT]: (0, headers_1.getAcrolinxClientHttpHeader)(this.props), | ||
[headers_1.HEADER_X_ACROLINX_AUTH]: tokenApiResult.appAccessToken, | ||
}, | ||
} }); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.validateAppAccessToken = function (appToken) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, getData(this.getJsonFromPath(VALIDATE_APP_ACCESS_TOKEN_PATH, appToken))]; | ||
}); | ||
} | ||
validateAppAccessToken(appToken) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return getData(this.getJsonFromPath(VALIDATE_APP_ACCESS_TOKEN_PATH, appToken)); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.getCapabilities = function (accessToken) { | ||
} | ||
getCapabilities(accessToken) { | ||
return getData(this.getJsonFromPath('/api/v1/capabilities', accessToken)); | ||
}; | ||
AcrolinxEndpoint.prototype.getFeatures = function (accessToken) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var responsePromise; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, getData(this.getJsonFromPath('/api/v1/configuration/features', accessToken))]; | ||
case 1: | ||
responsePromise = _a.sent(); | ||
return [2 /*return*/, responsePromise.features]; | ||
} | ||
}); | ||
} | ||
getFeatures(accessToken) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const responsePromise = yield getData(this.getJsonFromPath('/api/v1/configuration/features', accessToken)); | ||
return responsePromise.features; | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.getCheckingCapabilities = function (accessToken) { | ||
} | ||
getCheckingCapabilities(accessToken) { | ||
return getData(this.getJsonFromPath('/api/v1/checking/capabilities', accessToken)); | ||
}; | ||
AcrolinxEndpoint.prototype.check = function (accessToken, req) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, (0, fetch_1.post)('/api/v1/checking/checks', req, {}, this.props, accessToken)]; | ||
}); | ||
} | ||
check(accessToken, req) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return (0, fetch_1.post)('/api/v1/checking/checks', req, {}, this.props, accessToken); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.getLiveSuggestions = function (accessToken, req) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, (0, fetch_1.post)('/reuse-service/api/v1/phrases/preferred/with-description', req, {}, this.props, accessToken)]; | ||
}); | ||
} | ||
getLiveSuggestions(accessToken, req) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return (0, fetch_1.post)('/reuse-service/api/v1/phrases/preferred/with-description', req, {}, this.props, accessToken); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.checkAndGetResult = function (accessToken, req, opts) { | ||
if (opts === void 0) { opts = {}; } | ||
} | ||
checkAndGetResult(accessToken, req, opts = {}) { | ||
return this.startCancelablePollLoop(accessToken, this.check(accessToken, req), opts); | ||
}; | ||
AcrolinxEndpoint.prototype.analyzeAndPoll = function (accessToken, req, opts) { | ||
var _a; | ||
if (opts === void 0) { opts = {}; } | ||
var headers = (_a = {}, _a[headers_1.HEADER_X_ACROLINX_APP_SIGNATURE] = req.appSignature, _a); | ||
var asyncStartedProcessPromise = (0, fetch_1.post)('/api/v1/apps/analyses', req, headers, this.props, accessToken); | ||
return this.startCancelablePollLoop(accessToken, asyncStartedProcessPromise, __assign(__assign({}, opts), { headers: headers })); | ||
}; | ||
AcrolinxEndpoint.prototype.cancelCheck = function (accessToken, check) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, this.cancelAsyncStartedProcess(accessToken, check)]; | ||
}); | ||
} | ||
analyzeAndPoll(accessToken, req, opts = {}) { | ||
const headers = { [headers_1.HEADER_X_ACROLINX_APP_SIGNATURE]: req.appSignature }; | ||
const asyncStartedProcessPromise = (0, fetch_1.post)('/api/v1/apps/analyses', req, headers, this.props, accessToken); | ||
return this.startCancelablePollLoop(accessToken, asyncStartedProcessPromise, Object.assign(Object.assign({}, opts), { headers })); | ||
} | ||
cancelCheck(accessToken, check) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.cancelAsyncStartedProcess(accessToken, check); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.pollForCheckResult = function (accessToken, check) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, this.pollForAsyncResult(accessToken, check)]; | ||
}); | ||
} | ||
pollForCheckResult(accessToken, check) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.pollForAsyncResult(accessToken, check); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.getTermHarvestingReport = function (accessToken, reports) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, getData(this.getJsonFromUrl(reports.termHarvesting.link, accessToken))]; | ||
}); | ||
} | ||
getTermHarvestingReport(accessToken, reports) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return getData(this.getJsonFromUrl(reports.termHarvesting.link, accessToken)); | ||
}); | ||
}; | ||
} | ||
/** | ||
* @deprecated Please use {@link getContentAnalysisDashboard} | ||
*/ | ||
AcrolinxEndpoint.prototype.getLinkToAggregatedReport = function (accessToken, batchId) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, this.getJsonFromPath('/api/v1/checking/aggregation/' + encodeURIComponent(batchId), accessToken)]; | ||
}); | ||
getLinkToAggregatedReport(accessToken, batchId) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.getJsonFromPath('/api/v1/checking/aggregation/' + encodeURIComponent(batchId), accessToken); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.getContentAnalysisDashboard = function (accessToken, batchId) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var serviceResult, shortWithoutAccessToken; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, getData(this.getJsonFromPath("/api/v1/checking/".concat(encodeURIComponent(batchId), "/contentanalysis"), accessToken))]; | ||
case 1: | ||
serviceResult = _a.sent(); | ||
shortWithoutAccessToken = serviceResult.links.filter(function (link) { return link.linkType === 'shortWithoutAccessToken'; })[0]; | ||
return [2 /*return*/, shortWithoutAccessToken.link]; | ||
} | ||
}); | ||
} | ||
getContentAnalysisDashboard(accessToken, batchId) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const serviceResult = yield getData(this.getJsonFromPath(`/api/v1/checking/${encodeURIComponent(batchId)}/contentanalysis`, accessToken)); | ||
const shortWithoutAccessToken = serviceResult.links.filter((link) => link.linkType === 'shortWithoutAccessToken')[0]; | ||
return shortWithoutAccessToken.link; | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.getServerNotifications = function (accessToken, sinceTimeStamp) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, this.getJsonFromPath('/api/v1/broadcasts/platform-notifications/' + sinceTimeStamp, accessToken)]; | ||
}); | ||
} | ||
getServerNotifications(accessToken, sinceTimeStamp) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.getJsonFromPath('/api/v1/broadcasts/platform-notifications/' + sinceTimeStamp, accessToken); | ||
}); | ||
}; | ||
} | ||
// TODO (marco) Review! Added this method to test DEV-17460 | ||
AcrolinxEndpoint.prototype.postServerNotifications = function (accessToken, notification) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, (0, fetch_1.post)('/api/v1/broadcasts/platform-notifications/', notification, {}, this.props, accessToken)]; | ||
}); | ||
postServerNotifications(accessToken, notification) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return (0, fetch_1.post)('/api/v1/broadcasts/platform-notifications/', notification, {}, this.props, accessToken); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.getDictionaryCapabilities = function (accessToken) { | ||
} | ||
getDictionaryCapabilities(accessToken) { | ||
return getData(this.getJsonFromPath('/api/v1/dictionary/capabilities', accessToken)); | ||
}; | ||
AcrolinxEndpoint.prototype.addToDictionary = function (accessToken, req) { | ||
} | ||
addToDictionary(accessToken, req) { | ||
return getData((0, fetch_1.post)('/api/v1/dictionary/submit', req, {}, this.props, accessToken)); | ||
}; | ||
AcrolinxEndpoint.prototype.getUserData = function (accessToken, id) { | ||
} | ||
getUserData(accessToken, id) { | ||
return getData(this.getJsonFromPath('/api/v1/user/' + id, accessToken)); | ||
}; | ||
AcrolinxEndpoint.prototype.setUserCustomFields = function (accessToken, id, customFieldValues) { | ||
var requestBody = { id: id, customFields: customFieldValues }; | ||
} | ||
setUserCustomFields(accessToken, id, customFieldValues) { | ||
const requestBody = { id, customFields: customFieldValues }; | ||
return getData((0, fetch_1.put)('/api/v1/user/' + id, requestBody, {}, this.props, accessToken)); | ||
}; | ||
AcrolinxEndpoint.prototype.getDocumentDescriptor = function (accessToken, id) { | ||
} | ||
getDocumentDescriptor(accessToken, id) { | ||
return getData(this.getJsonFromPath('/api/v1/document/' + id, accessToken)).then(document_descriptor_1.sanitizeDocumentDescriptor); | ||
}; | ||
AcrolinxEndpoint.prototype.setDocumentCustomFields = function (accessToken, documentId, customFieldValues) { | ||
var requestBody = { id: documentId, customFields: customFieldValues }; | ||
} | ||
setDocumentCustomFields(accessToken, documentId, customFieldValues) { | ||
const requestBody = { id: documentId, customFields: customFieldValues }; | ||
return getData((0, fetch_1.put)('/api/v1/document/' + documentId, requestBody, {}, this.props, accessToken)); | ||
}; | ||
AcrolinxEndpoint.prototype.getJsonFromPath = function (path, accessToken, opts) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, this.getJsonFromUrl((0, fetch_1.getUrlOfPath)(this.props, path), accessToken, opts)]; | ||
}); | ||
} | ||
getJsonFromPath(path, accessToken, opts) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.getJsonFromUrl((0, fetch_1.getUrlOfPath)(this.props, path), accessToken, opts); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.getJsonFromUrl = function (url_1, accessToken_1) { | ||
return __awaiter(this, arguments, void 0, function (url, accessToken, opts) { | ||
if (opts === void 0) { opts = {}; } | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, (0, fetch_1.fetchJson)(url, this.props, { | ||
headers: __assign(__assign({}, (0, headers_1.getCommonHeaders)(this.props, accessToken, opts.serviceType)), opts.headers), | ||
})]; | ||
} | ||
getJsonFromUrl(url_1, accessToken_1) { | ||
return __awaiter(this, arguments, void 0, function* (url, accessToken, opts = {}) { | ||
return (0, fetch_1.fetchJson)(url, this.props, { | ||
headers: Object.assign(Object.assign({}, (0, headers_1.getCommonHeaders)(this.props, accessToken, opts.serviceType)), opts.headers), | ||
}); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.getTextFromUrl = function (url_1, accessToken_1) { | ||
return __awaiter(this, arguments, void 0, function (url, accessToken, opts) { | ||
var httpRequest; | ||
if (opts === void 0) { opts = {}; } | ||
return __generator(this, function (_a) { | ||
httpRequest = { url: url, method: 'GET' }; | ||
return [2 /*return*/, (0, fetch_1.fetchWithProps)(url, this.props, { | ||
headers: __assign(__assign({}, (0, headers_1.getCommonHeaders)(this.props, accessToken, opts.serviceType)), opts.headers), | ||
}).then(function (res) { return (0, fetch_1.handleExpectedTextResponse)(httpRequest, res); }, function (error) { return (0, errors_1.wrapFetchError)(httpRequest, error); })]; | ||
}); | ||
} | ||
getTextFromUrl(url_1, accessToken_1) { | ||
return __awaiter(this, arguments, void 0, function* (url, accessToken, opts = {}) { | ||
const httpRequest = { url, method: 'GET' }; | ||
return (0, fetch_1.fetchWithProps)(url, this.props, { | ||
headers: Object.assign(Object.assign({}, (0, headers_1.getCommonHeaders)(this.props, accessToken, opts.serviceType)), opts.headers), | ||
}).then((res) => (0, fetch_1.handleExpectedTextResponse)(httpRequest, res), (error) => (0, errors_1.wrapFetchError)(httpRequest, error)); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.pollForInteractiveSignIn = function (signinLinksResult, timeoutMs) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var startTime, pollResult; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
startTime = Date.now(); | ||
_a.label = 1; | ||
case 1: | ||
if (!(Date.now() < startTime + timeoutMs)) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, this.pollForSignin(signinLinksResult, pollResult)]; | ||
case 2: | ||
pollResult = _a.sent(); | ||
if ((0, signin_1.isSigninSuccessResult)(pollResult)) { | ||
return [2 /*return*/, pollResult.data]; | ||
} | ||
return [3 /*break*/, 1]; | ||
case 3: throw new errors_1.AcrolinxError({ | ||
type: errors_1.ErrorType.SigninTimedOut, | ||
title: 'Interactive sign-in time out', | ||
detail: "Interactive sign-in has timed out by client (".concat(Date.now() - startTime, " > ").concat(timeoutMs, " ms)."), | ||
}); | ||
} | ||
pollForInteractiveSignIn(signinLinksResult, timeoutMs) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const startTime = Date.now(); | ||
let pollResult; | ||
while (Date.now() < startTime + timeoutMs) { | ||
pollResult = yield this.pollForSignin(signinLinksResult, pollResult); | ||
if ((0, signin_1.isSigninSuccessResult)(pollResult)) { | ||
return pollResult.data; | ||
} | ||
} | ||
throw new errors_1.AcrolinxError({ | ||
type: errors_1.ErrorType.SigninTimedOut, | ||
title: 'Interactive sign-in time out', | ||
detail: `Interactive sign-in has timed out by client (${Date.now() - startTime} > ${timeoutMs} ms).`, | ||
}); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.startCancelablePollLoop = function (accessToken, asyncStartedProcessPromise, opts) { | ||
var _this = this; | ||
if (opts === void 0) { opts = {}; } | ||
var canceledByClient = false; | ||
var requestedCanceledOnServer = false; | ||
var runningCheck; | ||
var cancelPromiseReject; | ||
var cancelPromise = new Promise(function (_resolve, reject) { | ||
} | ||
startCancelablePollLoop(accessToken, asyncStartedProcessPromise, opts = {}) { | ||
let canceledByClient = false; | ||
let requestedCanceledOnServer = false; | ||
let runningCheck; | ||
let cancelPromiseReject; | ||
const cancelPromise = new Promise((_resolve, reject) => { | ||
cancelPromiseReject = reject; | ||
@@ -432,3 +303,3 @@ }); | ||
} | ||
var handlePotentialCancellation = function () { | ||
const handlePotentialCancellation = () => { | ||
if (canceledByClient) { | ||
@@ -441,78 +312,56 @@ cancelOnServerIfPossibleAndStillNeeded(); | ||
}; | ||
var cancelOnServerIfPossibleAndStillNeeded = function () { | ||
const cancelOnServerIfPossibleAndStillNeeded = () => { | ||
if (!requestedCanceledOnServer && runningCheck) { | ||
requestedCanceledOnServer = true; | ||
// eslint-disable-next-line @typescript-eslint/no-floating-promises | ||
_this.cancelAsyncStartedProcess(accessToken, runningCheck, opts); | ||
this.cancelAsyncStartedProcess(accessToken, runningCheck, opts); | ||
} | ||
}; | ||
var poll = function () { return __awaiter(_this, void 0, void 0, function () { | ||
var checkResultOrProgress; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, asyncStartedProcessPromise]; | ||
case 1: | ||
runningCheck = _a.sent(); | ||
handlePotentialCancellation(); | ||
_a.label = 2; | ||
case 2: return [4 /*yield*/, this.pollForAsyncResult(accessToken, runningCheck, opts)]; | ||
case 3: | ||
checkResultOrProgress = _a.sent(); | ||
handlePotentialCancellation(); | ||
if (!(0, common_types_1.isProgressResponse)(checkResultOrProgress)) return [3 /*break*/, 5]; | ||
if (opts.onProgress) { | ||
opts.onProgress(checkResultOrProgress.progress); | ||
} | ||
return [4 /*yield*/, (0, mixed_utils_1.waitMs)(checkResultOrProgress.progress.retryAfter * 1000)]; | ||
case 4: | ||
_a.sent(); | ||
handlePotentialCancellation(); | ||
_a.label = 5; | ||
case 5: | ||
if ((0, common_types_1.isProgressResponse)(checkResultOrProgress)) return [3 /*break*/, 2]; | ||
_a.label = 6; | ||
case 6: return [2 /*return*/, checkResultOrProgress.data]; | ||
const poll = () => __awaiter(this, void 0, void 0, function* () { | ||
runningCheck = yield asyncStartedProcessPromise; | ||
handlePotentialCancellation(); | ||
let checkResultOrProgress; | ||
do { | ||
checkResultOrProgress = yield this.pollForAsyncResult(accessToken, runningCheck, opts); | ||
handlePotentialCancellation(); | ||
if ((0, common_types_1.isProgressResponse)(checkResultOrProgress)) { | ||
if (opts.onProgress) { | ||
opts.onProgress(checkResultOrProgress.progress); | ||
} | ||
yield (0, mixed_utils_1.waitMs)(checkResultOrProgress.progress.retryAfter * 1000); | ||
handlePotentialCancellation(); | ||
} | ||
}); | ||
}); }; | ||
} while ((0, common_types_1.isProgressResponse)(checkResultOrProgress)); | ||
return checkResultOrProgress.data; | ||
}); | ||
return { | ||
promise: Promise.race([poll(), cancelPromise]), | ||
getId: function () { | ||
getId() { | ||
return runningCheck === null || runningCheck === void 0 ? void 0 : runningCheck.data.id; | ||
}, | ||
cancel: cancel, | ||
cancel, | ||
}; | ||
}; | ||
AcrolinxEndpoint.prototype.pollForAsyncResult = function (accessToken_1, check_1) { | ||
return __awaiter(this, arguments, void 0, function (accessToken, check, opts) { | ||
if (opts === void 0) { opts = {}; } | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, this.getJsonFromUrl(check.links.result, accessToken, opts)]; | ||
}); | ||
} | ||
pollForAsyncResult(accessToken_1, check_1) { | ||
return __awaiter(this, arguments, void 0, function* (accessToken, check, opts = {}) { | ||
return this.getJsonFromUrl(check.links.result, accessToken, opts); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.cancelAsyncStartedProcess = function (accessToken_1, process_1) { | ||
return __awaiter(this, arguments, void 0, function (accessToken, process, opts) { | ||
if (opts === void 0) { opts = {}; } | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, this.deleteUrl(process.links.cancel, accessToken, opts)]; | ||
}); | ||
} | ||
cancelAsyncStartedProcess(accessToken_1, process_1) { | ||
return __awaiter(this, arguments, void 0, function* (accessToken, process, opts = {}) { | ||
return this.deleteUrl(process.links.cancel, accessToken, opts); | ||
}); | ||
}; | ||
AcrolinxEndpoint.prototype.deleteUrl = function (url_1, accessToken_1) { | ||
return __awaiter(this, arguments, void 0, function (url, accessToken, opts) { | ||
if (opts === void 0) { opts = {}; } | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, (0, fetch_1.fetchJson)(url, this.props, { | ||
headers: __assign(__assign({}, (0, headers_1.getCommonHeaders)(this.props, accessToken, opts.serviceType)), opts.headers), | ||
method: 'DELETE', | ||
})]; | ||
} | ||
deleteUrl(url_1, accessToken_1) { | ||
return __awaiter(this, arguments, void 0, function* (url, accessToken, opts = {}) { | ||
return (0, fetch_1.fetchJson)(url, this.props, { | ||
headers: Object.assign(Object.assign({}, (0, headers_1.getCommonHeaders)(this.props, accessToken, opts.serviceType)), opts.headers), | ||
method: 'DELETE', | ||
}); | ||
}); | ||
}; | ||
return AcrolinxEndpoint; | ||
}()); | ||
} | ||
} | ||
exports.AcrolinxEndpoint = AcrolinxEndpoint; | ||
function getData(promise) { | ||
return promise.then(function (r) { return r.data; }); | ||
return promise.then((r) => r.data); | ||
} | ||
@@ -519,0 +368,0 @@ function createCheckCanceledByClientError() { |
@@ -26,97 +26,54 @@ "use strict"; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.AIService = void 0; | ||
var index_1 = require("../../index"); | ||
var fetch_1 = require("../../utils/fetch"); | ||
const index_1 = require("../../index"); | ||
const fetch_1 = require("../../utils/fetch"); | ||
/** | ||
* Available in Acrolinx One | ||
*/ | ||
var AIService = /** @class */ (function () { | ||
function AIService(endpoint) { | ||
class AIService { | ||
constructor(endpoint) { | ||
this.endpoint = endpoint; | ||
this.aiServiceBasePath = '/ai-service/api/v1'; | ||
} | ||
AIService.prototype.getAiFeatures = function (accessToken) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, this.endpoint.getJsonFromPath(this.constructFullPath('/tenants/features/ai'), accessToken, { | ||
serviceType: index_1.ServiceType.ACROLINX_ONE, | ||
})]; | ||
getAiFeatures(accessToken) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.endpoint.getJsonFromPath(this.constructFullPath('/tenants/features/ai'), accessToken, { | ||
serviceType: index_1.ServiceType.ACROLINX_ONE, | ||
}); | ||
}); | ||
}; | ||
AIService.prototype.getAIEnabled = function (accessToken) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, this.endpoint.getJsonFromPath(this.constructFullPath('/tenants/feature/ai-enabled?privilege=generate'), accessToken, { | ||
serviceType: index_1.ServiceType.ACROLINX_ONE, | ||
})]; | ||
} | ||
getAIEnabled(accessToken) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.endpoint.getJsonFromPath(this.constructFullPath('/tenants/feature/ai-enabled?privilege=generate'), accessToken, { | ||
serviceType: index_1.ServiceType.ACROLINX_ONE, | ||
}); | ||
}); | ||
}; | ||
AIService.prototype.isAIEnabled = function (accessToken) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var response, _a; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
_b.trys.push([0, 2, , 3]); | ||
return [4 /*yield*/, this.getAIEnabled(accessToken)]; | ||
case 1: | ||
response = _b.sent(); | ||
return [2 /*return*/, response.value && response.userHasPrivilege]; | ||
case 2: | ||
_a = _b.sent(); | ||
return [2 /*return*/, false]; | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
} | ||
isAIEnabled(accessToken) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
const response = yield this.getAIEnabled(accessToken); | ||
return response.value && response.userHasPrivilege; | ||
} | ||
catch (_a) { | ||
return false; | ||
} | ||
}); | ||
}; | ||
AIService.prototype.getAIChatCompletion = function (params, accessToken) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var _a, prompt, internalName, targetUuid; | ||
return __generator(this, function (_b) { | ||
_a = params.issue, prompt = _a.aiRephraseHint, internalName = _a.internalName; | ||
targetUuid = params.targetUuid; | ||
return [2 /*return*/, (0, fetch_1.post)(this.constructFullPath("/ai/chat-completions?count=".concat(params.count, "&issueInternalName=").concat(internalName)), { | ||
prompt: prompt, | ||
targetUuid: targetUuid, | ||
}, {}, this.endpoint.props, accessToken, index_1.ServiceType.ACROLINX_ONE)]; | ||
}); | ||
} | ||
getAIChatCompletion(params, accessToken) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const { aiRephraseHint: prompt, internalName } = params.issue; | ||
const { targetUuid } = params; | ||
return (0, fetch_1.post)(this.constructFullPath(`/ai/chat-completions?count=${params.count}&issueInternalName=${internalName}`), { | ||
prompt, | ||
targetUuid, | ||
}, {}, this.endpoint.props, accessToken, index_1.ServiceType.ACROLINX_ONE); | ||
}); | ||
}; | ||
AIService.prototype.constructFullPath = function (path) { | ||
} | ||
constructFullPath(path) { | ||
return this.aiServiceBasePath + path; | ||
}; | ||
return AIService; | ||
}()); | ||
} | ||
} | ||
exports.AIService = AIService; | ||
//# sourceMappingURL=ai-service.js.map |
@@ -19,3 +19,3 @@ "use strict"; | ||
exports.isAIServiceError = void 0; | ||
var ai_service_types_1 = require("./ai-service.types"); | ||
const ai_service_types_1 = require("./ai-service.types"); | ||
function isAIServiceError(error) { | ||
@@ -22,0 +22,0 @@ return (error && typeof error.message === 'string' && typeof error.code === 'number' && error.errorId in ai_service_types_1.AIServiceErrorTypes); |
@@ -19,22 +19,21 @@ "use strict"; | ||
exports.IntService = exports.integrationServiceDefaultConfig = void 0; | ||
var index_1 = require("../../index"); | ||
const index_1 = require("../../index"); | ||
exports.integrationServiceDefaultConfig = { | ||
activateGetSuggestionReplacement: false, | ||
}; | ||
var IntService = /** @class */ (function () { | ||
function IntService(endpoint) { | ||
class IntService { | ||
constructor(endpoint) { | ||
this.endpoint = endpoint; | ||
this.intServiceBasePath = '/int-service/api/v1'; | ||
} | ||
IntService.prototype.getConfig = function (accessToken) { | ||
getConfig(accessToken) { | ||
return this.endpoint.getJsonFromPath(this.constructFullPath('/config'), accessToken, { | ||
serviceType: index_1.ServiceType.ACROLINX_ONE, | ||
}); | ||
}; | ||
IntService.prototype.constructFullPath = function (path) { | ||
} | ||
constructFullPath(path) { | ||
return this.intServiceBasePath + path; | ||
}; | ||
return IntService; | ||
}()); | ||
} | ||
} | ||
exports.IntService = IntService; | ||
//# sourceMappingURL=int-service.js.map |
@@ -19,3 +19,3 @@ "use strict"; | ||
exports.isSsoSigninOption = exports.getSigninRequestHeaders = exports.AuthorizationType = exports.isSigninSuccessResult = exports.isSigninLinksResult = void 0; | ||
var headers_1 = require("./headers"); | ||
const headers_1 = require("./headers"); | ||
function isSigninLinksResult(signinResult) { | ||
@@ -26,3 +26,3 @@ return !!signinResult.links.interactive; | ||
function isSigninSuccessResult(signinResult) { | ||
var asSigninSuccessResult = signinResult; | ||
const asSigninSuccessResult = signinResult; | ||
return !!(asSigninSuccessResult && asSigninSuccessResult.data && asSigninSuccessResult.data.accessToken); | ||
@@ -37,7 +37,5 @@ } | ||
})(AuthorizationType || (exports.AuthorizationType = AuthorizationType = {})); | ||
function getSigninRequestHeaders(options) { | ||
var _a; | ||
if (options === void 0) { options = {}; } | ||
function getSigninRequestHeaders(options = {}) { | ||
if ('accessToken' in options && options.accessToken) { | ||
return _a = {}, _a[headers_1.HEADER_X_ACROLINX_AUTH] = options.accessToken, _a; | ||
return { [headers_1.HEADER_X_ACROLINX_AUTH]: options.accessToken }; | ||
} | ||
@@ -56,3 +54,3 @@ else if (isSsoSigninOption(options)) { | ||
function isSsoSigninOption(signinOptions) { | ||
var potentialSsoOptions = signinOptions; | ||
const potentialSsoOptions = signinOptions; | ||
return !!(potentialSsoOptions.genericToken && potentialSsoOptions.username); | ||
@@ -59,0 +57,0 @@ } |
@@ -17,13 +17,2 @@ "use strict"; | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -38,52 +27,19 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.put = exports.post = exports.getUrlOfPath = exports.send = exports.fetchJson = exports.fetchWithProps = exports.toJson = exports.handleExpectedTextResponse = exports.handleExpectedJsonResponse = void 0; | ||
var errors_1 = require("../errors"); | ||
var headers_1 = require("../headers"); | ||
const errors_1 = require("../errors"); | ||
const headers_1 = require("../headers"); | ||
// TODO: Simplify as soon as all API Urls wrap the error | ||
function handleExpectedJsonResponse(req, res) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var jsonResult; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!(200 <= res.status && res.status < 300)) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, toJson(req, res)]; | ||
case 1: | ||
jsonResult = _a.sent(); | ||
if (jsonResult.error) { | ||
throw (0, errors_1.createErrorFromFetchResponse)(req, res, jsonResult.error); | ||
} | ||
return [2 /*return*/, jsonResult]; | ||
case 2: return [4 /*yield*/, createErrorFromResponse(req, res)]; | ||
case 3: throw _a.sent(); | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (200 <= res.status && res.status < 300) { | ||
const jsonResult = yield toJson(req, res); | ||
if (jsonResult.error) { | ||
throw (0, errors_1.createErrorFromFetchResponse)(req, res, jsonResult.error); | ||
} | ||
}); | ||
return jsonResult; | ||
} | ||
else { | ||
throw yield createErrorFromResponse(req, res); | ||
} | ||
}); | ||
@@ -93,12 +49,9 @@ } | ||
function handleExpectedTextResponse(req, res) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!(200 <= res.status && res.status < 300)) return [3 /*break*/, 1]; | ||
return [2 /*return*/, res.text()]; | ||
case 1: return [4 /*yield*/, createErrorFromResponse(req, res)]; | ||
case 2: throw _a.sent(); | ||
} | ||
}); | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (200 <= res.status && res.status < 300) { | ||
return res.text(); | ||
} | ||
else { | ||
throw yield createErrorFromResponse(req, res); | ||
} | ||
}); | ||
@@ -108,32 +61,24 @@ } | ||
function createErrorFromResponse(req, res) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var error, jsonError, _a; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
_b.trys.push([0, 2, , 3]); | ||
return [4 /*yield*/, toJson(req, res)]; | ||
case 1: | ||
jsonError = _b.sent(); | ||
if (jsonError.error && typeof jsonError.error === 'object') { | ||
error = (0, errors_1.createErrorFromFetchResponse)(req, res, jsonError.error); | ||
} | ||
else { | ||
error = (0, errors_1.createErrorFromFetchResponse)(req, res, jsonError); | ||
} | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
_a = _b.sent(); | ||
error = (0, errors_1.createErrorFromFetchResponse)(req, res, undefined); | ||
return [3 /*break*/, 3]; | ||
case 3: return [2 /*return*/, error]; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
let error; | ||
try { | ||
const jsonError = yield toJson(req, res); | ||
if (jsonError.error && typeof jsonError.error === 'object') { | ||
error = (0, errors_1.createErrorFromFetchResponse)(req, res, jsonError.error); | ||
} | ||
}); | ||
else { | ||
error = (0, errors_1.createErrorFromFetchResponse)(req, res, jsonError); | ||
} | ||
} | ||
catch (_a) { | ||
error = (0, errors_1.createErrorFromFetchResponse)(req, res, undefined); | ||
} | ||
return error; | ||
}); | ||
} | ||
function toJson(httpRequest, res) { | ||
return res.json().catch(function (e) { | ||
return res.json().catch((e) => { | ||
throw new errors_1.AcrolinxError({ | ||
detail: e.message, | ||
httpRequest: httpRequest, | ||
httpRequest, | ||
title: 'Invalid Json', | ||
@@ -147,31 +92,22 @@ type: errors_1.ErrorType.InvalidJson, | ||
function fetchWithProps(input_1, props_1) { | ||
return __awaiter(this, arguments, void 0, function (input, props, init) { | ||
var fetchFunction, fetchProps, result, error_1; | ||
if (init === void 0) { init = {}; } | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
fetchFunction = props.fetch || fetch; | ||
fetchProps = __assign(__assign(__assign({}, init), { | ||
// Ensure credentials: 'same-origin' in old browsers: https://github.com/github/fetch#sending-cookies | ||
credentials: props.corsWithCredentials ? 'include' : 'same-origin' }), (props.additionalFetchProperties || {})); | ||
if (!props.enableHttpLogging) return [3 /*break*/, 5]; | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
console.log('Fetch', input, init, props.additionalFetchProperties); | ||
return [4 /*yield*/, fetchFunction(input, fetchProps)]; | ||
case 2: | ||
result = _a.sent(); | ||
console.log('Fetched Result', result.status); | ||
return [2 /*return*/, result]; | ||
case 3: | ||
error_1 = _a.sent(); | ||
console.error('Fetch Error', error_1); | ||
throw error_1; | ||
case 4: return [3 /*break*/, 6]; | ||
case 5: return [2 /*return*/, fetchFunction(input, fetchProps)]; | ||
case 6: return [2 /*return*/]; | ||
return __awaiter(this, arguments, void 0, function* (input, props, init = {}) { | ||
const fetchFunction = props.fetch || fetch; | ||
const fetchProps = Object.assign(Object.assign(Object.assign({}, init), { | ||
// Ensure credentials: 'same-origin' in old browsers: https://github.com/github/fetch#sending-cookies | ||
credentials: props.corsWithCredentials ? 'include' : 'same-origin' }), (props.additionalFetchProperties || {})); | ||
if (props.enableHttpLogging) { | ||
try { | ||
console.log('Fetch', input, init, props.additionalFetchProperties); | ||
const result = yield fetchFunction(input, fetchProps); | ||
console.log('Fetched Result', result.status); | ||
return result; | ||
} | ||
}); | ||
catch (error) { | ||
console.error('Fetch Error', error); | ||
throw error; | ||
} | ||
} | ||
else { | ||
return fetchFunction(input, fetchProps); | ||
} | ||
}); | ||
@@ -181,17 +117,13 @@ } | ||
function fetchJson(url_1, props_1) { | ||
return __awaiter(this, arguments, void 0, function (url, props, init) { | ||
var httpRequest; | ||
if (init === void 0) { init = {}; } | ||
return __generator(this, function (_a) { | ||
httpRequest = { | ||
url: url, | ||
method: init.method || 'GET', | ||
}; | ||
return [2 /*return*/, fetchWithProps(url, props, init).then(function (res) { | ||
console.log(res); | ||
return handleExpectedJsonResponse(httpRequest, res); | ||
}, function (error) { | ||
console.log(error); | ||
return (0, errors_1.wrapFetchError)(httpRequest, error); | ||
})]; | ||
return __awaiter(this, arguments, void 0, function* (url, props, init = {}) { | ||
const httpRequest = { | ||
url, | ||
method: init.method || 'GET', | ||
}; | ||
return fetchWithProps(url, props, init).then((res) => { | ||
console.log(res); | ||
return handleExpectedJsonResponse(httpRequest, res); | ||
}, (error) => { | ||
console.log(error); | ||
return (0, errors_1.wrapFetchError)(httpRequest, error); | ||
}); | ||
@@ -202,10 +134,7 @@ }); | ||
function send(method_1, path_1, body_1) { | ||
return __awaiter(this, arguments, void 0, function (method, path, body, headers, props, accessToken, serviceType) { | ||
if (headers === void 0) { headers = {}; } | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, fetchJson(getUrlOfPath(props, path), props, { | ||
body: JSON.stringify(body), | ||
headers: __assign(__assign({}, (0, headers_1.getCommonHeaders)(props, accessToken, serviceType)), headers), | ||
method: method, | ||
})]; | ||
return __awaiter(this, arguments, void 0, function* (method, path, body, headers = {}, props, accessToken, serviceType) { | ||
return fetchJson(getUrlOfPath(props, path), props, { | ||
body: JSON.stringify(body), | ||
headers: Object.assign(Object.assign({}, (0, headers_1.getCommonHeaders)(props, accessToken, serviceType)), headers), | ||
method, | ||
}); | ||
@@ -220,7 +149,4 @@ }); | ||
function post(path_1, body_1) { | ||
return __awaiter(this, arguments, void 0, function (path, body, headers, props, accessToken, serviceType) { | ||
if (headers === void 0) { headers = {}; } | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, send('POST', path, body, headers, props, accessToken, serviceType)]; | ||
}); | ||
return __awaiter(this, arguments, void 0, function* (path, body, headers = {}, props, accessToken, serviceType) { | ||
return send('POST', path, body, headers, props, accessToken, serviceType); | ||
}); | ||
@@ -230,7 +156,4 @@ } | ||
function put(path_1, body_1) { | ||
return __awaiter(this, arguments, void 0, function (path, body, headers, props, accessToken) { | ||
if (headers === void 0) { headers = {}; } | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, send('PUT', path, body, headers, props, accessToken)]; | ||
}); | ||
return __awaiter(this, arguments, void 0, function* (path, body, headers = {}, props, accessToken) { | ||
return send('PUT', path, body, headers, props, accessToken); | ||
}); | ||
@@ -237,0 +160,0 @@ } |
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -22,38 +11,2 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { | ||
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { | ||
if (ar || !(i in from)) { | ||
if (!ar) ar = Array.prototype.slice.call(from, 0, i); | ||
ar[i] = from[i]; | ||
} | ||
} | ||
return to.concat(ar || Array.prototype.slice.call(from)); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -67,4 +20,4 @@ exports.LogBuffer = exports.LogEntryType = void 0; | ||
})(LogEntryType || (exports.LogEntryType = LogEntryType = {})); | ||
var LogBuffer = /** @class */ (function () { | ||
function LogBuffer(acrolinxUrl, config) { | ||
class LogBuffer { | ||
constructor(acrolinxUrl, config) { | ||
this.acrolinxUrl = acrolinxUrl; | ||
@@ -76,3 +29,3 @@ this.buffer = []; | ||
} | ||
LogBuffer.prototype.log = function (logObj) { | ||
log(logObj) { | ||
this.consoleLog(logObj); | ||
@@ -83,19 +36,18 @@ if (this.config.logLevel && this.isLoggable(logObj.type)) { | ||
} | ||
}; | ||
LogBuffer.prototype.consoleLog = function (logObj) { | ||
} | ||
consoleLog(logObj) { | ||
switch (logObj.type) { | ||
case LogEntryType.info: | ||
console.log.apply(console, __spreadArray([logObj.message], logObj.details, false)); | ||
console.log(logObj.message, ...logObj.details); | ||
break; | ||
case LogEntryType.warning: | ||
console.warn.apply(console, __spreadArray([logObj.message], logObj.details, false)); | ||
console.warn(logObj.message, ...logObj.details); | ||
break; | ||
case LogEntryType.error: | ||
console.error.apply(console, __spreadArray([logObj.message], logObj.details, false)); | ||
console.error(logObj.message, ...logObj.details); | ||
break; | ||
} | ||
}; | ||
LogBuffer.prototype.createLoggingConfig = function (config) { | ||
if (config === void 0) { config = {}; } | ||
var defaultConfig = { | ||
} | ||
createLoggingConfig(config = {}) { | ||
const defaultConfig = { | ||
batchSize: 50, | ||
@@ -108,5 +60,5 @@ dispatchInterval: 10000, | ||
}; | ||
return __assign(__assign({}, defaultConfig), config); | ||
}; | ||
LogBuffer.prototype.isLoggable = function (entryType) { | ||
return Object.assign(Object.assign({}, defaultConfig), config); | ||
} | ||
isLoggable(entryType) { | ||
if (this.config.logLevel === null) { | ||
@@ -116,4 +68,4 @@ return false; // Do not log anything if logLevel is null | ||
return this.config.enableCloudLogging && LogEntryType[entryType] <= LogEntryType[this.config.logLevel]; | ||
}; | ||
LogBuffer.prototype.manageBuffer = function (logObj) { | ||
} | ||
manageBuffer(logObj) { | ||
if (logObj.type === LogEntryType.error || this.buffer.length >= this.config.batchSize) { | ||
@@ -125,57 +77,43 @@ void this.flush(); | ||
} | ||
}; | ||
LogBuffer.prototype.flush = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var logsToSend, response, error_1; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (this.buffer.length === 0) { | ||
return [2 /*return*/]; | ||
} | ||
logsToSend = __spreadArray([], this.buffer, true); | ||
this.buffer = []; | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, fetch("".concat(this.acrolinxUrl, "/int-service/api/v1/logs"), { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ | ||
appName: 'sidebar-client-app', | ||
logs: logsToSend, | ||
}), | ||
})]; | ||
case 2: | ||
response = _a.sent(); | ||
if (response.ok) { | ||
console.log('Logs successfully sent to the server'); | ||
this.retries = 0; | ||
} | ||
else { | ||
console.error('Failed to send logs to the server'); | ||
this.handleRetry(logsToSend); | ||
} | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
error_1 = _a.sent(); | ||
console.error('Error sending logs to the server:', error_1); | ||
this.handleRetry(logsToSend); | ||
return [3 /*break*/, 4]; | ||
case 4: return [2 /*return*/]; | ||
} | ||
flush() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (this.buffer.length === 0) { | ||
return; | ||
} | ||
const logsToSend = [...this.buffer]; | ||
this.buffer = []; | ||
try { | ||
const response = yield fetch(`${this.acrolinxUrl}/int-service/api/v1/logs`, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ | ||
appName: 'sidebar-client-app', | ||
logs: logsToSend, | ||
}), | ||
}); | ||
if (response.ok) { | ||
console.log('Logs successfully sent to the server'); | ||
this.retries = 0; | ||
} | ||
}); | ||
else { | ||
console.error('Failed to send logs to the server'); | ||
this.handleRetry(logsToSend); | ||
} | ||
} | ||
catch (error) { | ||
console.error('Error sending logs to the server:', error); | ||
this.handleRetry(logsToSend); | ||
} | ||
}); | ||
}; | ||
LogBuffer.prototype.handleRetry = function (logsToSend) { | ||
var _a; | ||
var _this = this; | ||
} | ||
handleRetry(logsToSend) { | ||
if (this.retries < this.config.maxRetries) { | ||
(_a = this.buffer).unshift.apply(_a, logsToSend); | ||
this.buffer.unshift(...logsToSend); | ||
this.retries++; | ||
var delay = this.getAdaptiveDelay(); | ||
setTimeout(function () { | ||
void _this.flush(); | ||
const delay = this.getAdaptiveDelay(); | ||
setTimeout(() => { | ||
void this.flush(); | ||
}, delay); | ||
@@ -187,5 +125,4 @@ } | ||
} | ||
}; | ||
LogBuffer.prototype.scheduleFlush = function () { | ||
var _this = this; | ||
} | ||
scheduleFlush() { | ||
if (this.buffer.length >= this.config.batchSize) { | ||
@@ -195,17 +132,16 @@ void this.flush(); | ||
else if (!this.timer) { | ||
var delay = this.getAdaptiveDelay(); | ||
this.timer = setTimeout(function () { | ||
void _this.flush(); | ||
_this.timer = null; | ||
const delay = this.getAdaptiveDelay(); | ||
this.timer = setTimeout(() => { | ||
void this.flush(); | ||
this.timer = null; | ||
}, delay); | ||
} | ||
}; | ||
LogBuffer.prototype.getAdaptiveDelay = function () { | ||
var baseDelay = this.config.dispatchInterval; | ||
var adaptiveDelay = baseDelay * Math.pow(2, this.retries); | ||
} | ||
getAdaptiveDelay() { | ||
const baseDelay = this.config.dispatchInterval; | ||
const adaptiveDelay = baseDelay * Math.pow(2, this.retries); | ||
return Math.min(adaptiveDelay, this.config.maxRetries * this.config.retryDelay); | ||
}; | ||
return LogBuffer; | ||
}()); | ||
} | ||
} | ||
exports.LogBuffer = LogBuffer; | ||
//# sourceMappingURL=logging-buffer.js.map |
@@ -20,8 +20,4 @@ "use strict"; | ||
/* tslint:disable:no-console */ | ||
var LOGGING_ENABLED = false; | ||
function log() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
let LOGGING_ENABLED = false; | ||
function log(...args) { | ||
if (!LOGGING_ENABLED) { | ||
@@ -31,3 +27,3 @@ return; | ||
try { | ||
console.log.apply(console, args); | ||
console.log(...args); | ||
} | ||
@@ -39,7 +35,3 @@ catch (e) { | ||
exports.log = log; | ||
function error() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
function error(...args) { | ||
if (!LOGGING_ENABLED) { | ||
@@ -49,3 +41,3 @@ return; | ||
try { | ||
console.error.apply(console, args); | ||
console.error(...args); | ||
} | ||
@@ -52,0 +44,0 @@ catch (e) { |
@@ -20,5 +20,5 @@ "use strict"; | ||
function waitMs(ms) { | ||
return new Promise(function (resolve) { return setTimeout(resolve, ms); }); | ||
return new Promise((resolve) => setTimeout(resolve, ms)); | ||
} | ||
exports.waitMs = waitMs; | ||
//# sourceMappingURL=mixed-utils.js.map |
@@ -11,42 +11,15 @@ "use strict"; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ACROLINX_DEV_SIGNATURE = void 0; | ||
var src_1 = require("../../src"); | ||
var dotenv = require("dotenv"); | ||
const src_1 = require("../../src"); | ||
const dotenv = require("dotenv"); | ||
require("cross-fetch/polyfill"); | ||
var ai_service_1 = require("../../src/services/ai-service/ai-service"); | ||
const ai_service_1 = require("../../src/services/ai-service/ai-service"); | ||
dotenv.config(); | ||
var TEST_SERVER_URL = process.env.TEST_SERVER_URL || ''; /* Add here your own test server URL */ | ||
var ACROLINX_API_TOKEN = process.env.ACROLINX_API_TOKEN || ''; | ||
const TEST_SERVER_URL = process.env.TEST_SERVER_URL || ''; /* Add here your own test server URL */ | ||
const ACROLINX_API_TOKEN = process.env.ACROLINX_API_TOKEN || ''; | ||
exports.ACROLINX_DEV_SIGNATURE = process.env.ACROLINX_DEV_SIGNATURE; | ||
function createEndpoint(acrolinxUrl) { | ||
return new src_1.AcrolinxEndpoint({ | ||
acrolinxUrl: acrolinxUrl, | ||
acrolinxUrl, | ||
enableHttpLogging: true, | ||
@@ -60,64 +33,37 @@ client: { | ||
} | ||
describe('Acrolinx One E2E Tests', function () { | ||
var endpoint; | ||
beforeEach(function () { | ||
describe('Acrolinx One E2E Tests', () => { | ||
let endpoint; | ||
beforeEach(() => { | ||
endpoint = createEndpoint(TEST_SERVER_URL); | ||
}); | ||
describe.skip('AI Service Integration Tests', function () { | ||
describe.skip('AI Service Integration Tests', () => { | ||
// This tests requires valid keycloak access token | ||
it('getAiFeatures returns whether certain AI features are enabled', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var aiService, aiFeatures; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
aiService = new ai_service_1.AIService(endpoint); | ||
return [4 /*yield*/, aiService.getAiFeatures(ACROLINX_API_TOKEN)]; | ||
case 1: | ||
aiFeatures = _a.sent(); | ||
expect(typeof aiFeatures.ai).toEqual('boolean'); | ||
expect(typeof aiFeatures.aiAssistant).toEqual('boolean'); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('check if the ai service is activated', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var aiService, aiResult; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
aiService = new ai_service_1.AIService(endpoint); | ||
return [4 /*yield*/, aiService.getAIEnabled(ACROLINX_API_TOKEN)]; | ||
case 1: | ||
aiResult = _a.sent(); | ||
expect(aiResult.tenant).toBeDefined(); | ||
expect(aiResult.value).toBeDefined(); | ||
expect(aiResult.userHasPrivilege).toBeDefined(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('get a chat completion from the ai service', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var aiService, aiResult; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
aiService = new ai_service_1.AIService(endpoint); | ||
return [4 /*yield*/, aiService.getAIChatCompletion({ | ||
issue: { | ||
aiRephraseHint: '[{"role": "system", "content": "Rewrite this content so that it mentions between 3 and 5 of the seven dwarfs"}]', | ||
internalName: 'simplify', | ||
}, | ||
count: 1, | ||
targetUuid: '123e4567-e89b-12d3-a456-426614174000', | ||
}, ACROLINX_API_TOKEN)]; | ||
case 1: | ||
aiResult = _a.sent(); | ||
expect(aiResult.response).toBeDefined(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }, 100000); | ||
it('getAiFeatures returns whether certain AI features are enabled', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const aiService = new ai_service_1.AIService(endpoint); | ||
const aiFeatures = yield aiService.getAiFeatures(ACROLINX_API_TOKEN); | ||
expect(typeof aiFeatures.ai).toEqual('boolean'); | ||
expect(typeof aiFeatures.aiAssistant).toEqual('boolean'); | ||
})); | ||
it('check if the ai service is activated', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const aiService = new ai_service_1.AIService(endpoint); | ||
const aiResult = yield aiService.getAIEnabled(ACROLINX_API_TOKEN); | ||
expect(aiResult.tenant).toBeDefined(); | ||
expect(aiResult.value).toBeDefined(); | ||
expect(aiResult.userHasPrivilege).toBeDefined(); | ||
})); | ||
it('get a chat completion from the ai service', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const aiService = new ai_service_1.AIService(endpoint); | ||
const aiResult = yield aiService.getAIChatCompletion({ | ||
issue: { | ||
aiRephraseHint: '[{"role": "system", "content": "Rewrite this content so that it mentions between 3 and 5 of the seven dwarfs"}]', | ||
internalName: 'simplify', | ||
}, | ||
count: 1, | ||
targetUuid: '123e4567-e89b-12d3-a456-426614174000', | ||
}, ACROLINX_API_TOKEN); | ||
expect(aiResult.response).toBeDefined(); | ||
}), 100000); | ||
}); | ||
describe('Logging Tests', function () { | ||
it('initialize logging', function () { | ||
describe('Logging Tests', () => { | ||
it('initialize logging', () => { | ||
expect(endpoint.loggingBuffer).toBeDefined(); | ||
@@ -124,0 +70,0 @@ }); |
@@ -19,7 +19,7 @@ "use strict"; | ||
exports.DUMMY_CHECK_RESULT = exports.DUMMY_CAPABILITIES = exports.DUMMY_AI_REWRITE_CONTEXT = void 0; | ||
var src_1 = require("../../src"); | ||
var capabilities_1 = require("../../src/capabilities"); | ||
var check_1 = require("../../src/check"); | ||
var GOAL_VOICE_ID = 'voice.readability'; | ||
var GOAL_TERM_ID = 'term.unsuitable'; | ||
const src_1 = require("../../src"); | ||
const capabilities_1 = require("../../src/capabilities"); | ||
const check_1 = require("../../src/check"); | ||
const GOAL_VOICE_ID = 'voice.readability'; | ||
const GOAL_TERM_ID = 'term.unsuitable'; | ||
exports.DUMMY_AI_REWRITE_CONTEXT = [ | ||
@@ -193,3 +193,3 @@ { | ||
}; | ||
var ENVIRONMENT_HASH = 'XVYQZVyCoFOr1TDeyXuMgg=='; | ||
const ENVIRONMENT_HASH = 'XVYQZVyCoFOr1TDeyXuMgg=='; | ||
exports.DUMMY_CHECK_RESULT = { | ||
@@ -260,3 +260,8 @@ id: '153', | ||
displayNameHtml: 'Use Chicago style for the title case?', | ||
guidanceHtml: "<div class=\"shortHelp\" lang=\"en\" xml:lang=\"en\">\n<p>According to\n the <q>Chicago Manual of Style</q>, here's how you write titles:</p>\n<ul>\n <li>Capitalize the first word and the last word.</li>\n<li>Capitalize all \"main\" words.</li>\n <li>Don't capitalize articles and conjunctions (example: <q>a</q>, <q>and</q>).</li>\n <li>Don't capitalize prepositions independent of their length (example: <q>about</q>, <q>around</q>).</li>\n </ul>\n</div>", | ||
guidanceHtml: `<div class="shortHelp" lang="en" xml:lang="en">\n<p>According to | ||
the <q>Chicago Manual of Style</q>, here's how you write titles:</p>\n<ul> | ||
<li>Capitalize the first word and the last word.</li>\n<li>Capitalize all "main" words.</li> | ||
<li>Don't capitalize articles and conjunctions (example: <q>a</q>, <q>and</q>).</li> | ||
<li>Don't capitalize prepositions independent of their length (example: <q>about</q>, <q>around</q>).</li> | ||
</ul>\n</div>`, | ||
displaySurface: 'zentense', | ||
@@ -329,3 +334,5 @@ positionalInformation: { | ||
displayNameHtml: '<b>Illegal sublanguage variant</b> of preferred term', | ||
guidanceHtml: "<div class=\"guidance term\">\n\t<b>Domains</b>\n\t\t\t<br/><i>Switches</i>\n\t\t\t\t\t<br/>\n \t\t<b>Note</b>\n\t\t<br/>\n\t\tUse 'please' in presale materials only. Do NOT use 'please'\n in postsale material.\n\t</div>\n", | ||
guidanceHtml: `<div class="guidance term">\n\t<b>Domains</b>\n\t\t\t<br/><i>Switches</i>\n\t\t\t\t\t<br/> | ||
\t\t<b>Note</b>\n\t\t<br/>\n\t\tUse 'please' in presale materials only. Do NOT use 'please' | ||
in postsale material.\n\t</div>\n`, | ||
displaySurface: 'Please', | ||
@@ -332,0 +339,0 @@ positionalInformation: { |
@@ -17,21 +17,10 @@ "use strict"; | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.CheckServiceMock = exports.Check = void 0; | ||
var _ = require("lodash"); | ||
var dummy_data_1 = require("./dummy-data"); | ||
var mocked_errors_1 = require("./mocked-errors"); | ||
var CHECK_TIME_MS = 10 * 1000; | ||
var Check = /** @class */ (function () { | ||
function Check(request) { | ||
const _ = require("lodash"); | ||
const dummy_data_1 = require("./dummy-data"); | ||
const mocked_errors_1 = require("./mocked-errors"); | ||
const CHECK_TIME_MS = 10 * 1000; | ||
class Check { | ||
constructor(request) { | ||
this.request = request; | ||
@@ -41,14 +30,14 @@ this.id = _.uniqueId('check-id-'); | ||
} | ||
Check.prototype.getCheckingResult = function (acrolinxUrl) { | ||
var elapsedTimeMs = Date.now() - this.startTime; | ||
getCheckingResult(acrolinxUrl) { | ||
const elapsedTimeMs = Date.now() - this.startTime; | ||
if (elapsedTimeMs < CHECK_TIME_MS) { | ||
var percent = Math.min((elapsedTimeMs / CHECK_TIME_MS) * 100, 100); | ||
const percent = Math.min((elapsedTimeMs / CHECK_TIME_MS) * 100, 100); | ||
return { | ||
progress: { | ||
percent: percent, | ||
message: "Still working ".concat(percent, "%"), | ||
percent, | ||
message: `Still working ${percent}%`, | ||
retryAfter: 1, | ||
}, | ||
links: { | ||
poll: "".concat(acrolinxUrl, "/api/v1/checking/checks/").concat(this.id), | ||
poll: `${acrolinxUrl}/api/v1/checking/checks/${this.id}`, | ||
}, | ||
@@ -58,18 +47,16 @@ }; | ||
else { | ||
return { data: __assign(__assign({}, dummy_data_1.DUMMY_CHECK_RESULT), { id: this.id }), links: {} }; | ||
return { data: Object.assign(Object.assign({}, dummy_data_1.DUMMY_CHECK_RESULT), { id: this.id }), links: {} }; | ||
} | ||
}; | ||
return Check; | ||
}()); | ||
} | ||
} | ||
exports.Check = Check; | ||
var CheckServiceMock = /** @class */ (function () { | ||
function CheckServiceMock(acrolinxUrl) { | ||
class CheckServiceMock { | ||
constructor(acrolinxUrl) { | ||
this.acrolinxUrl = acrolinxUrl; | ||
this.checks = []; | ||
} | ||
CheckServiceMock.prototype.getRoutes = function () { | ||
var _this = this; | ||
getRoutes() { | ||
return [ | ||
{ | ||
handler: function () { return _this.getCheckingCapabilities(); }, | ||
handler: () => this.getCheckingCapabilities(), | ||
method: 'GET', | ||
@@ -79,3 +66,3 @@ path: /api\/v1\/checking\/capabilities$/, | ||
{ | ||
handler: function (_args, opts) { return _this.submitCheck(opts); }, | ||
handler: (_args, opts) => this.submitCheck(opts), | ||
method: 'POST', | ||
@@ -85,3 +72,3 @@ path: /api\/v1\/checking\/checks$/, | ||
{ | ||
handler: function (args) { return _this.getCheckResult(args[1]); }, | ||
handler: (args) => this.getCheckResult(args[1]), | ||
method: 'GET', | ||
@@ -91,8 +78,8 @@ path: /api\/v1\/checking\/checks\/(.*)/, | ||
]; | ||
}; | ||
CheckServiceMock.prototype.getCheckingCapabilities = function () { | ||
} | ||
getCheckingCapabilities() { | ||
return { data: dummy_data_1.DUMMY_CAPABILITIES, links: {} }; | ||
}; | ||
CheckServiceMock.prototype.getCheckResult = function (checkId) { | ||
var check = _.find(this.checks, { id: checkId }); | ||
} | ||
getCheckResult(checkId) { | ||
const check = _.find(this.checks, { id: checkId }); | ||
if (!check) { | ||
@@ -102,5 +89,5 @@ return mocked_errors_1.NOT_FOUND_CHECK_ID; | ||
return check.getCheckingResult(this.acrolinxUrl); | ||
}; | ||
CheckServiceMock.prototype.submitCheck = function (opts) { | ||
var check = new Check(JSON.parse(opts.body)); | ||
} | ||
submitCheck(opts) { | ||
const check = new Check(JSON.parse(opts.body)); | ||
this.checks.push(check); | ||
@@ -110,10 +97,9 @@ return { | ||
links: { | ||
result: this.acrolinxUrl + "/api/v1/checking/checks/".concat(check.id), | ||
cancel: this.acrolinxUrl + "/api/v1/checking/checks/".concat(check.id), | ||
result: this.acrolinxUrl + `/api/v1/checking/checks/${check.id}`, | ||
cancel: this.acrolinxUrl + `/api/v1/checking/checks/${check.id}`, | ||
}, | ||
}; | ||
}; | ||
return CheckServiceMock; | ||
}()); | ||
} | ||
} | ||
exports.CheckServiceMock = CheckServiceMock; | ||
//# sourceMappingURL=mock-server-checking.js.map |
@@ -26,85 +26,49 @@ "use strict"; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/* tslint:disable:no-console */ | ||
var parse = require("co-body"); | ||
var http = require("http"); | ||
var mock_server_1 = require("./mock-server"); | ||
var PORT = 3000; | ||
var serverMock = new mock_server_1.AcrolinxServerMock('http://0.0.0.0:' + PORT); | ||
const parse = require("co-body"); | ||
const http = require("http"); | ||
const mock_server_1 = require("./mock-server"); | ||
const PORT = 3000; | ||
const serverMock = new mock_server_1.AcrolinxServerMock('http://0.0.0.0:' + PORT); | ||
http | ||
// eslint-disable-next-line @typescript-eslint/no-misused-promises | ||
.createServer(function (req, res) { return __awaiter(void 0, void 0, void 0, function () { | ||
var allowedHeaders, body, mockResponse, headers, contentType; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
res.setHeader('Access-Control-Allow-Origin', '*'); | ||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS'); | ||
allowedHeaders = req.headers['access-control-request-headers'] || ''; | ||
res.setHeader('Access-Control-Allow-Headers', allowedHeaders); | ||
if (req.method === 'OPTIONS') { | ||
// CORS preflight request | ||
res.end(); | ||
return [2 /*return*/]; | ||
} | ||
return [4 /*yield*/, parse.json(req)]; | ||
case 1: | ||
body = _a.sent(); | ||
mockResponse = serverMock.handleFetchRequest(req.url, { | ||
method: req.method, | ||
headers: req.headers, | ||
body: JSON.stringify(body), | ||
}); | ||
res.statusCode = mockResponse.status || 200; | ||
if (mockResponse.body) { | ||
headers = mockResponse.headers; | ||
contentType = (headers && headers['Content-Type']) || 'application/json'; | ||
// TODO: Headers, retryAfter | ||
res.setHeader('Content-Type', contentType); | ||
if (contentType === 'application/json') { | ||
res.write(JSON.stringify(mockResponse.body, null, 2)); | ||
} | ||
else { | ||
res.write(mockResponse.body); | ||
} | ||
} | ||
else { | ||
res.write(JSON.stringify(mockResponse)); | ||
} | ||
res.end(); | ||
return [2 /*return*/]; | ||
.createServer((req, res) => __awaiter(void 0, void 0, void 0, function* () { | ||
res.setHeader('Access-Control-Allow-Origin', '*'); | ||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS'); | ||
const allowedHeaders = req.headers['access-control-request-headers'] || ''; | ||
res.setHeader('Access-Control-Allow-Headers', allowedHeaders); | ||
if (req.method === 'OPTIONS') { | ||
// CORS preflight request | ||
res.end(); | ||
return; | ||
} | ||
const body = yield parse.json(req); | ||
const mockResponse = serverMock.handleFetchRequest(req.url, { | ||
method: req.method, | ||
headers: req.headers, | ||
body: JSON.stringify(body), | ||
}); | ||
res.statusCode = mockResponse.status || 200; | ||
if (mockResponse.body) { | ||
const headers = mockResponse.headers; | ||
const contentType = (headers && headers['Content-Type']) || 'application/json'; | ||
// TODO: Headers, retryAfter | ||
res.setHeader('Content-Type', contentType); | ||
if (contentType === 'application/json') { | ||
res.write(JSON.stringify(mockResponse.body, null, 2)); | ||
} | ||
}); | ||
}); }) | ||
.listen(PORT, function () { | ||
console.log("server start at port ".concat(PORT)); | ||
console.log("Try \"http://localhost:".concat(PORT, "/iq/services/v3/rest/core/serverVersion\"")); | ||
else { | ||
res.write(mockResponse.body); | ||
} | ||
} | ||
else { | ||
res.write(JSON.stringify(mockResponse)); | ||
} | ||
res.end(); | ||
})) | ||
.listen(PORT, () => { | ||
console.log(`server start at port ${PORT}`); | ||
console.log(`Try "http://localhost:${PORT}/iq/services/v3/rest/core/serverVersion"`); | ||
}); | ||
//# sourceMappingURL=mock-server-http.js.map |
@@ -17,36 +17,16 @@ "use strict"; | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { | ||
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { | ||
if (ar || !(i in from)) { | ||
if (!ar) ar = Array.prototype.slice.call(from, 0, i); | ||
ar[i] = from[i]; | ||
} | ||
} | ||
return to.concat(ar || Array.prototype.slice.call(from)); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.restoreOriginalFetch = exports.mockBrokenJsonServer = exports.mockAcrolinxServer = exports.AcrolinxServerMock = exports.SsoMockMode = exports.SSO_GENERIC_TOKEN = exports.ALLOWED_CLIENT_SIGNATURES = exports.DUMMY_INTERACTIVE_LINK_TIMEOUT = exports.DUMMY_RETRY_AFTER = exports.DUMMY_USER_NAME = exports.DUMMY_USER_ID = exports.DUMMY_ACCESS_TOKEN = exports.DUMMY_SIGNIN_LINK_PATH_INTERACTIVE = exports.SIGNIN_URL_EXPIRED_ERROR = void 0; | ||
/* tslint:disable:no-console object-literal-sort-keys */ | ||
var fetchMock = require("fetch-mock"); | ||
var _ = require("lodash"); | ||
var errors_1 = require("../../src/errors"); | ||
var headers_1 = require("../../src/headers"); | ||
var index_1 = require("../../src/index"); | ||
var signin_1 = require("../../src/signin"); | ||
var mock_server_checking_1 = require("./mock-server-checking"); | ||
var mocked_errors_1 = require("./mocked-errors"); | ||
const fetchMock = require("fetch-mock"); | ||
const _ = require("lodash"); | ||
const errors_1 = require("../../src/errors"); | ||
const headers_1 = require("../../src/headers"); | ||
const index_1 = require("../../src/index"); | ||
const signin_1 = require("../../src/signin"); | ||
const mock_server_checking_1 = require("./mock-server-checking"); | ||
const mocked_errors_1 = require("./mocked-errors"); | ||
Object.defineProperty(exports, "SIGNIN_URL_EXPIRED_ERROR", { enumerable: true, get: function () { return mocked_errors_1.SIGNIN_URL_EXPIRED_ERROR; } }); | ||
exports.DUMMY_SIGNIN_LINK_PATH_INTERACTIVE = '/signin-ui/'; | ||
var DUMMY_SIGNIN_LINK_PATH_POLL = '/api/v1/auth/sign-ins/'; | ||
const DUMMY_SIGNIN_LINK_PATH_POLL = '/api/v1/auth/sign-ins/'; | ||
exports.DUMMY_ACCESS_TOKEN = 'dummyAccessToken'; | ||
@@ -63,3 +43,3 @@ exports.DUMMY_USER_ID = 'dummyUserId'; | ||
function isAcrolinxApiError(o) { | ||
var potentialAcroApiError = o; | ||
const potentialAcroApiError = o; | ||
return !!(potentialAcroApiError.status && potentialAcroApiError.type && potentialAcroApiError.title); | ||
@@ -79,5 +59,4 @@ } | ||
})(SsoMockMode || (exports.SsoMockMode = SsoMockMode = {})); | ||
var AcrolinxServerMock = /** @class */ (function () { | ||
function AcrolinxServerMock(acrolinxUrl) { | ||
var _this = this; | ||
class AcrolinxServerMock { | ||
constructor(acrolinxUrl) { | ||
this.acrolinxUrl = acrolinxUrl; | ||
@@ -90,36 +69,34 @@ this.requests = []; | ||
// eslint-disable-next-line sonarjs/cognitive-complexity | ||
this.handleFetchRequest = function (url, optsArg) { | ||
if (optsArg === void 0) { optsArg = {}; } | ||
var opts = __assign(__assign({ method: 'GET' }, optsArg), { headers: (optsArg.headers || {}) }); | ||
_this.requests.push({ opts: opts, url: url }); | ||
var acrolinxClientHeader = getHeader(optsArg, headers_1.HEADER_X_ACROLINX_CLIENT); | ||
this.handleFetchRequest = (url, optsArg = {}) => { | ||
const opts = Object.assign(Object.assign({ method: 'GET' }, optsArg), { headers: (optsArg.headers || {}) }); | ||
this.requests.push({ opts, url }); | ||
const acrolinxClientHeader = getHeader(optsArg, headers_1.HEADER_X_ACROLINX_CLIENT); | ||
if (acrolinxClientHeader) { | ||
var _a = acrolinxClientHeader.split(';').map(function (s) { return s.trim(); }), signature = _a[0], version = _a[1]; | ||
const [signature, version] = acrolinxClientHeader.split(';').map((s) => s.trim()); | ||
if (!signature || !version) { | ||
return _this.createAcrolinxApiErrorResponse(mocked_errors_1.CLIENT_SIGNATURE_MISSING); | ||
return this.createAcrolinxApiErrorResponse(mocked_errors_1.CLIENT_SIGNATURE_MISSING); | ||
} | ||
if (!_.includes(exports.ALLOWED_CLIENT_SIGNATURES, signature)) { | ||
return _this.createAcrolinxApiErrorResponse(__assign(__assign({}, mocked_errors_1.CLIENT_SIGNATURE_INVALID), { title: signature })); | ||
return this.createAcrolinxApiErrorResponse(Object.assign(Object.assign({}, mocked_errors_1.CLIENT_SIGNATURE_INVALID), { title: signature })); | ||
} | ||
} | ||
else if (_.includes(url, 'api')) { | ||
return _this.createAcrolinxApiErrorResponse(mocked_errors_1.CLIENT_SIGNATURE_MISSING); | ||
return this.createAcrolinxApiErrorResponse(mocked_errors_1.CLIENT_SIGNATURE_MISSING); | ||
} | ||
if (_.includes(url, '/api/') && !_.includes(url, '/auth/')) { | ||
var token = getHeader(opts, headers_1.HEADER_X_ACROLINX_AUTH); | ||
const token = getHeader(opts, headers_1.HEADER_X_ACROLINX_AUTH); | ||
if (!token) { | ||
console.error('Missing Token', token); | ||
return _this.createAcrolinxApiErrorResponse(mocked_errors_1.AUTH_TOKEN_MISSING); | ||
return this.createAcrolinxApiErrorResponse(mocked_errors_1.AUTH_TOKEN_MISSING); | ||
} | ||
else if (token !== exports.DUMMY_ACCESS_TOKEN) { | ||
console.error('Invalid Token', token); | ||
return _this.createAcrolinxApiErrorResponse(mocked_errors_1.AUTH_TOKEN_INVALID); | ||
return this.createAcrolinxApiErrorResponse(mocked_errors_1.AUTH_TOKEN_INVALID); | ||
} | ||
} | ||
for (var _i = 0, _b = _this.routes; _i < _b.length; _i++) { | ||
var route = _b[_i]; | ||
var matches = url.match(route.path); | ||
for (const route of this.routes) { | ||
const matches = url.match(route.path); | ||
if (matches && opts.method === route.method) { | ||
try { | ||
var handlerResult = route.handler(matches, opts); | ||
const handlerResult = route.handler(matches, opts); | ||
if (isMockResponseObject(handlerResult)) { | ||
@@ -132,17 +109,17 @@ return handlerResult; | ||
else { | ||
return _this.returnResponse(handlerResult); | ||
return this.returnResponse(handlerResult); | ||
} | ||
} | ||
catch (error) { | ||
return { body: { error: error }, status: 500 }; | ||
return { body: { error }, status: 500 }; | ||
} | ||
} | ||
} | ||
console.log("FakeServer can not handle url \"".concat(url, "\""), opts); | ||
return _this.createAcrolinxApiErrorResponse({ status: 404 }); | ||
console.log(`FakeServer can not handle url "${url}"`, opts); | ||
return this.createAcrolinxApiErrorResponse({ status: 404 }); | ||
}; | ||
this.checkService = new mock_server_checking_1.CheckServiceMock(acrolinxUrl); | ||
this.routes = __spreadArray([ | ||
this.routes = [ | ||
{ | ||
handler: function (_args, opts) { return _this.signin(opts); }, | ||
handler: (_args, opts) => this.signin(opts), | ||
method: 'POST', | ||
@@ -152,3 +129,3 @@ path: /api\/v1\/auth\/sign-ins$/, | ||
{ | ||
handler: function (args, opts) { return _this.pollForSignin(args[1], opts); }, | ||
handler: (args, opts) => this.pollForSignin(args[1], opts), | ||
method: 'GET', | ||
@@ -158,3 +135,3 @@ path: /api\/v1\/auth\/sign-ins\/(.*)$/, | ||
{ | ||
handler: function (args, opts) { return _this.returnFakeSigninPage(args[1], opts); }, | ||
handler: (args, opts) => this.returnFakeSigninPage(args[1], opts), | ||
method: 'GET', | ||
@@ -164,3 +141,3 @@ path: /signin-ui\/(.*)$/, | ||
{ | ||
handler: function (args, opts) { return _this.returnConfirmSigninPage(args[1], opts); }, | ||
handler: (args, opts) => this.returnConfirmSigninPage(args[1], opts), | ||
method: 'POST', | ||
@@ -170,3 +147,3 @@ path: /signin-ui\/(.*)\/confirm$/, | ||
{ | ||
handler: function (args, opts) { return _this.returnSigninDeletedPage(args[1], opts); }, | ||
handler: (args, opts) => this.returnSigninDeletedPage(args[1], opts), | ||
method: 'POST', | ||
@@ -176,11 +153,11 @@ path: /signin-ui\/(.*)\/delete/, | ||
{ | ||
handler: function (args, opts) { return _this.getPlatformNotifications(args[1], opts); }, | ||
handler: (args, opts) => this.getPlatformNotifications(args[1], opts), | ||
method: 'GET', | ||
path: /api\/v1\/broadcasts\/platform-notifications\/(.*)$/, | ||
} | ||
], this.checkService.getRoutes(), true); | ||
}, | ||
...this.checkService.getRoutes(), | ||
]; | ||
this.signinIds.dummy = {}; | ||
} | ||
AcrolinxServerMock.prototype.fakeSignIn = function (authorizationType, signinId) { | ||
if (authorizationType === void 0) { authorizationType = signin_1.AuthorizationType.ACROLINX_SIGN_IN; } | ||
fakeSignIn(authorizationType = signin_1.AuthorizationType.ACROLINX_SIGN_IN, signinId) { | ||
if (signinId) { | ||
@@ -190,16 +167,16 @@ this.signinIds[signinId].authorizationType = authorizationType; | ||
else { | ||
_.forEach(this.signinIds, function (signinState) { | ||
_.forEach(this.signinIds, (signinState) => { | ||
signinState.authorizationType = authorizationType; | ||
}); | ||
} | ||
}; | ||
AcrolinxServerMock.prototype.enableSSO = function (ssoMockMode) { | ||
} | ||
enableSSO(ssoMockMode) { | ||
this.ssoMockMode = ssoMockMode; | ||
}; | ||
AcrolinxServerMock.prototype.deleteSigninPollUrl = function (url) { | ||
var signinId = url.substr(url.lastIndexOf('/') + 1); | ||
} | ||
deleteSigninPollUrl(url) { | ||
const signinId = url.substr(url.lastIndexOf('/') + 1); | ||
this.deleteSignin(signinId); | ||
}; | ||
AcrolinxServerMock.prototype.pollForSignin = function (signinId, _opts) { | ||
var signinState = this.signinIds[signinId]; | ||
} | ||
pollForSignin(signinId, _opts) { | ||
const signinState = this.signinIds[signinId]; | ||
if (!signinState) { | ||
@@ -221,13 +198,13 @@ return this.createAcrolinxApiErrorResponse(mocked_errors_1.SIGNIN_URL_EXPIRED_ERROR); | ||
} | ||
}; | ||
AcrolinxServerMock.prototype.deleteSignin = function (signinId) { | ||
} | ||
deleteSignin(signinId) { | ||
delete this.signinIds[signinId]; | ||
}; | ||
AcrolinxServerMock.prototype.returnResponse = function (body) { | ||
return { body: body }; | ||
}; | ||
AcrolinxServerMock.prototype.getPlatformNotifications = function (_sinceTimeStamp, _opts) { | ||
} | ||
returnResponse(body) { | ||
return { body }; | ||
} | ||
getPlatformNotifications(_sinceTimeStamp, _opts) { | ||
return { data: { platformNotifications: [], requestTimeInMilliseconds: Date.now() }, links: {} }; | ||
}; | ||
AcrolinxServerMock.prototype.signin = function (opts) { | ||
} | ||
signin(opts) { | ||
if (this.simulatedError.signin) { | ||
@@ -249,4 +226,4 @@ throw this.simulatedError.signin; | ||
} | ||
var baseUrl = getHeader(opts, headers_1.HEADER_X_ACROLINX_BASE_URL) || this.acrolinxUrl; | ||
var id = _.uniqueId('signin-id-'); | ||
const baseUrl = getHeader(opts, headers_1.HEADER_X_ACROLINX_BASE_URL) || this.acrolinxUrl; | ||
const id = _.uniqueId('signin-id-'); | ||
this.signinIds[id] = {}; | ||
@@ -260,5 +237,5 @@ return { | ||
}; | ||
}; | ||
AcrolinxServerMock.prototype.createAcrolinxApiErrorResponse = function (apiError) { | ||
var fullApiError = __assign({ detail: 'DummyErrorDetail', status: 400, title: 'DummyErrorTitle', type: 'DummyErrorType' }, apiError); | ||
} | ||
createAcrolinxApiErrorResponse(apiError) { | ||
const fullApiError = Object.assign({ detail: 'DummyErrorDetail', status: 400, title: 'DummyErrorTitle', type: 'DummyErrorType' }, apiError); | ||
return { | ||
@@ -268,13 +245,12 @@ body: fullApiError, | ||
}; | ||
}; | ||
AcrolinxServerMock.prototype.createLoginSuccessResult = function (authorizedUsing, username) { | ||
if (username === void 0) { username = exports.DUMMY_USER_NAME; } | ||
} | ||
createLoginSuccessResult(authorizedUsing, username = exports.DUMMY_USER_NAME) { | ||
return { | ||
data: { | ||
accessToken: exports.DUMMY_ACCESS_TOKEN, | ||
authorizedUsing: authorizedUsing, | ||
authorizedUsing, | ||
links: {}, | ||
user: { | ||
id: exports.DUMMY_USER_ID, | ||
username: username, | ||
username, | ||
}, | ||
@@ -288,7 +264,21 @@ integration: { | ||
}; | ||
}; | ||
AcrolinxServerMock.prototype.returnFakeSigninPage = function (signinId, opts) { | ||
var signinState = this.signinIds[signinId]; | ||
} | ||
returnFakeSigninPage(signinId, opts) { | ||
const signinState = this.signinIds[signinId]; | ||
return { | ||
body: "\n <html>\n <head><title>Signin UI</title></head>\n <body>\n <h1>Interactive Signin</h1>\n <p>SigninID: ".concat(signinId, "</p>\n <p>SigninState: ").concat((signinState && (signinState.authorizationType || 'Signed out')) || 'Unknown', "</p>\n <form action=\"").concat(signinId, "/confirm\" method=\"post\"><button>Confirm Signin</button></form>\n <form action=\"").concat(signinId, "/delete\" method=\"post\"><button>Delete Signin</button></form>\n <pre>\n ").concat(JSON.stringify(opts, null, 2), "\n </pre>\n </body>\n </html>\n "), | ||
body: ` | ||
<html> | ||
<head><title>Signin UI</title></head> | ||
<body> | ||
<h1>Interactive Signin</h1> | ||
<p>SigninID: ${signinId}</p> | ||
<p>SigninState: ${(signinState && (signinState.authorizationType || 'Signed out')) || 'Unknown'}</p> | ||
<form action="${signinId}/confirm" method="post"><button>Confirm Signin</button></form> | ||
<form action="${signinId}/delete" method="post"><button>Delete Signin</button></form> | ||
<pre> | ||
${JSON.stringify(opts, null, 2)} | ||
</pre> | ||
</body> | ||
</html> | ||
`, | ||
headers: { | ||
@@ -298,4 +288,4 @@ 'Content-Type': 'text/html', | ||
}; | ||
}; | ||
AcrolinxServerMock.prototype.returnConfirmSigninPage = function (signinId, opts) { | ||
} | ||
returnConfirmSigninPage(signinId, opts) { | ||
if (!this.signinIds[signinId]) { | ||
@@ -306,9 +296,8 @@ return { status: 404, body: { message: 'Unknown signinId ' + signinId } }; | ||
return this.pollForSignin(signinId, opts); | ||
}; | ||
AcrolinxServerMock.prototype.returnSigninDeletedPage = function (signinId, _opts) { | ||
} | ||
returnSigninDeletedPage(signinId, _opts) { | ||
this.deleteSignin(signinId); | ||
return { message: "".concat(signinId, " is deleted") }; | ||
}; | ||
return AcrolinxServerMock; | ||
}()); | ||
return { message: `${signinId} is deleted` }; | ||
} | ||
} | ||
exports.AcrolinxServerMock = AcrolinxServerMock; | ||
@@ -319,6 +308,6 @@ function getHeader(requestOpts, headerKey) { | ||
} | ||
return _.find(requestOpts.headers, function (_val, key) { return key.toLowerCase() === headerKey.toLowerCase(); }); | ||
return _.find(requestOpts.headers, (_val, key) => key.toLowerCase() === headerKey.toLowerCase()); | ||
} | ||
function mockAcrolinxServer(url) { | ||
var mockedServer = new AcrolinxServerMock(url); | ||
const mockedServer = new AcrolinxServerMock(url); | ||
fetchMock.mock('begin:' + url, mockedServer.handleFetchRequest); | ||
@@ -329,3 +318,3 @@ return mockedServer; | ||
function mockBrokenJsonServer(url) { | ||
fetchMock.mock('begin:' + url, function (_url, _opts) { | ||
fetchMock.mock('begin:' + url, (_url, _opts) => { | ||
return { body: "This isn't the json you are looking for" }; | ||
@@ -332,0 +321,0 @@ }); |
@@ -19,3 +19,3 @@ "use strict"; | ||
exports.NOT_FOUND_CHECK_ID = exports.AUTH_TOKEN_INVALID = exports.AUTH_TOKEN_MISSING = exports.CLIENT_SIGNATURE_INVALID = exports.CLIENT_SIGNATURE_MISSING = exports.SIGNIN_URL_EXPIRED_ERROR = void 0; | ||
var errors_1 = require("../../src/errors"); | ||
const errors_1 = require("../../src/errors"); | ||
exports.SIGNIN_URL_EXPIRED_ERROR = { | ||
@@ -22,0 +22,0 @@ detail: 'The sign-in URL does not exists or is expired. Please start a new sign-in process.', |
@@ -26,29 +26,2 @@ "use strict"; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -75,22 +48,15 @@ exports.expectFailingPromise = exports.describeIf = exports.testIf = void 0; | ||
function expectFailingPromise(promise, expectedErrorType, expectedHttpRequest) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var unexpectedSuccessfulResult, e_1; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
_a.trys.push([0, 2, , 3]); | ||
return [4 /*yield*/, promise]; | ||
case 1: | ||
unexpectedSuccessfulResult = _a.sent(); | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
e_1 = _a.sent(); | ||
expect(e_1.type).toEqual(expectedErrorType); | ||
if (expectedHttpRequest) { | ||
expect(e_1.httpRequest).toEqual(expectedHttpRequest); | ||
} | ||
return [2 /*return*/, e_1]; | ||
case 3: throw new Error('Unexpected success ' + JSON.stringify(unexpectedSuccessfulResult)); | ||
return __awaiter(this, void 0, void 0, function* () { | ||
let unexpectedSuccessfulResult; | ||
try { | ||
unexpectedSuccessfulResult = yield promise; | ||
} | ||
catch (e) { | ||
expect(e.type).toEqual(expectedErrorType); | ||
if (expectedHttpRequest) { | ||
expect(e.httpRequest).toEqual(expectedHttpRequest); | ||
} | ||
}); | ||
return e; | ||
} | ||
throw new Error('Unexpected success ' + JSON.stringify(unexpectedSuccessfulResult)); | ||
}); | ||
@@ -97,0 +63,0 @@ } |
@@ -18,8 +18,8 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var src_1 = require("../../src"); | ||
var index_1 = require("../../src/index"); | ||
var acrolinx_endpoint_test_1 = require("../integration-server/acrolinx-endpoint.test"); | ||
const src_1 = require("../../src"); | ||
const index_1 = require("../../src/index"); | ||
const acrolinx_endpoint_test_1 = require("../integration-server/acrolinx-endpoint.test"); | ||
function createEndpoint(acrolinxUrl) { | ||
return new index_1.AcrolinxEndpoint({ | ||
acrolinxUrl: acrolinxUrl, | ||
acrolinxUrl, | ||
enableHttpLogging: true, | ||
@@ -32,5 +32,5 @@ client: { | ||
} | ||
describe('AcrolinxEndpoint', function () { | ||
describe('sanitize acrolinxUrl', function () { | ||
it('trim and remove training slash', function () { | ||
describe('AcrolinxEndpoint', () => { | ||
describe('sanitize acrolinxUrl', () => { | ||
it('trim and remove training slash', () => { | ||
expect(createEndpoint(' http://host/ ').props.acrolinxUrl).toEqual('http://host'); | ||
@@ -37,0 +37,0 @@ // eslint-disable-next-line sonarjs/no-duplicate-string |
@@ -11,29 +11,2 @@ "use strict"; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -55,189 +28,126 @@ /* | ||
*/ | ||
var mockFetch = require("fetch-mock"); | ||
var index_1 = require("../../src/index"); | ||
var mock_server_1 = require("../test-utils/mock-server"); | ||
var common_1 = require("./common"); | ||
var dummy_data_1 = require("../test-utils/dummy-data"); | ||
var ai_service_types_1 = require("../../src/services/ai-service/ai-service.types"); | ||
var ai_service_1 = require("../../src/services/ai-service/ai-service"); | ||
describe('AI-service', function () { | ||
var endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
var aiService = new ai_service_1.AIService(endpoint); | ||
afterEach(function () { | ||
const mockFetch = require("fetch-mock"); | ||
const index_1 = require("../../src/index"); | ||
const mock_server_1 = require("../test-utils/mock-server"); | ||
const common_1 = require("./common"); | ||
const dummy_data_1 = require("../test-utils/dummy-data"); | ||
const ai_service_types_1 = require("../../src/services/ai-service/ai-service.types"); | ||
const ai_service_1 = require("../../src/services/ai-service/ai-service"); | ||
describe('AI-service', () => { | ||
let endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
const aiService = new ai_service_1.AIService(endpoint); | ||
afterEach(() => { | ||
mockFetch.restore(); | ||
}); | ||
describe('/ai-enabled', function () { | ||
var aiEnabledMatcher = 'end:/ai-enabled?privilege=generate'; | ||
it('truthy response', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var response; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
mockFetch.mock(aiEnabledMatcher, { | ||
status: 200, | ||
body: { value: true, tenant: 'int-1', userHasPrivilege: true }, | ||
}); | ||
return [4 /*yield*/, aiService.isAIEnabled(mock_server_1.DUMMY_ACCESS_TOKEN)]; | ||
case 1: | ||
response = _a.sent(); | ||
expect(response).toBe(true); | ||
return [2 /*return*/]; | ||
} | ||
describe('/ai-enabled', () => { | ||
const aiEnabledMatcher = 'end:/ai-enabled?privilege=generate'; | ||
it('truthy response', () => __awaiter(void 0, void 0, void 0, function* () { | ||
mockFetch.mock(aiEnabledMatcher, { | ||
status: 200, | ||
body: { value: true, tenant: 'int-1', userHasPrivilege: true }, | ||
}); | ||
}); }); | ||
it('falsy response', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var response1, response2, response3; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
mockFetch.mock(aiEnabledMatcher, { | ||
status: 200, | ||
body: { value: true, tenant: 'int-1', userHasPrivilege: false }, | ||
}); | ||
return [4 /*yield*/, aiService.isAIEnabled(mock_server_1.DUMMY_ACCESS_TOKEN)]; | ||
case 1: | ||
response1 = _a.sent(); | ||
expect(response1).toBe(false); | ||
mockFetch.restore(); | ||
mockFetch.mock(aiEnabledMatcher, { | ||
status: 200, | ||
body: { value: false, tenant: 'int-1', userHasPrivilege: true }, | ||
}); | ||
return [4 /*yield*/, aiService.isAIEnabled(mock_server_1.DUMMY_ACCESS_TOKEN)]; | ||
case 2: | ||
response2 = _a.sent(); | ||
expect(response2).toBe(false); | ||
mockFetch.restore(); | ||
mockFetch.mock(aiEnabledMatcher, { | ||
status: 200, | ||
body: { value: false, tenant: 'int-1', userHasPrivilege: false }, | ||
}); | ||
return [4 /*yield*/, aiService.isAIEnabled(mock_server_1.DUMMY_ACCESS_TOKEN)]; | ||
case 3: | ||
response3 = _a.sent(); | ||
expect(response3).toBe(false); | ||
return [2 /*return*/]; | ||
} | ||
const response = yield aiService.isAIEnabled(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
expect(response).toBe(true); | ||
})); | ||
it('falsy response', () => __awaiter(void 0, void 0, void 0, function* () { | ||
mockFetch.mock(aiEnabledMatcher, { | ||
status: 200, | ||
body: { value: true, tenant: 'int-1', userHasPrivilege: false }, | ||
}); | ||
}); }); | ||
it('error response', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var response; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
mockFetch.mock(aiEnabledMatcher, { | ||
status: 403, | ||
body: { | ||
code: 403, | ||
message: 'missing privilege GENERATE', | ||
errorId: 'INSUFFICIENT_PRIVILEGES', | ||
}, | ||
}); | ||
return [4 /*yield*/, aiService.isAIEnabled(mock_server_1.DUMMY_ACCESS_TOKEN)]; | ||
case 1: | ||
response = _a.sent(); | ||
expect(response).toBe(false); | ||
return [2 /*return*/]; | ||
} | ||
const response1 = yield aiService.isAIEnabled(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
expect(response1).toBe(false); | ||
mockFetch.restore(); | ||
mockFetch.mock(aiEnabledMatcher, { | ||
status: 200, | ||
body: { value: false, tenant: 'int-1', userHasPrivilege: true }, | ||
}); | ||
}); }); | ||
const response2 = yield aiService.isAIEnabled(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
expect(response2).toBe(false); | ||
mockFetch.restore(); | ||
mockFetch.mock(aiEnabledMatcher, { | ||
status: 200, | ||
body: { value: false, tenant: 'int-1', userHasPrivilege: false }, | ||
}); | ||
const response3 = yield aiService.isAIEnabled(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
expect(response3).toBe(false); | ||
})); | ||
it('error response', () => __awaiter(void 0, void 0, void 0, function* () { | ||
mockFetch.mock(aiEnabledMatcher, { | ||
status: 403, | ||
body: { | ||
code: 403, | ||
message: 'missing privilege GENERATE', | ||
errorId: 'INSUFFICIENT_PRIVILEGES', | ||
}, | ||
}); | ||
const response = yield aiService.isAIEnabled(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
expect(response).toBe(false); | ||
})); | ||
}); | ||
describe('/getAIChatCompletions', function () { | ||
var REQUEST_ERROR_MESSAGE = 'There was an error processing your request. It has been logged (ID some-random-id).'; | ||
var getGetAIChatCompletionMatcher = function (count, internalName) { | ||
return "end:/ai-service/api/v1/ai/chat-completions?count=".concat(count, "&issueInternalName=").concat(internalName); | ||
}; | ||
it('correct response', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var aiResponse, response; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
aiResponse = 'some responds'; | ||
return [4 /*yield*/, createDummyAIServiceRequest(200, { response: aiResponse })]; | ||
case 1: | ||
response = _a.sent(); | ||
expect(response.response).toBe(aiResponse); | ||
return [2 /*return*/]; | ||
} | ||
describe('/getAIChatCompletions', () => { | ||
const REQUEST_ERROR_MESSAGE = 'There was an error processing your request. It has been logged (ID some-random-id).'; | ||
const getGetAIChatCompletionMatcher = (count, internalName) => `end:/ai-service/api/v1/ai/chat-completions?count=${count}&issueInternalName=${internalName}`; | ||
it('correct response', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const aiResponse = 'some responds'; | ||
const response = yield createDummyAIServiceRequest(200, { response: aiResponse }); | ||
expect(response.response).toBe(aiResponse); | ||
})); | ||
it('error response', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const response = createDummyAIServiceRequest(500, { | ||
code: 500, | ||
message: REQUEST_ERROR_MESSAGE, | ||
errorId: ai_service_types_1.AIServiceErrorTypes.GENERAL_EXCEPTION, | ||
}); | ||
}); }); | ||
it('error response', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var response; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
response = createDummyAIServiceRequest(500, { | ||
code: 500, | ||
message: REQUEST_ERROR_MESSAGE, | ||
errorId: ai_service_types_1.AIServiceErrorTypes.GENERAL_EXCEPTION, | ||
}); | ||
return [4 /*yield*/, expect(response).rejects.toThrowError(new index_1.AcrolinxError({ | ||
detail: REQUEST_ERROR_MESSAGE, | ||
status: 500, | ||
type: ai_service_types_1.AIServiceErrorTypes.GENERAL_EXCEPTION, | ||
title: REQUEST_ERROR_MESSAGE, | ||
httpRequest: { | ||
url: expect.stringContaining('/ai-service/api/v1/ai/chat-completions'), | ||
method: 'POST', | ||
}, | ||
}))]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
yield expect(response).rejects.toThrowError(new index_1.AcrolinxError({ | ||
detail: REQUEST_ERROR_MESSAGE, | ||
status: 500, | ||
type: ai_service_types_1.AIServiceErrorTypes.GENERAL_EXCEPTION, | ||
title: REQUEST_ERROR_MESSAGE, | ||
httpRequest: { | ||
url: expect.stringContaining('/ai-service/api/v1/ai/chat-completions'), | ||
method: 'POST', | ||
}, | ||
})); | ||
})); | ||
it('should throw if response was filtered', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const FILTERED_RESPONSE_MESSAGE = 'The response was filtered...bla bla'; | ||
const response = createDummyAIServiceRequest(400, { | ||
code: 400, | ||
message: FILTERED_RESPONSE_MESSAGE, | ||
errorId: ai_service_types_1.AIServiceErrorTypes.INVALID_USER_INPUT, | ||
}); | ||
}); }); | ||
it('should throw if response was filtered', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var FILTERED_RESPONSE_MESSAGE, response; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
FILTERED_RESPONSE_MESSAGE = 'The response was filtered...bla bla'; | ||
response = createDummyAIServiceRequest(400, { | ||
code: 400, | ||
message: FILTERED_RESPONSE_MESSAGE, | ||
errorId: ai_service_types_1.AIServiceErrorTypes.INVALID_USER_INPUT, | ||
}); | ||
return [4 /*yield*/, expect(response).rejects.toThrowError(new index_1.AcrolinxError({ | ||
detail: FILTERED_RESPONSE_MESSAGE, | ||
status: 400, | ||
type: ai_service_types_1.AIServiceErrorTypes.INVALID_USER_INPUT, | ||
title: FILTERED_RESPONSE_MESSAGE, | ||
httpRequest: { | ||
url: expect.stringContaining('/ai-service/api/v1/ai/chat-completions'), | ||
method: 'POST', | ||
}, | ||
}))]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
yield expect(response).rejects.toThrowError(new index_1.AcrolinxError({ | ||
detail: FILTERED_RESPONSE_MESSAGE, | ||
status: 400, | ||
type: ai_service_types_1.AIServiceErrorTypes.INVALID_USER_INPUT, | ||
title: FILTERED_RESPONSE_MESSAGE, | ||
httpRequest: { | ||
url: expect.stringContaining('/ai-service/api/v1/ai/chat-completions'), | ||
method: 'POST', | ||
}, | ||
})); | ||
})); | ||
const createDummyAIServiceRequest = (responseStatus, dummyResponseBody) => __awaiter(void 0, void 0, void 0, function* () { | ||
endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
const count = 1; | ||
const internalName = 'simplefy'; | ||
const aiRephraseHint = 'some invalid data'; | ||
const targetUuid = '123e4567-e89b-12d3-a456-426614174000'; | ||
const aiRewriteContext = dummy_data_1.DUMMY_AI_REWRITE_CONTEXT; | ||
mockFetch.mock(getGetAIChatCompletionMatcher(count, internalName), { | ||
status: responseStatus, | ||
body: dummyResponseBody, | ||
}); | ||
}); }); | ||
var createDummyAIServiceRequest = function (responseStatus, dummyResponseBody) { return __awaiter(void 0, void 0, void 0, function () { | ||
var count, internalName, aiRephraseHint, targetUuid, aiRewriteContext; | ||
return __generator(this, function (_a) { | ||
endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
count = 1; | ||
internalName = 'simplefy'; | ||
aiRephraseHint = 'some invalid data'; | ||
targetUuid = '123e4567-e89b-12d3-a456-426614174000'; | ||
aiRewriteContext = dummy_data_1.DUMMY_AI_REWRITE_CONTEXT; | ||
mockFetch.mock(getGetAIChatCompletionMatcher(count, internalName), { | ||
status: responseStatus, | ||
body: dummyResponseBody, | ||
}); | ||
return [2 /*return*/, aiService.getAIChatCompletion({ | ||
issue: { | ||
internalName: internalName, | ||
aiRephraseHint: aiRephraseHint, | ||
aiRewriteContext: aiRewriteContext, | ||
}, | ||
count: count, | ||
targetUuid: targetUuid, | ||
}, mock_server_1.DUMMY_ACCESS_TOKEN)]; | ||
}); | ||
}); }; | ||
return aiService.getAIChatCompletion({ | ||
issue: { | ||
internalName, | ||
aiRephraseHint, | ||
aiRewriteContext, | ||
}, | ||
count, | ||
targetUuid, | ||
}, mock_server_1.DUMMY_ACCESS_TOKEN); | ||
}); | ||
}); | ||
}); | ||
//# sourceMappingURL=ai-service.test.js.map |
@@ -26,55 +26,20 @@ "use strict"; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var index_1 = require("../../src/index"); | ||
var mock_server_1 = require("../test-utils/mock-server"); | ||
var common_1 = require("./common"); | ||
describe('checking', function () { | ||
var endpoint; | ||
beforeEach(function () { | ||
const index_1 = require("../../src/index"); | ||
const mock_server_1 = require("../test-utils/mock-server"); | ||
const common_1 = require("./common"); | ||
describe('checking', () => { | ||
let endpoint; | ||
beforeEach(() => { | ||
(0, mock_server_1.mockAcrolinxServer)(common_1.DUMMY_SERVER_URL); | ||
endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
}); | ||
afterEach(function () { | ||
afterEach(() => { | ||
(0, mock_server_1.restoreOriginalFetch)(); | ||
}); | ||
it('get checking capabilities', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var capabilities; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, endpoint.getCheckingCapabilities(mock_server_1.DUMMY_ACCESS_TOKEN)]; | ||
case 1: | ||
capabilities = _a.sent(); | ||
expect(capabilities.guidanceProfiles.length).toBeGreaterThan(0); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('get checking capabilities', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const capabilities = yield endpoint.getCheckingCapabilities(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
expect(capabilities.guidanceProfiles.length).toBeGreaterThan(0); | ||
})); | ||
}); | ||
//# sourceMappingURL=checking.test.js.map |
@@ -19,3 +19,3 @@ "use strict"; | ||
exports.DUMMY_ENDPOINT_PROPS = exports.DUMMY_SERVER_URL = void 0; | ||
var src_1 = require("../../src"); | ||
const src_1 = require("../../src"); | ||
exports.DUMMY_SERVER_URL = 'http://dummy-server'; | ||
@@ -22,0 +22,0 @@ exports.DUMMY_ENDPOINT_PROPS = { |
@@ -17,13 +17,2 @@ "use strict"; | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -38,76 +27,31 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var index_1 = require("../../src/index"); | ||
var mock_server_1 = require("../test-utils/mock-server"); | ||
var common_1 = require("./common"); | ||
describe('corsWithCredentials', function () { | ||
var endpoint; | ||
var mockedAcrolinxServer; | ||
beforeEach(function () { | ||
const index_1 = require("../../src/index"); | ||
const mock_server_1 = require("../test-utils/mock-server"); | ||
const common_1 = require("./common"); | ||
describe('corsWithCredentials', () => { | ||
let endpoint; | ||
let mockedAcrolinxServer; | ||
beforeEach(() => { | ||
mockedAcrolinxServer = (0, mock_server_1.mockAcrolinxServer)(common_1.DUMMY_SERVER_URL); | ||
}); | ||
afterEach(function () { | ||
afterEach(() => { | ||
(0, mock_server_1.restoreOriginalFetch)(); | ||
}); | ||
it('corsWithCredentials === true should set fetch option credentials to "include"', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var result; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
endpoint = new index_1.AcrolinxEndpoint(__assign(__assign({}, common_1.DUMMY_ENDPOINT_PROPS), { corsWithCredentials: true })); | ||
return [4 /*yield*/, endpoint.signin()]; | ||
case 1: | ||
result = (_a.sent()); | ||
expect(result).toBeDefined(); | ||
expect(mockedAcrolinxServer.requests[0].opts.credentials).toEqual('include'); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('corsWithCredentials === true should set fetch option credentials to "include"', () => __awaiter(void 0, void 0, void 0, function* () { | ||
endpoint = new index_1.AcrolinxEndpoint(Object.assign(Object.assign({}, common_1.DUMMY_ENDPOINT_PROPS), { corsWithCredentials: true })); | ||
const result = (yield endpoint.signin()); | ||
expect(result).toBeDefined(); | ||
expect(mockedAcrolinxServer.requests[0].opts.credentials).toEqual('include'); | ||
})); | ||
/** | ||
* Ensure credentials: 'same-origin' in old browsers: https://github.com/github/fetch#sending-cookies | ||
*/ | ||
it('corsWithCredentials !== true should set fetch option credentials to "same-origin"', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var result; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
return [4 /*yield*/, endpoint.signin()]; | ||
case 1: | ||
result = (_a.sent()); | ||
expect(result).toBeDefined(); | ||
expect(mockedAcrolinxServer.requests[0].opts.credentials).toEqual('same-origin'); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('corsWithCredentials !== true should set fetch option credentials to "same-origin"', () => __awaiter(void 0, void 0, void 0, function* () { | ||
endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
const result = (yield endpoint.signin()); | ||
expect(result).toBeDefined(); | ||
expect(mockedAcrolinxServer.requests[0].opts.credentials).toEqual('same-origin'); | ||
})); | ||
}); | ||
//# sourceMappingURL=cors-with-credentials.test.js.map |
@@ -17,13 +17,2 @@ "use strict"; | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -38,99 +27,46 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var errors_1 = require("../../src/errors"); | ||
var index_1 = require("../../src/index"); | ||
var mock_server_1 = require("../test-utils/mock-server"); | ||
var common_1 = require("./common"); | ||
var BROKEN_JSON_SERVER = 'http://broken-json-server'; | ||
describe('errors', function () { | ||
beforeEach(function () { | ||
const errors_1 = require("../../src/errors"); | ||
const index_1 = require("../../src/index"); | ||
const mock_server_1 = require("../test-utils/mock-server"); | ||
const common_1 = require("./common"); | ||
const BROKEN_JSON_SERVER = 'http://broken-json-server'; | ||
describe('errors', () => { | ||
beforeEach(() => { | ||
(0, mock_server_1.mockAcrolinxServer)(common_1.DUMMY_SERVER_URL); | ||
(0, mock_server_1.mockBrokenJsonServer)(BROKEN_JSON_SERVER); | ||
}); | ||
afterEach(function () { | ||
afterEach(() => { | ||
(0, mock_server_1.restoreOriginalFetch)(); | ||
}); | ||
it('should return an failing promise for broken json', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var api, e_1; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
api = new index_1.AcrolinxEndpoint(__assign(__assign({}, common_1.DUMMY_ENDPOINT_PROPS), { acrolinxUrl: BROKEN_JSON_SERVER })); | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, api.getJsonFromUrl(BROKEN_JSON_SERVER)]; | ||
case 2: | ||
_a.sent(); | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
e_1 = _a.sent(); | ||
expect(e_1.type).toEqual(errors_1.ErrorType.InvalidJson); | ||
return [3 /*break*/, 4]; | ||
case 4: | ||
expect.hasAssertions(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('should return an api error for invalid signin poll address', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var api, e_2; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
api = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, api.pollForSignin({ | ||
data: { interactiveLinkTimeout: 0 }, | ||
links: { | ||
interactive: 'dummy', | ||
poll: common_1.DUMMY_ENDPOINT_PROPS.acrolinxUrl + '/api/v1/auth/sign-ins/0ddece9c-464a-442b-8a5d-d2f242d54c81', | ||
}, | ||
})]; | ||
case 2: | ||
_a.sent(); | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
e_2 = _a.sent(); | ||
expect(e_2.type).toEqual(errors_1.ErrorType.Client); | ||
return [3 /*break*/, 4]; | ||
case 4: | ||
expect.hasAssertions(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
describe('custom errors and instanceof', function () { | ||
it('should return an failing promise for broken json', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const api = new index_1.AcrolinxEndpoint(Object.assign(Object.assign({}, common_1.DUMMY_ENDPOINT_PROPS), { acrolinxUrl: BROKEN_JSON_SERVER })); | ||
try { | ||
yield api.getJsonFromUrl(BROKEN_JSON_SERVER); | ||
} | ||
catch (e) { | ||
expect(e.type).toEqual(errors_1.ErrorType.InvalidJson); | ||
} | ||
expect.hasAssertions(); | ||
})); | ||
it('should return an api error for invalid signin poll address', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const api = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
try { | ||
yield api.pollForSignin({ | ||
data: { interactiveLinkTimeout: 0 }, | ||
links: { | ||
interactive: 'dummy', | ||
poll: common_1.DUMMY_ENDPOINT_PROPS.acrolinxUrl + '/api/v1/auth/sign-ins/0ddece9c-464a-442b-8a5d-d2f242d54c81', | ||
}, | ||
}); | ||
} | ||
catch (e) { | ||
expect(e.type).toEqual(errors_1.ErrorType.Client); | ||
} | ||
expect.hasAssertions(); | ||
})); | ||
describe('custom errors and instanceof', () => { | ||
// Needed because of https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
it('CheckCanceledByClientError should support instanceof', function () { | ||
var error = new errors_1.CheckCanceledByClientError({ | ||
it('CheckCanceledByClientError should support instanceof', () => { | ||
const error = new errors_1.CheckCanceledByClientError({ | ||
detail: 'The check was canceled. No result is available.', | ||
@@ -137,0 +73,0 @@ type: errors_1.ErrorType.CheckCanceled, |
@@ -11,97 +11,52 @@ "use strict"; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var mockFetch = require("fetch-mock"); | ||
var index_1 = require("../../src/index"); | ||
var mock_server_1 = require("../test-utils/mock-server"); | ||
var common_1 = require("./common"); | ||
describe('Integration-service', function () { | ||
var endpoint; | ||
var intService; | ||
afterEach(function () { | ||
const mockFetch = require("fetch-mock"); | ||
const index_1 = require("../../src/index"); | ||
const mock_server_1 = require("../test-utils/mock-server"); | ||
const common_1 = require("./common"); | ||
describe('Integration-service', () => { | ||
let endpoint; | ||
let intService; | ||
afterEach(() => { | ||
mockFetch.restore(); | ||
}); | ||
describe('/config', function () { | ||
var configEndpointMatcher = 'end:/int-service/api/v1/config'; | ||
it('truthy response for correct client signature', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var response; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
intService = new index_1.IntService(endpoint); | ||
// Mock the endpoint with expected headers check and updated response property | ||
mockFetch.mock(configEndpointMatcher, function (_url, opts) { | ||
var headers = opts.headers; // Asserting headers to be of type Record<string, string> | ||
if (headers['X-Acrolinx-Client'].includes(common_1.DUMMY_ENDPOINT_PROPS.client.signature)) { | ||
return { | ||
status: 200, | ||
body: { activateGetSuggestionReplacement: true }, // Updated property name | ||
}; | ||
} | ||
else { | ||
return { | ||
status: 200, | ||
body: { activateGetSuggestionReplacement: false }, | ||
}; | ||
} | ||
}); | ||
return [4 /*yield*/, intService.getConfig(mock_server_1.DUMMY_ACCESS_TOKEN)]; | ||
case 1: | ||
response = _a.sent(); | ||
expect(response.activateGetSuggestionReplacement).toBe(true); // Assertion updated to check new property name | ||
return [2 /*return*/]; | ||
describe('/config', () => { | ||
const configEndpointMatcher = 'end:/int-service/api/v1/config'; | ||
it('truthy response for correct client signature', () => __awaiter(void 0, void 0, void 0, function* () { | ||
endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
intService = new index_1.IntService(endpoint); | ||
// Mock the endpoint with expected headers check and updated response property | ||
mockFetch.mock(configEndpointMatcher, (_url, opts) => { | ||
const headers = opts.headers; // Asserting headers to be of type Record<string, string> | ||
if (headers['X-Acrolinx-Client'].includes(common_1.DUMMY_ENDPOINT_PROPS.client.signature)) { | ||
return { | ||
status: 200, | ||
body: { activateGetSuggestionReplacement: true }, // Updated property name | ||
}; | ||
} | ||
}); | ||
}); }); | ||
it('Default config response for unavailable client signature', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var response; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
intService = new index_1.IntService(endpoint); | ||
// Mock the endpoint with expected headers check and updated response property | ||
mockFetch.mock(configEndpointMatcher, function () { | ||
return { | ||
status: 200, | ||
body: { activateGetSuggestionReplacement: false }, | ||
}; | ||
}); | ||
return [4 /*yield*/, intService.getConfig(mock_server_1.DUMMY_ACCESS_TOKEN)]; | ||
case 1: | ||
response = _a.sent(); | ||
expect(response.activateGetSuggestionReplacement).toBe(false); // Assertion updated to check new property name | ||
return [2 /*return*/]; | ||
else { | ||
return { | ||
status: 200, | ||
body: { activateGetSuggestionReplacement: false }, | ||
}; | ||
} | ||
}); | ||
}); }); | ||
const response = yield intService.getConfig(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
expect(response.activateGetSuggestionReplacement).toBe(true); // Assertion updated to check new property name | ||
})); | ||
it('Default config response for unavailable client signature', () => __awaiter(void 0, void 0, void 0, function* () { | ||
endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
intService = new index_1.IntService(endpoint); | ||
// Mock the endpoint with expected headers check and updated response property | ||
mockFetch.mock(configEndpointMatcher, () => { | ||
return { | ||
status: 200, | ||
body: { activateGetSuggestionReplacement: false }, | ||
}; | ||
}); | ||
const response = yield intService.getConfig(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
expect(response.activateGetSuggestionReplacement).toBe(false); // Assertion updated to check new property name | ||
})); | ||
}); | ||
}); | ||
//# sourceMappingURL=int-service.test.js.map |
@@ -11,38 +11,11 @@ "use strict"; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var logging_buffer_1 = require("../../src/utils/logging-buffer"); | ||
var TEST_LOG_MESSAGE = 'Test log message'; | ||
var NETWORK_ERROR_MESSAGE = 'Network error'; | ||
describe('LogBuffer', function () { | ||
var logBuffer; | ||
var mockConfig; | ||
var acrolinxUrl = 'http://example.com'; | ||
beforeEach(function () { | ||
const logging_buffer_1 = require("../../src/utils/logging-buffer"); | ||
const TEST_LOG_MESSAGE = 'Test log message'; | ||
const NETWORK_ERROR_MESSAGE = 'Network error'; | ||
describe('LogBuffer', () => { | ||
let logBuffer; | ||
let mockConfig; | ||
const acrolinxUrl = 'http://example.com'; | ||
beforeEach(() => { | ||
mockConfig = { | ||
@@ -57,9 +30,9 @@ batchSize: 10, | ||
logBuffer = new logging_buffer_1.LogBuffer(acrolinxUrl, mockConfig); | ||
jest.spyOn(console, 'error').mockImplementation(function () { }); | ||
jest.spyOn(console, 'error').mockImplementation(() => { }); | ||
}); | ||
afterEach(function () { | ||
afterEach(() => { | ||
jest.clearAllMocks(); | ||
}); | ||
test('should only add log entry to buffer if enableCloudLogging is true and log level is sufficient', function () { | ||
var logEntry = { | ||
test('should only add log entry to buffer if enableCloudLogging is true and log level is sufficient', () => { | ||
const logEntry = { | ||
type: logging_buffer_1.LogEntryType.info, | ||
@@ -81,4 +54,4 @@ message: TEST_LOG_MESSAGE, | ||
}); | ||
test('should not add log entry to buffer if log level is insufficient', function () { | ||
var logEntry = { | ||
test('should not add log entry to buffer if log level is insufficient', () => { | ||
const logEntry = { | ||
type: logging_buffer_1.LogEntryType.warning, | ||
@@ -93,60 +66,42 @@ message: TEST_LOG_MESSAGE, | ||
}); | ||
test('should flush logs to server when buffer reaches batch size', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var mockFetch, i, logEntry; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
mockFetch = jest.fn().mockResolvedValue({ ok: true }); | ||
global.fetch = mockFetch; | ||
for (i = 0; i < mockConfig.batchSize; i++) { | ||
logEntry = { | ||
type: logging_buffer_1.LogEntryType.info, | ||
message: "".concat(TEST_LOG_MESSAGE, " ").concat(i), | ||
details: [], | ||
}; | ||
logBuffer.log(logEntry); | ||
} | ||
return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 0); })]; | ||
case 1: | ||
_a.sent(); | ||
expect(mockFetch).toHaveBeenCalledTimes(1); | ||
expect(logBuffer['buffer']).toHaveLength(0); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
test('should retry sending logs on failure', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var mockFetch, logEntry, totalDelay, i, delay; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
mockFetch = jest.fn(); | ||
mockFetch | ||
.mockRejectedValueOnce(new Error(NETWORK_ERROR_MESSAGE)) | ||
.mockRejectedValueOnce(new Error(NETWORK_ERROR_MESSAGE)) | ||
.mockResolvedValueOnce({ ok: true }); | ||
global.fetch = mockFetch; | ||
logEntry = { | ||
type: logging_buffer_1.LogEntryType.warning, | ||
message: TEST_LOG_MESSAGE, | ||
details: [], | ||
}; | ||
logBuffer.log(logEntry); | ||
totalDelay = 0; | ||
for (i = 0; i < mockConfig.maxRetries; i++) { | ||
delay = mockConfig.dispatchInterval * Math.pow(2, i); | ||
totalDelay += Math.min(delay, mockConfig.maxRetries * mockConfig.retryDelay); | ||
} | ||
totalDelay += 300; | ||
return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, totalDelay); })]; | ||
case 1: | ||
_a.sent(); | ||
expect(mockFetch).toHaveBeenCalledTimes(mockConfig.maxRetries); | ||
expect(logBuffer['buffer']).toHaveLength(0); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
test('should not add log entry to buffer if logLevel is null', function () { | ||
var logEntry = { | ||
test('should flush logs to server when buffer reaches batch size', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const mockFetch = jest.fn().mockResolvedValue({ ok: true }); | ||
global.fetch = mockFetch; | ||
for (let i = 0; i < mockConfig.batchSize; i++) { | ||
const logEntry = { | ||
type: logging_buffer_1.LogEntryType.info, | ||
message: `${TEST_LOG_MESSAGE} ${i}`, | ||
details: [], | ||
}; | ||
logBuffer.log(logEntry); | ||
} | ||
yield new Promise((resolve) => setTimeout(resolve, 0)); | ||
expect(mockFetch).toHaveBeenCalledTimes(1); | ||
expect(logBuffer['buffer']).toHaveLength(0); | ||
})); | ||
test('should retry sending logs on failure', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const mockFetch = jest.fn(); | ||
mockFetch | ||
.mockRejectedValueOnce(new Error(NETWORK_ERROR_MESSAGE)) | ||
.mockRejectedValueOnce(new Error(NETWORK_ERROR_MESSAGE)) | ||
.mockResolvedValueOnce({ ok: true }); | ||
global.fetch = mockFetch; | ||
const logEntry = { | ||
type: logging_buffer_1.LogEntryType.warning, | ||
message: TEST_LOG_MESSAGE, | ||
details: [], | ||
}; | ||
logBuffer.log(logEntry); | ||
let totalDelay = 0; | ||
for (let i = 0; i < mockConfig.maxRetries; i++) { | ||
const delay = mockConfig.dispatchInterval * Math.pow(2, i); | ||
totalDelay += Math.min(delay, mockConfig.maxRetries * mockConfig.retryDelay); | ||
} | ||
totalDelay += 300; | ||
yield new Promise((resolve) => setTimeout(resolve, totalDelay)); | ||
expect(mockFetch).toHaveBeenCalledTimes(mockConfig.maxRetries); | ||
expect(logBuffer['buffer']).toHaveLength(0); | ||
})); | ||
test('should not add log entry to buffer if logLevel is null', () => { | ||
const logEntry = { | ||
type: logging_buffer_1.LogEntryType.info, | ||
@@ -161,53 +116,34 @@ message: TEST_LOG_MESSAGE, | ||
}); | ||
test('should handle failed server response', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var mockFetch, logEntry; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
mockFetch = jest.fn().mockResolvedValueOnce({ ok: false }); | ||
global.fetch = mockFetch; | ||
logEntry = { | ||
type: logging_buffer_1.LogEntryType.error, | ||
message: TEST_LOG_MESSAGE, | ||
details: [], | ||
}; | ||
logBuffer.log(logEntry); | ||
return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 300); })]; | ||
case 1: | ||
_a.sent(); | ||
expect(mockFetch).toHaveBeenCalledTimes(1); | ||
expect(logBuffer['retries']).toBe(1); | ||
expect(logBuffer['buffer']).toContain(logEntry); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
test('should flush logs immediately when log type is error and cloud logging is enabled', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var mockFetch, errorLogEntry; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
mockFetch = jest.fn().mockResolvedValueOnce({ ok: true }); | ||
global.fetch = mockFetch; | ||
errorLogEntry = { | ||
type: logging_buffer_1.LogEntryType.error, | ||
message: 'Error log message', | ||
details: [], | ||
}; | ||
// Ensure cloud logging is enabled | ||
mockConfig.enableCloudLogging = true; | ||
logBuffer = new logging_buffer_1.LogBuffer(acrolinxUrl, mockConfig); | ||
logBuffer.log(errorLogEntry); | ||
// Wait for a short delay to allow the flush to happen | ||
return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 100); })]; | ||
case 1: | ||
// Wait for a short delay to allow the flush to happen | ||
_a.sent(); | ||
expect(mockFetch).toHaveBeenCalledTimes(1); | ||
expect(logBuffer['buffer']).toHaveLength(0); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
test('should handle failed server response', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const mockFetch = jest.fn().mockResolvedValueOnce({ ok: false }); | ||
global.fetch = mockFetch; | ||
const logEntry = { | ||
type: logging_buffer_1.LogEntryType.error, | ||
message: TEST_LOG_MESSAGE, | ||
details: [], | ||
}; | ||
logBuffer.log(logEntry); | ||
yield new Promise((resolve) => setTimeout(resolve, 300)); | ||
expect(mockFetch).toHaveBeenCalledTimes(1); | ||
expect(logBuffer['retries']).toBe(1); | ||
expect(logBuffer['buffer']).toContain(logEntry); | ||
})); | ||
test('should flush logs immediately when log type is error and cloud logging is enabled', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const mockFetch = jest.fn().mockResolvedValueOnce({ ok: true }); | ||
global.fetch = mockFetch; | ||
const errorLogEntry = { | ||
type: logging_buffer_1.LogEntryType.error, | ||
message: 'Error log message', | ||
details: [], | ||
}; | ||
// Ensure cloud logging is enabled | ||
mockConfig.enableCloudLogging = true; | ||
logBuffer = new logging_buffer_1.LogBuffer(acrolinxUrl, mockConfig); | ||
logBuffer.log(errorLogEntry); | ||
// Wait for a short delay to allow the flush to happen | ||
yield new Promise((resolve) => setTimeout(resolve, 100)); | ||
expect(mockFetch).toHaveBeenCalledTimes(1); | ||
expect(logBuffer['buffer']).toHaveLength(0); | ||
})); | ||
}); | ||
//# sourceMappingURL=logging-buffer.test.js.map |
@@ -26,56 +26,21 @@ "use strict"; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var index_1 = require("../../src/index"); | ||
var mock_server_1 = require("../test-utils/mock-server"); | ||
var common_1 = require("./common"); | ||
describe('platform-notifications', function () { | ||
var endpoint; | ||
beforeEach(function () { | ||
const index_1 = require("../../src/index"); | ||
const mock_server_1 = require("../test-utils/mock-server"); | ||
const common_1 = require("./common"); | ||
describe('platform-notifications', () => { | ||
let endpoint; | ||
beforeEach(() => { | ||
(0, mock_server_1.mockAcrolinxServer)(common_1.DUMMY_SERVER_URL); | ||
endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
}); | ||
afterEach(function () { | ||
afterEach(() => { | ||
(0, mock_server_1.restoreOriginalFetch)(); | ||
}); | ||
it('get notifications', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var serverMessages; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, endpoint.getServerNotifications(mock_server_1.DUMMY_ACCESS_TOKEN, 0)]; | ||
case 1: | ||
serverMessages = _a.sent(); | ||
expect(Array.isArray(serverMessages.data.platformNotifications)).toBe(true); | ||
expect(serverMessages.data.requestTimeInMilliseconds).toBeGreaterThan(0); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('get notifications', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const serverMessages = yield endpoint.getServerNotifications(mock_server_1.DUMMY_ACCESS_TOKEN, 0); | ||
expect(Array.isArray(serverMessages.data.platformNotifications)).toBe(true); | ||
expect(serverMessages.data.requestTimeInMilliseconds).toBeGreaterThan(0); | ||
})); | ||
}); | ||
//# sourceMappingURL=platform-notifications.test.js.map |
@@ -26,181 +26,84 @@ "use strict"; | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var _ = require("lodash"); | ||
var index_1 = require("../../src/index"); | ||
var mixed_utils_1 = require("../../src/utils/mixed-utils"); | ||
var mock_server_1 = require("../test-utils/mock-server"); | ||
var utils_1 = require("../test-utils/utils"); | ||
var common_1 = require("./common"); | ||
describe('signin', function () { | ||
var endpoint; | ||
var mockedAcrolinxServer; | ||
beforeEach(function () { | ||
const _ = require("lodash"); | ||
const index_1 = require("../../src/index"); | ||
const mixed_utils_1 = require("../../src/utils/mixed-utils"); | ||
const mock_server_1 = require("../test-utils/mock-server"); | ||
const utils_1 = require("../test-utils/utils"); | ||
const common_1 = require("./common"); | ||
describe('signin', () => { | ||
let endpoint; | ||
let mockedAcrolinxServer; | ||
beforeEach(() => { | ||
mockedAcrolinxServer = (0, mock_server_1.mockAcrolinxServer)(common_1.DUMMY_SERVER_URL); | ||
endpoint = new index_1.AcrolinxEndpoint(common_1.DUMMY_ENDPOINT_PROPS); | ||
}); | ||
afterEach(function () { | ||
afterEach(() => { | ||
(0, mock_server_1.restoreOriginalFetch)(); | ||
}); | ||
it('should return the signin links', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var result; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, endpoint.signin()]; | ||
case 1: | ||
result = (_a.sent()); | ||
expect((0, index_1.isSigninLinksResult)(result)).toBeTruthy(); | ||
expect(_.startsWith(result.links.interactive, common_1.DUMMY_SERVER_URL + mock_server_1.DUMMY_SIGNIN_LINK_PATH_INTERACTIVE)).toBeTruthy(); | ||
expect(result.data.interactiveLinkTimeout).toEqual(mock_server_1.DUMMY_INTERACTIVE_LINK_TIMEOUT); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('should return the provided accessToken if valid', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var result; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, endpoint.signin({ accessToken: mock_server_1.DUMMY_ACCESS_TOKEN })]; | ||
case 1: | ||
result = (_a.sent()); | ||
if ((0, index_1.isSigninSuccessResult)(result)) { | ||
expect(result.data.accessToken).toEqual(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
} | ||
else { | ||
expect((0, index_1.isSigninSuccessResult)(result)).toBeTruthy(); | ||
} | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('polling should return accessToken after signin', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var signinLinks, pollResult1, signinSuccess; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, endpoint.signin()]; | ||
case 1: | ||
signinLinks = (_a.sent()); | ||
return [4 /*yield*/, endpoint.pollForSignin(signinLinks)]; | ||
case 2: | ||
pollResult1 = (_a.sent()); | ||
expect((0, index_1.isSigninSuccessResult)(pollResult1)).toBeFalsy(); | ||
expect(pollResult1.progress.retryAfter).toEqual(mock_server_1.DUMMY_RETRY_AFTER); | ||
mockedAcrolinxServer.fakeSignIn(); | ||
return [4 /*yield*/, endpoint.pollForSignin(signinLinks)]; | ||
case 3: | ||
signinSuccess = (_a.sent()); | ||
expect((0, index_1.isSigninSuccessResult)(signinSuccess)).toBeTruthy(); | ||
expect(signinSuccess.data.accessToken).toEqual(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
describe('signInWithSSO', function () { | ||
it('success', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var signinSuccess; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
mockedAcrolinxServer.enableSSO(mock_server_1.SsoMockMode.direct); | ||
return [4 /*yield*/, endpoint.signInWithSSO(mock_server_1.SSO_GENERIC_TOKEN, 'kaja')]; | ||
case 1: | ||
signinSuccess = _a.sent(); | ||
expect(signinSuccess.data.user.username).toEqual('kaja'); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('failure because of disabled SSO', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, (0, utils_1.expectFailingPromise)(endpoint.signInWithSSO(mock_server_1.SSO_GENERIC_TOKEN, 'kaja'), index_1.ErrorType.SSO)]; | ||
}); | ||
}); }); | ||
it('failure because of wrong generic password', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
mockedAcrolinxServer.enableSSO(mock_server_1.SsoMockMode.direct); | ||
return [2 /*return*/, (0, utils_1.expectFailingPromise)(endpoint.signInWithSSO('wrongGenericPassword', 'kaja'), index_1.ErrorType.SSO)]; | ||
}); | ||
}); }); | ||
it('should return the signin links', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const result = (yield endpoint.signin()); | ||
expect((0, index_1.isSigninLinksResult)(result)).toBeTruthy(); | ||
expect(_.startsWith(result.links.interactive, common_1.DUMMY_SERVER_URL + mock_server_1.DUMMY_SIGNIN_LINK_PATH_INTERACTIVE)).toBeTruthy(); | ||
expect(result.data.interactiveLinkTimeout).toEqual(mock_server_1.DUMMY_INTERACTIVE_LINK_TIMEOUT); | ||
})); | ||
it('should return the provided accessToken if valid', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const result = (yield endpoint.signin({ accessToken: mock_server_1.DUMMY_ACCESS_TOKEN })); | ||
if ((0, index_1.isSigninSuccessResult)(result)) { | ||
expect(result.data.accessToken).toEqual(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
} | ||
else { | ||
expect((0, index_1.isSigninSuccessResult)(result)).toBeTruthy(); | ||
} | ||
})); | ||
it('polling should return accessToken after signin', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const signinLinks = (yield endpoint.signin()); | ||
const pollResult1 = (yield endpoint.pollForSignin(signinLinks)); | ||
expect((0, index_1.isSigninSuccessResult)(pollResult1)).toBeFalsy(); | ||
expect(pollResult1.progress.retryAfter).toEqual(mock_server_1.DUMMY_RETRY_AFTER); | ||
mockedAcrolinxServer.fakeSignIn(); | ||
const signinSuccess = (yield endpoint.pollForSignin(signinLinks)); | ||
expect((0, index_1.isSigninSuccessResult)(signinSuccess)).toBeTruthy(); | ||
expect(signinSuccess.data.accessToken).toEqual(mock_server_1.DUMMY_ACCESS_TOKEN); | ||
})); | ||
describe('signInWithSSO', () => { | ||
it('success', () => __awaiter(void 0, void 0, void 0, function* () { | ||
mockedAcrolinxServer.enableSSO(mock_server_1.SsoMockMode.direct); | ||
const signinSuccess = yield endpoint.signInWithSSO(mock_server_1.SSO_GENERIC_TOKEN, 'kaja'); | ||
expect(signinSuccess.data.user.username).toEqual('kaja'); | ||
})); | ||
it('failure because of disabled SSO', () => __awaiter(void 0, void 0, void 0, function* () { | ||
return (0, utils_1.expectFailingPromise)(endpoint.signInWithSSO(mock_server_1.SSO_GENERIC_TOKEN, 'kaja'), index_1.ErrorType.SSO); | ||
})); | ||
it('failure because of wrong generic password', () => __awaiter(void 0, void 0, void 0, function* () { | ||
mockedAcrolinxServer.enableSSO(mock_server_1.SsoMockMode.direct); | ||
return (0, utils_1.expectFailingPromise)(endpoint.signInWithSSO('wrongGenericPassword', 'kaja'), index_1.ErrorType.SSO); | ||
})); | ||
}); | ||
describe.only('singInInteractive', function () { | ||
it('success with token', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var onSignInUrl, result; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
onSignInUrl = jest.fn(); | ||
return [4 /*yield*/, endpoint.singInInteractive({ onSignInUrl: onSignInUrl, accessToken: mock_server_1.DUMMY_ACCESS_TOKEN })]; | ||
case 1: | ||
result = _a.sent(); | ||
expect(onSignInUrl).toHaveBeenCalledTimes(0); | ||
expect(result.user.username).toEqual(mock_server_1.DUMMY_USER_NAME); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('polling', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var onSignInUrl, singInInteractivePromise, result; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
onSignInUrl = jest.fn(); | ||
singInInteractivePromise = endpoint.singInInteractive({ onSignInUrl: onSignInUrl }); | ||
mockedAcrolinxServer.fakeSignIn(); | ||
return [4 /*yield*/, singInInteractivePromise]; | ||
case 1: | ||
result = _a.sent(); | ||
expect(onSignInUrl).toHaveBeenCalledTimes(1); | ||
expect(onSignInUrl.mock.calls[0][0]).toMatch(/^http/); | ||
expect(result.user.username).toEqual(mock_server_1.DUMMY_USER_NAME); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
it('polling timeout', function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var onSignInUrl, singInInteractivePromise; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
onSignInUrl = jest.fn(); | ||
singInInteractivePromise = endpoint.singInInteractive({ onSignInUrl: onSignInUrl, timeoutMs: 100 }); | ||
return [4 /*yield*/, (0, mixed_utils_1.waitMs)(1000)]; | ||
case 1: | ||
_a.sent(); | ||
expect(onSignInUrl).toHaveBeenCalledTimes(1); | ||
expect(onSignInUrl.mock.calls[0][0]).toMatch(/^http/); | ||
return [4 /*yield*/, (0, utils_1.expectFailingPromise)(singInInteractivePromise, index_1.ErrorType.SigninTimedOut)]; | ||
case 2: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
describe.only('singInInteractive', () => { | ||
it('success with token', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const onSignInUrl = jest.fn(); | ||
const result = yield endpoint.singInInteractive({ onSignInUrl, accessToken: mock_server_1.DUMMY_ACCESS_TOKEN }); | ||
expect(onSignInUrl).toHaveBeenCalledTimes(0); | ||
expect(result.user.username).toEqual(mock_server_1.DUMMY_USER_NAME); | ||
})); | ||
it('polling', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const onSignInUrl = jest.fn(); | ||
const singInInteractivePromise = endpoint.singInInteractive({ onSignInUrl }); | ||
mockedAcrolinxServer.fakeSignIn(); | ||
const result = yield singInInteractivePromise; | ||
expect(onSignInUrl).toHaveBeenCalledTimes(1); | ||
expect(onSignInUrl.mock.calls[0][0]).toMatch(/^http/); | ||
expect(result.user.username).toEqual(mock_server_1.DUMMY_USER_NAME); | ||
})); | ||
it('polling timeout', () => __awaiter(void 0, void 0, void 0, function* () { | ||
const onSignInUrl = jest.fn(); | ||
const singInInteractivePromise = endpoint.singInInteractive({ onSignInUrl, timeoutMs: 100 }); | ||
yield (0, mixed_utils_1.waitMs)(1000); | ||
expect(onSignInUrl).toHaveBeenCalledTimes(1); | ||
expect(onSignInUrl.mock.calls[0][0]).toMatch(/^http/); | ||
yield (0, utils_1.expectFailingPromise)(singInInteractivePromise, index_1.ErrorType.SigninTimedOut); | ||
})); | ||
}); | ||
}); | ||
//# sourceMappingURL=signin.test.js.map |
@@ -18,37 +18,29 @@ /* | ||
module.exports = { | ||
"transform": { | ||
"^.+\\.ts$": "ts-jest" | ||
transform: { | ||
'^.+\\.ts$': 'ts-jest', | ||
}, | ||
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(ts)$", | ||
"moduleFileExtensions": [ | ||
"ts", | ||
"js" | ||
], | ||
"coverageDirectory": "tmp/coverage", | ||
"coverageReporters": [ | ||
"cobertura", | ||
"json", | ||
"lcov", | ||
"text" | ||
], | ||
"collectCoverageFrom": [ | ||
"src/**/*", | ||
], | ||
"coverageThreshold": { | ||
"global": { | ||
"statements": 93.5, | ||
"branches": 81, | ||
"functions": 86, | ||
"lines": 93.70, | ||
} | ||
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(ts)$', | ||
moduleFileExtensions: ['ts', 'js'], | ||
coverageDirectory: 'tmp/coverage', | ||
coverageReporters: ['cobertura', 'json', 'lcov', 'text'], | ||
collectCoverageFrom: ['src/**/*'], | ||
coverageThreshold: { | ||
global: { | ||
statements: 93.5, | ||
branches: 81, | ||
functions: 86, | ||
lines: 93.7, | ||
}, | ||
}, | ||
"reporters": [ | ||
"default", | ||
["jest-junit", { | ||
"outputDirectory": "tmp", | ||
"outputName": "junit.xml" | ||
} | ||
] | ||
reporters: [ | ||
'default', | ||
[ | ||
'jest-junit', | ||
{ | ||
outputDirectory: 'tmp', | ||
outputName: 'junit.xml', | ||
}, | ||
], | ||
], | ||
"testURL": "http://localhost/" | ||
testURL: 'http://localhost/', | ||
}; |
{ | ||
"name": "@acrolinx/sdk", | ||
"version": "1.2.0", | ||
"version": "1.3.0-dev.1", | ||
"description": "Acrolinx JavaScript SDK for the Acrolinx API", | ||
@@ -14,2 +14,5 @@ "license": "Apache-2.0", | ||
}, | ||
"publishConfig": { | ||
"tag": "dev" | ||
}, | ||
"scripts": { | ||
@@ -16,0 +19,0 @@ "ci": "npm run build && npm run lint && npm run testCoverage", |
{ | ||
"compilerOptions": { | ||
"target": "es5", | ||
"target": "ES6", | ||
"lib": [ | ||
"ES2015.Promise", | ||
"ES2015.Iterable", | ||
"ES5", | ||
"DOM" | ||
], | ||
"module": "commonjs", | ||
"module": "CommonJS", | ||
"resolveJsonModule": true, | ||
@@ -12,0 +9,0 @@ "noImplicitAny": true, |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
606485
12023
2