/
index.ts
267 lines (223 loc) · 6.27 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/*
* Copyright (c) 2018 by Filestack.
* Some rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Session } from '../client';
import { Hosts } from './../../config';
import { ExtensionsMap } from './extensions';
import { fromBuffer } from 'file-type';
import isutf8 from 'isutf8';
/**
* Resolve cdn url based on handle type
*
* @private
* @param session session object
* @param handle file handle (hash, src://alias, url)
*/
export const resolveCdnUrl = (session: Session, handle: string): string => {
const cdnURL = session.urls.cdnUrl;
if (handle && (handle.indexOf('src:') === 0 || handle.indexOf('http') === 0)) {
if (!session.apikey) {
throw new Error('Api key is required when storage alias is provided');
}
// apikey is required for alias or external sources call
return `${cdnURL}/${session.apikey}`;
}
return cdnURL;
};
/**
* Resolve all urls with provided cnames
*
* @private
* @param urls
* @param cname
*/
export const resolveHost = (urls: Hosts, cname: string): Hosts => {
if (!cname) {
return urls;
}
const hosts = /filestackapi.com|filestackcontent.com/i;
Object.keys(urls).forEach(key => {
urls[key] = urls[key].replace(hosts, cname);
});
return urls;
};
/**
* Removes empty options from object
*
* @private
* @param obj
*/
export const removeEmpty = (obj: any) => {
const newObj = { ...obj };
Object.keys(newObj).forEach(k => !newObj[k] && typeof newObj[k] !== 'boolean' && delete newObj[k]);
return newObj;
};
/**
* Returns unique time
*/
let last;
export const uniqueTime = () => {
const time = Date.now();
last = time === last ? time + 1 : time;
return last;
};
/**
* Generates random string with provided length
*
* @param len
*/
export const uniqueId = (len: number = 10): string => {
return new Array(len).join().replace(/(.|$)/g, () => ((Math.random() * 36) | 0).toString(36)[Math.random() < 0.5 ? 'toString' : 'toUpperCase']());
};
/**
* Check if input is a svg
*
* @param {Uint8Array | Buffer} file
* @returns {string} - mimetype
*/
export const getMimetype = async(file: Uint8Array | Buffer, name?: string): Promise<string> => {
let type;
try {
type = await fromBuffer(file);
} catch(e) {
console.warn("An exception occurred while processing the buffer:", e.message);
}
if (name && name.indexOf('.') > -1) {
const mime = extensionToMime(name);
if (mime) {
return mime;
}
}
const excludedMimetypes = ['text/plain', 'application/octet-stream', 'application/x-ms', 'application/x-msi', 'application/zip'];
if (type && excludedMimetypes.indexOf(type.mime) === -1) {
return type.mime;
}
try {
if (isutf8(file)) {
return 'text/plain';
}
} catch (e) {
/* istanbul ignore next */
console.warn('Additional mimetype checks (text/plain) are currently not supported for browsers');
}
// this is only fallback, omit it in coverage
/* istanbul ignore next */
// if we cant find types by extensions and we have magic bytes fallback to it
if (type) {
return type.mime;
}
return 'application/octet-stream';
};
/**
* Change extension to according mimetype using ext=>mimetype map
*
* @param ext - string
* @return string|boolean
*/
export const extensionToMime = (ext: string) => {
if (!ext || ext.length === 0) {
return;
}
if (ext.split('/').length === 2) {
return ext;
}
if (ext.indexOf('.') > -1) {
ext = ext.split('.').pop();
}
ext = ext.toLocaleLowerCase();
const keys = Object.keys(ExtensionsMap);
const mapLen = keys.length;
for (let i = 0; i < mapLen; i++) {
if (ExtensionsMap[keys[i]].indexOf(ext) > -1) {
return keys[i];
}
}
return;
};
/**
* Sanitizer Options
*/
export type SanitizeOptions =
| boolean
| {
exclude?: string[];
replacement?: string;
};
/**
* Sanitize file name
*
* @param name
* @param {bool} options - enable,disable sanitizer, default enabled
* @param {string} options.replacement - replacement for sanitized chars defaults to "-"
* @param {string[]} options.exclude - array with excluded chars default - `['\', '{', '}','|', '%', '`', '"', "'", '~', '[', ']', '#', '|', '^', '<', '>']`
*/
export const sanitizeName = (name: string, options: SanitizeOptions = true): string => {
if (typeof options === 'boolean' && !options) {
return name;
}
let ext;
const replacement = typeof options !== 'boolean' && options.replacement ? options.replacement : '-';
const exclude = typeof options !== 'boolean' && options.exclude ? options.exclude : ['\\', '{', '}', '|', '%', '`', '"', "'", '~', '[', ']', '#', '|', '^', '<', '>'];
if (!name || name.length === 0) {
return 'undefined';
}
const fileParts = name.split('.');
if (fileParts.length > 1) {
ext = fileParts.pop();
}
return `${fileParts
.join('.')
.split('')
.map(char => (exclude.indexOf(char) > -1 ? replacement : char))
.join('')}${ext ? '.' + ext : ''}`;
};
/**
* Filter object to given fields
*
* @param toFilter
* @param requiredFields
*/
export const filterObject = (toFilter, requiredFields: string[]) => {
if (!requiredFields || requiredFields.length === 0) {
return toFilter;
}
if (Object.keys(toFilter).length === 0) {
return toFilter;
}
return Object.keys(toFilter)
.filter(f => requiredFields.indexOf(f) > -1)
.reduce((obj, key) => ({ ...obj, [key]: toFilter[key] }), {});
};
/**
* Deep cleanup object from functions
*
* @param obj
*/
export const cleanUpCallbacks = (obj: any) => {
if (!obj || Object.keys(obj).length === 0) {
return obj;
}
Object.keys(obj).forEach(k => {
if (typeof obj[k] === 'function') {
obj[k] = undefined;
}
if (obj[k] === Object(obj[k])) {
obj[k] = cleanUpCallbacks(obj[k]);
}
});
return obj;
};
export * from './index.node';