@imagekit/react
Advanced tools
@@ -0,667 +1,5 @@ | ||
| import { buildSrc, getResponsiveImageAttributes } from '@imagekit/javascript'; | ||
| export { ImageKitAbortError, ImageKitInvalidRequestError, ImageKitServerError, ImageKitUploadNetworkError, buildSrc, buildTransformationString, getResponsiveImageAttributes, upload } from '@imagekit/javascript'; | ||
| import React, { createContext, useContext } from 'react'; | ||
| var errorMessages = { | ||
| MISSING_UPLOAD_FILE_PARAMETER: { | ||
| message: "Missing file parameter for upload" | ||
| }, | ||
| MISSING_UPLOAD_FILENAME_PARAMETER: { | ||
| message: "Missing fileName parameter for upload" | ||
| }, | ||
| MISSING_PUBLIC_KEY: { | ||
| message: "Missing public key for upload" | ||
| }, | ||
| UPLOAD_ENDPOINT_NETWORK_ERROR: { | ||
| message: "Request to ImageKit upload endpoint failed due to network error" | ||
| }, | ||
| MISSING_SIGNATURE: { | ||
| message: "Missing signature for upload. The SDK expects token, signature and expire for authentication." | ||
| }, | ||
| MISSING_TOKEN: { | ||
| message: "Missing token for upload. The SDK expects token, signature and expire for authentication." | ||
| }, | ||
| MISSING_EXPIRE: { | ||
| message: "Missing expire for upload. The SDK expects token, signature and expire for authentication." | ||
| }, | ||
| INVALID_TRANSFORMATION: { | ||
| message: "Invalid transformation parameter. Please include at least pre, post, or both." | ||
| }, | ||
| INVALID_PRE_TRANSFORMATION: { | ||
| message: "Invalid pre transformation parameter." | ||
| }, | ||
| INVALID_POST_TRANSFORMATION: { | ||
| message: "Invalid post transformation parameter." | ||
| } | ||
| }; | ||
| class ImageKitInvalidRequestError extends Error { | ||
| constructor(message, responseMetadata) { | ||
| super(message); | ||
| this.$ResponseMetadata = void 0; | ||
| this.name = "ImageKitInvalidRequestError"; | ||
| this.$ResponseMetadata = responseMetadata; | ||
| } | ||
| } | ||
| class ImageKitAbortError extends Error { | ||
| constructor(message, reason) { | ||
| super(message); | ||
| this.reason = void 0; | ||
| this.name = "ImageKitAbortError"; | ||
| this.reason = reason; | ||
| } | ||
| } | ||
| class ImageKitUploadNetworkError extends Error { | ||
| constructor(message) { | ||
| super(message); | ||
| this.name = "ImageKitUploadNetworkError"; | ||
| } | ||
| } | ||
| class ImageKitServerError extends Error { | ||
| constructor(message, responseMetadata) { | ||
| super(message); | ||
| this.$ResponseMetadata = void 0; | ||
| this.name = "ImageKitServerError"; | ||
| this.$ResponseMetadata = responseMetadata; | ||
| } | ||
| } | ||
| const upload = uploadOptions => { | ||
| if (!uploadOptions) { | ||
| return Promise.reject(new ImageKitInvalidRequestError("Invalid options provided for upload")); | ||
| } | ||
| return new Promise((resolve, reject) => { | ||
| const { | ||
| xhr: userProvidedXHR | ||
| } = uploadOptions || {}; | ||
| delete uploadOptions.xhr; | ||
| const xhr = userProvidedXHR || new XMLHttpRequest(); | ||
| if (!uploadOptions.file) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_UPLOAD_FILE_PARAMETER.message)); | ||
| } | ||
| if (!uploadOptions.fileName) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_UPLOAD_FILENAME_PARAMETER.message)); | ||
| } | ||
| if (!uploadOptions.publicKey || uploadOptions.publicKey.length === 0) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_PUBLIC_KEY.message)); | ||
| } | ||
| if (!uploadOptions.token) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_TOKEN.message)); | ||
| } | ||
| if (!uploadOptions.signature) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_SIGNATURE.message)); | ||
| } | ||
| if (!uploadOptions.expire) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_EXPIRE.message)); | ||
| } | ||
| if (uploadOptions.transformation) { | ||
| if (!(Object.keys(uploadOptions.transformation).includes("pre") || Object.keys(uploadOptions.transformation).includes("post"))) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_TRANSFORMATION.message)); | ||
| } | ||
| if (Object.keys(uploadOptions.transformation).includes("pre") && !uploadOptions.transformation.pre) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_PRE_TRANSFORMATION.message)); | ||
| } | ||
| if (Object.keys(uploadOptions.transformation).includes("post")) { | ||
| if (Array.isArray(uploadOptions.transformation.post)) { | ||
| for (let transformation of uploadOptions.transformation.post) { | ||
| if (transformation.type === "abs" && !(transformation.protocol || transformation.value)) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message)); | ||
| } else if (transformation.type === "transformation" && !transformation.value) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message)); | ||
| } | ||
| } | ||
| } else { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message)); | ||
| } | ||
| } | ||
| } | ||
| var formData = new FormData(); | ||
| let key; | ||
| for (key in uploadOptions) { | ||
| if (key) { | ||
| if (key === "file" && typeof uploadOptions.file != "string") { | ||
| formData.set('file', uploadOptions.file, String(uploadOptions.fileName)); | ||
| } else if (key === "tags" && Array.isArray(uploadOptions.tags)) { | ||
| formData.set('tags', uploadOptions.tags.join(",")); | ||
| } else if (key === 'signature') { | ||
| formData.set("signature", uploadOptions.signature); | ||
| } else if (key === 'expire') { | ||
| formData.set("expire", String(uploadOptions.expire)); | ||
| } else if (key === 'token') { | ||
| formData.set("token", uploadOptions.token); | ||
| } else if (key === "responseFields" && Array.isArray(uploadOptions.responseFields)) { | ||
| formData.set('responseFields', uploadOptions.responseFields.join(",")); | ||
| } else if (key === "extensions" && Array.isArray(uploadOptions.extensions)) { | ||
| formData.set('extensions', JSON.stringify(uploadOptions.extensions)); | ||
| } else if (key === "customMetadata" && typeof uploadOptions.customMetadata === "object" && !Array.isArray(uploadOptions.customMetadata) && uploadOptions.customMetadata !== null) { | ||
| formData.set('customMetadata', JSON.stringify(uploadOptions.customMetadata)); | ||
| } else if (key === "transformation" && typeof uploadOptions.transformation === "object" && uploadOptions.transformation !== null) { | ||
| formData.set(key, JSON.stringify(uploadOptions.transformation)); | ||
| } else if (key === 'checks' && uploadOptions.checks) { | ||
| formData.set("checks", uploadOptions.checks); | ||
| } else if (uploadOptions[key] !== undefined) { | ||
| if (["onProgress", "abortSignal"].includes(key)) continue; | ||
| formData.set(key, String(uploadOptions[key])); | ||
| } | ||
| } | ||
| } | ||
| if (uploadOptions.onProgress) { | ||
| xhr.upload.onprogress = function (event) { | ||
| if (uploadOptions.onProgress) uploadOptions.onProgress(event); | ||
| }; | ||
| } | ||
| function onAbortHandler() { | ||
| var _uploadOptions$abortS; | ||
| xhr.abort(); | ||
| return reject(new ImageKitAbortError("Upload aborted", (_uploadOptions$abortS = uploadOptions.abortSignal) === null || _uploadOptions$abortS === void 0 ? void 0 : _uploadOptions$abortS.reason)); | ||
| } | ||
| if (uploadOptions.abortSignal) { | ||
| if (uploadOptions.abortSignal.aborted) { | ||
| var _uploadOptions$abortS2; | ||
| return reject(new ImageKitAbortError("Upload aborted", (_uploadOptions$abortS2 = uploadOptions.abortSignal) === null || _uploadOptions$abortS2 === void 0 ? void 0 : _uploadOptions$abortS2.reason)); | ||
| } | ||
| uploadOptions.abortSignal.addEventListener("abort", onAbortHandler); | ||
| xhr.addEventListener("loadend", () => { | ||
| if (uploadOptions.abortSignal) { | ||
| uploadOptions.abortSignal.removeEventListener("abort", onAbortHandler); | ||
| } | ||
| }); | ||
| } | ||
| xhr.open('POST', 'https://upload.imagekit.io/api/v1/files/upload'); | ||
| xhr.onerror = function (e) { | ||
| return reject(new ImageKitUploadNetworkError(errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR.message)); | ||
| }; | ||
| xhr.onload = function () { | ||
| if (xhr.status >= 200 && xhr.status < 300) { | ||
| try { | ||
| var body = JSON.parse(xhr.responseText); | ||
| var uploadResponse = addResponseHeadersAndBody(body, xhr); | ||
| return resolve(uploadResponse); | ||
| } catch (ex) { | ||
| return reject(ex); | ||
| } | ||
| } else if (xhr.status >= 400 && xhr.status < 500) { | ||
| try { | ||
| var body = JSON.parse(xhr.responseText); | ||
| return reject(new ImageKitInvalidRequestError(body.message ?? "Invalid request. Please check the parameters.", getResponseMetadata(xhr))); | ||
| } catch (ex) { | ||
| return reject(ex); | ||
| } | ||
| } else { | ||
| try { | ||
| var body = JSON.parse(xhr.responseText); | ||
| return reject(new ImageKitServerError(body.message ?? "Server error occurred while uploading the file. This is rare and usually temporary.", getResponseMetadata(xhr))); | ||
| } catch (ex) { | ||
| return reject(new ImageKitServerError("Server error occurred while uploading the file. This is rare and usually temporary.", getResponseMetadata(xhr))); | ||
| } | ||
| } | ||
| }; | ||
| xhr.send(formData); | ||
| }); | ||
| }; | ||
| const addResponseHeadersAndBody = (body, xhr) => { | ||
| let response = { | ||
| ...body | ||
| }; | ||
| const responseMetadata = getResponseMetadata(xhr); | ||
| Object.defineProperty(response, "$ResponseMetadata", { | ||
| value: responseMetadata, | ||
| enumerable: false, | ||
| writable: false | ||
| }); | ||
| return response; | ||
| }; | ||
| const getResponseMetadata = xhr => { | ||
| const headers = getResponseHeaderMap(xhr); | ||
| const responseMetadata = { | ||
| statusCode: xhr.status, | ||
| headers: headers, | ||
| requestId: headers["x-request-id"] | ||
| }; | ||
| return responseMetadata; | ||
| }; | ||
| function getResponseHeaderMap(xhr) { | ||
| const headers = {}; | ||
| const responseHeaders = xhr.getAllResponseHeaders(); | ||
| if (Object.keys(responseHeaders).length) { | ||
| responseHeaders.trim().split(/[\r\n]+/).map(value => value.split(/: /)).forEach(keyValue => { | ||
| headers[keyValue[0].trim().toLowerCase()] = keyValue[1].trim(); | ||
| }); | ||
| } | ||
| return headers; | ||
| } | ||
| const supportedTransforms = { | ||
| width: "w", | ||
| height: "h", | ||
| aspectRatio: "ar", | ||
| background: "bg", | ||
| border: "b", | ||
| crop: "c", | ||
| cropMode: "cm", | ||
| dpr: "dpr", | ||
| focus: "fo", | ||
| quality: "q", | ||
| x: "x", | ||
| xCenter: "xc", | ||
| y: "y", | ||
| yCenter: "yc", | ||
| format: "f", | ||
| videoCodec: "vc", | ||
| audioCodec: "ac", | ||
| radius: "r", | ||
| rotation: "rt", | ||
| blur: "bl", | ||
| named: "n", | ||
| defaultImage: "di", | ||
| flip: "fl", | ||
| original: "orig", | ||
| startOffset: "so", | ||
| endOffset: "eo", | ||
| duration: "du", | ||
| streamingResolutions: "sr", | ||
| grayscale: "e-grayscale", | ||
| aiUpscale: "e-upscale", | ||
| aiRetouch: "e-retouch", | ||
| aiVariation: "e-genvar", | ||
| aiDropShadow: "e-dropshadow", | ||
| aiChangeBackground: "e-changebg", | ||
| aiRemoveBackground: "e-bgremove", | ||
| aiRemoveBackgroundExternal: "e-removedotbg", | ||
| contrastStretch: "e-contrast", | ||
| shadow: "e-shadow", | ||
| sharpen: "e-sharpen", | ||
| unsharpMask: "e-usm", | ||
| gradient: "e-gradient", | ||
| progressive: "pr", | ||
| lossless: "lo", | ||
| colorProfile: "cp", | ||
| metadata: "md", | ||
| opacity: "o", | ||
| trim: "t", | ||
| zoom: "z", | ||
| page: "pg", | ||
| fontSize: "fs", | ||
| fontFamily: "ff", | ||
| fontColor: "co", | ||
| innerAlignment: "ia", | ||
| padding: "pa", | ||
| alpha: "al", | ||
| typography: "tg", | ||
| lineHeight: "lh", | ||
| fontOutline: "fol", | ||
| fontShadow: "fsh", | ||
| raw: "raw" | ||
| }; | ||
| const QUERY_TRANSFORMATION_POSITION = "query"; | ||
| const CHAIN_TRANSFORM_DELIMITER = ":"; | ||
| const TRANSFORM_DELIMITER = ","; | ||
| const TRANSFORM_KEY_VALUE_DELIMITER = "-"; | ||
| var transformationUtils = { | ||
| addAsQueryParameter: options => { | ||
| return options.transformationPosition === QUERY_TRANSFORMATION_POSITION; | ||
| }, | ||
| getTransformKey: function (transform) { | ||
| if (!transform) { | ||
| return ""; | ||
| } | ||
| return supportedTransforms[transform] || supportedTransforms[transform.toLowerCase()] || ""; | ||
| }, | ||
| getChainTransformDelimiter: function () { | ||
| return CHAIN_TRANSFORM_DELIMITER; | ||
| }, | ||
| getTransformDelimiter: function () { | ||
| return TRANSFORM_DELIMITER; | ||
| }, | ||
| getTransformKeyValueDelimiter: function () { | ||
| return TRANSFORM_KEY_VALUE_DELIMITER; | ||
| } | ||
| }; | ||
| const safeBtoa = function (str) { | ||
| if (typeof window !== "undefined") { | ||
| return btoa(str); | ||
| } else { | ||
| return Buffer.from(str, "utf8").toString("base64"); | ||
| } | ||
| }; | ||
| const TRANSFORMATION_PARAMETER = "tr"; | ||
| const SIMPLE_OVERLAY_PATH_REGEX = new RegExp('^[a-zA-Z0-9-._/ ]*$'); | ||
| const SIMPLE_OVERLAY_TEXT_REGEX = new RegExp('^[a-zA-Z0-9-._ ]*$'); | ||
| function removeTrailingSlash(str) { | ||
| if (typeof str == "string" && str[str.length - 1] == "/") { | ||
| str = str.substring(0, str.length - 1); | ||
| } | ||
| return str; | ||
| } | ||
| function removeLeadingSlash(str) { | ||
| if (typeof str == "string" && str[0] == "/") { | ||
| str = str.slice(1); | ||
| } | ||
| return str; | ||
| } | ||
| function pathJoin(parts, sep) { | ||
| var separator = sep || "/"; | ||
| var replace = new RegExp(separator + "{1,}", "g"); | ||
| return parts.join(separator).replace(replace, separator); | ||
| } | ||
| const buildSrc = opts => { | ||
| opts.urlEndpoint = opts.urlEndpoint || ""; | ||
| opts.src = opts.src || ""; | ||
| opts.transformationPosition = opts.transformationPosition || "query"; | ||
| if (!opts.src) { | ||
| return ""; | ||
| } | ||
| const isAbsoluteURL = opts.src.startsWith("http://") || opts.src.startsWith("https://"); | ||
| var urlObj, isSrcParameterUsedForURL, urlEndpointPattern; | ||
| try { | ||
| if (!isAbsoluteURL) { | ||
| urlEndpointPattern = new URL(opts.urlEndpoint).pathname; | ||
| urlObj = new URL(pathJoin([opts.urlEndpoint.replace(urlEndpointPattern, ""), opts.src])); | ||
| } else { | ||
| urlObj = new URL(opts.src); | ||
| isSrcParameterUsedForURL = true; | ||
| } | ||
| } catch (e) { | ||
| console.error(e); | ||
| return ""; | ||
| } | ||
| for (var i in opts.queryParameters) { | ||
| urlObj.searchParams.append(i, String(opts.queryParameters[i])); | ||
| } | ||
| var transformationString = buildTransformationString(opts.transformation); | ||
| if (transformationString && transformationString.length) { | ||
| if (!transformationUtils.addAsQueryParameter(opts) && !isSrcParameterUsedForURL) { | ||
| urlObj.pathname = pathJoin([TRANSFORMATION_PARAMETER + transformationUtils.getChainTransformDelimiter() + transformationString, urlObj.pathname]); | ||
| } | ||
| } | ||
| if (urlEndpointPattern) { | ||
| urlObj.pathname = pathJoin([urlEndpointPattern, urlObj.pathname]); | ||
| } else { | ||
| urlObj.pathname = pathJoin([urlObj.pathname]); | ||
| } | ||
| if (transformationString && transformationString.length) { | ||
| if (transformationUtils.addAsQueryParameter(opts) || isSrcParameterUsedForURL) { | ||
| if (urlObj.searchParams.toString() !== "") { | ||
| return `${urlObj.href}&${TRANSFORMATION_PARAMETER}=${transformationString}`; | ||
| } else { | ||
| return `${urlObj.href}?${TRANSFORMATION_PARAMETER}=${transformationString}`; | ||
| } | ||
| } | ||
| } | ||
| return urlObj.href; | ||
| }; | ||
| function processInputPath(str, enccoding) { | ||
| str = removeTrailingSlash(removeLeadingSlash(str)); | ||
| if (enccoding === "plain") { | ||
| return `i-${str.replace(/\//g, "@@")}`; | ||
| } | ||
| if (enccoding === "base64") { | ||
| return `ie-${encodeURIComponent(safeBtoa(str))}`; | ||
| } | ||
| if (SIMPLE_OVERLAY_PATH_REGEX.test(str)) { | ||
| return `i-${str.replace(/\//g, "@@")}`; | ||
| } else { | ||
| return `ie-${encodeURIComponent(safeBtoa(str))}`; | ||
| } | ||
| } | ||
| function processText(str, enccoding) { | ||
| if (enccoding === "plain") { | ||
| return `i-${encodeURIComponent(str)}`; | ||
| } | ||
| if (enccoding === "base64") { | ||
| return `ie-${encodeURIComponent(safeBtoa(str))}`; | ||
| } | ||
| if (SIMPLE_OVERLAY_TEXT_REGEX.test(str)) { | ||
| return `i-${encodeURIComponent(str)}`; | ||
| } | ||
| return `ie-${encodeURIComponent(safeBtoa(str))}`; | ||
| } | ||
| function processOverlay(overlay) { | ||
| const entries = []; | ||
| const { | ||
| type, | ||
| position = {}, | ||
| timing = {}, | ||
| transformation = [] | ||
| } = overlay || {}; | ||
| if (!type) { | ||
| return; | ||
| } | ||
| switch (type) { | ||
| case "text": | ||
| { | ||
| const textOverlay = overlay; | ||
| if (!textOverlay.text) { | ||
| return; | ||
| } | ||
| const enccoding = textOverlay.encoding || "auto"; | ||
| entries.push("l-text"); | ||
| entries.push(processText(textOverlay.text, enccoding)); | ||
| } | ||
| break; | ||
| case "image": | ||
| entries.push("l-image"); | ||
| { | ||
| const imageOverlay = overlay; | ||
| const enccoding = imageOverlay.encoding || "auto"; | ||
| if (imageOverlay.input) { | ||
| entries.push(processInputPath(imageOverlay.input, enccoding)); | ||
| } else { | ||
| return; | ||
| } | ||
| } | ||
| break; | ||
| case "video": | ||
| entries.push("l-video"); | ||
| { | ||
| const videoOverlay = overlay; | ||
| const enccoding = videoOverlay.encoding || "auto"; | ||
| if (videoOverlay.input) { | ||
| entries.push(processInputPath(videoOverlay.input, enccoding)); | ||
| } else { | ||
| return; | ||
| } | ||
| } | ||
| break; | ||
| case "subtitle": | ||
| entries.push("l-subtitle"); | ||
| { | ||
| const subtitleOverlay = overlay; | ||
| const enccoding = subtitleOverlay.encoding || "auto"; | ||
| if (subtitleOverlay.input) { | ||
| entries.push(processInputPath(subtitleOverlay.input, enccoding)); | ||
| } else { | ||
| return; | ||
| } | ||
| } | ||
| break; | ||
| case "solidColor": | ||
| entries.push("l-image"); | ||
| entries.push(`i-ik_canvas`); | ||
| { | ||
| const solidColorOverlay = overlay; | ||
| if (solidColorOverlay.color) { | ||
| entries.push(`bg-${solidColorOverlay.color}`); | ||
| } else { | ||
| return; | ||
| } | ||
| } | ||
| break; | ||
| } | ||
| const { | ||
| x, | ||
| y, | ||
| focus | ||
| } = position; | ||
| if (x) { | ||
| entries.push(`lx-${x}`); | ||
| } | ||
| if (y) { | ||
| entries.push(`ly-${y}`); | ||
| } | ||
| if (focus) { | ||
| entries.push(`lfo-${focus}`); | ||
| } | ||
| const { | ||
| start, | ||
| end, | ||
| duration | ||
| } = timing; | ||
| if (start) { | ||
| entries.push(`lso-${start}`); | ||
| } | ||
| if (end) { | ||
| entries.push(`leo-${end}`); | ||
| } | ||
| if (duration) { | ||
| entries.push(`ldu-${duration}`); | ||
| } | ||
| const transformationString = buildTransformationString(transformation); | ||
| if (transformationString && transformationString.trim() !== "") entries.push(transformationString); | ||
| entries.push("l-end"); | ||
| return entries.join(transformationUtils.getTransformDelimiter()); | ||
| } | ||
| const buildTransformationString = function (transformation) { | ||
| if (!Array.isArray(transformation)) { | ||
| return ""; | ||
| } | ||
| var parsedTransforms = []; | ||
| for (var i = 0, l = transformation.length; i < l; i++) { | ||
| var parsedTransformStep = []; | ||
| for (var key in transformation[i]) { | ||
| let value = transformation[i][key]; | ||
| if (value === undefined || value === null) { | ||
| continue; | ||
| } | ||
| if (key === "overlay" && typeof value === "object") { | ||
| var rawString = processOverlay(value); | ||
| if (rawString && rawString.trim() !== "") { | ||
| parsedTransformStep.push(rawString); | ||
| } | ||
| continue; | ||
| } | ||
| var transformKey = transformationUtils.getTransformKey(key); | ||
| if (!transformKey) { | ||
| transformKey = key; | ||
| } | ||
| if (transformKey === "") { | ||
| continue; | ||
| } | ||
| if (["e-grayscale", "e-contrast", "e-removedotbg", "e-bgremove", "e-upscale", "e-retouch", "e-genvar"].includes(transformKey)) { | ||
| if (value === true || value === "-" || value === "true") { | ||
| parsedTransformStep.push(transformKey); | ||
| } else { | ||
| continue; | ||
| } | ||
| } else if (["e-sharpen", "e-shadow", "e-gradient", "e-usm", "e-dropshadow"].includes(transformKey) && (value.toString().trim() === "" || value === true || value === "true")) { | ||
| parsedTransformStep.push(transformKey); | ||
| } else if (key === "raw") { | ||
| parsedTransformStep.push(transformation[i][key]); | ||
| } else { | ||
| if (transformKey === "di") { | ||
| value = removeTrailingSlash(removeLeadingSlash(value || "")); | ||
| value = value.replace(/\//g, "@@"); | ||
| } | ||
| if (transformKey === "sr" && Array.isArray(value)) { | ||
| value = value.join("_"); | ||
| } | ||
| if (transformKey === "t" && value.toString().trim() === "") { | ||
| value = "true"; | ||
| } | ||
| parsedTransformStep.push([transformKey, value].join(transformationUtils.getTransformKeyValueDelimiter())); | ||
| } | ||
| } | ||
| if (parsedTransformStep.length) { | ||
| parsedTransforms.push(parsedTransformStep.join(transformationUtils.getTransformDelimiter())); | ||
| } | ||
| } | ||
| return parsedTransforms.join(transformationUtils.getChainTransformDelimiter()); | ||
| }; | ||
| const DEFAULT_DEVICE_BREAKPOINTS = [640, 750, 828, 1080, 1200, 1920, 2048, 3840]; | ||
| const DEFAULT_IMAGE_BREAKPOINTS = [16, 32, 48, 64, 96, 128, 256, 384]; | ||
| function getResponsiveImageAttributes(opts) { | ||
| const { | ||
| src, | ||
| urlEndpoint, | ||
| transformation = [], | ||
| queryParameters, | ||
| transformationPosition, | ||
| sizes, | ||
| width, | ||
| deviceBreakpoints = DEFAULT_DEVICE_BREAKPOINTS, | ||
| imageBreakpoints = DEFAULT_IMAGE_BREAKPOINTS | ||
| } = opts; | ||
| const sortedDeviceBreakpoints = [...deviceBreakpoints].sort((a, b) => a - b); | ||
| const sortedImageBreakpoints = [...imageBreakpoints].sort((a, b) => a - b); | ||
| const allBreakpoints = [...sortedImageBreakpoints, ...sortedDeviceBreakpoints].sort((a, b) => a - b); | ||
| const { | ||
| candidates, | ||
| descriptorKind | ||
| } = computeCandidateWidths({ | ||
| allBreakpoints, | ||
| deviceBreakpoints: sortedDeviceBreakpoints, | ||
| explicitWidth: width, | ||
| sizesAttr: sizes | ||
| }); | ||
| const buildURL = w => buildSrc({ | ||
| src, | ||
| urlEndpoint, | ||
| queryParameters, | ||
| transformationPosition, | ||
| transformation: [...transformation, { | ||
| width: w, | ||
| crop: 'at_max' | ||
| } | ||
| ] | ||
| }); | ||
| const srcSet = candidates.map((w, i) => `${buildURL(w)} ${descriptorKind === 'w' ? w : i + 1}${descriptorKind}`).join(', ') || undefined; | ||
| const finalSizes = sizes ?? (descriptorKind === 'w' ? '100vw' : undefined); | ||
| return { | ||
| src: buildURL(candidates[candidates.length - 1]), | ||
| srcSet, | ||
| ...(finalSizes ? { | ||
| sizes: finalSizes | ||
| } : {}), | ||
| ...(width !== undefined ? { | ||
| width | ||
| } : {}) | ||
| }; | ||
| } | ||
| function computeCandidateWidths(params) { | ||
| const { | ||
| allBreakpoints, | ||
| deviceBreakpoints, | ||
| explicitWidth, | ||
| sizesAttr | ||
| } = params; | ||
| if (sizesAttr) { | ||
| const vwTokens = sizesAttr.match(/(^|\s)(1?\d{1,2})vw/g) || []; | ||
| const vwPercents = vwTokens.map(t => parseInt(t, 10)); | ||
| if (vwPercents.length) { | ||
| const smallestRatio = Math.min(...vwPercents) / 100; | ||
| const minRequiredPx = deviceBreakpoints[0] * smallestRatio; | ||
| return { | ||
| candidates: allBreakpoints.filter(w => w >= minRequiredPx), | ||
| descriptorKind: 'w' | ||
| }; | ||
| } | ||
| return { | ||
| candidates: allBreakpoints, | ||
| descriptorKind: 'w' | ||
| }; | ||
| } | ||
| if (typeof explicitWidth !== 'number') { | ||
| return { | ||
| candidates: deviceBreakpoints, | ||
| descriptorKind: 'w' | ||
| }; | ||
| } | ||
| const nearest = t => allBreakpoints.find(n => n >= t) || allBreakpoints[allBreakpoints.length - 1]; | ||
| const unique = Array.from(new Set([nearest(explicitWidth), nearest(explicitWidth * 2)])); | ||
| return { | ||
| candidates: unique, | ||
| descriptorKind: 'x' | ||
| }; | ||
| } | ||
| /****************************************************************************** | ||
@@ -782,3 +120,3 @@ Copyright (c) Microsoft Corporation. | ||
| if (process.env.NODE_ENV !== "production") { | ||
| console.error("urlEndpoint is neither provided in this component nor in the ImageKitContext."); | ||
| console.error("urlEndpoint is neither provided in this component nor in any parent ImageKitProvider."); | ||
| } | ||
@@ -855,3 +193,3 @@ return null; | ||
| if (process.env.NODE_ENV !== "production") { | ||
| console.error("urlEndpoint is neither provided in this component nor in the ImageKitContext."); | ||
| console.error("urlEndpoint is neither provided in this component nor in any parent ImageKitProvider."); | ||
| } | ||
@@ -873,3 +211,3 @@ return null; | ||
| export { Image, ImageKitAbortError, ImageKitContext, ImageKitInvalidRequestError, ImageKitProvider, ImageKitServerError, ImageKitUploadNetworkError, Video, buildSrc, buildTransformationString, getResponsiveImageAttributes, upload }; | ||
| export { Image, ImageKitContext, ImageKitProvider, Video }; | ||
| //# sourceMappingURL=imagekitio-react.esm.js.map |
+38
-677
@@ -5,2 +5,3 @@ 'use strict'; | ||
| var javascript = require('@imagekit/javascript'); | ||
| var React = require('react'); | ||
@@ -12,666 +13,2 @@ | ||
| var errorMessages = { | ||
| MISSING_UPLOAD_FILE_PARAMETER: { | ||
| message: "Missing file parameter for upload" | ||
| }, | ||
| MISSING_UPLOAD_FILENAME_PARAMETER: { | ||
| message: "Missing fileName parameter for upload" | ||
| }, | ||
| MISSING_PUBLIC_KEY: { | ||
| message: "Missing public key for upload" | ||
| }, | ||
| UPLOAD_ENDPOINT_NETWORK_ERROR: { | ||
| message: "Request to ImageKit upload endpoint failed due to network error" | ||
| }, | ||
| MISSING_SIGNATURE: { | ||
| message: "Missing signature for upload. The SDK expects token, signature and expire for authentication." | ||
| }, | ||
| MISSING_TOKEN: { | ||
| message: "Missing token for upload. The SDK expects token, signature and expire for authentication." | ||
| }, | ||
| MISSING_EXPIRE: { | ||
| message: "Missing expire for upload. The SDK expects token, signature and expire for authentication." | ||
| }, | ||
| INVALID_TRANSFORMATION: { | ||
| message: "Invalid transformation parameter. Please include at least pre, post, or both." | ||
| }, | ||
| INVALID_PRE_TRANSFORMATION: { | ||
| message: "Invalid pre transformation parameter." | ||
| }, | ||
| INVALID_POST_TRANSFORMATION: { | ||
| message: "Invalid post transformation parameter." | ||
| } | ||
| }; | ||
| class ImageKitInvalidRequestError extends Error { | ||
| constructor(message, responseMetadata) { | ||
| super(message); | ||
| this.$ResponseMetadata = void 0; | ||
| this.name = "ImageKitInvalidRequestError"; | ||
| this.$ResponseMetadata = responseMetadata; | ||
| } | ||
| } | ||
| class ImageKitAbortError extends Error { | ||
| constructor(message, reason) { | ||
| super(message); | ||
| this.reason = void 0; | ||
| this.name = "ImageKitAbortError"; | ||
| this.reason = reason; | ||
| } | ||
| } | ||
| class ImageKitUploadNetworkError extends Error { | ||
| constructor(message) { | ||
| super(message); | ||
| this.name = "ImageKitUploadNetworkError"; | ||
| } | ||
| } | ||
| class ImageKitServerError extends Error { | ||
| constructor(message, responseMetadata) { | ||
| super(message); | ||
| this.$ResponseMetadata = void 0; | ||
| this.name = "ImageKitServerError"; | ||
| this.$ResponseMetadata = responseMetadata; | ||
| } | ||
| } | ||
| const upload = uploadOptions => { | ||
| if (!uploadOptions) { | ||
| return Promise.reject(new ImageKitInvalidRequestError("Invalid options provided for upload")); | ||
| } | ||
| return new Promise((resolve, reject) => { | ||
| const { | ||
| xhr: userProvidedXHR | ||
| } = uploadOptions || {}; | ||
| delete uploadOptions.xhr; | ||
| const xhr = userProvidedXHR || new XMLHttpRequest(); | ||
| if (!uploadOptions.file) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_UPLOAD_FILE_PARAMETER.message)); | ||
| } | ||
| if (!uploadOptions.fileName) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_UPLOAD_FILENAME_PARAMETER.message)); | ||
| } | ||
| if (!uploadOptions.publicKey || uploadOptions.publicKey.length === 0) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_PUBLIC_KEY.message)); | ||
| } | ||
| if (!uploadOptions.token) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_TOKEN.message)); | ||
| } | ||
| if (!uploadOptions.signature) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_SIGNATURE.message)); | ||
| } | ||
| if (!uploadOptions.expire) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_EXPIRE.message)); | ||
| } | ||
| if (uploadOptions.transformation) { | ||
| if (!(Object.keys(uploadOptions.transformation).includes("pre") || Object.keys(uploadOptions.transformation).includes("post"))) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_TRANSFORMATION.message)); | ||
| } | ||
| if (Object.keys(uploadOptions.transformation).includes("pre") && !uploadOptions.transformation.pre) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_PRE_TRANSFORMATION.message)); | ||
| } | ||
| if (Object.keys(uploadOptions.transformation).includes("post")) { | ||
| if (Array.isArray(uploadOptions.transformation.post)) { | ||
| for (let transformation of uploadOptions.transformation.post) { | ||
| if (transformation.type === "abs" && !(transformation.protocol || transformation.value)) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message)); | ||
| } else if (transformation.type === "transformation" && !transformation.value) { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message)); | ||
| } | ||
| } | ||
| } else { | ||
| return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message)); | ||
| } | ||
| } | ||
| } | ||
| var formData = new FormData(); | ||
| let key; | ||
| for (key in uploadOptions) { | ||
| if (key) { | ||
| if (key === "file" && typeof uploadOptions.file != "string") { | ||
| formData.set('file', uploadOptions.file, String(uploadOptions.fileName)); | ||
| } else if (key === "tags" && Array.isArray(uploadOptions.tags)) { | ||
| formData.set('tags', uploadOptions.tags.join(",")); | ||
| } else if (key === 'signature') { | ||
| formData.set("signature", uploadOptions.signature); | ||
| } else if (key === 'expire') { | ||
| formData.set("expire", String(uploadOptions.expire)); | ||
| } else if (key === 'token') { | ||
| formData.set("token", uploadOptions.token); | ||
| } else if (key === "responseFields" && Array.isArray(uploadOptions.responseFields)) { | ||
| formData.set('responseFields', uploadOptions.responseFields.join(",")); | ||
| } else if (key === "extensions" && Array.isArray(uploadOptions.extensions)) { | ||
| formData.set('extensions', JSON.stringify(uploadOptions.extensions)); | ||
| } else if (key === "customMetadata" && typeof uploadOptions.customMetadata === "object" && !Array.isArray(uploadOptions.customMetadata) && uploadOptions.customMetadata !== null) { | ||
| formData.set('customMetadata', JSON.stringify(uploadOptions.customMetadata)); | ||
| } else if (key === "transformation" && typeof uploadOptions.transformation === "object" && uploadOptions.transformation !== null) { | ||
| formData.set(key, JSON.stringify(uploadOptions.transformation)); | ||
| } else if (key === 'checks' && uploadOptions.checks) { | ||
| formData.set("checks", uploadOptions.checks); | ||
| } else if (uploadOptions[key] !== undefined) { | ||
| if (["onProgress", "abortSignal"].includes(key)) continue; | ||
| formData.set(key, String(uploadOptions[key])); | ||
| } | ||
| } | ||
| } | ||
| if (uploadOptions.onProgress) { | ||
| xhr.upload.onprogress = function (event) { | ||
| if (uploadOptions.onProgress) uploadOptions.onProgress(event); | ||
| }; | ||
| } | ||
| function onAbortHandler() { | ||
| var _uploadOptions$abortS; | ||
| xhr.abort(); | ||
| return reject(new ImageKitAbortError("Upload aborted", (_uploadOptions$abortS = uploadOptions.abortSignal) === null || _uploadOptions$abortS === void 0 ? void 0 : _uploadOptions$abortS.reason)); | ||
| } | ||
| if (uploadOptions.abortSignal) { | ||
| if (uploadOptions.abortSignal.aborted) { | ||
| var _uploadOptions$abortS2; | ||
| return reject(new ImageKitAbortError("Upload aborted", (_uploadOptions$abortS2 = uploadOptions.abortSignal) === null || _uploadOptions$abortS2 === void 0 ? void 0 : _uploadOptions$abortS2.reason)); | ||
| } | ||
| uploadOptions.abortSignal.addEventListener("abort", onAbortHandler); | ||
| xhr.addEventListener("loadend", () => { | ||
| if (uploadOptions.abortSignal) { | ||
| uploadOptions.abortSignal.removeEventListener("abort", onAbortHandler); | ||
| } | ||
| }); | ||
| } | ||
| xhr.open('POST', 'https://upload.imagekit.io/api/v1/files/upload'); | ||
| xhr.onerror = function (e) { | ||
| return reject(new ImageKitUploadNetworkError(errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR.message)); | ||
| }; | ||
| xhr.onload = function () { | ||
| if (xhr.status >= 200 && xhr.status < 300) { | ||
| try { | ||
| var body = JSON.parse(xhr.responseText); | ||
| var uploadResponse = addResponseHeadersAndBody(body, xhr); | ||
| return resolve(uploadResponse); | ||
| } catch (ex) { | ||
| return reject(ex); | ||
| } | ||
| } else if (xhr.status >= 400 && xhr.status < 500) { | ||
| try { | ||
| var body = JSON.parse(xhr.responseText); | ||
| return reject(new ImageKitInvalidRequestError(body.message ?? "Invalid request. Please check the parameters.", getResponseMetadata(xhr))); | ||
| } catch (ex) { | ||
| return reject(ex); | ||
| } | ||
| } else { | ||
| try { | ||
| var body = JSON.parse(xhr.responseText); | ||
| return reject(new ImageKitServerError(body.message ?? "Server error occurred while uploading the file. This is rare and usually temporary.", getResponseMetadata(xhr))); | ||
| } catch (ex) { | ||
| return reject(new ImageKitServerError("Server error occurred while uploading the file. This is rare and usually temporary.", getResponseMetadata(xhr))); | ||
| } | ||
| } | ||
| }; | ||
| xhr.send(formData); | ||
| }); | ||
| }; | ||
| const addResponseHeadersAndBody = (body, xhr) => { | ||
| let response = { | ||
| ...body | ||
| }; | ||
| const responseMetadata = getResponseMetadata(xhr); | ||
| Object.defineProperty(response, "$ResponseMetadata", { | ||
| value: responseMetadata, | ||
| enumerable: false, | ||
| writable: false | ||
| }); | ||
| return response; | ||
| }; | ||
| const getResponseMetadata = xhr => { | ||
| const headers = getResponseHeaderMap(xhr); | ||
| const responseMetadata = { | ||
| statusCode: xhr.status, | ||
| headers: headers, | ||
| requestId: headers["x-request-id"] | ||
| }; | ||
| return responseMetadata; | ||
| }; | ||
| function getResponseHeaderMap(xhr) { | ||
| const headers = {}; | ||
| const responseHeaders = xhr.getAllResponseHeaders(); | ||
| if (Object.keys(responseHeaders).length) { | ||
| responseHeaders.trim().split(/[\r\n]+/).map(value => value.split(/: /)).forEach(keyValue => { | ||
| headers[keyValue[0].trim().toLowerCase()] = keyValue[1].trim(); | ||
| }); | ||
| } | ||
| return headers; | ||
| } | ||
| const supportedTransforms = { | ||
| width: "w", | ||
| height: "h", | ||
| aspectRatio: "ar", | ||
| background: "bg", | ||
| border: "b", | ||
| crop: "c", | ||
| cropMode: "cm", | ||
| dpr: "dpr", | ||
| focus: "fo", | ||
| quality: "q", | ||
| x: "x", | ||
| xCenter: "xc", | ||
| y: "y", | ||
| yCenter: "yc", | ||
| format: "f", | ||
| videoCodec: "vc", | ||
| audioCodec: "ac", | ||
| radius: "r", | ||
| rotation: "rt", | ||
| blur: "bl", | ||
| named: "n", | ||
| defaultImage: "di", | ||
| flip: "fl", | ||
| original: "orig", | ||
| startOffset: "so", | ||
| endOffset: "eo", | ||
| duration: "du", | ||
| streamingResolutions: "sr", | ||
| grayscale: "e-grayscale", | ||
| aiUpscale: "e-upscale", | ||
| aiRetouch: "e-retouch", | ||
| aiVariation: "e-genvar", | ||
| aiDropShadow: "e-dropshadow", | ||
| aiChangeBackground: "e-changebg", | ||
| aiRemoveBackground: "e-bgremove", | ||
| aiRemoveBackgroundExternal: "e-removedotbg", | ||
| contrastStretch: "e-contrast", | ||
| shadow: "e-shadow", | ||
| sharpen: "e-sharpen", | ||
| unsharpMask: "e-usm", | ||
| gradient: "e-gradient", | ||
| progressive: "pr", | ||
| lossless: "lo", | ||
| colorProfile: "cp", | ||
| metadata: "md", | ||
| opacity: "o", | ||
| trim: "t", | ||
| zoom: "z", | ||
| page: "pg", | ||
| fontSize: "fs", | ||
| fontFamily: "ff", | ||
| fontColor: "co", | ||
| innerAlignment: "ia", | ||
| padding: "pa", | ||
| alpha: "al", | ||
| typography: "tg", | ||
| lineHeight: "lh", | ||
| fontOutline: "fol", | ||
| fontShadow: "fsh", | ||
| raw: "raw" | ||
| }; | ||
| const QUERY_TRANSFORMATION_POSITION = "query"; | ||
| const CHAIN_TRANSFORM_DELIMITER = ":"; | ||
| const TRANSFORM_DELIMITER = ","; | ||
| const TRANSFORM_KEY_VALUE_DELIMITER = "-"; | ||
| var transformationUtils = { | ||
| addAsQueryParameter: options => { | ||
| return options.transformationPosition === QUERY_TRANSFORMATION_POSITION; | ||
| }, | ||
| getTransformKey: function (transform) { | ||
| if (!transform) { | ||
| return ""; | ||
| } | ||
| return supportedTransforms[transform] || supportedTransforms[transform.toLowerCase()] || ""; | ||
| }, | ||
| getChainTransformDelimiter: function () { | ||
| return CHAIN_TRANSFORM_DELIMITER; | ||
| }, | ||
| getTransformDelimiter: function () { | ||
| return TRANSFORM_DELIMITER; | ||
| }, | ||
| getTransformKeyValueDelimiter: function () { | ||
| return TRANSFORM_KEY_VALUE_DELIMITER; | ||
| } | ||
| }; | ||
| const safeBtoa = function (str) { | ||
| if (typeof window !== "undefined") { | ||
| return btoa(str); | ||
| } else { | ||
| return Buffer.from(str, "utf8").toString("base64"); | ||
| } | ||
| }; | ||
| const TRANSFORMATION_PARAMETER = "tr"; | ||
| const SIMPLE_OVERLAY_PATH_REGEX = new RegExp('^[a-zA-Z0-9-._/ ]*$'); | ||
| const SIMPLE_OVERLAY_TEXT_REGEX = new RegExp('^[a-zA-Z0-9-._ ]*$'); | ||
| function removeTrailingSlash(str) { | ||
| if (typeof str == "string" && str[str.length - 1] == "/") { | ||
| str = str.substring(0, str.length - 1); | ||
| } | ||
| return str; | ||
| } | ||
| function removeLeadingSlash(str) { | ||
| if (typeof str == "string" && str[0] == "/") { | ||
| str = str.slice(1); | ||
| } | ||
| return str; | ||
| } | ||
| function pathJoin(parts, sep) { | ||
| var separator = sep || "/"; | ||
| var replace = new RegExp(separator + "{1,}", "g"); | ||
| return parts.join(separator).replace(replace, separator); | ||
| } | ||
| const buildSrc = opts => { | ||
| opts.urlEndpoint = opts.urlEndpoint || ""; | ||
| opts.src = opts.src || ""; | ||
| opts.transformationPosition = opts.transformationPosition || "query"; | ||
| if (!opts.src) { | ||
| return ""; | ||
| } | ||
| const isAbsoluteURL = opts.src.startsWith("http://") || opts.src.startsWith("https://"); | ||
| var urlObj, isSrcParameterUsedForURL, urlEndpointPattern; | ||
| try { | ||
| if (!isAbsoluteURL) { | ||
| urlEndpointPattern = new URL(opts.urlEndpoint).pathname; | ||
| urlObj = new URL(pathJoin([opts.urlEndpoint.replace(urlEndpointPattern, ""), opts.src])); | ||
| } else { | ||
| urlObj = new URL(opts.src); | ||
| isSrcParameterUsedForURL = true; | ||
| } | ||
| } catch (e) { | ||
| console.error(e); | ||
| return ""; | ||
| } | ||
| for (var i in opts.queryParameters) { | ||
| urlObj.searchParams.append(i, String(opts.queryParameters[i])); | ||
| } | ||
| var transformationString = buildTransformationString(opts.transformation); | ||
| if (transformationString && transformationString.length) { | ||
| if (!transformationUtils.addAsQueryParameter(opts) && !isSrcParameterUsedForURL) { | ||
| urlObj.pathname = pathJoin([TRANSFORMATION_PARAMETER + transformationUtils.getChainTransformDelimiter() + transformationString, urlObj.pathname]); | ||
| } | ||
| } | ||
| if (urlEndpointPattern) { | ||
| urlObj.pathname = pathJoin([urlEndpointPattern, urlObj.pathname]); | ||
| } else { | ||
| urlObj.pathname = pathJoin([urlObj.pathname]); | ||
| } | ||
| if (transformationString && transformationString.length) { | ||
| if (transformationUtils.addAsQueryParameter(opts) || isSrcParameterUsedForURL) { | ||
| if (urlObj.searchParams.toString() !== "") { | ||
| return `${urlObj.href}&${TRANSFORMATION_PARAMETER}=${transformationString}`; | ||
| } else { | ||
| return `${urlObj.href}?${TRANSFORMATION_PARAMETER}=${transformationString}`; | ||
| } | ||
| } | ||
| } | ||
| return urlObj.href; | ||
| }; | ||
| function processInputPath(str, enccoding) { | ||
| str = removeTrailingSlash(removeLeadingSlash(str)); | ||
| if (enccoding === "plain") { | ||
| return `i-${str.replace(/\//g, "@@")}`; | ||
| } | ||
| if (enccoding === "base64") { | ||
| return `ie-${encodeURIComponent(safeBtoa(str))}`; | ||
| } | ||
| if (SIMPLE_OVERLAY_PATH_REGEX.test(str)) { | ||
| return `i-${str.replace(/\//g, "@@")}`; | ||
| } else { | ||
| return `ie-${encodeURIComponent(safeBtoa(str))}`; | ||
| } | ||
| } | ||
| function processText(str, enccoding) { | ||
| if (enccoding === "plain") { | ||
| return `i-${encodeURIComponent(str)}`; | ||
| } | ||
| if (enccoding === "base64") { | ||
| return `ie-${encodeURIComponent(safeBtoa(str))}`; | ||
| } | ||
| if (SIMPLE_OVERLAY_TEXT_REGEX.test(str)) { | ||
| return `i-${encodeURIComponent(str)}`; | ||
| } | ||
| return `ie-${encodeURIComponent(safeBtoa(str))}`; | ||
| } | ||
| function processOverlay(overlay) { | ||
| const entries = []; | ||
| const { | ||
| type, | ||
| position = {}, | ||
| timing = {}, | ||
| transformation = [] | ||
| } = overlay || {}; | ||
| if (!type) { | ||
| return; | ||
| } | ||
| switch (type) { | ||
| case "text": | ||
| { | ||
| const textOverlay = overlay; | ||
| if (!textOverlay.text) { | ||
| return; | ||
| } | ||
| const enccoding = textOverlay.encoding || "auto"; | ||
| entries.push("l-text"); | ||
| entries.push(processText(textOverlay.text, enccoding)); | ||
| } | ||
| break; | ||
| case "image": | ||
| entries.push("l-image"); | ||
| { | ||
| const imageOverlay = overlay; | ||
| const enccoding = imageOverlay.encoding || "auto"; | ||
| if (imageOverlay.input) { | ||
| entries.push(processInputPath(imageOverlay.input, enccoding)); | ||
| } else { | ||
| return; | ||
| } | ||
| } | ||
| break; | ||
| case "video": | ||
| entries.push("l-video"); | ||
| { | ||
| const videoOverlay = overlay; | ||
| const enccoding = videoOverlay.encoding || "auto"; | ||
| if (videoOverlay.input) { | ||
| entries.push(processInputPath(videoOverlay.input, enccoding)); | ||
| } else { | ||
| return; | ||
| } | ||
| } | ||
| break; | ||
| case "subtitle": | ||
| entries.push("l-subtitle"); | ||
| { | ||
| const subtitleOverlay = overlay; | ||
| const enccoding = subtitleOverlay.encoding || "auto"; | ||
| if (subtitleOverlay.input) { | ||
| entries.push(processInputPath(subtitleOverlay.input, enccoding)); | ||
| } else { | ||
| return; | ||
| } | ||
| } | ||
| break; | ||
| case "solidColor": | ||
| entries.push("l-image"); | ||
| entries.push(`i-ik_canvas`); | ||
| { | ||
| const solidColorOverlay = overlay; | ||
| if (solidColorOverlay.color) { | ||
| entries.push(`bg-${solidColorOverlay.color}`); | ||
| } else { | ||
| return; | ||
| } | ||
| } | ||
| break; | ||
| } | ||
| const { | ||
| x, | ||
| y, | ||
| focus | ||
| } = position; | ||
| if (x) { | ||
| entries.push(`lx-${x}`); | ||
| } | ||
| if (y) { | ||
| entries.push(`ly-${y}`); | ||
| } | ||
| if (focus) { | ||
| entries.push(`lfo-${focus}`); | ||
| } | ||
| const { | ||
| start, | ||
| end, | ||
| duration | ||
| } = timing; | ||
| if (start) { | ||
| entries.push(`lso-${start}`); | ||
| } | ||
| if (end) { | ||
| entries.push(`leo-${end}`); | ||
| } | ||
| if (duration) { | ||
| entries.push(`ldu-${duration}`); | ||
| } | ||
| const transformationString = buildTransformationString(transformation); | ||
| if (transformationString && transformationString.trim() !== "") entries.push(transformationString); | ||
| entries.push("l-end"); | ||
| return entries.join(transformationUtils.getTransformDelimiter()); | ||
| } | ||
| const buildTransformationString = function (transformation) { | ||
| if (!Array.isArray(transformation)) { | ||
| return ""; | ||
| } | ||
| var parsedTransforms = []; | ||
| for (var i = 0, l = transformation.length; i < l; i++) { | ||
| var parsedTransformStep = []; | ||
| for (var key in transformation[i]) { | ||
| let value = transformation[i][key]; | ||
| if (value === undefined || value === null) { | ||
| continue; | ||
| } | ||
| if (key === "overlay" && typeof value === "object") { | ||
| var rawString = processOverlay(value); | ||
| if (rawString && rawString.trim() !== "") { | ||
| parsedTransformStep.push(rawString); | ||
| } | ||
| continue; | ||
| } | ||
| var transformKey = transformationUtils.getTransformKey(key); | ||
| if (!transformKey) { | ||
| transformKey = key; | ||
| } | ||
| if (transformKey === "") { | ||
| continue; | ||
| } | ||
| if (["e-grayscale", "e-contrast", "e-removedotbg", "e-bgremove", "e-upscale", "e-retouch", "e-genvar"].includes(transformKey)) { | ||
| if (value === true || value === "-" || value === "true") { | ||
| parsedTransformStep.push(transformKey); | ||
| } else { | ||
| continue; | ||
| } | ||
| } else if (["e-sharpen", "e-shadow", "e-gradient", "e-usm", "e-dropshadow"].includes(transformKey) && (value.toString().trim() === "" || value === true || value === "true")) { | ||
| parsedTransformStep.push(transformKey); | ||
| } else if (key === "raw") { | ||
| parsedTransformStep.push(transformation[i][key]); | ||
| } else { | ||
| if (transformKey === "di") { | ||
| value = removeTrailingSlash(removeLeadingSlash(value || "")); | ||
| value = value.replace(/\//g, "@@"); | ||
| } | ||
| if (transformKey === "sr" && Array.isArray(value)) { | ||
| value = value.join("_"); | ||
| } | ||
| if (transformKey === "t" && value.toString().trim() === "") { | ||
| value = "true"; | ||
| } | ||
| parsedTransformStep.push([transformKey, value].join(transformationUtils.getTransformKeyValueDelimiter())); | ||
| } | ||
| } | ||
| if (parsedTransformStep.length) { | ||
| parsedTransforms.push(parsedTransformStep.join(transformationUtils.getTransformDelimiter())); | ||
| } | ||
| } | ||
| return parsedTransforms.join(transformationUtils.getChainTransformDelimiter()); | ||
| }; | ||
| const DEFAULT_DEVICE_BREAKPOINTS = [640, 750, 828, 1080, 1200, 1920, 2048, 3840]; | ||
| const DEFAULT_IMAGE_BREAKPOINTS = [16, 32, 48, 64, 96, 128, 256, 384]; | ||
| function getResponsiveImageAttributes(opts) { | ||
| const { | ||
| src, | ||
| urlEndpoint, | ||
| transformation = [], | ||
| queryParameters, | ||
| transformationPosition, | ||
| sizes, | ||
| width, | ||
| deviceBreakpoints = DEFAULT_DEVICE_BREAKPOINTS, | ||
| imageBreakpoints = DEFAULT_IMAGE_BREAKPOINTS | ||
| } = opts; | ||
| const sortedDeviceBreakpoints = [...deviceBreakpoints].sort((a, b) => a - b); | ||
| const sortedImageBreakpoints = [...imageBreakpoints].sort((a, b) => a - b); | ||
| const allBreakpoints = [...sortedImageBreakpoints, ...sortedDeviceBreakpoints].sort((a, b) => a - b); | ||
| const { | ||
| candidates, | ||
| descriptorKind | ||
| } = computeCandidateWidths({ | ||
| allBreakpoints, | ||
| deviceBreakpoints: sortedDeviceBreakpoints, | ||
| explicitWidth: width, | ||
| sizesAttr: sizes | ||
| }); | ||
| const buildURL = w => buildSrc({ | ||
| src, | ||
| urlEndpoint, | ||
| queryParameters, | ||
| transformationPosition, | ||
| transformation: [...transformation, { | ||
| width: w, | ||
| crop: 'at_max' | ||
| } | ||
| ] | ||
| }); | ||
| const srcSet = candidates.map((w, i) => `${buildURL(w)} ${descriptorKind === 'w' ? w : i + 1}${descriptorKind}`).join(', ') || undefined; | ||
| const finalSizes = sizes ?? (descriptorKind === 'w' ? '100vw' : undefined); | ||
| return { | ||
| src: buildURL(candidates[candidates.length - 1]), | ||
| srcSet, | ||
| ...(finalSizes ? { | ||
| sizes: finalSizes | ||
| } : {}), | ||
| ...(width !== undefined ? { | ||
| width | ||
| } : {}) | ||
| }; | ||
| } | ||
| function computeCandidateWidths(params) { | ||
| const { | ||
| allBreakpoints, | ||
| deviceBreakpoints, | ||
| explicitWidth, | ||
| sizesAttr | ||
| } = params; | ||
| if (sizesAttr) { | ||
| const vwTokens = sizesAttr.match(/(^|\s)(1?\d{1,2})vw/g) || []; | ||
| const vwPercents = vwTokens.map(t => parseInt(t, 10)); | ||
| if (vwPercents.length) { | ||
| const smallestRatio = Math.min(...vwPercents) / 100; | ||
| const minRequiredPx = deviceBreakpoints[0] * smallestRatio; | ||
| return { | ||
| candidates: allBreakpoints.filter(w => w >= minRequiredPx), | ||
| descriptorKind: 'w' | ||
| }; | ||
| } | ||
| return { | ||
| candidates: allBreakpoints, | ||
| descriptorKind: 'w' | ||
| }; | ||
| } | ||
| if (typeof explicitWidth !== 'number') { | ||
| return { | ||
| candidates: deviceBreakpoints, | ||
| descriptorKind: 'w' | ||
| }; | ||
| } | ||
| const nearest = t => allBreakpoints.find(n => n >= t) || allBreakpoints[allBreakpoints.length - 1]; | ||
| const unique = Array.from(new Set([nearest(explicitWidth), nearest(explicitWidth * 2)])); | ||
| return { | ||
| candidates: unique, | ||
| descriptorKind: 'x' | ||
| }; | ||
| } | ||
| /****************************************************************************** | ||
@@ -792,3 +129,3 @@ Copyright (c) Microsoft Corporation. | ||
| if (process.env.NODE_ENV !== "production") { | ||
| console.error("urlEndpoint is neither provided in this component nor in the ImageKitContext."); | ||
| console.error("urlEndpoint is neither provided in this component nor in any parent ImageKitProvider."); | ||
| } | ||
@@ -799,3 +136,3 @@ return null; | ||
| if (!responsive) { | ||
| const nonResponsiveSrc = buildSrc({ | ||
| const nonResponsiveSrc = javascript.buildSrc({ | ||
| src, | ||
@@ -815,3 +152,3 @@ transformation, | ||
| srcSet | ||
| } = getResponsiveImageAttributes({ | ||
| } = javascript.getResponsiveImageAttributes({ | ||
| src, | ||
@@ -867,7 +204,7 @@ transformation, | ||
| if (process.env.NODE_ENV !== "production") { | ||
| console.error("urlEndpoint is neither provided in this component nor in the ImageKitContext."); | ||
| console.error("urlEndpoint is neither provided in this component nor in any parent ImageKitProvider."); | ||
| } | ||
| return null; | ||
| } | ||
| const finalSrc = buildSrc({ | ||
| const finalSrc = javascript.buildSrc({ | ||
| urlEndpoint, | ||
@@ -885,14 +222,38 @@ src, | ||
| Object.defineProperty(exports, 'ImageKitAbortError', { | ||
| enumerable: true, | ||
| get: function () { return javascript.ImageKitAbortError; } | ||
| }); | ||
| Object.defineProperty(exports, 'ImageKitInvalidRequestError', { | ||
| enumerable: true, | ||
| get: function () { return javascript.ImageKitInvalidRequestError; } | ||
| }); | ||
| Object.defineProperty(exports, 'ImageKitServerError', { | ||
| enumerable: true, | ||
| get: function () { return javascript.ImageKitServerError; } | ||
| }); | ||
| Object.defineProperty(exports, 'ImageKitUploadNetworkError', { | ||
| enumerable: true, | ||
| get: function () { return javascript.ImageKitUploadNetworkError; } | ||
| }); | ||
| Object.defineProperty(exports, 'buildSrc', { | ||
| enumerable: true, | ||
| get: function () { return javascript.buildSrc; } | ||
| }); | ||
| Object.defineProperty(exports, 'buildTransformationString', { | ||
| enumerable: true, | ||
| get: function () { return javascript.buildTransformationString; } | ||
| }); | ||
| Object.defineProperty(exports, 'getResponsiveImageAttributes', { | ||
| enumerable: true, | ||
| get: function () { return javascript.getResponsiveImageAttributes; } | ||
| }); | ||
| Object.defineProperty(exports, 'upload', { | ||
| enumerable: true, | ||
| get: function () { return javascript.upload; } | ||
| }); | ||
| exports.Image = Image; | ||
| exports.ImageKitAbortError = ImageKitAbortError; | ||
| exports.ImageKitContext = ImageKitContext; | ||
| exports.ImageKitInvalidRequestError = ImageKitInvalidRequestError; | ||
| exports.ImageKitProvider = ImageKitProvider; | ||
| exports.ImageKitServerError = ImageKitServerError; | ||
| exports.ImageKitUploadNetworkError = ImageKitUploadNetworkError; | ||
| exports.Video = Video; | ||
| exports.buildSrc = buildSrc; | ||
| exports.buildTransformationString = buildTransformationString; | ||
| exports.getResponsiveImageAttributes = getResponsiveImageAttributes; | ||
| exports.upload = upload; | ||
| //# sourceMappingURL=imagekitio-react.js.map |
+1
-1
| { | ||
| "name": "@imagekit/react", | ||
| "version": "5.0.1", | ||
| "version": "5.0.2", | ||
| "description": "React SDK for ImageKit.io which implements client-side upload and URL generation for use inside a react application.", | ||
@@ -5,0 +5,0 @@ "scripts": { |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
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
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
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
78582
-64.18%569
-69.38%1
Infinity%