mindee
Version:
Mindee Client Library for Node.js
195 lines (194 loc) • 7.29 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocalInputSource = exports.MIMETYPES = void 0;
const handler_1 = require("../../errors/handler");
const logger_1 = require("../../logger");
const imageOperations_1 = require("../../imageOperations");
const pdf_1 = require("../../pdf");
const path_1 = __importDefault(require("path"));
const fileType = __importStar(require("file-type"));
const pdf_2 = require("../../pdf");
const inputSource_1 = require("./inputSource");
exports.MIMETYPES = new Map([
[".pdf", "application/pdf"],
[".heic", "image/heic"],
[".jpg", "image/jpeg"],
[".jpeg", "image/jpeg"],
[".png", "image/png"],
[".tif", "image/tiff"],
[".tiff", "image/tiff"],
[".webp", "image/webp"],
]);
const ALLOWED_INPUT_TYPES = [
inputSource_1.INPUT_TYPE_STREAM,
inputSource_1.INPUT_TYPE_BASE64,
inputSource_1.INPUT_TYPE_BYTES,
inputSource_1.INPUT_TYPE_PATH,
inputSource_1.INPUT_TYPE_BUFFER,
];
class LocalInputSource extends inputSource_1.InputSource {
/**
* @param {InputConstructor} constructor Constructor parameters.
*/
constructor({ inputType }) {
super();
this.filename = "";
this.mimeType = "";
// Check if inputType is valid
if (!ALLOWED_INPUT_TYPES.includes(inputType)) {
const allowed = Array.from(ALLOWED_INPUT_TYPES.keys()).join(", ");
handler_1.errorHandler.throw(new Error(`Invalid input type, must be one of ${allowed}.`));
}
this.inputType = inputType;
logger_1.logger.debug(`Loading file from: ${inputType}`);
}
async checkMimetype() {
if (!(this.fileObject instanceof Buffer)) {
throw new Error(`MIME type cannot be verified on input source of type ${this.inputType}.`);
}
let mimeType;
const fileExt = path_1.default.extname(this.filename);
if (fileExt) {
mimeType = exports.MIMETYPES.get(fileExt.toLowerCase()) || "";
}
else {
const guess = await fileType.fromBuffer(this.fileObject);
if (guess !== undefined) {
mimeType = guess.mime;
}
else {
throw "Could not determine the MIME type of the file";
}
}
if (!mimeType) {
const allowed = Array.from(exports.MIMETYPES.keys()).join(", ");
const err = new Error(`Invalid file type, must be one of ${allowed}.`);
handler_1.errorHandler.throw(err);
}
logger_1.logger.debug(`File is of type: ${mimeType}`);
return mimeType;
}
/**
* Returns the file object as a Buffer.
* @returns Buffer representation of the file object
* @protected
*/
getBuffer() {
if (typeof this.fileObject === "string") {
return Buffer.from(this.fileObject);
}
return this.fileObject;
}
/**
* Determines whether the current file is a PDF.
* @returns {boolean} Returns true if the file is a PDF; otherwise, returns false.
*/
isPdf() {
if (!this.initialized) {
throw new Error("The `init()` method must be called before calling `isPdf()`.");
}
return this.mimeType === "application/pdf";
}
/**
* Cut PDF pages.
* @param pageOptions
*/
async applyPageOptions(pageOptions) {
await this.init();
const buffer = this.getBuffer();
const processedPdf = await (0, pdf_2.extractPages)(buffer, pageOptions);
this.fileObject = processedPdf.file;
}
/**
* Cut PDF pages.
* @param pageOptions
* @deprecated Deprecated in favor of {@link LocalInputSource.applyPageOptions}.
*/
async cutPdf(pageOptions) {
return this.applyPageOptions(pageOptions);
}
/**
* Compresses the file object, either as a PDF or an image.
*
* @param quality Quality of the compression. For images, this is the JPEG quality.
* For PDFs, this affects image quality within the PDF.
* @param maxWidth Maximum width for image resizing. Ignored for PDFs.
* @param maxHeight Maximum height for image resizing. Ignored for PDFs.
* @param forceSourceText For PDFs, whether to force compression even if source text is present.
* @param disableSourceText For PDFs, whether to disable source text during compression.
*
* @returns A Promise that resolves when the compression is complete.
*/
async compress(quality = 85, maxWidth = null, maxHeight = null, forceSourceText = false, disableSourceText = true) {
await this.init();
const buffer = this.getBuffer();
if (this.isPdf()) {
this.fileObject = await (0, pdf_1.compressPdf)(buffer, quality, forceSourceText, disableSourceText);
}
else {
this.fileObject = await (0, imageOperations_1.compressImage)(buffer, quality, maxWidth, maxHeight);
}
}
/**
* Returns true if the object is a PDF and has source text. False otherwise.
* @return boolean
*/
async hasSourceText() {
await this.init();
if (!this.isPdf()) {
return false;
}
const buffer = this.getBuffer();
return (0, pdf_2.hasSourceText)(buffer);
}
/**
* Returns the number of pages in the input source.
* For PDFs, returns the actual page count. For images, returns 1.
* @return Promise<number> The number of pages
*/
async getPageCount() {
await this.init();
if (!this.isPdf()) {
return 1;
}
const buffer = this.getBuffer();
return (0, pdf_1.countPages)(buffer);
}
}
exports.LocalInputSource = LocalInputSource;