Roll Back compile version

This commit is contained in:
Benjamin Toby
2025-07-05 16:14:11 +01:00
parent 4f4eb44a98
commit 728183b827
251 changed files with 10169 additions and 7458 deletions
+4 -1
View File
@@ -1,9 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getAccessToken;
/**
* Login with Github Function
* ===============================================================================
* @description This function uses github api to login a user with datasquirel
*/
export default function getAccessToken({ clientId, redirectUrl, setLoading, scopes, }) {
function getAccessToken({ clientId, redirectUrl, setLoading, scopes, }) {
if (setLoading)
setLoading(true);
const scopeString = scopes ? scopes.join("%20") : "read:user";
+31 -16
View File
@@ -1,29 +1,44 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getAccessToken;
exports.googleLogin = googleLogin;
let interval;
/**
* Login with Google Function
* ===============================================================================
* @description This function uses google identity api to login a user with datasquirel
*/
export default async function getAccessToken(params) {
var _a, _b;
(_a = params.setLoading) === null || _a === void 0 ? void 0 : _a.call(params, true);
const response = (await new Promise((resolve, reject) => {
interval = setInterval(() => {
// @ts-ignore
let google = window.google;
if (google) {
window.clearInterval(interval);
resolve(googleLogin(Object.assign(Object.assign({}, params), { google })));
}
}, 500);
}));
(_b = params.setLoading) === null || _b === void 0 ? void 0 : _b.call(params, false);
return response;
function getAccessToken(params) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
(_a = params.setLoading) === null || _a === void 0 ? void 0 : _a.call(params, true);
const response = (yield new Promise((resolve, reject) => {
interval = setInterval(() => {
// @ts-ignore
let google = window.google;
if (google) {
window.clearInterval(interval);
resolve(googleLogin(Object.assign(Object.assign({}, params), { google })));
}
}, 500);
}));
(_b = params.setLoading) === null || _b === void 0 ? void 0 : _b.call(params, false);
return response;
});
}
/**
* # Google Login Function
*/
export function googleLogin({ google, clientId, setLoading, triggerPrompt, }) {
function googleLogin({ google, clientId, setLoading, triggerPrompt, }) {
setTimeout(() => {
setLoading === null || setLoading === void 0 ? void 0 : setLoading(false);
}, 3000);
+89 -72
View File
@@ -1,86 +1,103 @@
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
import parseClientCookies from "../utils/parseClientCookies";
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = logout;
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
const parseClientCookies_1 = __importDefault(require("../utils/parseClientCookies"));
/**
* Login with Google Function
* ===============================================================================
* @description This function uses google identity api to login a user with datasquirel
*/
export default async function logout(params) {
try {
const localUser = localStorage.getItem("user");
let targetUser;
function logout(params) {
return __awaiter(this, void 0, void 0, function* () {
try {
targetUser = JSON.parse(localUser || "");
}
catch (error) {
console.log(error);
}
if (!targetUser) {
return false;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const cookies = parseClientCookies();
const socialId = (cookies === null || cookies === void 0 ? void 0 : cookies.datasquirel_social_id) &&
typeof cookies.datasquirel_social_id == "string" &&
!cookies.datasquirel_social_id.match(/^null$/i)
? cookies.datasquirel_social_id
: null;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
localStorage.setItem("user", "{}");
localStorage.removeItem(getCsrfHeaderName());
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const response = await new Promise((resolve, reject) => {
if (socialId && !(socialId === null || socialId === void 0 ? void 0 : socialId.match(/^null$/i))) {
const googleClientId = params === null || params === void 0 ? void 0 : params.googleClientId;
if (googleClientId) {
const googleScript = document.createElement("script");
googleScript.src = "https://accounts.google.com/gsi/client";
googleScript.className = "social-script-tag";
document.body.appendChild(googleScript);
const localUser = localStorage.getItem("user");
let targetUser;
try {
targetUser = JSON.parse(localUser || "");
}
catch (error) {
console.log(error);
}
if (!targetUser) {
return false;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const cookies = (0, parseClientCookies_1.default)();
const socialId = (cookies === null || cookies === void 0 ? void 0 : cookies.datasquirel_social_id) &&
typeof cookies.datasquirel_social_id == "string" &&
!cookies.datasquirel_social_id.match(/^null$/i)
? cookies.datasquirel_social_id
: null;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
localStorage.setItem("user", "{}");
localStorage.removeItem((0, get_csrf_header_name_1.default)());
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const response = yield new Promise((resolve, reject) => {
if (socialId && !(socialId === null || socialId === void 0 ? void 0 : socialId.match(/^null$/i))) {
const googleClientId = params === null || params === void 0 ? void 0 : params.googleClientId;
if (googleClientId) {
const googleScript = document.createElement("script");
googleScript.src = "https://accounts.google.com/gsi/client";
googleScript.className = "social-script-tag";
document.body.appendChild(googleScript);
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
googleScript.onload = function (e) {
// @ts-ignore
const google = window.google;
if (google) {
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
google.accounts.id.initialize({
client_id: googleClientId,
});
google.accounts.id.revoke(socialId, (done) => {
console.log(done.error);
resolve(true);
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
};
}
else {
resolve(true);
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
googleScript.onload = function (e) {
// @ts-ignore
const google = window.google;
if (google) {
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
google.accounts.id.initialize({
client_id: googleClientId,
});
google.accounts.id.revoke(socialId, (done) => {
console.log(done.error);
resolve(true);
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
};
}
else {
resolve(true);
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
else {
resolve(true);
}
});
return response;
}
catch (error) {
return false;
}
});
return response;
}
catch (error) {
return false;
}
});
}
+9 -3
View File
@@ -1,4 +1,10 @@
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = postLogin;
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
/**
* Client Setup After Login
* ===============================================================================
@@ -6,13 +12,13 @@ import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name
* is logged in. Use this in conjunction with the `datasquirel.user.loginUser`
* function
*/
export default function postLogin(res) {
function postLogin(res) {
try {
if (!res.payload)
return false;
if (!res.payload.csrf_k)
return false;
localStorage.setItem(getCsrfHeaderName(), res.payload.csrf_k);
localStorage.setItem((0, get_csrf_header_name_1.default)(), res.payload.csrf_k);
localStorage.setItem("user", JSON.stringify(res.payload));
return true;
}
+78 -61
View File
@@ -1,8 +1,23 @@
import _ from "lodash";
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = fetchApi;
const lodash_1 = __importDefault(require("lodash"));
/**
* # Fetch API
*/
export default async function fetchApi(url, options, csrf,
function fetchApi(url, options, csrf,
/**
* Key to use to grab local Storage csrf value.
*/
@@ -12,69 +27,71 @@ localStorageCSRFKey,
* value
*/
csrfHeaderKey) {
let data;
const csrfKey = "x-dsql-csrf-key";
const csrfValue = localStorage.getItem(localStorageCSRFKey || csrfKey);
let finalHeaders = {
"Content-Type": "application/json",
};
if (csrf && csrfValue) {
finalHeaders[localStorageCSRFKey || csrfKey] = csrfValue;
}
if (typeof options === "string") {
try {
let fetchData;
switch (options) {
case "post":
fetchData = await fetch(url, {
method: options,
headers: finalHeaders,
});
data = fetchData.json();
break;
default:
fetchData = await fetch(url);
data = fetchData.json();
break;
return __awaiter(this, void 0, void 0, function* () {
let data;
const csrfKey = "x-dsql-csrf-key";
const csrfValue = localStorage.getItem(localStorageCSRFKey || csrfKey);
let finalHeaders = {
"Content-Type": "application/json",
};
if (csrf && csrfValue) {
finalHeaders[localStorageCSRFKey || csrfKey] = csrfValue;
}
if (typeof options === "string") {
try {
let fetchData;
switch (options) {
case "post":
fetchData = yield fetch(url, {
method: options,
headers: finalHeaders,
});
data = fetchData.json();
break;
default:
fetchData = yield fetch(url);
data = fetchData.json();
break;
}
}
catch (error) {
console.log("FetchAPI error #1:", error.message);
data = null;
}
}
catch (error) {
console.log("FetchAPI error #1:", error.message);
data = null;
}
}
else if (typeof options === "object") {
try {
let fetchData;
if (options.body && typeof options.body === "object") {
let oldOptionsBody = _.cloneDeep(options.body);
options.body = JSON.stringify(oldOptionsBody);
else if (typeof options === "object") {
try {
let fetchData;
if (options.body && typeof options.body === "object") {
let oldOptionsBody = lodash_1.default.cloneDeep(options.body);
options.body = JSON.stringify(oldOptionsBody);
}
if (options.headers) {
options.headers = lodash_1.default.merge(options.headers, finalHeaders);
const finalOptions = Object.assign({}, options);
fetchData = yield fetch(url, finalOptions);
}
else {
const finalOptions = Object.assign(Object.assign({}, options), { headers: finalHeaders });
fetchData = yield fetch(url, finalOptions);
}
data = fetchData.json();
}
if (options.headers) {
options.headers = _.merge(options.headers, finalHeaders);
const finalOptions = Object.assign({}, options);
fetchData = await fetch(url, finalOptions);
catch (error) {
console.log("FetchAPI error #2:", error.message);
data = null;
}
else {
const finalOptions = Object.assign(Object.assign({}, options), { headers: finalHeaders });
fetchData = await fetch(url, finalOptions);
}
else {
try {
let fetchData = yield fetch(url);
data = yield fetchData.json();
}
catch (error) {
console.log("FetchAPI error #3:", error.message);
data = null;
}
data = fetchData.json();
}
catch (error) {
console.log("FetchAPI error #2:", error.message);
data = null;
}
}
else {
try {
let fetchData = await fetch(url);
data = await fetchData.json();
}
catch (error) {
console.log("FetchAPI error #3:", error.message);
data = null;
}
}
return data;
return data;
});
}
+38 -33
View File
@@ -1,55 +1,60 @@
import imageInputFileToBase64 from "./media/imageInputFileToBase64";
import imageInputToBase64 from "./media/imageInputToBase64";
import inputFileToBase64 from "./media/inputFileToBase64";
import getAccessToken from "./auth/google/getAccessToken";
import getGithubAccessToken from "./auth/github/getAccessToken";
import logout from "./auth/logout";
import fetchApi from "./fetch";
import clientFetch from "./fetch";
import serializeQuery from "../package-shared/utils/serialize-query";
import serializeCookies from "../package-shared/utils/serialize-cookies";
import EJSON from "../package-shared/utils/ejson";
import numberfy from "../package-shared/utils/numberfy";
import slugify from "../package-shared/utils/slugify";
import postLogin from "./auth/post-login";
import deserializeQuery from "../package-shared/utils/deserialize-query";
import debugLog from "../package-shared/utils/logging/debug-log";
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const imageInputFileToBase64_1 = __importDefault(require("./media/imageInputFileToBase64"));
const imageInputToBase64_1 = __importDefault(require("./media/imageInputToBase64"));
const inputFileToBase64_1 = __importDefault(require("./media/inputFileToBase64"));
const getAccessToken_1 = __importDefault(require("./auth/google/getAccessToken"));
const getAccessToken_2 = __importDefault(require("./auth/github/getAccessToken"));
const logout_1 = __importDefault(require("./auth/logout"));
const fetch_1 = __importDefault(require("./fetch"));
const fetch_2 = __importDefault(require("./fetch"));
const serialize_query_1 = __importDefault(require("../package-shared/utils/serialize-query"));
const serialize_cookies_1 = __importDefault(require("../package-shared/utils/serialize-cookies"));
const ejson_1 = __importDefault(require("../package-shared/utils/ejson"));
const numberfy_1 = __importDefault(require("../package-shared/utils/numberfy"));
const slugify_1 = __importDefault(require("../package-shared/utils/slugify"));
const post_login_1 = __importDefault(require("./auth/post-login"));
const deserialize_query_1 = __importDefault(require("../package-shared/utils/deserialize-query"));
const debug_log_1 = __importDefault(require("../package-shared/utils/logging/debug-log"));
const media = {
imageInputToBase64,
imageInputFileToBase64,
inputFileToBase64,
imageInputToBase64: imageInputToBase64_1.default,
imageInputFileToBase64: imageInputFileToBase64_1.default,
inputFileToBase64: inputFileToBase64_1.default,
};
/**
* User Auth Object
*/
const auth = {
google: {
getAccessToken: getAccessToken,
getAccessToken: getAccessToken_1.default,
},
github: {
getAccessToken: getGithubAccessToken,
getAccessToken: getAccessToken_2.default,
},
logout,
postLogin,
logout: logout_1.default,
postLogin: post_login_1.default,
};
const utils = {
deserializeQuery,
serializeQuery,
serializeCookies,
EJSON,
numberfy,
slugify,
debugLog,
deserializeQuery: deserialize_query_1.default,
serializeQuery: serialize_query_1.default,
serializeCookies: serialize_cookies_1.default,
EJSON: ejson_1.default,
numberfy: numberfy_1.default,
slugify: slugify_1.default,
debugLog: debug_log_1.default,
};
/**
* Fetch
*/
const fetch = {
fetchApi,
clientFetch,
fetchApi: fetch_1.default,
clientFetch: fetch_2.default,
};
/**
* Main Export
*/
const datasquirelClient = { media, auth, fetch, utils };
export default datasquirelClient;
exports.default = datasquirelClient;
+12 -7
View File
@@ -1,13 +1,18 @@
import imageInputFileToBase64 from "./imageInputFileToBase64";
import imageInputToBase64 from "./imageInputToBase64";
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const imageInputFileToBase64_1 = __importDefault(require("./imageInputFileToBase64"));
const imageInputToBase64_1 = __importDefault(require("./imageInputToBase64"));
/**
* ==========================
* Media Functions Object
* ==========================
*/
const media = {
imageInputToBase64: imageInputToBase64,
imageInputFileToBase64: imageInputFileToBase64,
imageInputToBase64: imageInputToBase64_1.default,
imageInputFileToBase64: imageInputFileToBase64_1.default,
};
/**
* ==========================
@@ -15,8 +20,8 @@ const media = {
* ==========================
*/
const auth = {
imageInputToBase64: imageInputToBase64,
imageInputFileToBase64: imageInputFileToBase64,
imageInputToBase64: imageInputToBase64_1.default,
imageInputFileToBase64: imageInputFileToBase64_1.default,
};
/**
* ==========================
@@ -26,4 +31,4 @@ const auth = {
const datasquirelClient = {
media: media,
};
export default datasquirelClient;
exports.default = datasquirelClient;
+86 -72
View File
@@ -1,78 +1,92 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = imageInputFileToBase64;
/**
* # Image input File top Base64
*/
export default async function imageInputFileToBase64({ imageInputFile, maxWidth, imagePreviewNode, }) {
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
try {
let imageName = imageInputFile.name.replace(/\..*/, "");
let imageDataBase64;
let imageSize;
let canvas = document.createElement("canvas");
const MIME_TYPE = imageInputFile.type;
const QUALITY = 0.95;
const MAX_WIDTH = maxWidth ? maxWidth : null;
const file = imageInputFile;
const blobURL = URL.createObjectURL(file);
const img = new Image();
/** ********************* Add source to new image */
img.src = blobURL;
imageDataBase64 = await new Promise((res, rej) => {
/** ********************* Handle Errors in loading image */
img.onerror = function () {
URL.revokeObjectURL(this.src);
console.log("Cannot load image");
function imageInputFileToBase64(_a) {
return __awaiter(this, arguments, void 0, function* ({ imageInputFile, maxWidth, imagePreviewNode, }) {
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
try {
let imageName = imageInputFile.name.replace(/\..*/, "");
let imageDataBase64;
let imageSize;
let canvas = document.createElement("canvas");
const MIME_TYPE = imageInputFile.type;
const QUALITY = 0.95;
const MAX_WIDTH = maxWidth ? maxWidth : null;
const file = imageInputFile;
const blobURL = URL.createObjectURL(file);
const img = new Image();
/** ********************* Add source to new image */
img.src = blobURL;
imageDataBase64 = yield new Promise((res, rej) => {
/** ********************* Handle Errors in loading image */
img.onerror = function () {
URL.revokeObjectURL(this.src);
console.log("Cannot load image");
};
/** ********************* Handle new image when loaded */
img.onload = function (e) {
const imgEl = e.target;
URL.revokeObjectURL(imgEl.src);
if (MAX_WIDTH) {
const scaleSize = MAX_WIDTH / img.naturalWidth;
canvas.width =
img.naturalWidth < MAX_WIDTH
? img.naturalWidth
: MAX_WIDTH;
canvas.height =
img.naturalWidth < MAX_WIDTH
? img.naturalHeight
: img.naturalHeight * scaleSize;
}
else {
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
}
const ctx = canvas.getContext("2d");
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
if (imagePreviewNode) {
imagePreviewNode.src = srcEncoded;
}
res(srcEncoded);
};
});
imageSize = yield new Promise((res, rej) => {
canvas.toBlob((blob) => {
res(blob === null || blob === void 0 ? void 0 : blob.size);
}, MIME_TYPE, QUALITY);
});
return {
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
imageBase64Full: imageDataBase64,
imageName: imageName,
imageSize: imageSize,
};
/** ********************* Handle new image when loaded */
img.onload = function (e) {
const imgEl = e.target;
URL.revokeObjectURL(imgEl.src);
if (MAX_WIDTH) {
const scaleSize = MAX_WIDTH / img.naturalWidth;
canvas.width =
img.naturalWidth < MAX_WIDTH
? img.naturalWidth
: MAX_WIDTH;
canvas.height =
img.naturalWidth < MAX_WIDTH
? img.naturalHeight
: img.naturalHeight * scaleSize;
}
else {
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
}
const ctx = canvas.getContext("2d");
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
if (imagePreviewNode) {
imagePreviewNode.src = srcEncoded;
}
res(srcEncoded);
}
catch (error) {
console.log("Image Processing Error! =>", error.message);
return {
imageBase64: undefined,
imageBase64Full: undefined,
imageName: undefined,
imageSize: undefined,
};
});
imageSize = await new Promise((res, rej) => {
canvas.toBlob((blob) => {
res(blob === null || blob === void 0 ? void 0 : blob.size);
}, MIME_TYPE, QUALITY);
});
return {
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
imageBase64Full: imageDataBase64,
imageName: imageName,
imageSize: imageSize,
};
}
catch (error) {
console.log("Image Processing Error! =>", error.message);
return {
imageBase64: undefined,
imageBase64Full: undefined,
imageName: undefined,
imageSize: undefined,
};
}
}
});
}
+82 -68
View File
@@ -1,76 +1,90 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = imageInputToBase64;
/**
* # Image Input Element to Base 64
*/
export default async function imageInputToBase64({ imageInput, maxWidth, mimeType, }) {
var _a, _b;
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
try {
let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`);
let imageName = (_a = imageInput.files) === null || _a === void 0 ? void 0 : _a[0].name.replace(/\..*/, "");
let imageDataBase64;
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
const QUALITY = 0.95;
const MAX_WIDTH = maxWidth ? maxWidth : null;
const file = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0];
const blobURL = file ? URL.createObjectURL(file) : undefined;
const img = new Image();
if (blobURL) {
img.src = blobURL;
imageDataBase64 = await new Promise((res, rej) => {
/** ********************* Handle Errors in loading image */
img.onerror = function () {
URL.revokeObjectURL(this.src);
window.alert("Cannot load image!");
function imageInputToBase64(_a) {
return __awaiter(this, arguments, void 0, function* ({ imageInput, maxWidth, mimeType, }) {
var _b, _c;
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
try {
let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`);
let imageName = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0].name.replace(/\..*/, "");
let imageDataBase64;
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
const QUALITY = 0.95;
const MAX_WIDTH = maxWidth ? maxWidth : null;
const file = (_c = imageInput.files) === null || _c === void 0 ? void 0 : _c[0];
const blobURL = file ? URL.createObjectURL(file) : undefined;
const img = new Image();
if (blobURL) {
img.src = blobURL;
imageDataBase64 = yield new Promise((res, rej) => {
/** ********************* Handle Errors in loading image */
img.onerror = function () {
URL.revokeObjectURL(this.src);
window.alert("Cannot load image!");
};
img.onload = function (e) {
const imgEl = e.target;
URL.revokeObjectURL(imgEl.src);
const canvas = document.createElement("canvas");
if (MAX_WIDTH) {
const scaleSize = MAX_WIDTH / img.naturalWidth;
canvas.width =
img.naturalWidth < MAX_WIDTH
? img.naturalWidth
: MAX_WIDTH;
canvas.height =
img.naturalWidth < MAX_WIDTH
? img.naturalHeight
: img.naturalHeight * scaleSize;
}
else {
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
}
const ctx = canvas.getContext("2d");
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
if (imagePreviewNode) {
document
.querySelectorAll(`[data-imagepreview='image']`)
.forEach((_img) => {
const _imgEl = _img;
_imgEl.src = srcEncoded;
});
}
res(srcEncoded);
};
});
return {
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
imageBase64Full: imageDataBase64,
imageName: imageName,
};
img.onload = function (e) {
const imgEl = e.target;
URL.revokeObjectURL(imgEl.src);
const canvas = document.createElement("canvas");
if (MAX_WIDTH) {
const scaleSize = MAX_WIDTH / img.naturalWidth;
canvas.width =
img.naturalWidth < MAX_WIDTH
? img.naturalWidth
: MAX_WIDTH;
canvas.height =
img.naturalWidth < MAX_WIDTH
? img.naturalHeight
: img.naturalHeight * scaleSize;
}
else {
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
}
const ctx = canvas.getContext("2d");
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
if (imagePreviewNode) {
document
.querySelectorAll(`[data-imagepreview='image']`)
.forEach((_img) => {
const _imgEl = _img;
_imgEl.src = srcEncoded;
});
}
res(srcEncoded);
};
});
return {
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
imageBase64Full: imageDataBase64,
imageName: imageName,
};
}
else {
return {};
}
}
else {
catch ( /** @type {*} */error) {
console.log("Image Processing Error! =>", error.message);
return {};
}
}
catch ( /** @type {*} */error) {
console.log("Image Processing Error! =>", error.message);
return {};
}
});
}
+48 -34
View File
@@ -1,3 +1,15 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = inputFileToBase64;
/**
* Input File to base64
* ==============================================================================
@@ -6,40 +18,42 @@
* HTML file input elements usually return an array of input objects, so be sure to select the target
* file from the array.
*/
export default async function inputFileToBase64({ inputFile, allowedRegex, }) {
var _a;
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
if (!((_a = inputFile === null || inputFile === void 0 ? void 0 : inputFile.type) === null || _a === void 0 ? void 0 : _a.match(allowedTypesRegex))) {
window.alert(`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`);
return {
fileName: inputFile.name,
};
}
try {
let fileName = inputFile.name.replace(/\..*/, "");
const fileData = await new Promise((resolve, reject) => {
var reader = new FileReader();
reader.readAsDataURL(inputFile);
reader.onload = function () {
var _a;
resolve((_a = reader.result) === null || _a === void 0 ? void 0 : _a.toString());
function inputFileToBase64(_a) {
return __awaiter(this, arguments, void 0, function* ({ inputFile, allowedRegex, }) {
var _b;
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
if (!((_b = inputFile === null || inputFile === void 0 ? void 0 : inputFile.type) === null || _b === void 0 ? void 0 : _b.match(allowedTypesRegex))) {
window.alert(`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`);
return {
fileName: inputFile.name,
};
reader.onerror = function (/** @type {*} */ error) {
console.log("Error: ", error.message);
}
try {
let fileName = inputFile.name.replace(/\..*/, "");
const fileData = yield new Promise((resolve, reject) => {
var reader = new FileReader();
reader.readAsDataURL(inputFile);
reader.onload = function () {
var _a;
resolve((_a = reader.result) === null || _a === void 0 ? void 0 : _a.toString());
};
reader.onerror = function (/** @type {*} */ error) {
console.log("Error: ", error.message);
};
});
return {
fileBase64: fileData === null || fileData === void 0 ? void 0 : fileData.replace(/.*?base64,/, ""),
fileBase64Full: fileData,
fileName: fileName,
fileSize: inputFile.size,
fileType: inputFile.type,
};
});
return {
fileBase64: fileData === null || fileData === void 0 ? void 0 : fileData.replace(/.*?base64,/, ""),
fileBase64Full: fileData,
fileName: fileName,
fileSize: inputFile.size,
fileType: inputFile.type,
};
}
catch (error) {
console.log("File Processing Error! =>", error.message);
return {
fileName: inputFile.name,
};
}
}
catch (error) {
console.log("File Processing Error! =>", error.message);
return {
fileName: inputFile.name,
};
}
});
}
+4 -1
View File
@@ -1,9 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
/**
* Parse request cookies
* ============================================================================== *
* @description This function takes in a request object and returns the cookies as a JS object
*/
export default function () {
function default_1() {
/**
* Check inputs
*