@kduprey/perspective-api-client
Version:
Client library for the Perspective API
157 lines (156 loc) • 5.17 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
MAX_LENGTH: () => MAX_LENGTH,
PerspectiveAPIClientError: () => PerspectiveAPIClientError,
ResponseError: () => ResponseError,
TextEmptyError: () => TextEmptyError,
TextTooLongError: () => TextTooLongError,
default: () => src_default
});
module.exports = __toCommonJS(src_exports);
var import_axios = __toESM(require("axios"));
var import_lodash = __toESM(require("lodash"));
var import_iso_639_1 = __toESM(require("iso-639-1"));
var COMMENT_ANALYZER_URL = "https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze";
var MAX_LENGTH = 20480;
var PerspectiveAPIClientError = class extends Error {
constructor(message) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = "PerspectiveAPIClientError";
}
};
var TextEmptyError = class extends PerspectiveAPIClientError {
constructor() {
super("text must not be empty");
this.name = "TextEmptyError";
}
};
var TextTooLongError = class extends PerspectiveAPIClientError {
constructor() {
super(
`text must not be greater than ${MAX_LENGTH.toString()} characters in length`
);
this.name = "TextTooLongError";
}
};
var ResponseError = class extends PerspectiveAPIClientError {
response;
constructor(message, response) {
super(message);
this.response = response;
this.name = "ResponseError";
}
};
var Perspective = class {
static PerspectiveAPIClientError;
static TextEmptyError;
static TextTooLongError;
static ResponseError;
apiKey;
constructor({ apiKey }) {
this.apiKey = apiKey;
if (!this.apiKey) {
throw new Error("Must provide options.apiKey");
}
}
async analyze(text, attriubtes, options) {
const request = {
comment: { text },
requestedAttributes: this.parseAttributes(attriubtes ?? { TOXICITY: {} }),
...options
};
this.validateComment(text);
if (options?.languages) {
this.validateLanguages(options.languages);
request.languages = options.languages;
}
const response = await import_axios.default.post(COMMENT_ANALYZER_URL, request, {
params: { key: this.apiKey }
}).catch((error) => {
if (import_axios.default.isAxiosError(error)) {
const responseError = new ResponseError(error.message, error);
throw responseError;
}
console.error("Unknown error", error);
return Promise.reject(new Error("Unknown error - see logs"));
});
return response.data;
}
validateComment(text) {
if (!text) {
throw new TextEmptyError();
}
if (text.length > MAX_LENGTH) {
throw new TextTooLongError();
}
}
validateLanguages(languages) {
languages.forEach((language) => {
if (import_iso_639_1.default.validate(language)) {
throw new PerspectiveAPIClientError(
`language ${language} is not supported`
);
}
});
}
parseAttributes(attributes) {
if (import_lodash.default.isArray(attributes)) {
return import_lodash.default.reduce(
attributes,
(acc, attribute) => {
acc[attribute] = {};
return acc;
},
{}
);
}
Object.values(attributes).forEach((attribute) => {
if (attribute.scoreThreshold && (attribute.scoreThreshold < 0 || attribute.scoreThreshold > 1)) {
throw new PerspectiveAPIClientError(
"scoreThreshold must be between 0 and 1"
);
}
});
return attributes;
}
};
var src_default = Perspective;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MAX_LENGTH,
PerspectiveAPIClientError,
ResponseError,
TextEmptyError,
TextTooLongError
});
//# sourceMappingURL=index.js.map