@imagekit/javascript 5.0.0 → 5.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/imagekit.cjs.js +88 -0
- package/dist/imagekit.esm.js +88 -1
- package/dist/imagekit.min.js +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/interfaces/Transformation.d.ts +13 -0
- package/dist/responsive.d.ts +58 -0
- package/package.json +1 -2
package/dist/imagekit.cjs.js
CHANGED
|
@@ -579,10 +579,98 @@ const buildTransformationString = function (transformation) {
|
|
|
579
579
|
return parsedTransforms.join(transformationUtils.getChainTransformDelimiter());
|
|
580
580
|
};
|
|
581
581
|
|
|
582
|
+
const DEFAULT_DEVICE_BREAKPOINTS = [640, 750, 828, 1080, 1200, 1920, 2048, 3840];
|
|
583
|
+
const DEFAULT_IMAGE_BREAKPOINTS = [16, 32, 48, 64, 96, 128, 256, 384];
|
|
584
|
+
function getResponsiveImageAttributes(opts) {
|
|
585
|
+
const {
|
|
586
|
+
src,
|
|
587
|
+
urlEndpoint,
|
|
588
|
+
transformation = [],
|
|
589
|
+
queryParameters,
|
|
590
|
+
transformationPosition,
|
|
591
|
+
sizes,
|
|
592
|
+
width,
|
|
593
|
+
deviceBreakpoints = DEFAULT_DEVICE_BREAKPOINTS,
|
|
594
|
+
imageBreakpoints = DEFAULT_IMAGE_BREAKPOINTS
|
|
595
|
+
} = opts;
|
|
596
|
+
const sortedDeviceBreakpoints = [...deviceBreakpoints].sort((a, b) => a - b);
|
|
597
|
+
const sortedImageBreakpoints = [...imageBreakpoints].sort((a, b) => a - b);
|
|
598
|
+
const allBreakpoints = [...sortedImageBreakpoints, ...sortedDeviceBreakpoints].sort((a, b) => a - b);
|
|
599
|
+
const {
|
|
600
|
+
candidates,
|
|
601
|
+
descriptorKind
|
|
602
|
+
} = computeCandidateWidths({
|
|
603
|
+
allBreakpoints,
|
|
604
|
+
deviceBreakpoints: sortedDeviceBreakpoints,
|
|
605
|
+
explicitWidth: width,
|
|
606
|
+
sizesAttr: sizes
|
|
607
|
+
});
|
|
608
|
+
const buildURL = w => buildSrc({
|
|
609
|
+
src,
|
|
610
|
+
urlEndpoint,
|
|
611
|
+
queryParameters,
|
|
612
|
+
transformationPosition,
|
|
613
|
+
transformation: [...transformation, {
|
|
614
|
+
width: w,
|
|
615
|
+
crop: 'at_max'
|
|
616
|
+
}
|
|
617
|
+
]
|
|
618
|
+
});
|
|
619
|
+
const srcSet = candidates.map((w, i) => `${buildURL(w)} ${descriptorKind === 'w' ? w : i + 1}${descriptorKind}`).join(', ') || undefined;
|
|
620
|
+
const finalSizes = sizes ?? (descriptorKind === 'w' ? '100vw' : undefined);
|
|
621
|
+
return {
|
|
622
|
+
src: buildURL(candidates[candidates.length - 1]),
|
|
623
|
+
srcSet,
|
|
624
|
+
...(finalSizes ? {
|
|
625
|
+
sizes: finalSizes
|
|
626
|
+
} : {}),
|
|
627
|
+
...(width !== undefined ? {
|
|
628
|
+
width
|
|
629
|
+
} : {})
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
function computeCandidateWidths(params) {
|
|
633
|
+
const {
|
|
634
|
+
allBreakpoints,
|
|
635
|
+
deviceBreakpoints,
|
|
636
|
+
explicitWidth,
|
|
637
|
+
sizesAttr
|
|
638
|
+
} = params;
|
|
639
|
+
if (sizesAttr) {
|
|
640
|
+
const vwTokens = sizesAttr.match(/(^|\s)(1?\d{1,2})vw/g) || [];
|
|
641
|
+
const vwPercents = vwTokens.map(t => parseInt(t, 10));
|
|
642
|
+
if (vwPercents.length) {
|
|
643
|
+
const smallestRatio = Math.min(...vwPercents) / 100;
|
|
644
|
+
const minRequiredPx = deviceBreakpoints[0] * smallestRatio;
|
|
645
|
+
return {
|
|
646
|
+
candidates: allBreakpoints.filter(w => w >= minRequiredPx),
|
|
647
|
+
descriptorKind: 'w'
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
return {
|
|
651
|
+
candidates: allBreakpoints,
|
|
652
|
+
descriptorKind: 'w'
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
if (typeof explicitWidth !== 'number') {
|
|
656
|
+
return {
|
|
657
|
+
candidates: deviceBreakpoints,
|
|
658
|
+
descriptorKind: 'w'
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
const nearest = t => allBreakpoints.find(n => n >= t) || allBreakpoints[allBreakpoints.length - 1];
|
|
662
|
+
const unique = Array.from(new Set([nearest(explicitWidth), nearest(explicitWidth * 2)]));
|
|
663
|
+
return {
|
|
664
|
+
candidates: unique,
|
|
665
|
+
descriptorKind: 'x'
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
582
669
|
exports.ImageKitAbortError = ImageKitAbortError;
|
|
583
670
|
exports.ImageKitInvalidRequestError = ImageKitInvalidRequestError;
|
|
584
671
|
exports.ImageKitServerError = ImageKitServerError;
|
|
585
672
|
exports.ImageKitUploadNetworkError = ImageKitUploadNetworkError;
|
|
586
673
|
exports.buildSrc = buildSrc;
|
|
587
674
|
exports.buildTransformationString = buildTransformationString;
|
|
675
|
+
exports.getResponsiveImageAttributes = getResponsiveImageAttributes;
|
|
588
676
|
exports.upload = upload;
|
package/dist/imagekit.esm.js
CHANGED
|
@@ -575,4 +575,91 @@ const buildTransformationString = function (transformation) {
|
|
|
575
575
|
return parsedTransforms.join(transformationUtils.getChainTransformDelimiter());
|
|
576
576
|
};
|
|
577
577
|
|
|
578
|
-
|
|
578
|
+
const DEFAULT_DEVICE_BREAKPOINTS = [640, 750, 828, 1080, 1200, 1920, 2048, 3840];
|
|
579
|
+
const DEFAULT_IMAGE_BREAKPOINTS = [16, 32, 48, 64, 96, 128, 256, 384];
|
|
580
|
+
function getResponsiveImageAttributes(opts) {
|
|
581
|
+
const {
|
|
582
|
+
src,
|
|
583
|
+
urlEndpoint,
|
|
584
|
+
transformation = [],
|
|
585
|
+
queryParameters,
|
|
586
|
+
transformationPosition,
|
|
587
|
+
sizes,
|
|
588
|
+
width,
|
|
589
|
+
deviceBreakpoints = DEFAULT_DEVICE_BREAKPOINTS,
|
|
590
|
+
imageBreakpoints = DEFAULT_IMAGE_BREAKPOINTS
|
|
591
|
+
} = opts;
|
|
592
|
+
const sortedDeviceBreakpoints = [...deviceBreakpoints].sort((a, b) => a - b);
|
|
593
|
+
const sortedImageBreakpoints = [...imageBreakpoints].sort((a, b) => a - b);
|
|
594
|
+
const allBreakpoints = [...sortedImageBreakpoints, ...sortedDeviceBreakpoints].sort((a, b) => a - b);
|
|
595
|
+
const {
|
|
596
|
+
candidates,
|
|
597
|
+
descriptorKind
|
|
598
|
+
} = computeCandidateWidths({
|
|
599
|
+
allBreakpoints,
|
|
600
|
+
deviceBreakpoints: sortedDeviceBreakpoints,
|
|
601
|
+
explicitWidth: width,
|
|
602
|
+
sizesAttr: sizes
|
|
603
|
+
});
|
|
604
|
+
const buildURL = w => buildSrc({
|
|
605
|
+
src,
|
|
606
|
+
urlEndpoint,
|
|
607
|
+
queryParameters,
|
|
608
|
+
transformationPosition,
|
|
609
|
+
transformation: [...transformation, {
|
|
610
|
+
width: w,
|
|
611
|
+
crop: 'at_max'
|
|
612
|
+
}
|
|
613
|
+
]
|
|
614
|
+
});
|
|
615
|
+
const srcSet = candidates.map((w, i) => `${buildURL(w)} ${descriptorKind === 'w' ? w : i + 1}${descriptorKind}`).join(', ') || undefined;
|
|
616
|
+
const finalSizes = sizes ?? (descriptorKind === 'w' ? '100vw' : undefined);
|
|
617
|
+
return {
|
|
618
|
+
src: buildURL(candidates[candidates.length - 1]),
|
|
619
|
+
srcSet,
|
|
620
|
+
...(finalSizes ? {
|
|
621
|
+
sizes: finalSizes
|
|
622
|
+
} : {}),
|
|
623
|
+
...(width !== undefined ? {
|
|
624
|
+
width
|
|
625
|
+
} : {})
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
function computeCandidateWidths(params) {
|
|
629
|
+
const {
|
|
630
|
+
allBreakpoints,
|
|
631
|
+
deviceBreakpoints,
|
|
632
|
+
explicitWidth,
|
|
633
|
+
sizesAttr
|
|
634
|
+
} = params;
|
|
635
|
+
if (sizesAttr) {
|
|
636
|
+
const vwTokens = sizesAttr.match(/(^|\s)(1?\d{1,2})vw/g) || [];
|
|
637
|
+
const vwPercents = vwTokens.map(t => parseInt(t, 10));
|
|
638
|
+
if (vwPercents.length) {
|
|
639
|
+
const smallestRatio = Math.min(...vwPercents) / 100;
|
|
640
|
+
const minRequiredPx = deviceBreakpoints[0] * smallestRatio;
|
|
641
|
+
return {
|
|
642
|
+
candidates: allBreakpoints.filter(w => w >= minRequiredPx),
|
|
643
|
+
descriptorKind: 'w'
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
return {
|
|
647
|
+
candidates: allBreakpoints,
|
|
648
|
+
descriptorKind: 'w'
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
if (typeof explicitWidth !== 'number') {
|
|
652
|
+
return {
|
|
653
|
+
candidates: deviceBreakpoints,
|
|
654
|
+
descriptorKind: 'w'
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
const nearest = t => allBreakpoints.find(n => n >= t) || allBreakpoints[allBreakpoints.length - 1];
|
|
658
|
+
const unique = Array.from(new Set([nearest(explicitWidth), nearest(explicitWidth * 2)]));
|
|
659
|
+
return {
|
|
660
|
+
candidates: unique,
|
|
661
|
+
descriptorKind: 'x'
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
export { ImageKitAbortError, ImageKitInvalidRequestError, ImageKitServerError, ImageKitUploadNetworkError, buildSrc, buildTransformationString, getResponsiveImageAttributes, upload };
|
package/dist/imagekit.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).ImageKit={})}(this,(function(e){"use strict";var r={message:"Missing file parameter for upload"},t={message:"Missing fileName parameter for upload"},n={message:"Missing public key for upload"},s={message:"Request to ImageKit upload endpoint failed due to network error"},a={message:"Missing signature for upload. The SDK expects token, signature and expire for authentication."},o={message:"Missing token for upload. The SDK expects token, signature and expire for authentication."},i={message:"Missing expire for upload. The SDK expects token, signature and expire for authentication."},u={message:"Invalid transformation parameter. Please include at least pre, post, or both."},l={message:"Invalid pre transformation parameter."},p={message:"Invalid post transformation parameter."};class c extends Error{constructor(e,r){super(e),this.$ResponseMetadata=void 0,this.name="ImageKitInvalidRequestError",this.$ResponseMetadata=r}}class f extends Error{constructor(e,r){super(e),this.reason=void 0,this.name="ImageKitAbortError",this.reason=r}}class d extends Error{constructor(e){super(e),this.name="ImageKitUploadNetworkError"}}class g extends Error{constructor(e,r){super(e),this.$ResponseMetadata=void 0,this.name="ImageKitServerError",this.$ResponseMetadata=r}}const m=(e,r)=>{let t={...e};const n=h(r);return Object.defineProperty(t,"$ResponseMetadata",{value:n,enumerable:!1,writable:!1}),t},h=e=>{const r=function(e){const r={},t=e.getAllResponseHeaders();Object.keys(t).length&&t.trim().split(/[\r\n]+/).map(e=>e.split(/: /)).forEach(e=>{r[e[0].trim().toLowerCase()]=e[1].trim()});return r}(e);return{statusCode:e.status,headers:r,requestId:r["x-request-id"]}};const y={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"};var b=e=>"query"===e.transformationPosition,v=function(e){return e&&(y[e]||y[e.toLowerCase()])||""},w=function(){return":"},x=function(){return","},S=function(){return"-"};const k=function(e){return"undefined"!=typeof window?btoa(e):Buffer.from(e,"utf8").toString("base64")},R=new RegExp("^[a-zA-Z0-9-._/ ]*$"),I=new RegExp("^[a-zA-Z0-9-._ ]*$");function E(e){return"string"==typeof e&&"/"==e[e.length-1]&&(e=e.substring(0,e.length-1)),e}function M(e){return"string"==typeof e&&"/"==e[0]&&(e=e.slice(1)),e}function j(e,r){var t=r||"/",n=new RegExp(t+"{1,}","g");return e.join(t).replace(n,t)}function A(e,r){return e=E(M(e)),"plain"===r?"i-"+e.replace(/\//g,"@@"):"base64"===r?"ie-"+encodeURIComponent(k(e)):R.test(e)?"i-"+e.replace(/\//g,"@@"):"ie-"+encodeURIComponent(k(e))}function P(e){const r=[],{type:t,position:n={},timing:s={},transformation:a=[]}=e||{};if(!t)return;switch(t){case"text":{const t=e;if(!t.text)return;const n=t.encoding||"auto";r.push("l-text"),r.push(function(e,r){return"plain"===r?"i-"+encodeURIComponent(e):"base64"===r?"ie-"+encodeURIComponent(k(e)):I.test(e)?"i-"+encodeURIComponent(e):"ie-"+encodeURIComponent(k(e))}(t.text,n))}break;case"image":r.push("l-image");{const t=e,n=t.encoding||"auto";if(!t.input)return;r.push(A(t.input,n))}break;case"video":r.push("l-video");{const t=e,n=t.encoding||"auto";if(!t.input)return;r.push(A(t.input,n))}break;case"subtitle":r.push("l-subtitle");{const t=e,n=t.encoding||"auto";if(!t.input)return;r.push(A(t.input,n))}break;case"solidColor":r.push("l-image"),r.push("i-ik_canvas");{const t=e;if(!t.color)return;r.push("bg-"+t.color)}}const{x:o,y:i,focus:u}=n;o&&r.push("lx-"+o),i&&r.push("ly-"+i),u&&r.push("lfo-"+u);const{start:l,end:p,duration:c}=s;l&&r.push("lso-"+l),p&&r.push("leo-"+p),c&&r.push("ldu-"+c);const f=O(a);return f&&""!==f.trim()&&r.push(f),r.push("l-end"),r.join(x())}const O=function(e){if(!Array.isArray(e))return"";for(var r=[],t=0,n=e.length;t<n;t++){var s=[];for(var a in e[t]){let r=e[t][a];if(null!=r)if("overlay"!==a||"object"!=typeof r){var o=v(a);if(o||(o=a),""!==o)if(["e-grayscale","e-contrast","e-removedotbg","e-bgremove","e-upscale","e-retouch","e-genvar"].includes(o)){if(!0!==r&&"-"!==r&&"true"!==r)continue;s.push(o)}else!["e-sharpen","e-shadow","e-gradient","e-usm","e-dropshadow"].includes(o)||""!==r.toString().trim()&&!0!==r&&"true"!==r?"raw"===a?s.push(e[t][a]):("di"===o&&(r=E(M(r||"")),r=r.replace(/\//g,"@@")),"sr"===o&&Array.isArray(r)&&(r=r.join("_")),"t"===o&&""===r.toString().trim()&&(r="true"),s.push([o,r].join(S()))):s.push(o)}else{var i=P(r);i&&""!==i.trim()&&s.push(i)}}s.length&&r.push(s.join(x()))}return r.join(w())};e.ImageKitAbortError=f,e.ImageKitInvalidRequestError=c,e.ImageKitServerError=g,e.ImageKitUploadNetworkError=d,e.buildSrc=e=>{if(e.urlEndpoint=e.urlEndpoint||"",e.src=e.src||"",e.transformationPosition=e.transformationPosition||"query",!e.src)return"";const r=e.src.startsWith("http://")||e.src.startsWith("https://");var t,n,s;try{r?(t=new URL(e.src),n=!0):(s=new URL(e.urlEndpoint).pathname,t=new URL(j([e.urlEndpoint.replace(s,""),e.src])))}catch(e){return console.error(e),""}for(var a in e.queryParameters)t.searchParams.append(a,String(e.queryParameters[a]));var o=O(e.transformation);return o&&o.length&&(b(e)||n||(t.pathname=j(["tr"+w()+o,t.pathname]))),t.pathname=j(s?[s,t.pathname]:[t.pathname]),o&&o.length&&(b(e)||n)?""!==t.searchParams.toString()?`${t.href}&tr=${o}`:`${t.href}?tr=${o}`:t.href},e.buildTransformationString=O,e.upload=e=>e?new Promise((y,b)=>{const{xhr:v}=e||{};delete e.xhr;const w=v||new XMLHttpRequest;if(!e.file)return b(new c(r.message));if(!e.fileName)return b(new c(t.message));if(!e.publicKey||0===e.publicKey.length)return b(new c(n.message));if(!e.token)return b(new c(o.message));if(!e.signature)return b(new c(a.message));if(!e.expire)return b(new c(i.message));if(e.transformation){if(!Object.keys(e.transformation).includes("pre")&&!Object.keys(e.transformation).includes("post"))return b(new c(u.message));if(Object.keys(e.transformation).includes("pre")&&!e.transformation.pre)return b(new c(l.message));if(Object.keys(e.transformation).includes("post")){if(!Array.isArray(e.transformation.post))return b(new c(p.message));for(let r of e.transformation.post){if("abs"===r.type&&!r.protocol&&!r.value)return b(new c(p.message));if("transformation"===r.type&&!r.value)return b(new c(p.message))}}}var x=new FormData;let S;for(S in e)if(S)if("file"===S&&"string"!=typeof e.file)x.set("file",e.file,String(e.fileName));else if("tags"===S&&Array.isArray(e.tags))x.set("tags",e.tags.join(","));else if("signature"===S)x.set("signature",e.signature);else if("expire"===S)x.set("expire",String(e.expire));else if("token"===S)x.set("token",e.token);else if("responseFields"===S&&Array.isArray(e.responseFields))x.set("responseFields",e.responseFields.join(","));else if("extensions"===S&&Array.isArray(e.extensions))x.set("extensions",JSON.stringify(e.extensions));else if("customMetadata"!==S||"object"!=typeof e.customMetadata||Array.isArray(e.customMetadata)||null===e.customMetadata){if("transformation"===S&&"object"==typeof e.transformation&&null!==e.transformation)x.set(S,JSON.stringify(e.transformation));else if("checks"===S&&e.checks)x.set("checks",e.checks);else if(void 0!==e[S]){if(["onProgress","abortSignal"].includes(S))continue;x.set(S,String(e[S]))}}else x.set("customMetadata",JSON.stringify(e.customMetadata));function k(){var r;return w.abort(),b(new f("Upload aborted",null===(r=e.abortSignal)||void 0===r?void 0:r.reason))}if(e.onProgress&&(w.upload.onprogress=function(r){e.onProgress&&e.onProgress(r)}),e.abortSignal){var R;if(e.abortSignal.aborted)return b(new f("Upload aborted",null===(R=e.abortSignal)||void 0===R?void 0:R.reason));e.abortSignal.addEventListener("abort",k),w.addEventListener("loadend",()=>{e.abortSignal&&e.abortSignal.removeEventListener("abort",k)})}w.open("POST","https://upload.imagekit.io/api/v1/files/upload"),w.onerror=function(e){return b(new d(s.message))},w.onload=function(){if(w.status>=200&&w.status<300)try{var e=JSON.parse(w.responseText),r=m(e,w);return y(r)}catch(e){return b(e)}else if(w.status>=400&&w.status<500)try{e=JSON.parse(w.responseText);return b(new c(e.message??"Invalid request. Please check the parameters.",h(w)))}catch(e){return b(e)}else try{e=JSON.parse(w.responseText);return b(new g(e.message??"Server error occurred while uploading the file. This is rare and usually temporary.",h(w)))}catch(e){return b(new g("Server error occurred while uploading the file. This is rare and usually temporary.",h(w)))}},w.send(x)}):Promise.reject(new c("Invalid options provided for upload")),Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ImageKit={})}(this,(function(e){"use strict";var t={message:"Missing file parameter for upload"},r={message:"Missing fileName parameter for upload"},n={message:"Missing public key for upload"},s={message:"Request to ImageKit upload endpoint failed due to network error"},o={message:"Missing signature for upload. The SDK expects token, signature and expire for authentication."},a={message:"Missing token for upload. The SDK expects token, signature and expire for authentication."},i={message:"Missing expire for upload. The SDK expects token, signature and expire for authentication."},u={message:"Invalid transformation parameter. Please include at least pre, post, or both."},c={message:"Invalid pre transformation parameter."},p={message:"Invalid post transformation parameter."};class l extends Error{constructor(e,t){super(e),this.$ResponseMetadata=void 0,this.name="ImageKitInvalidRequestError",this.$ResponseMetadata=t}}class d extends Error{constructor(e,t){super(e),this.reason=void 0,this.name="ImageKitAbortError",this.reason=t}}class f extends Error{constructor(e){super(e),this.name="ImageKitUploadNetworkError"}}class g extends Error{constructor(e,t){super(e),this.$ResponseMetadata=void 0,this.name="ImageKitServerError",this.$ResponseMetadata=t}}const m=(e,t)=>{let r={...e};const n=h(t);return Object.defineProperty(r,"$ResponseMetadata",{value:n,enumerable:!1,writable:!1}),r},h=e=>{const t=function(e){const t={},r=e.getAllResponseHeaders();Object.keys(r).length&&r.trim().split(/[\r\n]+/).map(e=>e.split(/: /)).forEach(e=>{t[e[0].trim().toLowerCase()]=e[1].trim()});return t}(e);return{statusCode:e.status,headers:t,requestId:t["x-request-id"]}};const y={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"};var v=e=>"query"===e.transformationPosition,b=function(e){return e&&(y[e]||y[e.toLowerCase()])||""},w=function(){return":"},x=function(){return","},k=function(){return"-"};const S=function(e){return"undefined"!=typeof window?btoa(e):Buffer.from(e,"utf8").toString("base64")},R=new RegExp("^[a-zA-Z0-9-._/ ]*$"),I=new RegExp("^[a-zA-Z0-9-._ ]*$");function E(e){return"string"==typeof e&&"/"==e[e.length-1]&&(e=e.substring(0,e.length-1)),e}function A(e){return"string"==typeof e&&"/"==e[0]&&(e=e.slice(1)),e}function P(e,t){var r=t||"/",n=new RegExp(r+"{1,}","g");return e.join(r).replace(n,r)}const M=e=>{if(e.urlEndpoint=e.urlEndpoint||"",e.src=e.src||"",e.transformationPosition=e.transformationPosition||"query",!e.src)return"";const t=e.src.startsWith("http://")||e.src.startsWith("https://");var r,n,s;try{t?(r=new URL(e.src),n=!0):(s=new URL(e.urlEndpoint).pathname,r=new URL(P([e.urlEndpoint.replace(s,""),e.src])))}catch(e){return console.error(e),""}for(var o in e.queryParameters)r.searchParams.append(o,String(e.queryParameters[o]));var a=O(e.transformation);return a&&a.length&&(v(e)||n||(r.pathname=P(["tr"+w()+a,r.pathname]))),r.pathname=P(s?[s,r.pathname]:[r.pathname]),a&&a.length&&(v(e)||n)?""!==r.searchParams.toString()?`${r.href}&tr=${a}`:`${r.href}?tr=${a}`:r.href};function j(e,t){return e=E(A(e)),"plain"===t?"i-"+e.replace(/\//g,"@@"):"base64"===t?"ie-"+encodeURIComponent(S(e)):R.test(e)?"i-"+e.replace(/\//g,"@@"):"ie-"+encodeURIComponent(S(e))}function K(e){const t=[],{type:r,position:n={},timing:s={},transformation:o=[]}=e||{};if(!r)return;switch(r){case"text":{const r=e;if(!r.text)return;const n=r.encoding||"auto";t.push("l-text"),t.push(function(e,t){return"plain"===t?"i-"+encodeURIComponent(e):"base64"===t?"ie-"+encodeURIComponent(S(e)):I.test(e)?"i-"+encodeURIComponent(e):"ie-"+encodeURIComponent(S(e))}(r.text,n))}break;case"image":t.push("l-image");{const r=e,n=r.encoding||"auto";if(!r.input)return;t.push(j(r.input,n))}break;case"video":t.push("l-video");{const r=e,n=r.encoding||"auto";if(!r.input)return;t.push(j(r.input,n))}break;case"subtitle":t.push("l-subtitle");{const r=e,n=r.encoding||"auto";if(!r.input)return;t.push(j(r.input,n))}break;case"solidColor":t.push("l-image"),t.push("i-ik_canvas");{const r=e;if(!r.color)return;t.push("bg-"+r.color)}}const{x:a,y:i,focus:u}=n;a&&t.push("lx-"+a),i&&t.push("ly-"+i),u&&t.push("lfo-"+u);const{start:c,end:p,duration:l}=s;c&&t.push("lso-"+c),p&&t.push("leo-"+p),l&&t.push("ldu-"+l);const d=O(o);return d&&""!==d.trim()&&t.push(d),t.push("l-end"),t.join(x())}const O=function(e){if(!Array.isArray(e))return"";for(var t=[],r=0,n=e.length;r<n;r++){var s=[];for(var o in e[r]){let t=e[r][o];if(null!=t)if("overlay"!==o||"object"!=typeof t){var a=b(o);if(a||(a=o),""!==a)if(["e-grayscale","e-contrast","e-removedotbg","e-bgremove","e-upscale","e-retouch","e-genvar"].includes(a)){if(!0!==t&&"-"!==t&&"true"!==t)continue;s.push(a)}else!["e-sharpen","e-shadow","e-gradient","e-usm","e-dropshadow"].includes(a)||""!==t.toString().trim()&&!0!==t&&"true"!==t?"raw"===o?s.push(e[r][o]):("di"===a&&(t=E(A(t||"")),t=t.replace(/\//g,"@@")),"sr"===a&&Array.isArray(t)&&(t=t.join("_")),"t"===a&&""===t.toString().trim()&&(t="true"),s.push([a,t].join(k()))):s.push(a)}else{var i=K(t);i&&""!==i.trim()&&s.push(i)}}s.length&&t.push(s.join(x()))}return t.join(w())},C=[640,750,828,1080,1200,1920,2048,3840],q=[16,32,48,64,96,128,256,384];e.ImageKitAbortError=d,e.ImageKitInvalidRequestError=l,e.ImageKitServerError=g,e.ImageKitUploadNetworkError=f,e.buildSrc=M,e.buildTransformationString=O,e.getResponsiveImageAttributes=function(e){const{src:t,urlEndpoint:r,transformation:n=[],queryParameters:s,transformationPosition:o,sizes:a,width:i,deviceBreakpoints:u=C,imageBreakpoints:c=q}=e,p=[...u].sort((e,t)=>e-t),l=[...[...c].sort((e,t)=>e-t),...p].sort((e,t)=>e-t),{candidates:d,descriptorKind:f}=function(e){const{allBreakpoints:t,deviceBreakpoints:r,explicitWidth:n,sizesAttr:s}=e;if(s){const e=(s.match(/(^|\s)(1?\d{1,2})vw/g)||[]).map(e=>parseInt(e,10));if(e.length){const n=Math.min(...e)/100,s=r[0]*n;return{candidates:t.filter(e=>e>=s),descriptorKind:"w"}}return{candidates:t,descriptorKind:"w"}}if("number"!=typeof n)return{candidates:r,descriptorKind:"w"};const o=e=>t.find(t=>t>=e)||t[t.length-1];return{candidates:Array.from(new Set([o(n),o(2*n)])),descriptorKind:"x"}}({allBreakpoints:l,deviceBreakpoints:p,explicitWidth:i,sizesAttr:a}),g=e=>M({src:t,urlEndpoint:r,queryParameters:s,transformationPosition:o,transformation:[...n,{width:e,crop:"at_max"}]}),m=d.map((e,t)=>`${g(e)} ${"w"===f?e:t+1}${f}`).join(", ")||void 0,h=a??("w"===f?"100vw":void 0);return{src:g(d[d.length-1]),srcSet:m,...h?{sizes:h}:{},...void 0!==i?{width:i}:{}}},e.upload=e=>e?new Promise((y,v)=>{const{xhr:b}=e||{};delete e.xhr;const w=b||new XMLHttpRequest;if(!e.file)return v(new l(t.message));if(!e.fileName)return v(new l(r.message));if(!e.publicKey||0===e.publicKey.length)return v(new l(n.message));if(!e.token)return v(new l(a.message));if(!e.signature)return v(new l(o.message));if(!e.expire)return v(new l(i.message));if(e.transformation){if(!Object.keys(e.transformation).includes("pre")&&!Object.keys(e.transformation).includes("post"))return v(new l(u.message));if(Object.keys(e.transformation).includes("pre")&&!e.transformation.pre)return v(new l(c.message));if(Object.keys(e.transformation).includes("post")){if(!Array.isArray(e.transformation.post))return v(new l(p.message));for(let t of e.transformation.post){if("abs"===t.type&&!t.protocol&&!t.value)return v(new l(p.message));if("transformation"===t.type&&!t.value)return v(new l(p.message))}}}var x=new FormData;let k;for(k in e)if(k)if("file"===k&&"string"!=typeof e.file)x.set("file",e.file,String(e.fileName));else if("tags"===k&&Array.isArray(e.tags))x.set("tags",e.tags.join(","));else if("signature"===k)x.set("signature",e.signature);else if("expire"===k)x.set("expire",String(e.expire));else if("token"===k)x.set("token",e.token);else if("responseFields"===k&&Array.isArray(e.responseFields))x.set("responseFields",e.responseFields.join(","));else if("extensions"===k&&Array.isArray(e.extensions))x.set("extensions",JSON.stringify(e.extensions));else if("customMetadata"!==k||"object"!=typeof e.customMetadata||Array.isArray(e.customMetadata)||null===e.customMetadata){if("transformation"===k&&"object"==typeof e.transformation&&null!==e.transformation)x.set(k,JSON.stringify(e.transformation));else if("checks"===k&&e.checks)x.set("checks",e.checks);else if(void 0!==e[k]){if(["onProgress","abortSignal"].includes(k))continue;x.set(k,String(e[k]))}}else x.set("customMetadata",JSON.stringify(e.customMetadata));function S(){var t;return w.abort(),v(new d("Upload aborted",null===(t=e.abortSignal)||void 0===t?void 0:t.reason))}if(e.onProgress&&(w.upload.onprogress=function(t){e.onProgress&&e.onProgress(t)}),e.abortSignal){var R;if(e.abortSignal.aborted)return v(new d("Upload aborted",null===(R=e.abortSignal)||void 0===R?void 0:R.reason));e.abortSignal.addEventListener("abort",S),w.addEventListener("loadend",()=>{e.abortSignal&&e.abortSignal.removeEventListener("abort",S)})}w.open("POST","https://upload.imagekit.io/api/v1/files/upload"),w.onerror=function(e){return v(new f(s.message))},w.onload=function(){if(w.status>=200&&w.status<300)try{var e=JSON.parse(w.responseText),t=m(e,w);return y(t)}catch(e){return v(e)}else if(w.status>=400&&w.status<500)try{e=JSON.parse(w.responseText);return v(new l(e.message??"Invalid request. Please check the parameters.",h(w)))}catch(e){return v(e)}else try{e=JSON.parse(w.responseText);return v(new g(e.message??"Server error occurred while uploading the file. This is rare and usually temporary.",h(w)))}catch(e){return v(new g("Server error occurred while uploading the file. This is rare and usually temporary.",h(w)))}},w.send(x)}):Promise.reject(new l("Invalid options provided for upload")),Object.defineProperty(e,"__esModule",{value:!0})}));
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { SrcOptions, Transformation, UploadOptions, UploadResponse } from "./interfaces";
|
|
2
2
|
import { ImageKitAbortError, ImageKitInvalidRequestError, ImageKitServerError, ImageKitUploadNetworkError, upload } from "./upload";
|
|
3
3
|
import { buildSrc, buildTransformationString } from "./url";
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
import { getResponsiveImageAttributes } from "./responsive";
|
|
5
|
+
import type { GetImageAttributesOptions, ResponsiveImageAttributes } from "./responsive";
|
|
6
|
+
export { buildSrc, buildTransformationString, upload, getResponsiveImageAttributes, ImageKitInvalidRequestError, ImageKitAbortError, ImageKitServerError, ImageKitUploadNetworkError };
|
|
7
|
+
export type { Transformation, SrcOptions, UploadOptions, UploadResponse, GetImageAttributesOptions, ResponsiveImageAttributes };
|
|
@@ -621,4 +621,17 @@ export type SolidColorOverlayTransformation = Pick<Transformation, "width" | "he
|
|
|
621
621
|
* Specifies the transparency level of the overlaid solid color layer. Supports integers from `1` to `9`.
|
|
622
622
|
*/
|
|
623
623
|
alpha?: number;
|
|
624
|
+
/**
|
|
625
|
+
* Specifies the background color of the solid color overlay.
|
|
626
|
+
* Accepts an RGB hex code, an RGBA code, or a color name.
|
|
627
|
+
*/
|
|
628
|
+
background?: string;
|
|
629
|
+
/**
|
|
630
|
+
* Only works if base asset is an image.
|
|
631
|
+
*
|
|
632
|
+
* Creates a linear gradient with two colors. Pass `true` for a default gradient, or provide a string for a custom gradient.
|
|
633
|
+
*
|
|
634
|
+
* [Effects and Enhancements - Gradient](https://imagekit.io/docs/effects-and-enhancements#gradient---e-gradient)
|
|
635
|
+
*/
|
|
636
|
+
gradient?: Transformation["gradient"];
|
|
624
637
|
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { SrcOptions } from './interfaces';
|
|
2
|
+
export interface GetImageAttributesOptions extends SrcOptions {
|
|
3
|
+
/**
|
|
4
|
+
* The intended display width of the image in pixels,
|
|
5
|
+
* used **only when the `sizes` attribute is not provided**.
|
|
6
|
+
*
|
|
7
|
+
* Triggers a DPR-based strategy (1x and 2x variants) and generates `x` descriptors in `srcSet`.
|
|
8
|
+
*
|
|
9
|
+
* Ignored if `sizes` is present.
|
|
10
|
+
*/
|
|
11
|
+
width?: number;
|
|
12
|
+
/**
|
|
13
|
+
* The value for the HTML `sizes` attribute
|
|
14
|
+
* (e.g., `"100vw"` or `"(min-width:768px) 50vw, 100vw"`).
|
|
15
|
+
*
|
|
16
|
+
* - If it includes one or more `vw` units, breakpoints smaller than the corresponding percentage of the smallest device width are excluded.
|
|
17
|
+
* - If it contains no `vw` units, the full breakpoint list is used.
|
|
18
|
+
*
|
|
19
|
+
* Enables a width-based strategy and generates `w` descriptors in `srcSet`.
|
|
20
|
+
*/
|
|
21
|
+
sizes?: string;
|
|
22
|
+
/**
|
|
23
|
+
* Custom list of **device-width breakpoints** in pixels.
|
|
24
|
+
* These define common screen widths for responsive image generation.
|
|
25
|
+
*
|
|
26
|
+
* Defaults to `[640, 750, 828, 1080, 1200, 1920, 2048, 3840]`.
|
|
27
|
+
* Sorted automatically.
|
|
28
|
+
*/
|
|
29
|
+
deviceBreakpoints?: number[];
|
|
30
|
+
/**
|
|
31
|
+
* Custom list of **image-specific breakpoints** in pixels.
|
|
32
|
+
* Useful for generating small variants (e.g., placeholders or thumbnails).
|
|
33
|
+
*
|
|
34
|
+
* Merged with `deviceBreakpoints` before calculating `srcSet`.
|
|
35
|
+
* Defaults to `[16, 32, 48, 64, 96, 128, 256, 384]`.
|
|
36
|
+
* Sorted automatically.
|
|
37
|
+
*/
|
|
38
|
+
imageBreakpoints?: number[];
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Resulting set of attributes suitable for an HTML `<img>` element.
|
|
42
|
+
* Useful for enabling responsive image loading.
|
|
43
|
+
*/
|
|
44
|
+
export interface ResponsiveImageAttributes {
|
|
45
|
+
/** URL for the *largest* candidate (assigned to plain `src`). */
|
|
46
|
+
src: string;
|
|
47
|
+
/** Candidate set with `w` or `x` descriptors. */
|
|
48
|
+
srcSet?: string;
|
|
49
|
+
/** `sizes` returned (or synthesised as `100vw`). */
|
|
50
|
+
sizes?: string;
|
|
51
|
+
/** Width as a number (if `width` was provided). */
|
|
52
|
+
width?: number;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Generates a responsive image URL, `srcSet`, and `sizes` attributes
|
|
56
|
+
* based on the input options such as `width`, `sizes`, and breakpoints.
|
|
57
|
+
*/
|
|
58
|
+
export declare function getResponsiveImageAttributes(opts: GetImageAttributesOptions): ResponsiveImageAttributes;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imagekit/javascript",
|
|
3
|
-
"version": "5.0.
|
|
3
|
+
"version": "5.1.0-beta.1",
|
|
4
4
|
"description": "ImageKit Javascript SDK",
|
|
5
5
|
"main": "dist/imagekit.cjs.js",
|
|
6
6
|
"module": "dist/imagekit.esm.js",
|
|
@@ -48,7 +48,6 @@
|
|
|
48
48
|
"startSampleApp": "yarn build && cd samples/sample-app/ && yarn install && node index.js"
|
|
49
49
|
},
|
|
50
50
|
"publishConfig": {
|
|
51
|
-
"tag": "beta",
|
|
52
51
|
"access": "public"
|
|
53
52
|
},
|
|
54
53
|
"repository": {
|