@azure/ai-text-analytics
Version:
An isomorphic client library for the Azure Text Analytics service.
187 lines • 6.61 kB
JavaScript
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __rest } from "tslib";
import { RestError } from "@azure/core-rest-pipeline";
import { URL, URLSearchParams } from "./utils/url";
import { logger } from "./logger";
/**
* Given a sorted array of input objects (with a unique ID) and an unsorted array of results,
* return a sorted array of results.
*
* @internal
* @param sortedArray - An array of entries sorted by `id`
* @param unsortedArray - An array of entries that contain `id` but are not sorted
*/
export function sortResponseIdObjects(sortedArray, unsortedArray) {
const unsortedMap = new Map();
for (const item of unsortedArray) {
unsortedMap.set(item.id, item);
}
if (unsortedArray.length !== sortedArray.length) {
const ordinal = unsortedArray.length > sortedArray.length ? "more" : "fewer";
logger.warning(`The service returned ${ordinal} responses than inputs. Some errors may be treated as fatal.`);
}
const result = [];
for (const sortedItem of sortedArray) {
const item = unsortedMap.get(sortedItem.id);
if (item) {
result.push(item);
}
}
return result;
}
/**
* @internal
*/
export function parseAssessmentIndex(pointer) {
const regex = new RegExp(/#\/documents\/(\d+)\/sentences\/(\d+)\/assessments\/(\d+)/);
const res = regex.exec(pointer);
if (res !== null) {
const assessmentIndex = {
document: parseInt(res[1]),
sentence: parseInt(res[2]),
assessment: parseInt(res[3])
};
return assessmentIndex;
}
else {
throw new Error(`Pointer "${pointer}" is not a valid Assessment pointer`);
}
}
/**
* Parses the index of the healthcare entity from a JSON pointer.
* @param pointer - a JSON pointer representing an entity
* @internal
*/
export function parseHealthcareEntityIndex(pointer) {
const regex = new RegExp(/#\/results\/documents\/(\d+)\/entities\/(\d+)/);
const res = regex.exec(pointer);
if (res !== null) {
return parseInt(res[2]);
}
else {
throw new Error(`Pointer "${pointer}" is not a valid healthcare entity pointer`);
}
}
const jsEncodingUnit = "Utf16CodeUnit";
/**
* @internal
*/
export function addStrEncodingParam(options) {
return Object.assign(Object.assign({}, options), { stringIndexType: options.stringIndexType || jsEncodingUnit });
}
/**
* Set the stringIndexType property with default if it does not exist in x.
* @param options - operation options bag that has a {@link StringIndexType}
* @internal
*/
export function setStrEncodingParam(x) {
return Object.assign(Object.assign({}, x), { stringIndexType: x.stringIndexType || jsEncodingUnit });
}
export function setStrEncodingParamValue(stringIndexType) {
return stringIndexType || jsEncodingUnit;
}
/**
* Set the opinion mining property
* @internal
*/
export function setOpinionMining(x) {
return Object.assign(Object.assign({}, x), { opinionMining: x.includeOpinionMining });
}
/**
* Set the pii categories property
* @internal
*/
export function setCategoriesFilter(x) {
return Object.assign(Object.assign({}, x), { piiCategories: x.categoriesFilter });
}
/**
* @internal
*/
export function addParamsToTask(action) {
const { actionName } = action, params = __rest(action, ["actionName"]);
return { parameters: params, taskName: actionName };
}
/**
* Set the modelVersion property with default if it does not exist in x.
* @param options - operation options bag that has a {@link StringIndexType}
* @internal
*/
export function setModelVersionParam(x) {
return Object.assign(Object.assign({}, x), { modelVersion: x.modelVersion || "latest" });
}
/**
* @internal
*/
export function nextLinkToTopAndSkip(nextLink) {
const url = new URL(nextLink);
const searchParams = new URLSearchParams(url.searchParams);
let top;
if (searchParams.has("$top")) {
top = parseInt(searchParams.get("$top"));
}
else {
throw new Error(`nextLink URL does not have the $top param: ${nextLink}`);
}
let skip;
if (searchParams.has("$skip")) {
skip = parseInt(searchParams.get("$skip"));
}
else {
throw new Error(`nextLink URL does not have the $skip param: ${nextLink}`);
}
return {
skip: skip,
top: top
};
}
/**
* @internal
*/
export function getOperationId(operationLocation) {
const lastSlashIndex = operationLocation.lastIndexOf("/");
return operationLocation.substring(lastSlashIndex + 1);
}
/**
* @internal
* parses incoming errors from the service and if the inner error code is
* InvalidDocumentBatch, it exposes that as the statusCode instead.
* @param error - the incoming error
*/
export function handleInvalidDocumentBatch(error) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const castError = error;
const innerCode = (_d = (_c = (_b = (_a = castError.response) === null || _a === void 0 ? void 0 : _a.parsedBody) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.innererror) === null || _d === void 0 ? void 0 : _d.code;
const innerMessage = (_h = (_g = (_f = (_e = castError.response) === null || _e === void 0 ? void 0 : _e.parsedBody) === null || _f === void 0 ? void 0 : _f.error) === null || _g === void 0 ? void 0 : _g.innererror) === null || _h === void 0 ? void 0 : _h.message;
if (innerMessage) {
return innerCode === "InvalidDocumentBatch"
? new RestError(innerMessage, { code: innerCode, statusCode: castError.statusCode })
: error;
}
else {
// unfortunately, the service currently does not follow the swagger definition
// for errors in some cases.
// Issue: https://msazure.visualstudio.com/Cognitive%20Services/_workitems/edit/8775003/?workitem=8972164
// throw new Error(
// `The error coming from the service does not follow the expected structure: ${error}`
// );
logger.warning(`The error coming from the service does not follow the expected structure: ${error}`);
return error;
}
}
/**
* A wrapper for setTimeout that resolves a promise after t milliseconds.
* @internal
* @param timeInMs - The number of milliseconds to be delayed.
* @returns Resolved promise
*/
export function delay(timeInMs) {
return new Promise((resolve) => setTimeout(() => resolve(), timeInMs));
}
/**
* @internal
*/
export function compose(fn1, fn2) {
return (value) => fn2(fn1(value));
}
//# sourceMappingURL=util.js.map