@imagekit/javascript 5.1.0 → 5.2.0
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/README.md +14 -3
- package/dist/imagekit.cjs.js +236 -228
- package/dist/imagekit.esm.js +236 -228
- package/dist/imagekit.min.js +1 -1
- package/dist/index.d.ts +4 -5
- package/dist/interfaces/UploadOptions.d.ts +205 -102
- package/dist/interfaces/UploadResponse.d.ts +363 -122
- package/dist/interfaces/index.d.ts +1 -2
- package/dist/interfaces/shared.d.ts +1475 -0
- package/dist/responsive.d.ts +1 -53
- package/dist/url.d.ts +1 -2
- package/package.json +1 -1
- package/dist/interfaces/SrcOptions.d.ts +0 -32
- package/dist/interfaces/Transformation.d.ts +0 -637
package/dist/imagekit.esm.js
CHANGED
|
@@ -1,231 +1,3 @@
|
|
|
1
|
-
var errorMessages = {
|
|
2
|
-
MISSING_UPLOAD_FILE_PARAMETER: {
|
|
3
|
-
message: "Missing file parameter for upload"
|
|
4
|
-
},
|
|
5
|
-
MISSING_UPLOAD_FILENAME_PARAMETER: {
|
|
6
|
-
message: "Missing fileName parameter for upload"
|
|
7
|
-
},
|
|
8
|
-
MISSING_PUBLIC_KEY: {
|
|
9
|
-
message: "Missing public key for upload"
|
|
10
|
-
},
|
|
11
|
-
UPLOAD_ENDPOINT_NETWORK_ERROR: {
|
|
12
|
-
message: "Request to ImageKit upload endpoint failed due to network error"
|
|
13
|
-
},
|
|
14
|
-
MISSING_SIGNATURE: {
|
|
15
|
-
message: "Missing signature for upload. The SDK expects token, signature and expire for authentication."
|
|
16
|
-
},
|
|
17
|
-
MISSING_TOKEN: {
|
|
18
|
-
message: "Missing token for upload. The SDK expects token, signature and expire for authentication."
|
|
19
|
-
},
|
|
20
|
-
MISSING_EXPIRE: {
|
|
21
|
-
message: "Missing expire for upload. The SDK expects token, signature and expire for authentication."
|
|
22
|
-
},
|
|
23
|
-
INVALID_TRANSFORMATION: {
|
|
24
|
-
message: "Invalid transformation parameter. Please include at least pre, post, or both."
|
|
25
|
-
},
|
|
26
|
-
INVALID_PRE_TRANSFORMATION: {
|
|
27
|
-
message: "Invalid pre transformation parameter."
|
|
28
|
-
},
|
|
29
|
-
INVALID_POST_TRANSFORMATION: {
|
|
30
|
-
message: "Invalid post transformation parameter."
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
class ImageKitInvalidRequestError extends Error {
|
|
35
|
-
constructor(message, responseMetadata) {
|
|
36
|
-
super(message);
|
|
37
|
-
this.$ResponseMetadata = void 0;
|
|
38
|
-
this.name = "ImageKitInvalidRequestError";
|
|
39
|
-
this.$ResponseMetadata = responseMetadata;
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
class ImageKitAbortError extends Error {
|
|
43
|
-
constructor(message, reason) {
|
|
44
|
-
super(message);
|
|
45
|
-
this.reason = void 0;
|
|
46
|
-
this.name = "ImageKitAbortError";
|
|
47
|
-
this.reason = reason;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
class ImageKitUploadNetworkError extends Error {
|
|
51
|
-
constructor(message) {
|
|
52
|
-
super(message);
|
|
53
|
-
this.name = "ImageKitUploadNetworkError";
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
class ImageKitServerError extends Error {
|
|
57
|
-
constructor(message, responseMetadata) {
|
|
58
|
-
super(message);
|
|
59
|
-
this.$ResponseMetadata = void 0;
|
|
60
|
-
this.name = "ImageKitServerError";
|
|
61
|
-
this.$ResponseMetadata = responseMetadata;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
const upload = uploadOptions => {
|
|
65
|
-
if (!uploadOptions) {
|
|
66
|
-
return Promise.reject(new ImageKitInvalidRequestError("Invalid options provided for upload"));
|
|
67
|
-
}
|
|
68
|
-
return new Promise((resolve, reject) => {
|
|
69
|
-
const {
|
|
70
|
-
xhr: userProvidedXHR
|
|
71
|
-
} = uploadOptions || {};
|
|
72
|
-
delete uploadOptions.xhr;
|
|
73
|
-
const xhr = userProvidedXHR || new XMLHttpRequest();
|
|
74
|
-
if (!uploadOptions.file) {
|
|
75
|
-
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_UPLOAD_FILE_PARAMETER.message));
|
|
76
|
-
}
|
|
77
|
-
if (!uploadOptions.fileName) {
|
|
78
|
-
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_UPLOAD_FILENAME_PARAMETER.message));
|
|
79
|
-
}
|
|
80
|
-
if (!uploadOptions.publicKey || uploadOptions.publicKey.length === 0) {
|
|
81
|
-
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_PUBLIC_KEY.message));
|
|
82
|
-
}
|
|
83
|
-
if (!uploadOptions.token) {
|
|
84
|
-
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_TOKEN.message));
|
|
85
|
-
}
|
|
86
|
-
if (!uploadOptions.signature) {
|
|
87
|
-
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_SIGNATURE.message));
|
|
88
|
-
}
|
|
89
|
-
if (!uploadOptions.expire) {
|
|
90
|
-
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_EXPIRE.message));
|
|
91
|
-
}
|
|
92
|
-
if (uploadOptions.transformation) {
|
|
93
|
-
if (!(Object.keys(uploadOptions.transformation).includes("pre") || Object.keys(uploadOptions.transformation).includes("post"))) {
|
|
94
|
-
return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_TRANSFORMATION.message));
|
|
95
|
-
}
|
|
96
|
-
if (Object.keys(uploadOptions.transformation).includes("pre") && !uploadOptions.transformation.pre) {
|
|
97
|
-
return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_PRE_TRANSFORMATION.message));
|
|
98
|
-
}
|
|
99
|
-
if (Object.keys(uploadOptions.transformation).includes("post")) {
|
|
100
|
-
if (Array.isArray(uploadOptions.transformation.post)) {
|
|
101
|
-
for (let transformation of uploadOptions.transformation.post) {
|
|
102
|
-
if (transformation.type === "abs" && !(transformation.protocol || transformation.value)) {
|
|
103
|
-
return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message));
|
|
104
|
-
} else if (transformation.type === "transformation" && !transformation.value) {
|
|
105
|
-
return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message));
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
} else {
|
|
109
|
-
return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message));
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
var formData = new FormData();
|
|
114
|
-
let key;
|
|
115
|
-
for (key in uploadOptions) {
|
|
116
|
-
if (key) {
|
|
117
|
-
if (key === "file" && typeof uploadOptions.file != "string") {
|
|
118
|
-
formData.set('file', uploadOptions.file, String(uploadOptions.fileName));
|
|
119
|
-
} else if (key === "tags" && Array.isArray(uploadOptions.tags)) {
|
|
120
|
-
formData.set('tags', uploadOptions.tags.join(","));
|
|
121
|
-
} else if (key === 'signature') {
|
|
122
|
-
formData.set("signature", uploadOptions.signature);
|
|
123
|
-
} else if (key === 'expire') {
|
|
124
|
-
formData.set("expire", String(uploadOptions.expire));
|
|
125
|
-
} else if (key === 'token') {
|
|
126
|
-
formData.set("token", uploadOptions.token);
|
|
127
|
-
} else if (key === "responseFields" && Array.isArray(uploadOptions.responseFields)) {
|
|
128
|
-
formData.set('responseFields', uploadOptions.responseFields.join(","));
|
|
129
|
-
} else if (key === "extensions" && Array.isArray(uploadOptions.extensions)) {
|
|
130
|
-
formData.set('extensions', JSON.stringify(uploadOptions.extensions));
|
|
131
|
-
} else if (key === "customMetadata" && typeof uploadOptions.customMetadata === "object" && !Array.isArray(uploadOptions.customMetadata) && uploadOptions.customMetadata !== null) {
|
|
132
|
-
formData.set('customMetadata', JSON.stringify(uploadOptions.customMetadata));
|
|
133
|
-
} else if (key === "transformation" && typeof uploadOptions.transformation === "object" && uploadOptions.transformation !== null) {
|
|
134
|
-
formData.set(key, JSON.stringify(uploadOptions.transformation));
|
|
135
|
-
} else if (key === 'checks' && uploadOptions.checks) {
|
|
136
|
-
formData.set("checks", uploadOptions.checks);
|
|
137
|
-
} else if (uploadOptions[key] !== undefined) {
|
|
138
|
-
if (["onProgress", "abortSignal"].includes(key)) continue;
|
|
139
|
-
formData.set(key, String(uploadOptions[key]));
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
if (uploadOptions.onProgress) {
|
|
144
|
-
xhr.upload.onprogress = function (event) {
|
|
145
|
-
if (uploadOptions.onProgress) uploadOptions.onProgress(event);
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
function onAbortHandler() {
|
|
149
|
-
var _uploadOptions$abortS;
|
|
150
|
-
xhr.abort();
|
|
151
|
-
return reject(new ImageKitAbortError("Upload aborted", (_uploadOptions$abortS = uploadOptions.abortSignal) === null || _uploadOptions$abortS === void 0 ? void 0 : _uploadOptions$abortS.reason));
|
|
152
|
-
}
|
|
153
|
-
if (uploadOptions.abortSignal) {
|
|
154
|
-
if (uploadOptions.abortSignal.aborted) {
|
|
155
|
-
var _uploadOptions$abortS2;
|
|
156
|
-
return reject(new ImageKitAbortError("Upload aborted", (_uploadOptions$abortS2 = uploadOptions.abortSignal) === null || _uploadOptions$abortS2 === void 0 ? void 0 : _uploadOptions$abortS2.reason));
|
|
157
|
-
}
|
|
158
|
-
uploadOptions.abortSignal.addEventListener("abort", onAbortHandler);
|
|
159
|
-
xhr.addEventListener("loadend", () => {
|
|
160
|
-
if (uploadOptions.abortSignal) {
|
|
161
|
-
uploadOptions.abortSignal.removeEventListener("abort", onAbortHandler);
|
|
162
|
-
}
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
xhr.open('POST', 'https://upload.imagekit.io/api/v1/files/upload');
|
|
166
|
-
xhr.onerror = function (e) {
|
|
167
|
-
return reject(new ImageKitUploadNetworkError(errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR.message));
|
|
168
|
-
};
|
|
169
|
-
xhr.onload = function () {
|
|
170
|
-
if (xhr.status >= 200 && xhr.status < 300) {
|
|
171
|
-
try {
|
|
172
|
-
var body = JSON.parse(xhr.responseText);
|
|
173
|
-
var uploadResponse = addResponseHeadersAndBody(body, xhr);
|
|
174
|
-
return resolve(uploadResponse);
|
|
175
|
-
} catch (ex) {
|
|
176
|
-
return reject(ex);
|
|
177
|
-
}
|
|
178
|
-
} else if (xhr.status >= 400 && xhr.status < 500) {
|
|
179
|
-
try {
|
|
180
|
-
var body = JSON.parse(xhr.responseText);
|
|
181
|
-
return reject(new ImageKitInvalidRequestError(body.message ?? "Invalid request. Please check the parameters.", getResponseMetadata(xhr)));
|
|
182
|
-
} catch (ex) {
|
|
183
|
-
return reject(ex);
|
|
184
|
-
}
|
|
185
|
-
} else {
|
|
186
|
-
try {
|
|
187
|
-
var body = JSON.parse(xhr.responseText);
|
|
188
|
-
return reject(new ImageKitServerError(body.message ?? "Server error occurred while uploading the file. This is rare and usually temporary.", getResponseMetadata(xhr)));
|
|
189
|
-
} catch (ex) {
|
|
190
|
-
return reject(new ImageKitServerError("Server error occurred while uploading the file. This is rare and usually temporary.", getResponseMetadata(xhr)));
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
};
|
|
194
|
-
xhr.send(formData);
|
|
195
|
-
});
|
|
196
|
-
};
|
|
197
|
-
const addResponseHeadersAndBody = (body, xhr) => {
|
|
198
|
-
let response = {
|
|
199
|
-
...body
|
|
200
|
-
};
|
|
201
|
-
const responseMetadata = getResponseMetadata(xhr);
|
|
202
|
-
Object.defineProperty(response, "$ResponseMetadata", {
|
|
203
|
-
value: responseMetadata,
|
|
204
|
-
enumerable: false,
|
|
205
|
-
writable: false
|
|
206
|
-
});
|
|
207
|
-
return response;
|
|
208
|
-
};
|
|
209
|
-
const getResponseMetadata = xhr => {
|
|
210
|
-
const headers = getResponseHeaderMap(xhr);
|
|
211
|
-
const responseMetadata = {
|
|
212
|
-
statusCode: xhr.status,
|
|
213
|
-
headers: headers,
|
|
214
|
-
requestId: headers["x-request-id"]
|
|
215
|
-
};
|
|
216
|
-
return responseMetadata;
|
|
217
|
-
};
|
|
218
|
-
function getResponseHeaderMap(xhr) {
|
|
219
|
-
const headers = {};
|
|
220
|
-
const responseHeaders = xhr.getAllResponseHeaders();
|
|
221
|
-
if (Object.keys(responseHeaders).length) {
|
|
222
|
-
responseHeaders.trim().split(/[\r\n]+/).map(value => value.split(/: /)).forEach(keyValue => {
|
|
223
|
-
headers[keyValue[0].trim().toLowerCase()] = keyValue[1].trim();
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
return headers;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
1
|
const supportedTransforms = {
|
|
230
2
|
width: "w",
|
|
231
3
|
height: "h",
|
|
@@ -261,6 +33,7 @@ const supportedTransforms = {
|
|
|
261
33
|
aiVariation: "e-genvar",
|
|
262
34
|
aiDropShadow: "e-dropshadow",
|
|
263
35
|
aiChangeBackground: "e-changebg",
|
|
36
|
+
aiEdit: "e-edit",
|
|
264
37
|
aiRemoveBackground: "e-bgremove",
|
|
265
38
|
aiRemoveBackgroundExternal: "e-removedotbg",
|
|
266
39
|
contrastStretch: "e-contrast",
|
|
@@ -268,6 +41,8 @@ const supportedTransforms = {
|
|
|
268
41
|
sharpen: "e-sharpen",
|
|
269
42
|
unsharpMask: "e-usm",
|
|
270
43
|
gradient: "e-gradient",
|
|
44
|
+
colorReplace: "cr",
|
|
45
|
+
distort: "e-distort",
|
|
271
46
|
progressive: "pr",
|
|
272
47
|
lossless: "lo",
|
|
273
48
|
colorProfile: "cp",
|
|
@@ -276,6 +51,7 @@ const supportedTransforms = {
|
|
|
276
51
|
trim: "t",
|
|
277
52
|
zoom: "z",
|
|
278
53
|
page: "pg",
|
|
54
|
+
layerMode: "lm",
|
|
279
55
|
fontSize: "fs",
|
|
280
56
|
fontFamily: "ff",
|
|
281
57
|
fontColor: "co",
|
|
@@ -417,6 +193,7 @@ function processOverlay(overlay) {
|
|
|
417
193
|
const entries = [];
|
|
418
194
|
const {
|
|
419
195
|
type,
|
|
196
|
+
layerMode,
|
|
420
197
|
position = {},
|
|
421
198
|
timing = {},
|
|
422
199
|
transformation = []
|
|
@@ -485,6 +262,9 @@ function processOverlay(overlay) {
|
|
|
485
262
|
}
|
|
486
263
|
break;
|
|
487
264
|
}
|
|
265
|
+
if (layerMode) {
|
|
266
|
+
entries.push(`lm-${layerMode}`);
|
|
267
|
+
}
|
|
488
268
|
const {
|
|
489
269
|
x,
|
|
490
270
|
y,
|
|
@@ -662,4 +442,232 @@ function computeCandidateWidths(params) {
|
|
|
662
442
|
};
|
|
663
443
|
}
|
|
664
444
|
|
|
445
|
+
var errorMessages = {
|
|
446
|
+
MISSING_UPLOAD_FILE_PARAMETER: {
|
|
447
|
+
message: "Missing file parameter for upload"
|
|
448
|
+
},
|
|
449
|
+
MISSING_UPLOAD_FILENAME_PARAMETER: {
|
|
450
|
+
message: "Missing fileName parameter for upload"
|
|
451
|
+
},
|
|
452
|
+
MISSING_PUBLIC_KEY: {
|
|
453
|
+
message: "Missing public key for upload"
|
|
454
|
+
},
|
|
455
|
+
UPLOAD_ENDPOINT_NETWORK_ERROR: {
|
|
456
|
+
message: "Request to ImageKit upload endpoint failed due to network error"
|
|
457
|
+
},
|
|
458
|
+
MISSING_SIGNATURE: {
|
|
459
|
+
message: "Missing signature for upload. The SDK expects token, signature and expire for authentication."
|
|
460
|
+
},
|
|
461
|
+
MISSING_TOKEN: {
|
|
462
|
+
message: "Missing token for upload. The SDK expects token, signature and expire for authentication."
|
|
463
|
+
},
|
|
464
|
+
MISSING_EXPIRE: {
|
|
465
|
+
message: "Missing expire for upload. The SDK expects token, signature and expire for authentication."
|
|
466
|
+
},
|
|
467
|
+
INVALID_TRANSFORMATION: {
|
|
468
|
+
message: "Invalid transformation parameter. Please include at least pre, post, or both."
|
|
469
|
+
},
|
|
470
|
+
INVALID_PRE_TRANSFORMATION: {
|
|
471
|
+
message: "Invalid pre transformation parameter."
|
|
472
|
+
},
|
|
473
|
+
INVALID_POST_TRANSFORMATION: {
|
|
474
|
+
message: "Invalid post transformation parameter."
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
class ImageKitInvalidRequestError extends Error {
|
|
479
|
+
constructor(message, responseMetadata) {
|
|
480
|
+
super(message);
|
|
481
|
+
this.$ResponseMetadata = void 0;
|
|
482
|
+
this.name = "ImageKitInvalidRequestError";
|
|
483
|
+
this.$ResponseMetadata = responseMetadata;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
class ImageKitAbortError extends Error {
|
|
487
|
+
constructor(message, reason) {
|
|
488
|
+
super(message);
|
|
489
|
+
this.reason = void 0;
|
|
490
|
+
this.name = "ImageKitAbortError";
|
|
491
|
+
this.reason = reason;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
class ImageKitUploadNetworkError extends Error {
|
|
495
|
+
constructor(message) {
|
|
496
|
+
super(message);
|
|
497
|
+
this.name = "ImageKitUploadNetworkError";
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
class ImageKitServerError extends Error {
|
|
501
|
+
constructor(message, responseMetadata) {
|
|
502
|
+
super(message);
|
|
503
|
+
this.$ResponseMetadata = void 0;
|
|
504
|
+
this.name = "ImageKitServerError";
|
|
505
|
+
this.$ResponseMetadata = responseMetadata;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
const upload = uploadOptions => {
|
|
509
|
+
if (!uploadOptions) {
|
|
510
|
+
return Promise.reject(new ImageKitInvalidRequestError("Invalid options provided for upload"));
|
|
511
|
+
}
|
|
512
|
+
return new Promise((resolve, reject) => {
|
|
513
|
+
const {
|
|
514
|
+
xhr: userProvidedXHR
|
|
515
|
+
} = uploadOptions || {};
|
|
516
|
+
delete uploadOptions.xhr;
|
|
517
|
+
const xhr = userProvidedXHR || new XMLHttpRequest();
|
|
518
|
+
if (!uploadOptions.file) {
|
|
519
|
+
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_UPLOAD_FILE_PARAMETER.message));
|
|
520
|
+
}
|
|
521
|
+
if (!uploadOptions.fileName) {
|
|
522
|
+
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_UPLOAD_FILENAME_PARAMETER.message));
|
|
523
|
+
}
|
|
524
|
+
if (!uploadOptions.publicKey || uploadOptions.publicKey.length === 0) {
|
|
525
|
+
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_PUBLIC_KEY.message));
|
|
526
|
+
}
|
|
527
|
+
if (!uploadOptions.token) {
|
|
528
|
+
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_TOKEN.message));
|
|
529
|
+
}
|
|
530
|
+
if (!uploadOptions.signature) {
|
|
531
|
+
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_SIGNATURE.message));
|
|
532
|
+
}
|
|
533
|
+
if (!uploadOptions.expire) {
|
|
534
|
+
return reject(new ImageKitInvalidRequestError(errorMessages.MISSING_EXPIRE.message));
|
|
535
|
+
}
|
|
536
|
+
if (uploadOptions.transformation) {
|
|
537
|
+
if (!(Object.keys(uploadOptions.transformation).includes("pre") || Object.keys(uploadOptions.transformation).includes("post"))) {
|
|
538
|
+
return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_TRANSFORMATION.message));
|
|
539
|
+
}
|
|
540
|
+
if (Object.keys(uploadOptions.transformation).includes("pre") && !uploadOptions.transformation.pre) {
|
|
541
|
+
return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_PRE_TRANSFORMATION.message));
|
|
542
|
+
}
|
|
543
|
+
if (Object.keys(uploadOptions.transformation).includes("post")) {
|
|
544
|
+
if (Array.isArray(uploadOptions.transformation.post)) {
|
|
545
|
+
for (let transformation of uploadOptions.transformation.post) {
|
|
546
|
+
if (transformation.type === "abs" && !(transformation.protocol || transformation.value)) {
|
|
547
|
+
return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message));
|
|
548
|
+
} else if (transformation.type === "transformation" && !transformation.value) {
|
|
549
|
+
return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message));
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
} else {
|
|
553
|
+
return reject(new ImageKitInvalidRequestError(errorMessages.INVALID_POST_TRANSFORMATION.message));
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
var formData = new FormData();
|
|
558
|
+
let key;
|
|
559
|
+
for (key in uploadOptions) {
|
|
560
|
+
if (key) {
|
|
561
|
+
if (key === "file" && typeof uploadOptions.file != "string") {
|
|
562
|
+
formData.set('file', uploadOptions.file, String(uploadOptions.fileName));
|
|
563
|
+
} else if (key === "tags" && Array.isArray(uploadOptions.tags)) {
|
|
564
|
+
formData.set('tags', uploadOptions.tags.join(","));
|
|
565
|
+
} else if (key === 'signature') {
|
|
566
|
+
formData.set("signature", uploadOptions.signature);
|
|
567
|
+
} else if (key === 'expire') {
|
|
568
|
+
formData.set("expire", String(uploadOptions.expire));
|
|
569
|
+
} else if (key === 'token') {
|
|
570
|
+
formData.set("token", uploadOptions.token);
|
|
571
|
+
} else if (key === "responseFields" && Array.isArray(uploadOptions.responseFields)) {
|
|
572
|
+
formData.set('responseFields', uploadOptions.responseFields.join(","));
|
|
573
|
+
} else if (key === "extensions" && Array.isArray(uploadOptions.extensions)) {
|
|
574
|
+
formData.set('extensions', JSON.stringify(uploadOptions.extensions));
|
|
575
|
+
} else if (key === "customMetadata" && typeof uploadOptions.customMetadata === "object" && !Array.isArray(uploadOptions.customMetadata) && uploadOptions.customMetadata !== null) {
|
|
576
|
+
formData.set('customMetadata', JSON.stringify(uploadOptions.customMetadata));
|
|
577
|
+
} else if (key === "transformation" && typeof uploadOptions.transformation === "object" && uploadOptions.transformation !== null) {
|
|
578
|
+
formData.set(key, JSON.stringify(uploadOptions.transformation));
|
|
579
|
+
} else if (key === 'checks' && uploadOptions.checks) {
|
|
580
|
+
formData.set("checks", uploadOptions.checks);
|
|
581
|
+
} else if (uploadOptions[key] !== undefined) {
|
|
582
|
+
if (["onProgress", "abortSignal"].includes(key)) continue;
|
|
583
|
+
formData.set(key, String(uploadOptions[key]));
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
if (uploadOptions.onProgress) {
|
|
588
|
+
xhr.upload.onprogress = function (event) {
|
|
589
|
+
if (uploadOptions.onProgress) uploadOptions.onProgress(event);
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
function onAbortHandler() {
|
|
593
|
+
var _uploadOptions$abortS;
|
|
594
|
+
xhr.abort();
|
|
595
|
+
return reject(new ImageKitAbortError("Upload aborted", (_uploadOptions$abortS = uploadOptions.abortSignal) === null || _uploadOptions$abortS === void 0 ? void 0 : _uploadOptions$abortS.reason));
|
|
596
|
+
}
|
|
597
|
+
if (uploadOptions.abortSignal) {
|
|
598
|
+
if (uploadOptions.abortSignal.aborted) {
|
|
599
|
+
var _uploadOptions$abortS2;
|
|
600
|
+
return reject(new ImageKitAbortError("Upload aborted", (_uploadOptions$abortS2 = uploadOptions.abortSignal) === null || _uploadOptions$abortS2 === void 0 ? void 0 : _uploadOptions$abortS2.reason));
|
|
601
|
+
}
|
|
602
|
+
uploadOptions.abortSignal.addEventListener("abort", onAbortHandler);
|
|
603
|
+
xhr.addEventListener("loadend", () => {
|
|
604
|
+
if (uploadOptions.abortSignal) {
|
|
605
|
+
uploadOptions.abortSignal.removeEventListener("abort", onAbortHandler);
|
|
606
|
+
}
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
xhr.open('POST', 'https://upload.imagekit.io/api/v1/files/upload');
|
|
610
|
+
xhr.onerror = function (e) {
|
|
611
|
+
return reject(new ImageKitUploadNetworkError(errorMessages.UPLOAD_ENDPOINT_NETWORK_ERROR.message));
|
|
612
|
+
};
|
|
613
|
+
xhr.onload = function () {
|
|
614
|
+
if (xhr.status >= 200 && xhr.status < 300) {
|
|
615
|
+
try {
|
|
616
|
+
var body = JSON.parse(xhr.responseText);
|
|
617
|
+
var uploadResponse = addResponseHeadersAndBody(body, xhr);
|
|
618
|
+
return resolve(uploadResponse);
|
|
619
|
+
} catch (ex) {
|
|
620
|
+
return reject(ex);
|
|
621
|
+
}
|
|
622
|
+
} else if (xhr.status >= 400 && xhr.status < 500) {
|
|
623
|
+
try {
|
|
624
|
+
var body = JSON.parse(xhr.responseText);
|
|
625
|
+
return reject(new ImageKitInvalidRequestError(body.message ?? "Invalid request. Please check the parameters.", getResponseMetadata(xhr)));
|
|
626
|
+
} catch (ex) {
|
|
627
|
+
return reject(ex);
|
|
628
|
+
}
|
|
629
|
+
} else {
|
|
630
|
+
try {
|
|
631
|
+
var body = JSON.parse(xhr.responseText);
|
|
632
|
+
return reject(new ImageKitServerError(body.message ?? "Server error occurred while uploading the file. This is rare and usually temporary.", getResponseMetadata(xhr)));
|
|
633
|
+
} catch (ex) {
|
|
634
|
+
return reject(new ImageKitServerError("Server error occurred while uploading the file. This is rare and usually temporary.", getResponseMetadata(xhr)));
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
xhr.send(formData);
|
|
639
|
+
});
|
|
640
|
+
};
|
|
641
|
+
const addResponseHeadersAndBody = (body, xhr) => {
|
|
642
|
+
let response = {
|
|
643
|
+
...body
|
|
644
|
+
};
|
|
645
|
+
const responseMetadata = getResponseMetadata(xhr);
|
|
646
|
+
Object.defineProperty(response, "$ResponseMetadata", {
|
|
647
|
+
value: responseMetadata,
|
|
648
|
+
enumerable: false,
|
|
649
|
+
writable: false
|
|
650
|
+
});
|
|
651
|
+
return response;
|
|
652
|
+
};
|
|
653
|
+
const getResponseMetadata = xhr => {
|
|
654
|
+
const headers = getResponseHeaderMap(xhr);
|
|
655
|
+
const responseMetadata = {
|
|
656
|
+
statusCode: xhr.status,
|
|
657
|
+
headers: headers,
|
|
658
|
+
requestId: headers["x-request-id"]
|
|
659
|
+
};
|
|
660
|
+
return responseMetadata;
|
|
661
|
+
};
|
|
662
|
+
function getResponseHeaderMap(xhr) {
|
|
663
|
+
const headers = {};
|
|
664
|
+
const responseHeaders = xhr.getAllResponseHeaders();
|
|
665
|
+
if (Object.keys(responseHeaders).length) {
|
|
666
|
+
responseHeaders.trim().split(/[\r\n]+/).map(value => value.split(/: /)).forEach(keyValue => {
|
|
667
|
+
headers[keyValue[0].trim().toLowerCase()] = keyValue[1].trim();
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
return headers;
|
|
671
|
+
}
|
|
672
|
+
|
|
665
673
|
export { ImageKitAbortError, ImageKitInvalidRequestError, ImageKitServerError, ImageKitUploadNetworkError, buildSrc, buildTransformationString, getResponsiveImageAttributes, upload };
|
package/dist/imagekit.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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})}));
|
|
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";const t={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",aiEdit:"e-edit",aiRemoveBackground:"e-bgremove",aiRemoveBackgroundExternal:"e-removedotbg",contrastStretch:"e-contrast",shadow:"e-shadow",sharpen:"e-sharpen",unsharpMask:"e-usm",gradient:"e-gradient",colorReplace:"cr",distort:"e-distort",progressive:"pr",lossless:"lo",colorProfile:"cp",metadata:"md",opacity:"o",trim:"t",zoom:"z",page:"pg",layerMode:"lm",fontSize:"fs",fontFamily:"ff",fontColor:"co",innerAlignment:"ia",padding:"pa",alpha:"al",typography:"tg",lineHeight:"lh",fontOutline:"fol",fontShadow:"fsh",raw:"raw"};var r=e=>"query"===e.transformationPosition,n=function(e){return e&&(t[e]||t[e.toLowerCase()])||""},s=function(){return":"},o=function(){return","},a=function(){return"-"};const i=function(e){return"undefined"!=typeof window?btoa(e):Buffer.from(e,"utf8").toString("base64")},u=new RegExp("^[a-zA-Z0-9-._/ ]*$"),c=new RegExp("^[a-zA-Z0-9-._ ]*$");function p(e){return"string"==typeof e&&"/"==e[e.length-1]&&(e=e.substring(0,e.length-1)),e}function l(e){return"string"==typeof e&&"/"==e[0]&&(e=e.slice(1)),e}function d(e,t){var r=t||"/",n=new RegExp(r+"{1,}","g");return e.join(r).replace(n,r)}const f=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 n,o,a;try{t?(n=new URL(e.src),o=!0):(a=new URL(e.urlEndpoint).pathname,n=new URL(d([e.urlEndpoint.replace(a,""),e.src])))}catch(e){return console.error(e),""}for(var i in e.queryParameters)n.searchParams.append(i,String(e.queryParameters[i]));var u=h(e.transformation);return u&&u.length&&(r(e)||o||(n.pathname=d(["tr"+s()+u,n.pathname]))),n.pathname=d(a?[a,n.pathname]:[n.pathname]),u&&u.length&&(r(e)||o)?""!==n.searchParams.toString()?`${n.href}&tr=${u}`:`${n.href}?tr=${u}`:n.href};function g(e,t){return e=p(l(e)),"plain"===t?"i-"+e.replace(/\//g,"@@"):"base64"===t?"ie-"+encodeURIComponent(i(e)):u.test(e)?"i-"+e.replace(/\//g,"@@"):"ie-"+encodeURIComponent(i(e))}function m(e){const t=[],{type:r,layerMode:n,position:s={},timing:a={},transformation:u=[]}=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(i(e)):c.test(e)?"i-"+encodeURIComponent(e):"ie-"+encodeURIComponent(i(e))}(r.text,n))}break;case"image":t.push("l-image");{const r=e,n=r.encoding||"auto";if(!r.input)return;t.push(g(r.input,n))}break;case"video":t.push("l-video");{const r=e,n=r.encoding||"auto";if(!r.input)return;t.push(g(r.input,n))}break;case"subtitle":t.push("l-subtitle");{const r=e,n=r.encoding||"auto";if(!r.input)return;t.push(g(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)}}n&&t.push("lm-"+n);const{x:p,y:l,focus:d}=s;p&&t.push("lx-"+p),l&&t.push("ly-"+l),d&&t.push("lfo-"+d);const{start:f,end:m,duration:y}=a;f&&t.push("lso-"+f),m&&t.push("leo-"+m),y&&t.push("ldu-"+y);const v=h(u);return v&&""!==v.trim()&&t.push(v),t.push("l-end"),t.join(o())}const h=function(e){if(!Array.isArray(e))return"";for(var t=[],r=0,i=e.length;r<i;r++){var u=[];for(var c in e[r]){let t=e[r][c];if(null!=t)if("overlay"!==c||"object"!=typeof t){var d=n(c);if(d||(d=c),""!==d)if(["e-grayscale","e-contrast","e-removedotbg","e-bgremove","e-upscale","e-retouch","e-genvar"].includes(d)){if(!0!==t&&"-"!==t&&"true"!==t)continue;u.push(d)}else!["e-sharpen","e-shadow","e-gradient","e-usm","e-dropshadow"].includes(d)||""!==t.toString().trim()&&!0!==t&&"true"!==t?"raw"===c?u.push(e[r][c]):("di"===d&&(t=p(l(t||"")),t=t.replace(/\//g,"@@")),"sr"===d&&Array.isArray(t)&&(t=t.join("_")),"t"===d&&""===t.toString().trim()&&(t="true"),u.push([d,t].join(a()))):u.push(d)}else{var f=m(t);f&&""!==f.trim()&&u.push(f)}}u.length&&t.push(u.join(o()))}return t.join(s())},y=[640,750,828,1080,1200,1920,2048,3840],v=[16,32,48,64,96,128,256,384];var b={message:"Missing file parameter for upload"},w={message:"Missing fileName parameter for upload"},x={message:"Missing public key for upload"},k={message:"Request to ImageKit upload endpoint failed due to network error"},S={message:"Missing signature for upload. The SDK expects token, signature and expire for authentication."},R={message:"Missing token for upload. The SDK expects token, signature and expire for authentication."},E={message:"Missing expire for upload. The SDK expects token, signature and expire for authentication."},I={message:"Invalid transformation parameter. Please include at least pre, post, or both."},A={message:"Invalid pre transformation parameter."},M={message:"Invalid post transformation parameter."};class P extends Error{constructor(e,t){super(e),this.$ResponseMetadata=void 0,this.name="ImageKitInvalidRequestError",this.$ResponseMetadata=t}}class j extends Error{constructor(e,t){super(e),this.reason=void 0,this.name="ImageKitAbortError",this.reason=t}}class K extends Error{constructor(e){super(e),this.name="ImageKitUploadNetworkError"}}class O extends Error{constructor(e,t){super(e),this.$ResponseMetadata=void 0,this.name="ImageKitServerError",this.$ResponseMetadata=t}}const C=(e,t)=>{let r={...e};const n=q(t);return Object.defineProperty(r,"$ResponseMetadata",{value:n,enumerable:!1,writable:!1}),r},q=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"]}};e.ImageKitAbortError=j,e.ImageKitInvalidRequestError=P,e.ImageKitServerError=O,e.ImageKitUploadNetworkError=K,e.buildSrc=f,e.buildTransformationString=h,e.getResponsiveImageAttributes=function(e){const{src:t,urlEndpoint:r,transformation:n=[],queryParameters:s,transformationPosition:o,sizes:a,width:i,deviceBreakpoints:u=y,imageBreakpoints:c=v}=e,p=[...u].sort((e,t)=>e-t),l=[...[...c].sort((e,t)=>e-t),...p].sort((e,t)=>e-t),{candidates:d,descriptorKind:g}=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}),m=e=>f({src:t,urlEndpoint:r,queryParameters:s,transformationPosition:o,transformation:[...n,{width:e,crop:"at_max"}]}),h=d.map((e,t)=>`${m(e)} ${"w"===g?e:t+1}${g}`).join(", ")||void 0,b=a??("w"===g?"100vw":void 0);return{src:m(d[d.length-1]),srcSet:h,...b?{sizes:b}:{},...void 0!==i?{width:i}:{}}},e.upload=e=>e?new Promise((t,r)=>{const{xhr:n}=e||{};delete e.xhr;const s=n||new XMLHttpRequest;if(!e.file)return r(new P(b.message));if(!e.fileName)return r(new P(w.message));if(!e.publicKey||0===e.publicKey.length)return r(new P(x.message));if(!e.token)return r(new P(R.message));if(!e.signature)return r(new P(S.message));if(!e.expire)return r(new P(E.message));if(e.transformation){if(!Object.keys(e.transformation).includes("pre")&&!Object.keys(e.transformation).includes("post"))return r(new P(I.message));if(Object.keys(e.transformation).includes("pre")&&!e.transformation.pre)return r(new P(A.message));if(Object.keys(e.transformation).includes("post")){if(!Array.isArray(e.transformation.post))return r(new P(M.message));for(let t of e.transformation.post){if("abs"===t.type&&!t.protocol&&!t.value)return r(new P(M.message));if("transformation"===t.type&&!t.value)return r(new P(M.message))}}}var o=new FormData;let a;for(a in e)if(a)if("file"===a&&"string"!=typeof e.file)o.set("file",e.file,String(e.fileName));else if("tags"===a&&Array.isArray(e.tags))o.set("tags",e.tags.join(","));else if("signature"===a)o.set("signature",e.signature);else if("expire"===a)o.set("expire",String(e.expire));else if("token"===a)o.set("token",e.token);else if("responseFields"===a&&Array.isArray(e.responseFields))o.set("responseFields",e.responseFields.join(","));else if("extensions"===a&&Array.isArray(e.extensions))o.set("extensions",JSON.stringify(e.extensions));else if("customMetadata"!==a||"object"!=typeof e.customMetadata||Array.isArray(e.customMetadata)||null===e.customMetadata){if("transformation"===a&&"object"==typeof e.transformation&&null!==e.transformation)o.set(a,JSON.stringify(e.transformation));else if("checks"===a&&e.checks)o.set("checks",e.checks);else if(void 0!==e[a]){if(["onProgress","abortSignal"].includes(a))continue;o.set(a,String(e[a]))}}else o.set("customMetadata",JSON.stringify(e.customMetadata));function i(){var t;return s.abort(),r(new j("Upload aborted",null===(t=e.abortSignal)||void 0===t?void 0:t.reason))}if(e.onProgress&&(s.upload.onprogress=function(t){e.onProgress&&e.onProgress(t)}),e.abortSignal){var u;if(e.abortSignal.aborted)return r(new j("Upload aborted",null===(u=e.abortSignal)||void 0===u?void 0:u.reason));e.abortSignal.addEventListener("abort",i),s.addEventListener("loadend",()=>{e.abortSignal&&e.abortSignal.removeEventListener("abort",i)})}s.open("POST","https://upload.imagekit.io/api/v1/files/upload"),s.onerror=function(e){return r(new K(k.message))},s.onload=function(){if(s.status>=200&&s.status<300)try{var e=JSON.parse(s.responseText),n=C(e,s);return t(n)}catch(e){return r(e)}else if(s.status>=400&&s.status<500)try{e=JSON.parse(s.responseText);return r(new P(e.message??"Invalid request. Please check the parameters.",q(s)))}catch(e){return r(e)}else try{e=JSON.parse(s.responseText);return r(new O(e.message??"Server error occurred while uploading the file. This is rare and usually temporary.",q(s)))}catch(e){return r(new O("Server error occurred while uploading the file. This is rare and usually temporary.",q(s)))}},s.send(o)}):Promise.reject(new P("Invalid options provided for upload")),Object.defineProperty(e,"__esModule",{value:!0})}));
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import type { SrcOptions, Transformation, UploadOptions, UploadResponse } from "./interfaces";
|
|
1
|
+
import type { GetImageAttributesOptions, ResponsiveImageAttributes, SrcOptions, Transformation, UploadOptions, UploadResponse } from "./interfaces";
|
|
2
|
+
import { getResponsiveImageAttributes } from "./responsive";
|
|
2
3
|
import { ImageKitAbortError, ImageKitInvalidRequestError, ImageKitServerError, ImageKitUploadNetworkError, upload } from "./upload";
|
|
3
4
|
import { buildSrc, buildTransformationString } from "./url";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
export { buildSrc, buildTransformationString, upload, getResponsiveImageAttributes, ImageKitInvalidRequestError, ImageKitAbortError, ImageKitServerError, ImageKitUploadNetworkError };
|
|
7
|
-
export type { Transformation, SrcOptions, UploadOptions, UploadResponse, GetImageAttributesOptions, ResponsiveImageAttributes };
|
|
5
|
+
export { buildSrc, buildTransformationString, getResponsiveImageAttributes, ImageKitAbortError, ImageKitInvalidRequestError, ImageKitServerError, ImageKitUploadNetworkError, upload };
|
|
6
|
+
export type { GetImageAttributesOptions, ResponsiveImageAttributes, SrcOptions, Transformation, UploadOptions, UploadResponse };
|