imagekit-javascript
Advanced tools
Comparing version
'use strict'; | ||
require('regenerator-runtime/runtime'); | ||
function _typeof(obj) { | ||
"@babel/helpers - typeof"; | ||
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { | ||
_typeof = function (obj) { | ||
return typeof obj; | ||
}; | ||
} else { | ||
_typeof = function (obj) { | ||
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; | ||
}; | ||
} | ||
return _typeof(obj); | ||
} | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { | ||
try { | ||
var info = gen[key](arg); | ||
var value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
Promise.resolve(value).then(_next, _throw); | ||
} | ||
} | ||
function _asyncToGenerator(fn) { | ||
return function () { | ||
var self = this, | ||
args = arguments; | ||
return new Promise(function (resolve, reject) { | ||
var gen = fn.apply(self, args); | ||
function _next(value) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); | ||
} | ||
function _throw(err) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); | ||
} | ||
_next(undefined); | ||
}); | ||
}; | ||
} | ||
function _classCallCheck(instance, Constructor) { | ||
@@ -74,3 +128,3 @@ if (!(instance instanceof Constructor)) { | ||
var version = "1.4.3"; | ||
var version = "1.5.0"; | ||
@@ -118,2 +172,6 @@ var errorMessages = { | ||
}, | ||
AUTH_INVALID_RESPONSE: { | ||
message: "Invalid response from authenticationEndpoint. The SDK expects a JSON response with three fields i.e. signature, token and expire.", | ||
help: "" | ||
}, | ||
UPLOAD_ENDPOINT_NETWORK_ERROR: { | ||
@@ -139,82 +197,134 @@ message: "Request to ImageKit upload endpoint failed due to network error", | ||
var request = function request(formData, options, callback) { | ||
generateSignatureToken(options, function (err, signaturObj) { | ||
if (err) { | ||
return respond(true, err, callback); | ||
} else { | ||
formData.append("signature", (signaturObj === null || signaturObj === void 0 ? void 0 : signaturObj.signature) || ""); | ||
formData.append("expire", String((signaturObj === null || signaturObj === void 0 ? void 0 : signaturObj.expire) || 0)); | ||
formData.append("token", (signaturObj === null || signaturObj === void 0 ? void 0 : signaturObj.token) || ""); | ||
uploadFile(formData, function (err, responseSucessText) { | ||
if (err) { | ||
return respond(true, err, callback); | ||
} | ||
return respond(false, responseSucessText, callback); | ||
}); | ||
} | ||
function getResponseHeaderMap(xhr) { | ||
var headers = {}; | ||
var responseHeaders = xhr.getAllResponseHeaders(); | ||
if (Object.keys(responseHeaders).length) { | ||
responseHeaders.trim().split(/[\r\n]+/).map(function (value) { | ||
return value.split(/: /); | ||
}).forEach(function (keyValue) { | ||
headers[keyValue[0].trim()] = keyValue[1].trim(); | ||
}); | ||
} | ||
return headers; | ||
} | ||
var addResponseHeadersAndBody = function addResponseHeadersAndBody(body, xhr) { | ||
var response = _objectSpread2({}, body); | ||
var responseMetadata = { | ||
statusCode: xhr.status, | ||
headers: getResponseHeaderMap(xhr) | ||
}; | ||
Object.defineProperty(response, "$ResponseMetadata", { | ||
value: responseMetadata, | ||
enumerable: false, | ||
writable: false | ||
}); | ||
return response; | ||
}; | ||
var generateSignatureToken = function generateSignatureToken(options, callback) { | ||
var xhr = new XMLHttpRequest(); | ||
xhr.timeout = 60000; | ||
xhr.open('GET', options.authenticationEndpoint); | ||
xhr.ontimeout = function (e) { | ||
respond(true, errorMessages.AUTH_ENDPOINT_TIMEOUT, callback); | ||
var request = function () { | ||
var _ref = _asyncToGenerator( regeneratorRuntime.mark(function _callee(uploadFileXHR, formData, options, callback) { | ||
var signaturObj, result; | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
_context.prev = 0; | ||
_context.next = 3; | ||
return generateSignatureToken(options.authenticationEndpoint); | ||
case 3: | ||
signaturObj = _context.sent; | ||
_context.next = 9; | ||
break; | ||
case 6: | ||
_context.prev = 6; | ||
_context.t0 = _context["catch"](0); | ||
return _context.abrupt("return", respond(true, _context.t0, callback)); | ||
case 9: | ||
formData.append("signature", signaturObj.signature); | ||
formData.append("expire", String(signaturObj.expire)); | ||
formData.append("token", signaturObj.token); | ||
_context.prev = 12; | ||
_context.next = 15; | ||
return uploadFile(uploadFileXHR, formData); | ||
case 15: | ||
result = _context.sent; | ||
return _context.abrupt("return", respond(false, result, callback)); | ||
case 19: | ||
_context.prev = 19; | ||
_context.t1 = _context["catch"](12); | ||
return _context.abrupt("return", respond(true, _context.t1, callback)); | ||
case 22: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, null, [[0, 6], [12, 19]]); | ||
})); | ||
return function request(_x, _x2, _x3, _x4) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
xhr.onerror = function () { | ||
respond(true, errorMessages.AUTH_ENDPOINT_NETWORK_ERROR, callback); | ||
}; | ||
xhr.onload = function () { | ||
if (xhr.status === 200) { | ||
try { | ||
var body = JSON.parse(xhr.responseText); | ||
var obj = { | ||
signature: body.signature, | ||
expire: body.expire, | ||
token: body.token | ||
}; | ||
respond(false, obj, callback); | ||
} catch (ex) { | ||
respond(true, ex, callback); | ||
}(); | ||
var generateSignatureToken = function generateSignatureToken(authenticationEndpoint) { | ||
return new Promise(function (resolve, reject) { | ||
var xhr = new XMLHttpRequest(); | ||
xhr.timeout = 60000; | ||
xhr.open('GET', authenticationEndpoint); | ||
xhr.ontimeout = function (e) { | ||
return reject(errorMessages.AUTH_ENDPOINT_TIMEOUT); | ||
}; | ||
xhr.onerror = function () { | ||
return reject(errorMessages.AUTH_ENDPOINT_NETWORK_ERROR); | ||
}; | ||
xhr.onload = function () { | ||
if (xhr.status === 200) { | ||
try { | ||
var body = JSON.parse(xhr.responseText); | ||
var obj = { | ||
signature: body.signature, | ||
expire: body.expire, | ||
token: body.token | ||
}; | ||
if (!obj.signature || !obj.expire || !obj.token) { | ||
return reject(errorMessages.AUTH_INVALID_RESPONSE); | ||
} | ||
return resolve(obj); | ||
} catch (ex) { | ||
return reject(errorMessages.AUTH_INVALID_RESPONSE); | ||
} | ||
} else { | ||
return reject(errorMessages.AUTH_INVALID_RESPONSE); | ||
} | ||
} else { | ||
try { | ||
var error = JSON.parse(xhr.responseText); | ||
respond(true, error, callback); | ||
} catch (ex) { | ||
respond(true, ex, callback); | ||
} | ||
} | ||
}; | ||
xhr.send(); | ||
return; | ||
}; | ||
xhr.send(); | ||
}); | ||
}; | ||
var uploadFile = function uploadFile(formData, callback) { | ||
var uploadFileXHR = new XMLHttpRequest(); | ||
uploadFileXHR.open('POST', 'https://upload.imagekit.io/api/v1/files/upload'); | ||
uploadFileXHR.onerror = function () { | ||
respond(true, errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR, callback); | ||
return; | ||
}; | ||
uploadFileXHR.onload = function () { | ||
if (uploadFileXHR.status === 200) { | ||
var uploadResponse = JSON.parse(uploadFileXHR.responseText); | ||
callback(null, uploadResponse); | ||
} else if (uploadFileXHR.status !== 200) { | ||
try { | ||
callback(JSON.parse(uploadFileXHR.responseText), null); | ||
} catch (ex) { | ||
callback(ex, null); | ||
var uploadFile = function uploadFile(uploadFileXHR, formData) { | ||
return new Promise(function (resolve, reject) { | ||
uploadFileXHR.open('POST', 'https://upload.imagekit.io/api/v1/files/upload'); | ||
uploadFileXHR.onerror = function (e) { | ||
return reject(errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR); | ||
}; | ||
uploadFileXHR.onload = function () { | ||
if (uploadFileXHR.status === 200) { | ||
try { | ||
var body = JSON.parse(uploadFileXHR.responseText); | ||
var uploadResponse = addResponseHeadersAndBody(body, uploadFileXHR); | ||
return resolve(uploadResponse); | ||
} catch (ex) { | ||
return reject(ex); | ||
} | ||
} else { | ||
try { | ||
var body = JSON.parse(uploadFileXHR.responseText); | ||
var uploadError = addResponseHeadersAndBody(body, uploadFileXHR); | ||
return reject(uploadError); | ||
} catch (ex) { | ||
return reject(ex); | ||
} | ||
} | ||
} | ||
}; | ||
uploadFileXHR.send(formData); | ||
return; | ||
}; | ||
uploadFileXHR.send(formData); | ||
}); | ||
}; | ||
var upload = function upload(uploadOptions, options, callback) { | ||
if (!uploadOptions) { | ||
respond(true, errorMessages.INVALID_UPLOAD_OPTIONS, callback); | ||
return; | ||
} | ||
var upload = function upload(xhr, uploadOptions, options, callback) { | ||
if (!uploadOptions.file) { | ||
@@ -236,16 +346,18 @@ respond(true, errorMessages.MISSING_UPLOAD_FILE_PARAMETER, callback); | ||
} | ||
if (uploadOptions.tags && Array.isArray(uploadOptions.tags)) { | ||
uploadOptions.tags = String(uploadOptions.tags); | ||
} | ||
var formData = new FormData(); | ||
var i; | ||
for (i in uploadOptions) { | ||
var param = uploadOptions[i]; | ||
if (typeof param !== "undefined") { | ||
if (typeof param === "string" || typeof param === "boolean") { | ||
formData.append(i, String(param)); | ||
} else if (Array.isArray(param)) { | ||
formData.append(i, JSON.stringify(param)); | ||
var key; | ||
for (key in uploadOptions) { | ||
if (key) { | ||
if (key === "file" && typeof uploadOptions.file != "string") { | ||
formData.append('file', uploadOptions.file, String(uploadOptions.fileName)); | ||
} else if (key === "tags" && Array.isArray(uploadOptions.tags)) { | ||
formData.append('tags', uploadOptions.tags.join(",")); | ||
} else if (key === "responseFields" && Array.isArray(uploadOptions.responseFields)) { | ||
formData.append('responseFields', uploadOptions.responseFields.join(",")); | ||
} else if (key === "extensions" && Array.isArray(uploadOptions.extensions)) { | ||
formData.append('extensions', JSON.stringify(uploadOptions.extensions)); | ||
} else if (key === "customMetadata" && _typeof(uploadOptions.customMetadata) === "object" && !Array.isArray(uploadOptions.customMetadata) && uploadOptions.customMetadata !== null) { | ||
formData.append('customMetadata', JSON.stringify(uploadOptions.customMetadata)); | ||
} else { | ||
formData.append(i, param); | ||
formData.append(key, String(uploadOptions[key])); | ||
} | ||
@@ -255,3 +367,3 @@ } | ||
formData.append("publicKey", options.publicKey); | ||
request(formData, _objectSpread2(_objectSpread2({}, options), {}, { | ||
request(xhr, formData, _objectSpread2(_objectSpread2({}, options), {}, { | ||
authenticationEndpoint: options.authenticationEndpoint | ||
@@ -317,3 +429,4 @@ }), callback); | ||
effectGray: "e-grayscale", | ||
original: "orig" | ||
original: "orig", | ||
raw: "raw" | ||
}; | ||
@@ -448,5 +561,31 @@ | ||
} | ||
function privateKeyPassed(options) { | ||
return typeof options.privateKey != "undefined"; | ||
} | ||
var promisify = function promisify(thisContext, fn) { | ||
return function () { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
if (args.length === fn.length && typeof args[args.length - 1] !== "undefined") { | ||
if (typeof args[args.length - 1] !== "function") { | ||
throw new Error("Callback must be a function."); | ||
} | ||
fn.call.apply(fn, [thisContext].concat(args)); | ||
} else { | ||
return new Promise(function (resolve, reject) { | ||
var callback = function callback(err) { | ||
if (err) { | ||
return reject(err); | ||
} else { | ||
for (var _len2 = arguments.length, results = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | ||
results[_key2 - 1] = arguments[_key2]; | ||
} | ||
resolve(results.length > 1 ? results : results[0]); | ||
} | ||
}; | ||
args.pop(); | ||
args.push(callback); | ||
fn.call.apply(fn, [thisContext].concat(args)); | ||
}); | ||
} | ||
}; | ||
}; | ||
var ImageKit = function () { | ||
@@ -465,5 +604,2 @@ function ImageKit(opts) { | ||
} | ||
if (privateKeyPassed(this.options)) { | ||
throw errorMessages.PRIVATE_KEY_CLIENT_SIDE; | ||
} | ||
if (!transformationUtils.validParameters(this.options)) { | ||
@@ -480,5 +616,18 @@ throw errorMessages.INVALID_TRANSFORMATION_POSITION; | ||
key: "upload", | ||
value: function upload$1(uploadOptions, callback, options) { | ||
value: function upload$1(uploadOptions, callbackOrOptions, options) { | ||
var callback; | ||
if (typeof callbackOrOptions === 'function') { | ||
callback = callbackOrOptions; | ||
} else { | ||
options = callbackOrOptions || {}; | ||
} | ||
if (!uploadOptions || _typeof(uploadOptions) !== "object") { | ||
return respond(true, errorMessages.INVALID_UPLOAD_OPTIONS, callback); | ||
} | ||
var mergedOptions = _objectSpread2(_objectSpread2({}, this.options), options); | ||
return upload(uploadOptions, mergedOptions, callback); | ||
var _ref = uploadOptions || {}, | ||
userProvidedXHR = _ref.xhr; | ||
delete uploadOptions.xhr; | ||
var xhr = userProvidedXHR || new XMLHttpRequest(); | ||
return promisify(this, upload)(xhr, uploadOptions, mergedOptions, callback); | ||
} | ||
@@ -485,0 +634,0 @@ }]); |
@@ -0,1 +1,55 @@ | ||
import 'regenerator-runtime/runtime'; | ||
function _typeof(obj) { | ||
"@babel/helpers - typeof"; | ||
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { | ||
_typeof = function (obj) { | ||
return typeof obj; | ||
}; | ||
} else { | ||
_typeof = function (obj) { | ||
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; | ||
}; | ||
} | ||
return _typeof(obj); | ||
} | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { | ||
try { | ||
var info = gen[key](arg); | ||
var value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
Promise.resolve(value).then(_next, _throw); | ||
} | ||
} | ||
function _asyncToGenerator(fn) { | ||
return function () { | ||
var self = this, | ||
args = arguments; | ||
return new Promise(function (resolve, reject) { | ||
var gen = fn.apply(self, args); | ||
function _next(value) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); | ||
} | ||
function _throw(err) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); | ||
} | ||
_next(undefined); | ||
}); | ||
}; | ||
} | ||
function _classCallCheck(instance, Constructor) { | ||
@@ -72,3 +126,3 @@ if (!(instance instanceof Constructor)) { | ||
var version = "1.4.3"; | ||
var version = "1.5.0"; | ||
@@ -116,2 +170,6 @@ var errorMessages = { | ||
}, | ||
AUTH_INVALID_RESPONSE: { | ||
message: "Invalid response from authenticationEndpoint. The SDK expects a JSON response with three fields i.e. signature, token and expire.", | ||
help: "" | ||
}, | ||
UPLOAD_ENDPOINT_NETWORK_ERROR: { | ||
@@ -137,82 +195,134 @@ message: "Request to ImageKit upload endpoint failed due to network error", | ||
var request = function request(formData, options, callback) { | ||
generateSignatureToken(options, function (err, signaturObj) { | ||
if (err) { | ||
return respond(true, err, callback); | ||
} else { | ||
formData.append("signature", (signaturObj === null || signaturObj === void 0 ? void 0 : signaturObj.signature) || ""); | ||
formData.append("expire", String((signaturObj === null || signaturObj === void 0 ? void 0 : signaturObj.expire) || 0)); | ||
formData.append("token", (signaturObj === null || signaturObj === void 0 ? void 0 : signaturObj.token) || ""); | ||
uploadFile(formData, function (err, responseSucessText) { | ||
if (err) { | ||
return respond(true, err, callback); | ||
} | ||
return respond(false, responseSucessText, callback); | ||
}); | ||
} | ||
function getResponseHeaderMap(xhr) { | ||
var headers = {}; | ||
var responseHeaders = xhr.getAllResponseHeaders(); | ||
if (Object.keys(responseHeaders).length) { | ||
responseHeaders.trim().split(/[\r\n]+/).map(function (value) { | ||
return value.split(/: /); | ||
}).forEach(function (keyValue) { | ||
headers[keyValue[0].trim()] = keyValue[1].trim(); | ||
}); | ||
} | ||
return headers; | ||
} | ||
var addResponseHeadersAndBody = function addResponseHeadersAndBody(body, xhr) { | ||
var response = _objectSpread2({}, body); | ||
var responseMetadata = { | ||
statusCode: xhr.status, | ||
headers: getResponseHeaderMap(xhr) | ||
}; | ||
Object.defineProperty(response, "$ResponseMetadata", { | ||
value: responseMetadata, | ||
enumerable: false, | ||
writable: false | ||
}); | ||
return response; | ||
}; | ||
var generateSignatureToken = function generateSignatureToken(options, callback) { | ||
var xhr = new XMLHttpRequest(); | ||
xhr.timeout = 60000; | ||
xhr.open('GET', options.authenticationEndpoint); | ||
xhr.ontimeout = function (e) { | ||
respond(true, errorMessages.AUTH_ENDPOINT_TIMEOUT, callback); | ||
var request = function () { | ||
var _ref = _asyncToGenerator( regeneratorRuntime.mark(function _callee(uploadFileXHR, formData, options, callback) { | ||
var signaturObj, result; | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
_context.prev = 0; | ||
_context.next = 3; | ||
return generateSignatureToken(options.authenticationEndpoint); | ||
case 3: | ||
signaturObj = _context.sent; | ||
_context.next = 9; | ||
break; | ||
case 6: | ||
_context.prev = 6; | ||
_context.t0 = _context["catch"](0); | ||
return _context.abrupt("return", respond(true, _context.t0, callback)); | ||
case 9: | ||
formData.append("signature", signaturObj.signature); | ||
formData.append("expire", String(signaturObj.expire)); | ||
formData.append("token", signaturObj.token); | ||
_context.prev = 12; | ||
_context.next = 15; | ||
return uploadFile(uploadFileXHR, formData); | ||
case 15: | ||
result = _context.sent; | ||
return _context.abrupt("return", respond(false, result, callback)); | ||
case 19: | ||
_context.prev = 19; | ||
_context.t1 = _context["catch"](12); | ||
return _context.abrupt("return", respond(true, _context.t1, callback)); | ||
case 22: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, null, [[0, 6], [12, 19]]); | ||
})); | ||
return function request(_x, _x2, _x3, _x4) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
xhr.onerror = function () { | ||
respond(true, errorMessages.AUTH_ENDPOINT_NETWORK_ERROR, callback); | ||
}; | ||
xhr.onload = function () { | ||
if (xhr.status === 200) { | ||
try { | ||
var body = JSON.parse(xhr.responseText); | ||
var obj = { | ||
signature: body.signature, | ||
expire: body.expire, | ||
token: body.token | ||
}; | ||
respond(false, obj, callback); | ||
} catch (ex) { | ||
respond(true, ex, callback); | ||
}(); | ||
var generateSignatureToken = function generateSignatureToken(authenticationEndpoint) { | ||
return new Promise(function (resolve, reject) { | ||
var xhr = new XMLHttpRequest(); | ||
xhr.timeout = 60000; | ||
xhr.open('GET', authenticationEndpoint); | ||
xhr.ontimeout = function (e) { | ||
return reject(errorMessages.AUTH_ENDPOINT_TIMEOUT); | ||
}; | ||
xhr.onerror = function () { | ||
return reject(errorMessages.AUTH_ENDPOINT_NETWORK_ERROR); | ||
}; | ||
xhr.onload = function () { | ||
if (xhr.status === 200) { | ||
try { | ||
var body = JSON.parse(xhr.responseText); | ||
var obj = { | ||
signature: body.signature, | ||
expire: body.expire, | ||
token: body.token | ||
}; | ||
if (!obj.signature || !obj.expire || !obj.token) { | ||
return reject(errorMessages.AUTH_INVALID_RESPONSE); | ||
} | ||
return resolve(obj); | ||
} catch (ex) { | ||
return reject(errorMessages.AUTH_INVALID_RESPONSE); | ||
} | ||
} else { | ||
return reject(errorMessages.AUTH_INVALID_RESPONSE); | ||
} | ||
} else { | ||
try { | ||
var error = JSON.parse(xhr.responseText); | ||
respond(true, error, callback); | ||
} catch (ex) { | ||
respond(true, ex, callback); | ||
} | ||
} | ||
}; | ||
xhr.send(); | ||
return; | ||
}; | ||
xhr.send(); | ||
}); | ||
}; | ||
var uploadFile = function uploadFile(formData, callback) { | ||
var uploadFileXHR = new XMLHttpRequest(); | ||
uploadFileXHR.open('POST', 'https://upload.imagekit.io/api/v1/files/upload'); | ||
uploadFileXHR.onerror = function () { | ||
respond(true, errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR, callback); | ||
return; | ||
}; | ||
uploadFileXHR.onload = function () { | ||
if (uploadFileXHR.status === 200) { | ||
var uploadResponse = JSON.parse(uploadFileXHR.responseText); | ||
callback(null, uploadResponse); | ||
} else if (uploadFileXHR.status !== 200) { | ||
try { | ||
callback(JSON.parse(uploadFileXHR.responseText), null); | ||
} catch (ex) { | ||
callback(ex, null); | ||
var uploadFile = function uploadFile(uploadFileXHR, formData) { | ||
return new Promise(function (resolve, reject) { | ||
uploadFileXHR.open('POST', 'https://upload.imagekit.io/api/v1/files/upload'); | ||
uploadFileXHR.onerror = function (e) { | ||
return reject(errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR); | ||
}; | ||
uploadFileXHR.onload = function () { | ||
if (uploadFileXHR.status === 200) { | ||
try { | ||
var body = JSON.parse(uploadFileXHR.responseText); | ||
var uploadResponse = addResponseHeadersAndBody(body, uploadFileXHR); | ||
return resolve(uploadResponse); | ||
} catch (ex) { | ||
return reject(ex); | ||
} | ||
} else { | ||
try { | ||
var body = JSON.parse(uploadFileXHR.responseText); | ||
var uploadError = addResponseHeadersAndBody(body, uploadFileXHR); | ||
return reject(uploadError); | ||
} catch (ex) { | ||
return reject(ex); | ||
} | ||
} | ||
} | ||
}; | ||
uploadFileXHR.send(formData); | ||
return; | ||
}; | ||
uploadFileXHR.send(formData); | ||
}); | ||
}; | ||
var upload = function upload(uploadOptions, options, callback) { | ||
if (!uploadOptions) { | ||
respond(true, errorMessages.INVALID_UPLOAD_OPTIONS, callback); | ||
return; | ||
} | ||
var upload = function upload(xhr, uploadOptions, options, callback) { | ||
if (!uploadOptions.file) { | ||
@@ -234,16 +344,18 @@ respond(true, errorMessages.MISSING_UPLOAD_FILE_PARAMETER, callback); | ||
} | ||
if (uploadOptions.tags && Array.isArray(uploadOptions.tags)) { | ||
uploadOptions.tags = String(uploadOptions.tags); | ||
} | ||
var formData = new FormData(); | ||
var i; | ||
for (i in uploadOptions) { | ||
var param = uploadOptions[i]; | ||
if (typeof param !== "undefined") { | ||
if (typeof param === "string" || typeof param === "boolean") { | ||
formData.append(i, String(param)); | ||
} else if (Array.isArray(param)) { | ||
formData.append(i, JSON.stringify(param)); | ||
var key; | ||
for (key in uploadOptions) { | ||
if (key) { | ||
if (key === "file" && typeof uploadOptions.file != "string") { | ||
formData.append('file', uploadOptions.file, String(uploadOptions.fileName)); | ||
} else if (key === "tags" && Array.isArray(uploadOptions.tags)) { | ||
formData.append('tags', uploadOptions.tags.join(",")); | ||
} else if (key === "responseFields" && Array.isArray(uploadOptions.responseFields)) { | ||
formData.append('responseFields', uploadOptions.responseFields.join(",")); | ||
} else if (key === "extensions" && Array.isArray(uploadOptions.extensions)) { | ||
formData.append('extensions', JSON.stringify(uploadOptions.extensions)); | ||
} else if (key === "customMetadata" && _typeof(uploadOptions.customMetadata) === "object" && !Array.isArray(uploadOptions.customMetadata) && uploadOptions.customMetadata !== null) { | ||
formData.append('customMetadata', JSON.stringify(uploadOptions.customMetadata)); | ||
} else { | ||
formData.append(i, param); | ||
formData.append(key, String(uploadOptions[key])); | ||
} | ||
@@ -253,3 +365,3 @@ } | ||
formData.append("publicKey", options.publicKey); | ||
request(formData, _objectSpread2(_objectSpread2({}, options), {}, { | ||
request(xhr, formData, _objectSpread2(_objectSpread2({}, options), {}, { | ||
authenticationEndpoint: options.authenticationEndpoint | ||
@@ -315,3 +427,4 @@ }), callback); | ||
effectGray: "e-grayscale", | ||
original: "orig" | ||
original: "orig", | ||
raw: "raw" | ||
}; | ||
@@ -446,5 +559,31 @@ | ||
} | ||
function privateKeyPassed(options) { | ||
return typeof options.privateKey != "undefined"; | ||
} | ||
var promisify = function promisify(thisContext, fn) { | ||
return function () { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
if (args.length === fn.length && typeof args[args.length - 1] !== "undefined") { | ||
if (typeof args[args.length - 1] !== "function") { | ||
throw new Error("Callback must be a function."); | ||
} | ||
fn.call.apply(fn, [thisContext].concat(args)); | ||
} else { | ||
return new Promise(function (resolve, reject) { | ||
var callback = function callback(err) { | ||
if (err) { | ||
return reject(err); | ||
} else { | ||
for (var _len2 = arguments.length, results = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | ||
results[_key2 - 1] = arguments[_key2]; | ||
} | ||
resolve(results.length > 1 ? results : results[0]); | ||
} | ||
}; | ||
args.pop(); | ||
args.push(callback); | ||
fn.call.apply(fn, [thisContext].concat(args)); | ||
}); | ||
} | ||
}; | ||
}; | ||
var ImageKit = function () { | ||
@@ -463,5 +602,2 @@ function ImageKit(opts) { | ||
} | ||
if (privateKeyPassed(this.options)) { | ||
throw errorMessages.PRIVATE_KEY_CLIENT_SIDE; | ||
} | ||
if (!transformationUtils.validParameters(this.options)) { | ||
@@ -478,5 +614,18 @@ throw errorMessages.INVALID_TRANSFORMATION_POSITION; | ||
key: "upload", | ||
value: function upload$1(uploadOptions, callback, options) { | ||
value: function upload$1(uploadOptions, callbackOrOptions, options) { | ||
var callback; | ||
if (typeof callbackOrOptions === 'function') { | ||
callback = callbackOrOptions; | ||
} else { | ||
options = callbackOrOptions || {}; | ||
} | ||
if (!uploadOptions || _typeof(uploadOptions) !== "object") { | ||
return respond(true, errorMessages.INVALID_UPLOAD_OPTIONS, callback); | ||
} | ||
var mergedOptions = _objectSpread2(_objectSpread2({}, this.options), options); | ||
return upload(uploadOptions, mergedOptions, callback); | ||
var _ref = uploadOptions || {}, | ||
userProvidedXHR = _ref.xhr; | ||
delete uploadOptions.xhr; | ||
var xhr = userProvidedXHR || new XMLHttpRequest(); | ||
return promisify(this, upload)(xhr, uploadOptions, mergedOptions, callback); | ||
} | ||
@@ -483,0 +632,0 @@ }]); |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).ImageKit=t()}(this,(function(){"use strict";function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function t(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function r(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function n(e){for(var n=1;n<arguments.length;n++){var o=null!=arguments[n]?arguments[n]:{};n%2?r(Object(o),!0).forEach((function(r){t(e,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):r(Object(o)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(o,t))}))}return e}var o={message:"Missing urlEndpoint during SDK initialization",help:""},a={message:"Invalid transformationPosition parameter",help:""},i={message:"privateKey should not be passed on the client side",help:""},s={message:"Missing file parameter for upload",help:""},p={message:"Missing fileName parameter for upload",help:""},u={message:"Missing authentication endpoint for upload",help:""},l={message:"Missing public key for upload",help:""},c={message:"The authenticationEndpoint you provided timed out in 60 seconds",help:""},f={message:"Request to authenticationEndpoint failed due to network error",help:""},d={message:"Request to ImageKit upload endpoint failed due to network error",help:""},y={message:"Invalid uploadOptions parameter",help:""};function g(e,t,r){"function"==typeof r&&(e?r(t,null):r(null,t))}var h=function(e,t){var r=new XMLHttpRequest;r.timeout=6e4,r.open("GET",e.authenticationEndpoint),r.ontimeout=function(e){g(!0,c,t)},r.onerror=function(){g(!0,f,t)},r.onload=function(){if(200===r.status)try{var e=JSON.parse(r.responseText);g(!1,{signature:e.signature,expire:e.expire,token:e.token},t)}catch(e){g(!0,e,t)}else try{g(!0,JSON.parse(r.responseText),t)}catch(e){g(!0,e,t)}},r.send()},v=function(e,t){var r=new XMLHttpRequest;r.open("POST","https://upload.imagekit.io/api/v1/files/upload"),r.onerror=function(){g(!0,d,t)},r.onload=function(){if(200===r.status){var e=JSON.parse(r.responseText);t(null,e)}else if(200!==r.status)try{t(JSON.parse(r.responseText),null)}catch(e){t(e,null)}},r.send(e)},m=function(e,t,r){if(e)if(e.file)if(e.fileName)if(t.authenticationEndpoint)if(t.publicKey){e.tags&&Array.isArray(e.tags)&&(e.tags=String(e.tags));var o,a=new FormData;for(o in e){var i=e[o];void 0!==i&&("string"==typeof i||"boolean"==typeof i?a.append(o,String(i)):Array.isArray(i)?a.append(o,JSON.stringify(i)):a.append(o,i))}a.append("publicKey",t.publicKey),function(e,t,r){h(t,(function(t,n){if(t)return g(!0,t,r);e.append("signature",(null==n?void 0:n.signature)||""),e.append("expire",String((null==n?void 0:n.expire)||0)),e.append("token",(null==n?void 0:n.token)||""),v(e,(function(e,t){return e?g(!0,e,r):g(!1,t,r)}))}))}(a,n(n({},t),{},{authenticationEndpoint:t.authenticationEndpoint}),r)}else g(!0,l,r);else g(!0,u,r);else g(!0,p,r);else g(!0,s,r);else g(!0,y,r)},b={width:"w",height:"h",aspectRatio:"ar",quality:"q",crop:"c",cropMode:"cm",focus:"fo",x:"x",y:"y",format:"f",radius:"r",background:"bg",border:"b",rotation:"rt",rotate:"rt",blur:"bl",named:"n",overlayImage:"oi",overlayImageAspectRatio:"oiar",overlayImageBackground:"oibg",overlayImageBorder:"oib",overlayImageDPR:"oidpr",overlayImageQuality:"oiq",overlayImageCropping:"oic",overlayImageTrim:"oit",overlayX:"ox",overlayY:"oy",overlayFocus:"ofo",overlayHeight:"oh",overlayWidth:"ow",overlayText:"ot",overlayTextFontSize:"ots",overlayTextFontFamily:"otf",overlayTextColor:"otc",overlayTextTransparency:"oa",overlayAlpha:"oa",overlayTextTypography:"ott",overlayBackground:"obg",overlayTextEncoded:"ote",overlayTextWidth:"otw",overlayTextBackground:"otbg",overlayTextPadding:"otp",overlayTextInnerAlignment:"otia",overlayRadius:"or",progressive:"pr",lossless:"lo",trim:"t",metadata:"md",colorProfile:"cp",defaultImage:"di",dpr:"dpr",effectSharpen:"e-sharpen",effectUSM:"e-usm",effectContrast:"e-contrast",effectGray:"e-grayscale",original:"orig"},w=["path","query"],O=function(){return"path"},x=function(e){return"query"===e.transformationPosition},P=function(e){return void 0!==e.transformationPosition&&-1!=w.indexOf(e.transformationPosition)},T=function(e){return e&&(b[e]||b[e.toLowerCase()])||""},k=function(){return":"},j=function(){return","},E=function(){return"-"};function S(e){return"string"==typeof e&&"/"==e[e.length-1]&&(e=e.substring(0,e.length-1)),e}function I(e,t){var r=t||"/",n=new RegExp(r+"{1,}","g");return e.join(r).replace(n,r)}var R=function(e){if(!e.path&&!e.src)return"";var t,r,n;try{e.path?(n=new URL(e.urlEndpoint).pathname,t=new URL(I([e.urlEndpoint.replace(n,""),e.path]))):(t=new URL(e.src),r=!0)}catch(e){return console.error(e),""}for(var o in e.sdkVersion&&""!=e.sdkVersion.trim()&&t.searchParams.append("ik-sdk-version",e.sdkVersion.trim()),e.queryParameters)t.searchParams.append(o,String(e.queryParameters[o]));var a=function(e){if(!Array.isArray(e))return"";for(var t=[],r=0,n=e.length;r<n;r++){var o=[];for(var a in e[r]){var i=T(a);if(i||(i=a),"-"===e[r][a])o.push(i);else if("raw"===a)o.push(e[r][a]);else{var s=e[r][a];"oi"!==i&&"di"!==i||(s=(s=S(("string"==typeof(p=s||"")&&"/"==p[0]&&(p=p.slice(1)),p))).replace(/\//g,"@@")),o.push([i,s].join(E()))}}t.push(o.join(j()))}var p;return t.join(k())}(e.transformation);return a&&a.length&&(x(e)||r?t.searchParams.append("tr",a):t.pathname=I(["tr"+k()+a,t.pathname])),t.pathname=I(n?[n,t.pathname]:[t.pathname]),t.href};return function(){function r(e){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,r),t(this,"options",{sdkVersion:"javascript-".concat("1.4.3"),publicKey:"",urlEndpoint:"",transformationPosition:O()}),this.options=n(n({},this.options),e||{}),!this.options.urlEndpoint)throw o;if(function(e){return void 0!==e.privateKey}(this.options))throw i;if(!P(this.options))throw a}var s,p,u;return s=r,(p=[{key:"url",value:function(e){return t=e,r=this.options,R(n(n({},r),t));var t,r}},{key:"upload",value:function(e,t,r){var o=n(n({},this.options),r);return m(e,o,t)}}])&&e(s.prototype,p),u&&e(s,u),r}()})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("regenerator-runtime/runtime")):"function"==typeof define&&define.amd?define(["regenerator-runtime/runtime"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).ImageKit=t()}(this,(function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t,r,n,o,a,i){try{var s=e[a](i),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function r(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function n(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function a(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?o(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):o(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var i={message:"Missing urlEndpoint during SDK initialization",help:""},s={message:"Invalid transformationPosition parameter",help:""},u={message:"Missing file parameter for upload",help:""},p={message:"Missing fileName parameter for upload",help:""},l={message:"Missing authentication endpoint for upload",help:""},c={message:"Missing public key for upload",help:""},f={message:"The authenticationEndpoint you provided timed out in 60 seconds",help:""},d={message:"Request to authenticationEndpoint failed due to network error",help:""},y={message:"Invalid response from authenticationEndpoint. The SDK expects a JSON response with three fields i.e. signature, token and expire.",help:""},h={message:"Request to ImageKit upload endpoint failed due to network error",help:""},m={message:"Invalid uploadOptions parameter",help:""};function g(e,t,r){"function"==typeof r&&(e?r(t,null):r(null,t))}function v(e){var t={},r=e.getAllResponseHeaders();return Object.keys(r).length&&r.trim().split(/[\r\n]+/).map((function(e){return e.split(/: /)})).forEach((function(e){t[e[0].trim()]=e[1].trim()})),t}var b=function(e,t){var r=a({},e),n={statusCode:t.status,headers:v(t)};return Object.defineProperty(r,"$ResponseMetadata",{value:n,enumerable:!1,writable:!1}),r},w=function(){var e,r=(e=regeneratorRuntime.mark((function e(t,r,n,o){var a,i;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,x(n.authenticationEndpoint);case 3:a=e.sent,e.next=9;break;case 6:return e.prev=6,e.t0=e.catch(0),e.abrupt("return",g(!0,e.t0,o));case 9:return r.append("signature",a.signature),r.append("expire",String(a.expire)),r.append("token",a.token),e.prev=12,e.next=15,O(t,r);case 15:return i=e.sent,e.abrupt("return",g(!1,i,o));case 19:return e.prev=19,e.t1=e.catch(12),e.abrupt("return",g(!0,e.t1,o));case 22:case"end":return e.stop()}}),e,null,[[0,6],[12,19]])})),function(){var r=this,n=arguments;return new Promise((function(o,a){var i=e.apply(r,n);function s(e){t(i,o,a,s,u,"next",e)}function u(e){t(i,o,a,s,u,"throw",e)}s(void 0)}))});return function(e,t,n,o){return r.apply(this,arguments)}}(),x=function(e){return new Promise((function(t,r){var n=new XMLHttpRequest;n.timeout=6e4,n.open("GET",e),n.ontimeout=function(e){return r(f)},n.onerror=function(){return r(d)},n.onload=function(){if(200!==n.status)return r(y);try{var e=JSON.parse(n.responseText),o={signature:e.signature,expire:e.expire,token:e.token};return o.signature&&o.expire&&o.token?t(o):r(y)}catch(e){return r(y)}},n.send()}))},O=function(e,t){return new Promise((function(r,n){e.open("POST","https://upload.imagekit.io/api/v1/files/upload"),e.onerror=function(e){return n(h)},e.onload=function(){if(200===e.status)try{var t=JSON.parse(e.responseText),o=b(t,e);return r(o)}catch(e){return n(e)}else try{t=JSON.parse(e.responseText);var a=b(t,e);return n(a)}catch(e){return n(e)}},e.send(t)}))},P=function(t,r,n,o){if(r.file)if(r.fileName)if(n.authenticationEndpoint)if(n.publicKey){var i,s=new FormData;for(i in r)i&&("file"===i&&"string"!=typeof r.file?s.append("file",r.file,String(r.fileName)):"tags"===i&&Array.isArray(r.tags)?s.append("tags",r.tags.join(",")):"responseFields"===i&&Array.isArray(r.responseFields)?s.append("responseFields",r.responseFields.join(",")):"extensions"===i&&Array.isArray(r.extensions)?s.append("extensions",JSON.stringify(r.extensions)):"customMetadata"!==i||"object"!==e(r.customMetadata)||Array.isArray(r.customMetadata)||null===r.customMetadata?s.append(i,String(r[i])):s.append("customMetadata",JSON.stringify(r.customMetadata)));s.append("publicKey",n.publicKey),w(t,s,a(a({},n),{},{authenticationEndpoint:n.authenticationEndpoint}),o)}else g(!0,c,o);else g(!0,l,o);else g(!0,p,o);else g(!0,u,o)},k={width:"w",height:"h",aspectRatio:"ar",quality:"q",crop:"c",cropMode:"cm",focus:"fo",x:"x",y:"y",format:"f",radius:"r",background:"bg",border:"b",rotation:"rt",rotate:"rt",blur:"bl",named:"n",overlayImage:"oi",overlayImageAspectRatio:"oiar",overlayImageBackground:"oibg",overlayImageBorder:"oib",overlayImageDPR:"oidpr",overlayImageQuality:"oiq",overlayImageCropping:"oic",overlayImageTrim:"oit",overlayX:"ox",overlayY:"oy",overlayFocus:"ofo",overlayHeight:"oh",overlayWidth:"ow",overlayText:"ot",overlayTextFontSize:"ots",overlayTextFontFamily:"otf",overlayTextColor:"otc",overlayTextTransparency:"oa",overlayAlpha:"oa",overlayTextTypography:"ott",overlayBackground:"obg",overlayTextEncoded:"ote",overlayTextWidth:"otw",overlayTextBackground:"otbg",overlayTextPadding:"otp",overlayTextInnerAlignment:"otia",overlayRadius:"or",progressive:"pr",lossless:"lo",trim:"t",metadata:"md",colorProfile:"cp",defaultImage:"di",dpr:"dpr",effectSharpen:"e-sharpen",effectUSM:"e-usm",effectContrast:"e-contrast",effectGray:"e-grayscale",original:"orig",raw:"raw"},j=["path","query"],T=function(){return"path"},S=function(e){return"query"===e.transformationPosition},E=function(e){return void 0!==e.transformationPosition&&-1!=j.indexOf(e.transformationPosition)},A=function(e){return e&&(k[e]||k[e.toLowerCase()])||""},M=function(){return":"},R=function(){return","},I=function(){return"-"};function q(e){return"string"==typeof e&&"/"==e[e.length-1]&&(e=e.substring(0,e.length-1)),e}function F(e,t){var r=t||"/",n=new RegExp(r+"{1,}","g");return e.join(r).replace(n,r)}var N=function(e){if(!e.path&&!e.src)return"";var t,r,n;try{e.path?(n=new URL(e.urlEndpoint).pathname,t=new URL(F([e.urlEndpoint.replace(n,""),e.path]))):(t=new URL(e.src),r=!0)}catch(e){return console.error(e),""}for(var o in e.sdkVersion&&""!=e.sdkVersion.trim()&&t.searchParams.append("ik-sdk-version",e.sdkVersion.trim()),e.queryParameters)t.searchParams.append(o,String(e.queryParameters[o]));var a=function(e){if(!Array.isArray(e))return"";for(var t=[],r=0,n=e.length;r<n;r++){var o=[];for(var a in e[r]){var i=A(a);if(i||(i=a),"-"===e[r][a])o.push(i);else if("raw"===a)o.push(e[r][a]);else{var s=e[r][a];"oi"!==i&&"di"!==i||(s=(s=q(("string"==typeof(u=s||"")&&"/"==u[0]&&(u=u.slice(1)),u))).replace(/\//g,"@@")),o.push([i,s].join(I()))}}t.push(o.join(R()))}var u;return t.join(M())}(e.transformation);return a&&a.length&&(S(e)||r?t.searchParams.append("tr",a):t.pathname=F(["tr"+M()+a,t.pathname])),t.pathname=F(n?[n,t.pathname]:[t.pathname]),t.href};return function(){function t(e){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),n(this,"options",{sdkVersion:"javascript-".concat("1.5.0"),publicKey:"",urlEndpoint:"",transformationPosition:T()}),this.options=a(a({},this.options),e||{}),!this.options.urlEndpoint)throw i;if(!E(this.options))throw s}var o,u,p;return o=t,(u=[{key:"url",value:function(e){return t=e,r=this.options,N(a(a({},r),t));var t,r}},{key:"upload",value:function(t,r,n){var o;if("function"==typeof r?o=r:n=r||{},!t||"object"!==e(t))return g(!0,m,o);var i=a(a({},this.options),n),s=(t||{}).xhr;delete t.xhr;var u,p,l=s||new XMLHttpRequest;return(u=this,p=P,function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length!==p.length||void 0===t[t.length-1])return new Promise((function(e,r){t.pop(),t.push((function(t){if(t)return r(t);for(var n=arguments.length,o=new Array(n>1?n-1:0),a=1;a<n;a++)o[a-1]=arguments[a];e(o.length>1?o:o[0])})),p.call.apply(p,[u].concat(t))}));if("function"!=typeof t[t.length-1])throw new Error("Callback must be a function.");p.call.apply(p,[u].concat(t))})(l,t,i,o)}}])&&r(o.prototype,u),p&&r(o,p),t}()})); |
@@ -42,2 +42,6 @@ declare const _default: { | ||
}; | ||
AUTH_INVALID_RESPONSE: { | ||
message: string; | ||
help: string; | ||
}; | ||
UPLOAD_ENDPOINT_NETWORK_ERROR: { | ||
@@ -44,0 +48,0 @@ message: string; |
import { ImageKitOptions, UploadOptions, UploadResponse, UrlOptions } from "./interfaces"; | ||
import IKResponse from "./interfaces/IKResponse"; | ||
declare class ImageKit { | ||
@@ -25,4 +26,5 @@ options: ImageKitOptions; | ||
*/ | ||
upload(uploadOptions: UploadOptions, callback?: (err: Error | null, response: UploadResponse | null) => void, options?: Partial<ImageKitOptions>): void; | ||
upload(uploadOptions: UploadOptions, options?: Partial<ImageKitOptions>): Promise<IKResponse<UploadResponse>>; | ||
upload(uploadOptions: UploadOptions, callback: (err: Error | null, response: IKResponse<UploadResponse> | null) => void, options?: Partial<ImageKitOptions>): void; | ||
} | ||
export default ImageKit; |
@@ -39,3 +39,3 @@ /** | ||
*/ | ||
tags?: string; | ||
tags?: string | string[]; | ||
/** | ||
@@ -70,5 +70,14 @@ * The folder path (e.g. /images/folder/) in which the image has to be uploaded. If the folder(s) didn't exist before, a new folder(s) is created. | ||
*/ | ||
responseFields?: string; | ||
responseFields?: string | string[]; | ||
extensions?: object[]; | ||
webhookUrl?: string; | ||
overwriteFile?: boolean; | ||
overwriteAITags?: boolean; | ||
overwriteTags?: boolean; | ||
overwriteCustomMetadata?: boolean; | ||
customMetadata?: string | Record<string, string | number | boolean | Array<string | number | boolean>>; | ||
/** | ||
* Optional XMLHttpRequest object that you can send for upload API request. You can listen to `progress` and other events on this object for any custom logic. | ||
*/ | ||
xhr?: XMLHttpRequest; | ||
} |
import { ImageKitOptions, UploadOptions, UploadResponse } from "../interfaces"; | ||
export declare const upload: (uploadOptions: UploadOptions, options: ImageKitOptions, callback?: ((err: Error | null, response: UploadResponse | null) => void) | undefined) => void; | ||
export declare const upload: (xhr: XMLHttpRequest, uploadOptions: UploadOptions, options: ImageKitOptions, callback?: ((err: Error | null, response: UploadResponse | null) => void) | undefined) => void; |
import { ImageKitOptions, UploadResponse } from "../interfaces"; | ||
import IKResponse from "../interfaces/IKResponse"; | ||
import 'regenerator-runtime/runtime'; | ||
interface SignatureResponse { | ||
@@ -7,9 +9,7 @@ signature: string; | ||
} | ||
export declare const request: (formData: FormData, options: ImageKitOptions & { | ||
export declare const request: (uploadFileXHR: XMLHttpRequest, formData: FormData, options: ImageKitOptions & { | ||
authenticationEndpoint: string; | ||
}, callback?: ((err: Error | null, response: UploadResponse | null) => void) | undefined) => void; | ||
export declare const generateSignatureToken: (options: ImageKitOptions & { | ||
authenticationEndpoint: string; | ||
}, callback: (err: Error | null, response: SignatureResponse | null) => void) => void; | ||
export declare const uploadFile: (formData: FormData, callback: (err: Error | null, response: UploadResponse | null) => void) => void; | ||
}, callback?: ((err: Error | null, response: UploadResponse | null) => void) | undefined) => Promise<void>; | ||
export declare const generateSignatureToken: (authenticationEndpoint: string) => Promise<SignatureResponse>; | ||
export declare const uploadFile: (uploadFileXHR: XMLHttpRequest, formData: FormData) => Promise<IKResponse<UploadResponse> | Error>; | ||
export {}; |
{ | ||
"name": "imagekit-javascript", | ||
"version": "1.4.3", | ||
"version": "1.5.0", | ||
"description": "Javascript SDK for using ImageKit.io in the browser", | ||
@@ -71,3 +71,6 @@ "main": "dist/imagekit.cjs.js", | ||
}, | ||
"homepage": "https://github.com/imagekit-developer/imagekit-javascript#readme" | ||
"homepage": "https://github.com/imagekit-developer/imagekit-javascript#readme", | ||
"dependencies": { | ||
"regenerator-runtime": "^0.13.9" | ||
} | ||
} |
134
README.md
@@ -13,5 +13,5 @@ [<img width="250" alt="ImageKit.io" src="https://raw.githubusercontent.com/imagekit-developer/imagekit-javascript/master/assets/imagekit-light-logo.svg"/>](https://imagekit.io) | ||
ImageKit Javascript SDK allows you to use real-time [image resizing](https://docs.imagekit.io/features/image-transformations), [optimization](https://docs.imagekit.io/features/image-optimization), and [file uploading](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload) in the client-side. | ||
Javascript SDK for [ImageKit](https://imagekit.io/) provides URL generation for image & video resizing and provides an interface for file upload. This SDK is lightweight and you can also use this as an ES module. | ||
This SDK is lightweight and has no dependency. You can also use this as an ES module. | ||
ImageKit is complete media storage, optimization, and transformation solution that comes with an [image and video CDN](https://imagekit.io/features/imagekit-infrastructure). It can be integrated with your existing infrastructure - storage like AWS S3, web servers, your CDN, and custom domain names, allowing you to deliver optimized images in minutes with minimal code changes. | ||
@@ -89,2 +89,3 @@ ## Installation | ||
``` | ||
// Run it from project root | ||
yarn startSampleApp | ||
@@ -100,3 +101,3 @@ ``` | ||
This method allows you to create a URL using the `path` where the image exists and the URL endpoint (`urlEndpoint`) you want to use to access the image. You can refer to the documentation [here](https://docs.imagekit.io/integration/url-endpoints) to read more about URL endpoints in ImageKit and the section about [image origins](https://docs.imagekit.io/integration/configure-origin) to understand about paths with different kinds of origins. | ||
This method allows you to create an URL to access a file using the relative file path and the ImageKit URL endpoint (`urlEndpoint`). The file can be an image, video, or any other static file supported by ImageKit. | ||
@@ -122,3 +123,3 @@ ``` | ||
This method allows you to add transformation parameters to an existing, complete URL that is already mapped to ImageKit using the `src` parameter. This method should be used if you have the complete URL mapped to ImageKit stored in your database. | ||
This method allows you to add transformation parameters to an absolute URL. For example, if you have configured a custom CNAME and have absolute asset URLs in your database or CMS, you will often need this. | ||
@@ -148,7 +149,7 @@ | ||
| urlEndpoint | Optional. The base URL to be appended before the path of the image. If not specified, the URL Endpoint specified at the time of SDK initialization is used. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/ | | ||
| path | Conditional. This is the path at which the image exists. For example, `/path/to/image.jpg`. Either the `path` or `src` parameter need to be specified for URL generation. | | ||
| src | Conditional. This is the complete URL of an image already mapped to ImageKit. For example, `https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg`. Either the `path` or `src` parameter need to be specified for URL generation. | | ||
| transformation | Optional. An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a [chained transformation](https://docs.imagekit.io/features/image-transformations/chained-transformations) can be specified as different objects of the array. The complete list of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL. | | ||
| transformationPostion | Optional. The default value is `path` that places the transformation string as a path parameter in the URL. It can also be specified as `query` which adds the transformation string as the query parameter `tr` in the URL. If you use `src` parameter to create the URL, then the transformation string is always added as a query parameter. | | ||
| queryParameters | Optional. These are the other query parameters that you want to add to the final URL. These can be any query parameters and not necessarily related to ImageKit. Especially useful if you want to add some versioning parameter to your URLs. | | ||
| path | Conditional. This is the path at which the image exists. For example, `/path/to/image.jpg`. Either the `path` or `src` parameter needs to be specified for URL generation. | | ||
| src | Conditional. This is the complete URL of an image already mapped to ImageKit. For example, `https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg`. Either the `path` or `src` parameter needs to be specified for URL generation. | | ||
| transformation | Optional. An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a [chained transformation](https://docs.imagekit.io/features/image-transformations/chained-transformations) can be specified as different objects of the array. The complete list of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL. | | ||
| transformationPostion | Optional. The default value is `path`, which places the transformation string as a path parameter in the URL. It can also be specified as `query`, which adds the transformation string as the query parameter `tr` in the URL. If you use the `src` parameter to create the URL, then the transformation string is always added as a query parameter. | | ||
| queryParameters | Optional. These are the other query parameters that you want to add to the final URL. These can be any query parameters and are not necessarily related to ImageKit. Especially useful if you want to add some versioning parameters to your URLs. | | ||
@@ -197,3 +198,3 @@ #### Examples of generating URLs | ||
The complete list of transformations supported and their usage in ImageKit can be found [here](https://docs.imagekit.io/features/image-transformations). The SDK gives a name to each transformation parameter, making the code simpler and readable. If a transformation is supported in ImageKit, but a name for it cannot be found in the table below, then use the transformation code from ImageKit docs as the name when using in the `url` function. | ||
See the complete list of transformations supported in ImageKit [here](https://docs.imagekit.io/features/image-transformations). The SDK gives a name to each transformation parameter e.g. `height` for `h` and `width` for `w` parameter. It makes your code more readable. If the property does not match any of the following supported options, it is added as it is. | ||
@@ -265,5 +266,5 @@ If you want to generate transformations in your application and add them to the URL as it is, use the `raw` parameter. | ||
The SDK provides a simple interface using the `.upload()` method to upload files to the ImageKit Media Library. It accepts all the parameters supported by the [ImageKit Upload API](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload). | ||
The SDK provides a simple interface using the `.upload()` method to upload files to the ImageKit Media Library. | ||
The `upload()` method requires `file` and the `fileName` parameter. | ||
The `upload()` method requires mandatory `file` and the `fileName` parameter. In addition, it accepts all the parameters supported by the [ImageKit Upload API](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload). | ||
@@ -276,4 +277,5 @@ Also, make sure that you have specified `authenticationEndpoint` during SDK initialization. The SDK makes an HTTP GET request to this endpoint and expects a JSON response with three fields, i.e. `signature`, `token`, and `expire`. | ||
Sample usage | ||
``` | ||
#### Sample usage | ||
```html | ||
<form action="#" onsubmit="upload()"> | ||
@@ -298,2 +300,4 @@ <input type="file" id="file1" /> | ||
var file = document.getElementById("file1"); | ||
// Using Callback Function | ||
imagekit.upload({ | ||
@@ -311,8 +315,22 @@ file: file.files[0], | ||
}, function(err, result) { | ||
console.log(arguments); | ||
console.log(imagekit.url({ | ||
src: result.url, | ||
transformation: [{ height: 300, width: 400}] | ||
})); | ||
console.log(result); | ||
}) | ||
// Using Promises | ||
imagekit.upload({ | ||
file: file.files[0], | ||
fileName: "abc1.jpg", | ||
tags: ["tag1"], | ||
extensions: [ | ||
{ | ||
name: "aws-auto-tagging", | ||
minConfidence: 80, | ||
maxTags: 10 | ||
} | ||
] | ||
}).then(result => { | ||
console.log(result); | ||
}).then(error => { | ||
console.log(error); | ||
}) | ||
} | ||
@@ -325,1 +343,79 @@ </script> | ||
## Tracking upload progress using custom XMLHttpRequest | ||
You can use a custom XMLHttpRequest object as the following to bind `progress` or any other events for a customized implementation. | ||
```js | ||
var fileSize = file.files[0].size; | ||
var customXHR = new XMLHttpRequest(); | ||
customXHR.upload.addEventListener('progress', function (e) { | ||
if (e.loaded <= fileSize) { | ||
var percent = Math.round(e.loaded / fileSize * 100); | ||
console.log(`Uploaded ${percent}%`); | ||
} | ||
if(e.loaded == e.total){ | ||
console.log("Upload done"); | ||
} | ||
}); | ||
imagekit.upload({ | ||
xhr: customXHR, | ||
file: file.files[0], | ||
fileName: "abc1.jpg", | ||
tags: ["tag1"], | ||
extensions: [ | ||
{ | ||
name: "aws-auto-tagging", | ||
minConfidence: 80, | ||
maxTags: 10 | ||
} | ||
] | ||
}).then(result => { | ||
console.log(result); | ||
}).then(error => { | ||
console.log(error); | ||
}) | ||
``` | ||
## Access request-id, other response headers, and HTTP status code | ||
You can access `$ResponseMetadata` on success or error object to access the HTTP status code and response headers. | ||
```js | ||
// Success | ||
var response = await imagekit.upload({ | ||
file: file.files[0], | ||
fileName: "abc1.jpg", | ||
tags: ["tag1"], | ||
extensions: [ | ||
{ | ||
name: "aws-auto-tagging", | ||
minConfidence: 80, | ||
maxTags: 10 | ||
} | ||
] | ||
}); | ||
console.log(response.$ResponseMetadata.statusCode); // 200 | ||
// { 'content-length': "300", 'content-type': 'application/json', 'x-request-id': 'ee560df4-d44f-455e-a48e-29dfda49aec5'} | ||
console.log(response.$ResponseMetadata.headers); | ||
// Error | ||
try { | ||
await imagekit.upload({ | ||
file: file.files[0], | ||
fileName: "abc1.jpg", | ||
tags: ["tag1"], | ||
extensions: [ | ||
{ | ||
name: "aws-auto-tagging", | ||
minConfidence: 80, | ||
maxTags: 10 | ||
} | ||
] | ||
}); | ||
} catch (ex) { | ||
console.log(response.$ResponseMetadata.statusCode); // 400 | ||
// {'content-type': 'application/json', 'x-request-id': 'ee560df4-d44f-455e-a48e-29dfda49aec5'} | ||
console.log(response.$ResponseMetadata.headers); | ||
} |
@@ -9,5 +9,6 @@ export default { | ||
MISSING_AUTHENTICATION_ENDPOINT: { message: "Missing authentication endpoint for upload", help: "" }, | ||
MISSING_PUBLIC_KEY : { message: "Missing public key for upload", help: "" }, | ||
MISSING_PUBLIC_KEY: { message: "Missing public key for upload", help: "" }, | ||
AUTH_ENDPOINT_TIMEOUT: { message: "The authenticationEndpoint you provided timed out in 60 seconds", help: "" }, | ||
AUTH_ENDPOINT_NETWORK_ERROR: { message: "Request to authenticationEndpoint failed due to network error", help: "" }, | ||
AUTH_INVALID_RESPONSE: { message: "Invalid response from authenticationEndpoint. The SDK expects a JSON response with three fields i.e. signature, token and expire.", help: "" }, | ||
UPLOAD_ENDPOINT_NETWORK_ERROR: { | ||
@@ -14,0 +15,0 @@ message: "Request to ImageKit upload endpoint failed due to network error", |
@@ -284,2 +284,7 @@ /** | ||
original: "orig", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/conditional-transformations | ||
*/ | ||
raw: "raw", | ||
} | ||
@@ -286,0 +291,0 @@ |
import { version } from "../package.json"; | ||
import errorMessages from "./constants/errorMessages"; | ||
import { ImageKitOptions, UploadOptions, UploadResponse, UrlOptions } from "./interfaces"; | ||
import IKResponse from "./interfaces/IKResponse"; | ||
import { upload } from "./upload/index"; | ||
import respond from "./utils/respond"; | ||
import { url } from "./url/index"; | ||
@@ -12,5 +14,25 @@ import transformationUtils from "./utils/transformation"; | ||
function privateKeyPassed(options: ImageKitOptions) { | ||
return typeof (options as any).privateKey != "undefined"; | ||
} | ||
const promisify = function <T = void>(thisContext: ImageKit, fn: Function) { | ||
return function (...args: any[]): Promise<T> | void { | ||
if (args.length === fn.length && typeof args[args.length - 1] !== "undefined") { | ||
if (typeof args[args.length - 1] !== "function") { | ||
throw new Error("Callback must be a function."); | ||
} | ||
fn.call(thisContext, ...args); | ||
} else { | ||
return new Promise<T>((resolve, reject) => { | ||
const callback = function (err: Error, ...results: any[]) { | ||
if (err) { | ||
return reject(err); | ||
} else { | ||
resolve(results.length > 1 ? results : results[0]); | ||
} | ||
}; | ||
args.pop() | ||
args.push(callback); | ||
fn.call(thisContext, ...args); | ||
}); | ||
} | ||
}; | ||
}; | ||
@@ -30,5 +52,2 @@ class ImageKit { | ||
} | ||
if (privateKeyPassed(this.options)) { | ||
throw errorMessages.PRIVATE_KEY_CLIENT_SIDE; | ||
} | ||
@@ -63,7 +82,14 @@ if (!transformationUtils.validParameters(this.options)) { | ||
*/ | ||
upload( | ||
uploadOptions: UploadOptions, | ||
callback?: (err: Error | null, response: UploadResponse | null) => void, | ||
options?: Partial<ImageKitOptions>, | ||
): void { | ||
upload(uploadOptions: UploadOptions, options?: Partial<ImageKitOptions>): Promise<IKResponse<UploadResponse>> | ||
upload(uploadOptions: UploadOptions, callback: (err: Error | null, response: IKResponse<UploadResponse> | null) => void, options?: Partial<ImageKitOptions>): void; | ||
upload(uploadOptions: UploadOptions, callbackOrOptions?: ((err: Error | null, response: IKResponse<UploadResponse> | null) => void) | Partial<ImageKitOptions>, options?: Partial<ImageKitOptions>): void | Promise<IKResponse<UploadResponse>> { | ||
let callback; | ||
if (typeof callbackOrOptions === 'function') { | ||
callback = callbackOrOptions; | ||
} else { | ||
options = callbackOrOptions || {}; | ||
} | ||
if (!uploadOptions || typeof uploadOptions !== "object") { | ||
return respond(true, errorMessages.INVALID_UPLOAD_OPTIONS, callback); | ||
} | ||
var mergedOptions = { | ||
@@ -73,3 +99,6 @@ ...this.options, | ||
}; | ||
return upload(uploadOptions, mergedOptions, callback); | ||
const { xhr: userProvidedXHR } = uploadOptions || {}; | ||
delete uploadOptions.xhr; | ||
const xhr = userProvidedXHR || new XMLHttpRequest(); | ||
return promisify<IKResponse<UploadResponse>>(this, upload)(xhr, uploadOptions, mergedOptions, callback); | ||
} | ||
@@ -76,0 +105,0 @@ } |
@@ -39,3 +39,3 @@ /** | ||
*/ | ||
tags?: string; | ||
tags?: string | string[]; | ||
/** | ||
@@ -70,3 +70,3 @@ * The folder path (e.g. /images/folder/) in which the image has to be uploaded. If the folder(s) didn't exist before, a new folder(s) is created. | ||
*/ | ||
responseFields?: string; | ||
responseFields?: string | string[]; | ||
/* | ||
@@ -80,2 +80,30 @@ * Object with array of extensions to be processed on the image. | ||
webhookUrl?: string | ||
/* | ||
* Default is true. If overwriteFile is set to false and useUniqueFileName is also false, and a file already exists at the exact location, upload API will return an error immediately. | ||
*/ | ||
overwriteFile?: boolean | ||
/* | ||
* Default is true. If set to true and a file already exists at the exact location, its AITags will be removed. Set overwriteAITags to false to preserve AITags. | ||
*/ | ||
overwriteAITags?: boolean | ||
/* | ||
* Default is true. If the request does not have tags , overwriteTags is set to true and a file already exists at the exact location, existing tags will be removed. | ||
* In case the request body has tags, setting overwriteTags to false has no effect and request's tags are set on the asset. | ||
*/ | ||
overwriteTags?: boolean | ||
/* | ||
* Default is true. If the request does not have customMetadata , overwriteCustomMetadata is set to true and a file already exists at the exact location, exiting customMetadata will be removed. | ||
* In case the request body has customMetadata, setting overwriteCustomMetadata to false has no effect and request's customMetadata is set on the asset. | ||
*/ | ||
overwriteCustomMetadata?: boolean | ||
/* | ||
* Stringified JSON key-value data to be associated with the asset. Checkout overwriteCustomMetadata parameter to understand default behaviour. | ||
* Before setting any custom metadata on an asset you have to create the field using custom metadata fields API. | ||
*/ | ||
customMetadata?: string | Record<string, string | number | boolean | Array<string | number | boolean>> | ||
/** | ||
* Optional XMLHttpRequest object that you can send for upload API request. You can listen to `progress` and other events on this object for any custom logic. | ||
*/ | ||
xhr?: XMLHttpRequest | ||
} |
@@ -7,2 +7,3 @@ import errorMessages from "../constants/errorMessages"; | ||
export const upload = ( | ||
xhr: XMLHttpRequest, | ||
uploadOptions: UploadOptions, | ||
@@ -12,7 +13,2 @@ options: ImageKitOptions, | ||
) => { | ||
if (!uploadOptions) { | ||
respond(true, errorMessages.INVALID_UPLOAD_OPTIONS, callback); | ||
return; | ||
} | ||
if (!uploadOptions.file) { | ||
@@ -38,20 +34,20 @@ respond(true, errorMessages.MISSING_UPLOAD_FILE_PARAMETER, callback); | ||
if(uploadOptions.tags && Array.isArray(uploadOptions.tags)) | ||
{ | ||
uploadOptions.tags = String(uploadOptions.tags); | ||
} | ||
var formData = new FormData(); | ||
let i: keyof typeof uploadOptions; | ||
for (i in uploadOptions) { | ||
const param = uploadOptions[i]; | ||
if (typeof param !== "undefined") { | ||
if (typeof param === "string" || typeof param === "boolean") { | ||
formData.append(i, String(param)); | ||
} | ||
else if(Array.isArray(param)) { | ||
formData.append(i, JSON.stringify(param)); | ||
let key: keyof typeof uploadOptions; | ||
for (key in uploadOptions) { | ||
if (key) { | ||
if (key === "file" && typeof uploadOptions.file != "string") { | ||
formData.append('file', uploadOptions.file, String(uploadOptions.fileName)); | ||
} else if (key === "tags" && Array.isArray(uploadOptions.tags)) { | ||
formData.append('tags', uploadOptions.tags.join(",")); | ||
} else if (key === "responseFields" && Array.isArray(uploadOptions.responseFields)) { | ||
formData.append('responseFields', uploadOptions.responseFields.join(",")); | ||
} else if (key === "extensions" && Array.isArray(uploadOptions.extensions)) { | ||
formData.append('extensions', JSON.stringify(uploadOptions.extensions)); | ||
} else if (key === "customMetadata" && typeof uploadOptions.customMetadata === "object" && | ||
!Array.isArray(uploadOptions.customMetadata) && uploadOptions.customMetadata !== null) { | ||
formData.append('customMetadata', JSON.stringify(uploadOptions.customMetadata)); | ||
} | ||
else { | ||
formData.append(i, param); | ||
formData.append(key, String(uploadOptions[key])); | ||
} | ||
@@ -63,3 +59,3 @@ } | ||
request(formData, { ...options, authenticationEndpoint: options.authenticationEndpoint }, callback); | ||
request(xhr, formData, { ...options, authenticationEndpoint: options.authenticationEndpoint }, callback); | ||
}; |
import respond from "../utils/respond"; | ||
import errorMessages from "../constants/errorMessages" | ||
import { ImageKitOptions, UploadResponse } from "../interfaces"; | ||
import IKResponse from "../interfaces/IKResponse"; | ||
import 'regenerator-runtime/runtime' | ||
@@ -11,80 +13,121 @@ interface SignatureResponse { | ||
export const request = (formData: FormData, options: ImageKitOptions & { authenticationEndpoint: string }, callback?: (err: Error | null, response: UploadResponse | null) => void) => { | ||
generateSignatureToken(options, (err, signaturObj) => { | ||
if (err) { | ||
return respond(true, err, callback) | ||
} else { | ||
formData.append("signature", signaturObj?.signature || ""); | ||
formData.append("expire", String(signaturObj?.expire || 0)); | ||
formData.append("token", signaturObj?.token || ""); | ||
function getResponseHeaderMap(xhr: XMLHttpRequest) { | ||
const headers: Record<string, string | number | boolean> = {}; | ||
const responseHeaders = xhr.getAllResponseHeaders(); | ||
if (Object.keys(responseHeaders).length) { | ||
responseHeaders | ||
.trim() | ||
.split(/[\r\n]+/) | ||
.map(value => value.split(/: /)) | ||
.forEach(keyValue => { | ||
headers[keyValue[0].trim()] = keyValue[1].trim(); | ||
}); | ||
} | ||
return headers; | ||
} | ||
uploadFile(formData, (err, responseSucessText) => { | ||
if (err) { | ||
return respond(true, err, callback) | ||
} | ||
return respond(false, responseSucessText!, callback) | ||
}); | ||
} | ||
const addResponseHeadersAndBody = (body: any, xhr: XMLHttpRequest): IKResponse<UploadResponse> => { | ||
let response = { ...body }; | ||
const responseMetadata = { | ||
statusCode: xhr.status, | ||
headers: getResponseHeaderMap(xhr) | ||
} | ||
Object.defineProperty(response, "$ResponseMetadata", { | ||
value: responseMetadata, | ||
enumerable: false, | ||
writable: false | ||
}); | ||
return response as IKResponse<UploadResponse>; | ||
} | ||
export const generateSignatureToken = (options: ImageKitOptions & { authenticationEndpoint: string }, callback: (err: Error | null, response: SignatureResponse | null) => void) => { | ||
var xhr = new XMLHttpRequest(); | ||
xhr.timeout = 60000; | ||
xhr.open('GET', options.authenticationEndpoint); | ||
xhr.ontimeout = function (e) { | ||
respond(true, errorMessages.AUTH_ENDPOINT_TIMEOUT, callback); | ||
}; | ||
xhr.onerror = function() { | ||
respond(true, errorMessages.AUTH_ENDPOINT_NETWORK_ERROR, callback); | ||
export const request = async ( | ||
uploadFileXHR: XMLHttpRequest, | ||
formData: FormData, | ||
options: ImageKitOptions & { authenticationEndpoint: string }, | ||
callback?: (err: Error | null, response: UploadResponse | null) => void) => { | ||
try { | ||
var signaturObj = await generateSignatureToken(options.authenticationEndpoint); | ||
} catch (ex) { | ||
return respond(true, ex, callback); | ||
} | ||
xhr.onload = function () { | ||
if (xhr.status === 200) { | ||
try { | ||
var body = JSON.parse(xhr.responseText); | ||
var obj = { | ||
signature: body.signature, | ||
expire: body.expire, | ||
token: body.token | ||
formData.append("signature", signaturObj.signature); | ||
formData.append("expire", String(signaturObj.expire)); | ||
formData.append("token", signaturObj.token); | ||
try { | ||
var result = await uploadFile(uploadFileXHR, formData); | ||
return respond(false, result, callback); | ||
} catch (ex) { | ||
return respond(true, ex, callback); | ||
} | ||
} | ||
export const generateSignatureToken = ( | ||
authenticationEndpoint: string | ||
): Promise<SignatureResponse> => { | ||
return new Promise((resolve, reject) => { | ||
var xhr = new XMLHttpRequest(); | ||
xhr.timeout = 60000; | ||
xhr.open('GET', authenticationEndpoint); | ||
xhr.ontimeout = function (e) { | ||
return reject(errorMessages.AUTH_ENDPOINT_TIMEOUT); | ||
}; | ||
xhr.onerror = function () { | ||
return reject(errorMessages.AUTH_ENDPOINT_NETWORK_ERROR); | ||
} | ||
xhr.onload = function () { | ||
if (xhr.status === 200) { | ||
try { | ||
var body = JSON.parse(xhr.responseText); | ||
var obj = { | ||
signature: body.signature, | ||
expire: body.expire, | ||
token: body.token | ||
} | ||
if (!obj.signature || !obj.expire || !obj.token) { | ||
return reject(errorMessages.AUTH_INVALID_RESPONSE); | ||
} | ||
return resolve(obj); | ||
} catch (ex) { | ||
return reject(errorMessages.AUTH_INVALID_RESPONSE); | ||
} | ||
respond(false, obj, callback) | ||
} catch (ex) { | ||
respond(true, ex, callback) | ||
} else { | ||
return reject(errorMessages.AUTH_INVALID_RESPONSE); | ||
} | ||
} else { | ||
try { | ||
var error = JSON.parse(xhr.responseText); | ||
respond(true, error, callback); | ||
} catch (ex) { | ||
respond(true, ex, callback); | ||
} | ||
} | ||
}; | ||
xhr.send(); | ||
return; | ||
}; | ||
xhr.send(); | ||
}); | ||
} | ||
export const uploadFile = (formData: FormData, callback: (err: Error | null, response: UploadResponse | null) => void) => { | ||
var uploadFileXHR = new XMLHttpRequest(); | ||
uploadFileXHR.open('POST', 'https://upload.imagekit.io/api/v1/files/upload'); | ||
uploadFileXHR.onerror = function() { | ||
respond(true, errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR, callback); | ||
return; | ||
} | ||
uploadFileXHR.onload = function () { | ||
if (uploadFileXHR.status === 200) { | ||
var uploadResponse = JSON.parse(uploadFileXHR.responseText); | ||
callback(null, uploadResponse); | ||
export const uploadFile = ( | ||
uploadFileXHR: XMLHttpRequest, | ||
formData: FormData | ||
): Promise<IKResponse<UploadResponse> | Error> => { | ||
return new Promise((resolve, reject) => { | ||
uploadFileXHR.open('POST', 'https://upload.imagekit.io/api/v1/files/upload'); | ||
uploadFileXHR.onerror = function (e) { | ||
return reject(errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR); | ||
} | ||
else if (uploadFileXHR.status !== 200) { | ||
try { | ||
callback(JSON.parse(uploadFileXHR.responseText), null); | ||
} catch (ex : any) { | ||
callback(ex, null); | ||
uploadFileXHR.onload = function () { | ||
if (uploadFileXHR.status === 200) { | ||
try { | ||
var body = JSON.parse(uploadFileXHR.responseText); | ||
var uploadResponse = addResponseHeadersAndBody(body, uploadFileXHR); | ||
return resolve(uploadResponse); | ||
} catch (ex: any) { | ||
return reject(ex); | ||
} | ||
} else { | ||
try { | ||
var body = JSON.parse(uploadFileXHR.responseText); | ||
var uploadError = addResponseHeadersAndBody(body, uploadFileXHR); | ||
return reject(uploadError) | ||
} catch (ex: any) { | ||
return reject(ex); | ||
} | ||
} | ||
} | ||
}; | ||
uploadFileXHR.send(formData); | ||
return | ||
} | ||
}; | ||
uploadFileXHR.send(formData); | ||
}); | ||
} |
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
123995
21.75%37
5.71%2671
18.66%410
30.16%1
Infinity%1
Infinity%1
Infinity%+ Added
+ Added