: playground hash gzip

This commit is contained in:
sight 2022-06-26 17:32:47 +08:00
parent 129106705e
commit 802e6696d0
2 changed files with 34 additions and 19 deletions

View File

@ -28,7 +28,8 @@
"rollup": "^2.70.1",
"typescript": "^4.6.3",
"vite-plugin-md": "^0.13.1",
"vite": "2.9.8"
"vite": "2.9.8",
"fflate": "^0.7.3"
},
"files": [
"lib",

View File

@ -1,4 +1,5 @@
import type { BuiltInParserName } from "prettier";
import { zlibSync, unzlibSync, strToU8, strFromU8 } from "fflate";
const scriptRe = /<script[^>]*>([\s\S]*)<\/script>/;
const exportDefaultRe = /export\s*default\s*\{([\s\S]*)\}\;?\s*<\/script>/;
@ -77,24 +78,6 @@ export const usePlayGround = async (
};
};
/**
*
* @param data
* @returns
*/
function utoa(data: string): string {
return btoa(unescape(encodeURIComponent(data)));
}
/**
*
* @param str
* @returns
*/
function trimBr(str: string): string {
return str.replace(/(^[\r\n]*)|([\r\n]*$)/, "");
}
/**
*
* @returns
@ -131,3 +114,34 @@ async function formatCode(filename: string, data: string) {
return code;
}
/**
*
* @param str
* @returns
*/
function trimBr(str: string): string {
return str.replace(/(^[\r\n]*)|([\r\n]*$)/, "");
}
export function utoa(data: string): string {
const buffer = strToU8(data);
const zipped = zlibSync(buffer, { level: 9 });
const binary = strFromU8(zipped, true);
return btoa(binary);
}
export function atou(base64: string): string {
const binary = atob(base64);
// zlib header (x78), level 9 (xDA)
if (binary.startsWith("\x78\xDA")) {
const buffer = strToU8(binary, true);
const unzipped = unzlibSync(buffer);
return strFromU8(unzipped);
}
// old unicode hacks for backward compatibility
// https://base64.guru/developers/javascript/examples/unicode-strings
return decodeURIComponent(escape(binary));
}