diff --git a/package-lock.json b/package-lock.json index 86cafad0..11dc1c53 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,17 +1,14 @@ { - "name": "@vector-express/api-client", + "name": "@vector-express/sdk", "version": "2.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "@vector-express/api-client", + "name": "@vector-express/sdk", "version": "2.0.0", "hasInstallScript": true, "license": "ISC", - "dependencies": { - "axios": "^1.4.0" - }, "devDependencies": { "@types/mocha": "^10.0.1", "@types/node": "^18.0.0", @@ -1469,21 +1466,6 @@ "node": ">=8" } }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" - }, - "node_modules/axios": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.4.0.tgz", - "integrity": "sha512-S4XCWMEmzvo64T9GfvQDOXgYRDJ/wsSZc7Jvdgx5u1sd0JwsuPLqb3SYmusag+edF6ziyMensPVqLTSc1PiSEA==", - "dependencies": { - "follow-redirects": "^1.15.0", - "form-data": "^4.0.0", - "proxy-from-env": "^1.1.0" - } - }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -1701,17 +1683,6 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/commondir": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", @@ -1797,14 +1768,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/diff": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", @@ -2290,25 +2253,6 @@ "integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==", "dev": true }, - "node_modules/follow-redirects": { - "version": "1.15.2", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", - "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } - }, "node_modules/foreground-child": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-2.0.0.tgz", @@ -2322,19 +2266,6 @@ "node": ">=8.0.0" } }, - "node_modules/form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" - } - }, "node_modules/fromentries": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/fromentries/-/fromentries-1.3.2.tgz", @@ -2987,25 +2918,6 @@ "node": ">=8.6" } }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -3595,11 +3507,6 @@ "node": ">=8" } }, - "node_modules/proxy-from-env": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", - "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" - }, "node_modules/punycode": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", diff --git a/package.json b/package.json index 27388b25..30676d9a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@vector-express/sdk", - "version": "2.0.0", + "version": "2.0.1", "description": "An API wrapper for the Vector Express API (v2)", "main": "dist/index.js", "module": "./dist/index.mjs", @@ -11,6 +11,7 @@ "files": [ "dist/**/*" ], + "type": "module", "scripts": { "lint": "eslint . --ext .js,.jsx,.ts,.tsx", "lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix", @@ -41,11 +42,10 @@ }, "license": "ISC", "dependencies": { - "axios": "^1.4.0" }, "devDependencies": { "@types/mocha": "^10.0.1", - "@types/node": "^18.0.0", + "@types/node": "^20.0.0", "@typescript-eslint/eslint-plugin": "^5.57.1", "@typescript-eslint/parser": "^5.57.1", "esbuild": "^0.17.15", diff --git a/samples/analyze.ts b/samples/analyze.ts index 96bea53e..1bcca80a 100644 --- a/samples/analyze.ts +++ b/samples/analyze.ts @@ -14,9 +14,9 @@ */ import fs from 'node:fs'; -import vectorExpress from '../src/index.js'; +import * as vectorExpress from '../src/index.js'; -const file = fs.readFileSync(__dirname + '/files/drawing2.svg'); +const file = fs.readFileSync(process.cwd() + '/files/drawing2.svg'); /* analyze svg file */ vectorExpress.analyze('svg', ['groups'], { file }).then(console.log); diff --git a/samples/convert.ts b/samples/convert.ts index 4879cd60..0934e553 100644 --- a/samples/convert.ts +++ b/samples/convert.ts @@ -14,9 +14,9 @@ */ import fs from 'node:fs'; -import vectorExpress from '../src/index.js'; +import * as vectorExpress from '../src/index.js'; -const file = fs.readFileSync(__dirname + '/files/drawing3.dwg'); +const file = fs.readFileSync(process.cwd() + '/files/drawing3.dwg'); /* convert file from .dwg to .pdf */ vectorExpress.convert('dwg', 'pdf', { file }).then(console.log); diff --git a/samples/convertAndSave.ts b/samples/convertAndSave.ts index 75605721..8fe97817 100644 --- a/samples/convertAndSave.ts +++ b/samples/convertAndSave.ts @@ -14,16 +14,16 @@ */ import fs from 'node:fs'; -import vectorExpress from '../src/index.js'; +import * as vectorExpress from '../src/index.js'; -const file = fs.readFileSync(__dirname + '/files/drawing3.dwg'); +const file = fs.readFileSync(process.cwd() + '/files/drawing3.dwg'); /* convert file from .dwg to .pdf */ vectorExpress .convert('dwg', 'pdf', { file, save: true, - path: __dirname + '/mysuperfolder/mysuperfile.pdf', + path: process.cwd() + '/mysuperfolder/mysuperfile.pdf', }) .then(console.log); /* diff --git a/samples/convertProcessAnalyze.ts b/samples/convertProcessAnalyze.ts index 1c9e4327..24000bf1 100644 --- a/samples/convertProcessAnalyze.ts +++ b/samples/convertProcessAnalyze.ts @@ -14,9 +14,9 @@ */ import fs from 'node:fs'; -import vectorExpress from '../src/index.js'; +import * as vectorExpress from '../src/index.js'; -const file = fs.readFileSync(__dirname + '/files/drawing3.dwg'); +const file = fs.readFileSync(process.cwd() + '/files/drawing3.dwg'); (async function () { /* send file to the server */ diff --git a/samples/convertSpecifyConvertionPath.ts b/samples/convertSpecifyConvertionPath.ts index 593451b5..8c6ee521 100644 --- a/samples/convertSpecifyConvertionPath.ts +++ b/samples/convertSpecifyConvertionPath.ts @@ -14,9 +14,9 @@ */ import fs from 'node:fs'; -import vectorExpress from '../src/index.js'; +import * as vectorExpress from '../src/index.js'; -const file = fs.readFileSync(__dirname + '/files/drawing1.svg'); +const file = fs.readFileSync(process.cwd() + '/files/drawing1.svg'); /* convert file from .svg to .pdf using these converters : 'librsvg', 'eps', 'gs' */ vectorExpress diff --git a/samples/convertWithOptions.ts b/samples/convertWithOptions.ts index d604617d..d0d85d64 100644 --- a/samples/convertWithOptions.ts +++ b/samples/convertWithOptions.ts @@ -14,9 +14,9 @@ */ import fs from 'node:fs'; -import vectorExpress from '../src/index.js'; +import * as vectorExpress from '../src/index.js'; -const file = fs.readFileSync(__dirname + '/files/drawing3.dwg'); +const file = fs.readFileSync(process.cwd() + '/files/drawing3.dwg'); /* convert file from .dwg to .svg diff --git a/samples/get.ts b/samples/get.ts index 614c80be..d64a5d2f 100644 --- a/samples/get.ts +++ b/samples/get.ts @@ -13,7 +13,7 @@ * PERFORMANCE OF THIS SOFTWARE. */ -import vectorExpress from '../src/index.js'; +import * as vectorExpress from '../src/index.js'; /* get data */ vectorExpress diff --git a/samples/post.ts b/samples/post.ts index 5dd1e523..9db3b72f 100644 --- a/samples/post.ts +++ b/samples/post.ts @@ -14,9 +14,9 @@ */ import fs from 'node:fs'; -import vectorExpress from '../src/index.js'; +import * as vectorExpress from '../src/index.js'; -const file = fs.readFileSync(__dirname + '/files/drawing1.svg'); +const file = fs.readFileSync(process.cwd() + '/files/drawing1.svg'); /* post data */ vectorExpress diff --git a/samples/process.ts b/samples/process.ts index 49bb8cac..2288ce56 100644 --- a/samples/process.ts +++ b/samples/process.ts @@ -14,9 +14,9 @@ */ import fs from 'node:fs'; -import vectorExpress from '../src/index.js'; +import * as vectorExpress from '../src/index.js'; -const file = fs.readFileSync(__dirname + '/files/drawing2.svg'); +const file = fs.readFileSync(process.cwd() + '/files/drawing2.svg'); /* process svg file */ vectorExpress.process('svg', ['exclude-groups'], { file }).then((res) => { diff --git a/samples/processAndSave.ts b/samples/processAndSave.ts index 752d78c9..bbfd6fcc 100644 --- a/samples/processAndSave.ts +++ b/samples/processAndSave.ts @@ -14,9 +14,9 @@ */ import fs from 'node:fs'; -import vectorExpress from '../src/index.js'; +import * as vectorExpress from '../src/index.js'; -const file = fs.readFileSync(__dirname + '/files/drawing2.svg'); +const file = fs.readFileSync(process.cwd() + '/files/drawing2.svg'); /* process svg file */ vectorExpress diff --git a/samples/processWithOptions.ts b/samples/processWithOptions.ts index 94ed655f..9fe6f39d 100644 --- a/samples/processWithOptions.ts +++ b/samples/processWithOptions.ts @@ -14,9 +14,9 @@ */ import fs from 'node:fs'; -import vectorExpress from '../src/index.js'; +import * as vectorExpress from '../src/index.js'; -const file = fs.readFileSync(__dirname + '/files/drawing2.svg'); +const file = fs.readFileSync(process.cwd() + '/files/drawing2.svg'); /* process svg file diff --git a/src/index.ts b/src/index.ts index 67058553..a5d4c19c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,59 +26,92 @@ */ import fs from 'node:fs/promises'; -import axios, { AxiosRequestConfig } from 'axios'; +import { join } from 'node:path'; +import { cwd } from 'node:process'; -const APIWrapper_ = Object.create(null); - -APIWrapper_.basePath = 'https://vector.express'; -APIWrapper_.publicPath = 'https://vector.express/api/v2/public'; -APIWrapper_.meteredPath = 'https://vector.express/api/v2/metered'; +const basePath = 'https://vector.express'; +const publicPath = 'https://vector.express/api/v2/public'; +const meteredPath = 'https://vector.express/api/v2/metered'; /** * Sends request to a url, returns Promise. */ -APIWrapper_.get = async function (url: string, format: string) { +const get_ = async ( + url: string | URL, + format?: T, +): Promise> => { if (!url) - throw new Error('Please provide all obligatory args : url, format'); + throw new TypeError('Please provide all obligatory args: url, format'); - if (typeof url !== 'string') - throw new Error('Please provide url string as a parameter'); + if (typeof url !== 'string' && !(url instanceof URL)) + throw new TypeError('Please provide url string as a parameter'); - const res = await axios.get(url); + const res = await fetch(url); + if (!res.ok) { + throw new Error( + `Error fetching ${url}: unexpected response code ${res.status}`, + ); + } if (format === 'full') return res; - return res.data; + return res.json(); }; /** * Sends data to the url, returns Promise. */ -APIWrapper_.post = async function (url: string, data: Uint8Array) { - if (!url) throw new Error('Please provide all obligatory args : url, data'); +const post_ = async (url: string | URL, data: BodyInit): Promise => { + if (!url) + throw new TypeError('Please provide all obligatory args: url, data'); - if (typeof url !== 'string') + if (typeof url !== 'string' && !(url instanceof URL)) throw new Error('Please provide url string as a parameter'); - const res = await axios({ url, method: 'post', data }); + const res = await fetch(url, { method: 'POST', body: data }); + if (!res.ok) { + throw new Error( + `Error fetching ${url}: unexpected response code ${res.status}`, + ); + } return res; }; -APIWrapper_.convert = async function ( +const convert_ = async < + T extends + | { + ['transformers']?: string[]; + ['params']: + | string + | URLSearchParams + | string[][] + | Record; + ['token']?: string | null; + ['save']?: boolean | null; + ['path']?: string | null; + } + | { + ['file']: BodyInit; + ['transformers']?: string[]; + ['params']?: + | string + | URLSearchParams + | string[][] + | Record + | undefined + | null; + ['token']?: string | null; + ['save']?: boolean | null; + ['path']?: string | null; + }, +>( inputFormat: string, outputFormat: string, - options?: { - ['file']?: Buffer | null; - ['transformers']?: string[]; - ['params']?: Record | null; - ['token']?: string | null; - ['save']?: boolean | null; - ['path']?: string | null; - }, -) { + options: T, +) => { /* obligatory : inputFormat @@ -96,19 +129,24 @@ APIWrapper_.convert = async function ( either options.file or options.params[ 'use-file' ] must be specified */ - if (!inputFormat || !outputFormat) - throw new Error( + if (!inputFormat || !outputFormat) { + throw new TypeError( 'Please provide all obligatory args : inputFormat, outputFormat', ); - - if (!options) { - options = {}; } - if (!options.file && (!options.params || !options.params['use-file'])) - throw new Error( + const params = options['params'] + ? new URLSearchParams(options['params']) + : null; + + if ( + Object.prototype.hasOwnProperty.call(options, 'file') === + !!params?.get('use-file') + ) { + throw new TypeError( "Please provide a file or specify file on a server through 3d arg : options( options.params[ 'use-file' ] field )", ); + } let url: string; let transformers: string; @@ -116,68 +154,99 @@ APIWrapper_.convert = async function ( if (!options.transformers) { let paths; - if (options.token) { - paths = await axios({ - url: `${this.meteredPath}/convert/${inputFormat}/auto/${outputFormat}/`, - method: 'get', - headers: { Authorization: `Bearer ${options.token}` }, - }); + if (options['token']) { + paths = await fetch( + `${meteredPath}/convert/${inputFormat}/auto/${outputFormat}/`, + { + ['headers']: [['authorization', `Bearer ${options.token}`]], + }, + ); } else { - paths = await axios.get( - `${this.publicPath}/convert/${inputFormat}/auto/${outputFormat}/`, + paths = await fetch( + `${publicPath}/convert/${inputFormat}/auto/${outputFormat}/`, ); } - paths = paths.data.alternatives.map( + if (!paths.ok) { + if (!paths.ok) { + throw new Error( + `Error fetching possible transformers: unexpected response code ${paths.status}`, + ); + } + } + + paths = (await paths.json())['alternatives'].map( (el: { ['path']: string }) => el.path, ); - url = `${this.basePath}${paths[0]}`; + url = `${basePath}${paths[0]}${params ? `?${params}` : ''}`; } else { transformers = options.transformers.join('/'); url = `${ - options.token ? this.meteredPath : this.publicPath - }/convert/${inputFormat}/${transformers}/${outputFormat}`; + options.token ? meteredPath : publicPath + }/convert/${inputFormat}/${transformers}/${outputFormat}${ + params ? `?${params}` : '' + }`; } /* - config - */ - const config = Object.create(null); + const config: RequestInit = Object.create(null); - config.url = url; - config.method = 'post'; + config['method'] = 'POST'; - if (options.params) config.params = options.params; + if (Object.prototype.hasOwnProperty.call(config, 'file')) + config['body'] = (options as unknown as { ['file']: BodyInit })['file']; - if (options.params && options.params['use-file']) config.data = undefined; - else config.data = options.file; - - if (options.token) - config.headers = { Authorization: `Bearer ${options.token}` }; + if (options['token']) + config['headers'] = [['authorization', `Bearer ${options.token}`]]; /* - config - */ - const res = await axios(config); + const res = await fetch(url, config); + if (!res.ok) { + throw new Error( + `Error fetching ${url}: unexpected response code ${res.status}`, + ); + } - if (options.save) { - const path = options.path || `${__dirname}/file.${res.data.format}`; - return APIWrapper_.downloadAndSave(res.data.resultUrl, path); + const result = await res.json(); + if (options['save']) { + const path = options.path || join(cwd(), `file.${result['format']}`); + return downloadAndSave_(result['resultUrl'], path); } else { - return res.data.resultUrl; + return result['resultUrl']; } }; /* */ -APIWrapper_.analyze = async function ( +const analyze_ = async < + T extends + | { + ['params']: + | string + | URLSearchParams + | string[][] + | Record; + ['token']?: string | null; + } + | { + ['file']: BodyInit; + ['params']?: + | string + | URLSearchParams + | string[][] + | Record + | undefined + | null; + ['token']?: string | null; + }, +>( format: string, analyzers: string | string[], - options?: { - ['file']?: Buffer | null; - ['params']?: Record | null; - ['token']?: string | null; - }, -) { + options: T, +) => { /* obligatory : format @@ -192,10 +261,24 @@ APIWrapper_.analyze = async function ( either options.file or options.params[ 'use-file' ] must be specified */ - if (!format || !analyzers) - throw new Error( + if (!format || !analyzers) { + throw new TypeError( 'Please provide all mandatory args : format, analyzers', ); + } + + const params = options['params'] + ? new URLSearchParams(options['params']) + : null; + + if ( + Object.prototype.hasOwnProperty.call(options, 'file') === + !!params?.get('use-file') + ) { + throw new TypeError( + "Please provide a file or specify file on a server through 3d arg : options( options.params[ 'use-file' ] field )", + ); + } if (Array.isArray(analyzers)) { analyzers = analyzers.join('/'); @@ -203,58 +286,73 @@ APIWrapper_.analyze = async function ( throw new Error('Analyzers can either be an array or string'); } - if (!options) { - options = {}; - } - - if (!options.file && (!options.params || !options.params['use-file'])) - throw new Error( - "Please provide a file or specify file on a server through 3d arg : options( options.params[ 'use-file' ] field )", - ); - /* - config - */ - const config = Object.create(null); + const config: RequestInit = Object.create(null); - config.method = 'post'; + config['method'] = 'POST'; - if (options.params) config.params = options.params; + if (Object.prototype.hasOwnProperty.call(config, 'file')) + config['body'] = (options as unknown as { ['file']: BodyInit })['file']; - if (options.params && options.params['use-file']) config.data = undefined; - else config.data = options.file; + if (options['token']) + config['headers'] = [['authorization', `Bearer ${options.token}`]]; - let url: string; + const url = `${ + options['token'] ? meteredPath : publicPath + }/analyze/${format}/${analyzers}${params ? `?${params}` : ''}`; + /* - config - */ - if (options.token) { - config.headers = { Authorization: `Bearer ${options.token}` }; - url = `${this.meteredPath}/analyze/${format}/${analyzers}`; - } else { - url = `${this.publicPath}/analyze/${format}/${analyzers}`; + const res = await fetch(url, config); + if (!res.ok) { + throw new Error( + `Error fetching ${url}: unexpected response code ${res.status}`, + ); } - config.url = url; - - /* - config - */ - - const res = await axios(config); - const analytics = await axios.get(res.data.resultUrl); + const result = await res.json(); + const analytics = await fetch(result['resultUrl']); + if (!analytics.ok) { + throw new Error( + `Error fetching result: unexpected response code ${res.status}`, + ); + } - return analytics.data; + return analytics.json(); }; /* */ -APIWrapper_.process = async function ( +const process_ = async < + T extends + | { + ['params']: + | string + | URLSearchParams + | string[][] + | Record; + ['token']?: string | null; + ['save']?: boolean | null; + ['path']?: string | null; + } + | { + ['file']: BodyInit; + ['params']?: + | string + | URLSearchParams + | string[][] + | Record + | undefined + | null; + ['token']?: string | null; + ['save']?: boolean | null; + ['path']?: string | null; + }, +>( format: string, processors: string | string[], - options?: { - ['file']?: Buffer | null; - ['params']?: Record | null; - ['token']?: string | null; - ['save']?: boolean | null; - ['path']?: string | null; - }, -) { + options: T, +) => { /* obligatory : format @@ -271,76 +369,87 @@ APIWrapper_.process = async function ( either options.file or options.params[ 'use-file' ] must be specified */ - if (!format || !processors) - throw new Error( + if (!format || !processors) { + throw new TypeError( 'Please provide all obligatory args : file, format, processors', ); + } if (Array.isArray(processors)) processors = processors.join('/'); - else if (!(Object(processors) instanceof String)) - throw new Error('Processors can either be an array or string'); - - if (!options) { - options = {}; + else if (!(Object(processors) instanceof String)) { + throw new TypeError('Processors can either be an array or string'); } - if (!options.file && (!options.params || !options.params['use-file'])) - throw new Error( + const params = options['params'] + ? new URLSearchParams(options['params']) + : null; + + if ( + Object.prototype.hasOwnProperty.call(options, 'file') === + !!params?.get('use-file') + ) { + throw new TypeError( "Please provide a file or specify file on a server through 3d arg : options( options.params[ 'use-file' ] field )", ); - - let url; + } /* - config - */ - const config: AxiosRequestConfig = Object.create(null); + const config: RequestInit = Object.create(null); - config.method = 'post'; + config['method'] = 'POST'; - if (options.params) config.params = options.params; + if (Object.prototype.hasOwnProperty.call(config, 'file')) + config['body'] = (options as unknown as { ['file']: BodyInit })['file']; - if (options.params && options.params['use-file']) config.data = undefined; - else config.data = options.file; + if (options['token']) + config['headers'] = [['authorization', `Bearer ${options.token}`]]; - if (options.token) { - config.headers = { Authorization: `Bearer ${options.token}` }; - url = `${this.meteredPath}/process/${format}/${processors}`; - } else { - url = `${this.publicPath}/process/${format}/${processors}`; - } - - config.url = url; + const url = `${ + options['token'] ? meteredPath : publicPath + }/process/${format}/${processors}${params ? `?${params}` : ''}`; /* - config - */ - const res = await axios(config); + const res = await fetch(url, config); + if (!res.ok) { + throw new Error( + `Error fetching ${url}: unexpected response code ${res.status}`, + ); + } - if (options.save) { - const path = options.path || `${process.cwd()}/file.${res.data.format}`; - return APIWrapper_.downloadAndSave(res.data.resultUrl, path); + const result = await res.json(); + if (options['save']) { + const path = options.path || join(cwd(), `file.${result['format']}`); + return downloadAndSave_(result['resultUrl'], path); } else { - return res.data.resultUrl; + return result['resultUrl']; } }; /* */ -APIWrapper_.downloadAndSave = async (url: string, path: string) => { +const downloadAndSave_ = async (url: string | URL, path: string) => { if (!url) throw new Error('Please provide all obligatory args : url'); - if (!path) path = __dirname + '/file'; + if (!path) path = join(cwd(), 'file'); - const response = await axios({ - url, - method: 'get', - responseType: 'stream', - }); + const response = await fetch(url); // create directories const dirPath = path.split('/').slice(0, -1).join('/') + '/'; await fs.mkdir(dirPath, { recursive: true }); - await fs.writeFile(path, response.data); + const data = await response.arrayBuffer(); + + await fs.writeFile(path, new Uint8Array(data)); }; -export default APIWrapper_; +export { + analyze_ as analyze, + convert_ as convert, + downloadAndSave_ as downloadAndSave, + get_ as get, + post_ as post, + process_ as process, +}; diff --git a/tsconfig.json b/tsconfig.json index 3b6dab32..bef6ac7f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "target": "es2020", - "module": "commonjs", + "module": "esnext", "outDir": "dist", "strict": true, "strictNullChecks": true,