mirror of
https://github.com/sharevb/it-tools.git
synced 2026-11-24 14:50:17 +03:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97e8ff6c5c |
No files matched your search
Vendored
+2
-6
@@ -114,7 +114,6 @@ declare module '@vue/runtime-core' {
|
||||
JsonToXml: typeof import('./src/tools/json-to-xml/json-to-xml.vue')['default']
|
||||
JsonToYaml: typeof import('./src/tools/json-to-yaml-converter/json-to-yaml.vue')['default']
|
||||
JsonViewer: typeof import('./src/tools/json-viewer/json-viewer.vue')['default']
|
||||
JwtGenerator: typeof import('./src/tools/jwt-generator/jwt-generator.vue')['default']
|
||||
JwtParser: typeof import('./src/tools/jwt-parser/jwt-parser.vue')['default']
|
||||
KeycodeInfo: typeof import('./src/tools/keycode-info/keycode-info.vue')['default']
|
||||
ListConverter: typeof import('./src/tools/list-converter/list-converter.vue')['default']
|
||||
@@ -130,23 +129,20 @@ declare module '@vue/runtime-core' {
|
||||
MenuLayout: typeof import('./src/components/MenuLayout.vue')['default']
|
||||
MetaTagGenerator: typeof import('./src/tools/meta-tag-generator/meta-tag-generator.vue')['default']
|
||||
MimeTypes: typeof import('./src/tools/mime-types/mime-types.vue')['default']
|
||||
NAlert: typeof import('naive-ui')['NAlert']
|
||||
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
|
||||
NCode: typeof import('naive-ui')['NCode']
|
||||
NCheckbox: typeof import('naive-ui')['NCheckbox']
|
||||
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
|
||||
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
|
||||
NDivider: typeof import('naive-ui')['NDivider']
|
||||
NEllipsis: typeof import('naive-ui')['NEllipsis']
|
||||
NForm: typeof import('naive-ui')['NForm']
|
||||
NFormItem: typeof import('naive-ui')['NFormItem']
|
||||
NH1: typeof import('naive-ui')['NH1']
|
||||
NH3: typeof import('naive-ui')['NH3']
|
||||
NIcon: typeof import('naive-ui')['NIcon']
|
||||
NInputNumber: typeof import('naive-ui')['NInputNumber']
|
||||
NLayout: typeof import('naive-ui')['NLayout']
|
||||
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
|
||||
NMenu: typeof import('naive-ui')['NMenu']
|
||||
NScrollbar: typeof import('naive-ui')['NScrollbar']
|
||||
NSpace: typeof import('naive-ui')['NSpace']
|
||||
NTable: typeof import('naive-ui')['NTable']
|
||||
NumeronymGenerator: typeof import('./src/tools/numeronym-generator/numeronym-generator.vue')['default']
|
||||
OtpCodeGeneratorAndValidator: typeof import('./src/tools/otp-code-generator-and-validator/otp-code-generator-and-validator.vue')['default']
|
||||
|
||||
@@ -70,7 +70,6 @@
|
||||
"highlight.js": "^11.7.0",
|
||||
"iarna-toml-esm": "^3.0.5",
|
||||
"ibantools": "^4.3.3",
|
||||
"jose": "^5.9.6",
|
||||
"js-base64": "^3.7.6",
|
||||
"json5": "^2.2.3",
|
||||
"jwt-decode": "^3.1.2",
|
||||
|
||||
Generated
+986
-1282
File diff suppressed because it is too large.
Load diff
@@ -7,15 +7,8 @@ import sqlHljs from 'highlight.js/lib/languages/sql';
|
||||
import xmlHljs from 'highlight.js/lib/languages/xml';
|
||||
import yamlHljs from 'highlight.js/lib/languages/yaml';
|
||||
import iniHljs from 'highlight.js/lib/languages/ini';
|
||||
import bashHljs from 'highlight.js/lib/languages/bash';
|
||||
import markdownHljs from 'highlight.js/lib/languages/markdown';
|
||||
import jsHljs from 'highlight.js/lib/languages/javascript';
|
||||
import cssHljs from 'highlight.js/lib/languages/css';
|
||||
import goHljs from 'highlight.js/lib/languages/go';
|
||||
import csharpHljs from 'highlight.js/lib/languages/csharp';
|
||||
import { Base64 } from 'js-base64';
|
||||
import { useCopy } from '@/composable/copy';
|
||||
import { useDownloadFileFromBase64 } from '@/composable/downloadBase64';
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
@@ -24,17 +17,12 @@ const props = withDefaults(
|
||||
language?: string
|
||||
copyPlacement?: 'top-right' | 'bottom-right' | 'outside' | 'none'
|
||||
copyMessage?: string
|
||||
wordWrap?: boolean
|
||||
downloadFileName?: string
|
||||
downloadButtonText?: string
|
||||
}>(),
|
||||
{
|
||||
followHeightOf: null,
|
||||
language: 'txt',
|
||||
copyPlacement: 'top-right',
|
||||
copyMessage: 'Copy to clipboard',
|
||||
downloadFileName: '',
|
||||
downloadButtonText: 'Download',
|
||||
},
|
||||
);
|
||||
hljs.registerLanguage('sql', sqlHljs);
|
||||
@@ -43,25 +31,13 @@ hljs.registerLanguage('html', xmlHljs);
|
||||
hljs.registerLanguage('xml', xmlHljs);
|
||||
hljs.registerLanguage('yaml', yamlHljs);
|
||||
hljs.registerLanguage('toml', iniHljs);
|
||||
hljs.registerLanguage('bash', bashHljs);
|
||||
hljs.registerLanguage('markdown', markdownHljs);
|
||||
hljs.registerLanguage('css', cssHljs);
|
||||
hljs.registerLanguage('javascript', jsHljs);
|
||||
hljs.registerLanguage('go', goHljs);
|
||||
hljs.registerLanguage('csharp', csharpHljs);
|
||||
|
||||
const { value, language, followHeightOf, copyPlacement, copyMessage, downloadFileName, downloadButtonText } = toRefs(props);
|
||||
const { value, language, followHeightOf, copyPlacement, copyMessage } = toRefs(props);
|
||||
const { height } = followHeightOf.value ? useElementSize(followHeightOf) : { height: ref(null) };
|
||||
|
||||
const { copy, isJustCopied } = useCopy({ source: value, createToast: false });
|
||||
const tooltipText = computed(() => isJustCopied.value ? 'Copied!' : copyMessage.value);
|
||||
|
||||
const valueBase64 = computed(() => Base64.encode(value.value));
|
||||
const { download } = useDownloadFileFromBase64(
|
||||
{
|
||||
source: valueBase64,
|
||||
filename: downloadFileName,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -73,16 +49,11 @@ const { download } = useDownloadFileFromBase64(
|
||||
:style="height ? `min-height: ${height - 40 /* card padding */ + 10 /* negative margin compensation */}px` : ''"
|
||||
>
|
||||
<n-config-provider :hljs="hljs">
|
||||
<n-code :code="value" :language="language" :word-wrap="wordWrap" :trim="false" data-test-id="area-content" />
|
||||
<n-code :code="value" :language="language" :trim="false" data-test-id="area-content" />
|
||||
</n-config-provider>
|
||||
</n-scrollbar>
|
||||
<div
|
||||
v-if="value && copyPlacement !== 'none'"
|
||||
absolute right-10px
|
||||
:top-10px="copyPlacement === 'top-right' ? '' : 'no'"
|
||||
:bottom-10px="copyPlacement === 'bottom-right' ? '' : 'no'"
|
||||
>
|
||||
<c-tooltip v-if="value && copyPlacement !== 'outside'" :tooltip="tooltipText" position="left">
|
||||
<div absolute right-10px top-10px>
|
||||
<c-tooltip v-if="value" :tooltip="tooltipText" position="left">
|
||||
<c-button circle important:h-10 important:w-10 @click="copy()">
|
||||
<n-icon size="22" :component="Copy" />
|
||||
</c-button>
|
||||
@@ -94,11 +65,6 @@ const { download } = useDownloadFileFromBase64(
|
||||
{{ tooltipText }}
|
||||
</c-button>
|
||||
</div>
|
||||
<div v-if="downloadFileName !== '' && value !== ''" mt-5 flex justify-center>
|
||||
<c-button secondary @click="download">
|
||||
{{ downloadButtonText }}
|
||||
</c-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { extension as getExtensionFromMimeType, extension as getMimeTypeFromExtension } from 'mime-types';
|
||||
import type { MaybeRef, Ref } from 'vue';
|
||||
import type { Ref } from 'vue';
|
||||
import _ from 'lodash';
|
||||
import { get } from '@vueuse/core';
|
||||
|
||||
export {
|
||||
getMimeTypeFromBase64,
|
||||
@@ -76,11 +75,21 @@ function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }:
|
||||
}
|
||||
|
||||
function useDownloadFileFromBase64(
|
||||
{ source, filename, extension }:
|
||||
{ source: MaybeRef<string>; filename?: MaybeRef<string>; extension?: MaybeRef<string> }) {
|
||||
{ source, filename, extension, fileMimeType }:
|
||||
{ source: Ref<string>; filename?: string; extension?: string; fileMimeType?: string }) {
|
||||
return {
|
||||
download() {
|
||||
downloadFromBase64({ sourceValue: get(source), filename: get(filename), extension: get(extension) });
|
||||
downloadFromBase64({ sourceValue: source.value, filename, extension, fileMimeType });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function useDownloadFileFromBase64Refs(
|
||||
{ source, filename, extension }:
|
||||
{ source: Ref<string>; filename?: Ref<string>; extension?: Ref<string> }) {
|
||||
return {
|
||||
download() {
|
||||
downloadFromBase64({ sourceValue: source.value, filename: filename?.value, extension: extension?.value });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -107,13 +116,3 @@ function previewImageFromBase64(base64String: string): HTMLImageElement {
|
||||
|
||||
return img;
|
||||
}
|
||||
|
||||
function useDownloadFileFromBase64Refs(
|
||||
{ source, filename, extension }:
|
||||
{ source: Ref<string>; filename?: Ref<string>; extension?: Ref<string> }) {
|
||||
return {
|
||||
download() {
|
||||
downloadFromBase64({ sourceValue: source.value, filename: filename?.value, extension: extension?.value });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import { tool as base64FileConverter } from './base64-file-converter';
|
||||
import { tool as base64StringConverter } from './base64-string-converter';
|
||||
import { tool as basicAuthGenerator } from './basic-auth-generator';
|
||||
import { tool as emailNormalizer } from './email-normalizer';
|
||||
import { tool as jwtGenerator } from './jwt-generator';
|
||||
|
||||
import { tool as asciiTextDrawer } from './ascii-text-drawer';
|
||||
|
||||
@@ -131,7 +130,6 @@ export const toolsByCategory: ToolCategory[] = [
|
||||
otpCodeGeneratorAndValidator,
|
||||
mimeTypes,
|
||||
jwtParser,
|
||||
jwtGenerator,
|
||||
keycodeInfo,
|
||||
slugifyString,
|
||||
htmlWysiwygEditor,
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { Key } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: 'JWT Generator',
|
||||
path: '/jwt-generator',
|
||||
description: 'JWT Token generator and editor',
|
||||
keywords: [
|
||||
'jwt',
|
||||
'generator',
|
||||
'editor',
|
||||
'encode',
|
||||
'typ',
|
||||
'alg',
|
||||
'iss',
|
||||
'sub',
|
||||
'aud',
|
||||
'exp',
|
||||
'nbf',
|
||||
'iat',
|
||||
'jti',
|
||||
'json',
|
||||
'web',
|
||||
'token',
|
||||
],
|
||||
component: () => import('./jwt-generator.vue'),
|
||||
icon: Key,
|
||||
createdAt: new Date('2024-08-15'),
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
export const jwsAlgorithms = [
|
||||
{ alg: 'HS256', keyDesc: '256 bit (32 byte) secret', key: 'secret', verify: 'HMAC-SHA256' },
|
||||
{ alg: 'HS384', keyDesc: '384 bit (48 byte) secret', key: 'secret', verify: 'HMAC-SHA384' },
|
||||
{ alg: 'HS512', keyDesc: '512 bit (64 byte) secret', key: 'secret', verify: 'HMAC-SHA512' },
|
||||
{ alg: 'ES256', keyDesc: 'NIST P-256 elliptic curve key', key: 'keyspair', verify: 'ECDSA-SHA256' },
|
||||
{ alg: 'ES256K', keyDesc: 'secp256k1 elliptic curve key', key: 'keyspair', verify: 'ECDSA-SHA256(secp256k1)' },
|
||||
{ alg: 'ES384', keyDesc: 'NIST P-384 elliptic curve key', key: 'keyspair', verify: 'ECDSA-SHA384' },
|
||||
{ alg: 'ES512', keyDesc: 'NIST P-521 elliptic curve key', key: 'keyspair', verify: 'ECDSA-SHA512' },
|
||||
{ alg: 'PS256', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-PSS-SHA256' },
|
||||
{ alg: 'PS384', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-PSS-SHA384' },
|
||||
{ alg: 'PS512', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-PSS-SHA512' },
|
||||
{ alg: 'RS256', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-SHA256' },
|
||||
{ alg: 'RS384', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-SHA384' },
|
||||
{ alg: 'RS512', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-SHA512' },
|
||||
];
|
||||
@@ -1,187 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import * as jose from 'jose';
|
||||
import { type KeyLike } from 'jose';
|
||||
import JSON5 from 'json5';
|
||||
import { jwsAlgorithms } from './jwt-generator.constants';
|
||||
import { useValidation } from '@/composable/validation';
|
||||
import { useQueryParamOrStorage } from '@/composable/queryParams';
|
||||
|
||||
const payload = ref(`{
|
||||
"sub": "1234567890",
|
||||
"name": "John Doe",
|
||||
"iat": 1516239022
|
||||
}`);
|
||||
|
||||
const alg = useQueryParamOrStorage({ name: 'alg', storageName: 'jwt-gen:alg', defaultValue: 'HS512' });
|
||||
const algInfo = computed(() => jwsAlgorithms.find(a => a.alg === alg.value) || { alg: 'UNK', keyDesc: '', key: 'secret', verify: '' });
|
||||
const isSecret = computed(() => algInfo.value.key === 'secret');
|
||||
|
||||
const secret = ref('');
|
||||
|
||||
const publicKeyPEM = ref('');
|
||||
const publicKeyJWK = ref('');
|
||||
const privateKeyJWK = ref('');
|
||||
const privateKeyPEM = ref('');
|
||||
|
||||
watch(publicKeyPEM, async (newValue) => {
|
||||
try {
|
||||
publicKeyJWK.value = JSON.stringify(await jose.exportJWK(await jose.importSPKI(newValue, alg.value, { extractable: true })), null, 2);
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}, { immediate: true });
|
||||
watch(privateKeyPEM, async (newValue) => {
|
||||
try {
|
||||
privateKeyJWK.value = JSON.stringify(await jose.exportJWK(await jose.importPKCS8(newValue, alg.value, { extractable: true })), null, 2);
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}, { immediate: true });
|
||||
watch(publicKeyJWK, async (newValue) => {
|
||||
try {
|
||||
publicKeyPEM.value = await jose.exportSPKI(await jose.importJWK({ ...JSON.parse(newValue), ...{ ext: true } }, alg.value) as KeyLike);
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}, { immediate: true });
|
||||
watch(privateKeyJWK, async (newValue) => {
|
||||
try {
|
||||
privateKeyPEM.value = await jose.exportPKCS8(await jose.importJWK({ ...JSON.parse(newValue), ...{ ext: true } }, alg.value) as KeyLike);
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}, { immediate: true });
|
||||
|
||||
watchEffect(async () => {
|
||||
if (isSecret.value) {
|
||||
secret.value = 'your-secret';
|
||||
privateKeyJWK.value = '';
|
||||
publicKeyJWK.value = '';
|
||||
privateKeyPEM.value = '';
|
||||
publicKeyPEM.value = '';
|
||||
}
|
||||
else {
|
||||
const { publicKey, privateKey } = await jose.generateKeyPair(alg.value, { extractable: true });
|
||||
privateKeyJWK.value = JSON.stringify(await jose.exportJWK(privateKey), null, 2);
|
||||
publicKeyJWK.value = JSON.stringify(await jose.exportJWK(publicKey), null, 2);
|
||||
privateKeyPEM.value = await jose.exportPKCS8(privateKey);
|
||||
publicKeyPEM.value = await jose.exportSPKI(publicKey);
|
||||
}
|
||||
});
|
||||
|
||||
const header = computed(() => JSON.stringify({ alg: alg.value, typ: 'JWT' }, null, 2));
|
||||
const encodedJWT = computedAsync(async () => {
|
||||
const isSecretValue = isSecret.value;
|
||||
const secretValue = secret.value;
|
||||
const privateKeyValue = privateKeyJWK.value;
|
||||
const algValue = alg.value;
|
||||
const payloadValue = payload.value;
|
||||
try {
|
||||
let privateKeyOrSecret;
|
||||
if (isSecretValue) {
|
||||
privateKeyOrSecret = new TextEncoder().encode(secretValue);
|
||||
}
|
||||
else {
|
||||
privateKeyOrSecret = await jose.importJWK(JSON.parse(privateKeyValue), algValue);
|
||||
}
|
||||
return {
|
||||
token: await (new jose.SignJWT(JSON5.parse(payloadValue))
|
||||
.setProtectedHeader({ alg: algValue })
|
||||
.sign(privateKeyOrSecret)),
|
||||
error: '',
|
||||
};
|
||||
}
|
||||
catch (e: any) {
|
||||
return { error: e.toString(), token: '' };
|
||||
}
|
||||
});
|
||||
|
||||
const jsonInputValidation = useValidation({
|
||||
source: payload,
|
||||
rules: [
|
||||
{
|
||||
message: 'Invalid JSON string',
|
||||
validator: value => JSON5.parse(value),
|
||||
},
|
||||
],
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<c-select
|
||||
v-model:value="alg"
|
||||
:options="jwsAlgorithms.map(a => ({ value: a.alg, label: `${a.alg}: ${a.verify}` }))"
|
||||
placeholder="Algorithms"
|
||||
mb-2
|
||||
/>
|
||||
<n-form-item label="Description:" label-placement="left" mb-2>
|
||||
{{ algInfo.alg }}: {{ algInfo.keyDesc }} (verify with {{ algInfo.verify }})
|
||||
</n-form-item>
|
||||
|
||||
<c-card title="Token Content" mb-2>
|
||||
<n-form-item label="Header:">
|
||||
<textarea-copyable :value="header" language="json" />
|
||||
</n-form-item>
|
||||
|
||||
<c-input-text
|
||||
v-model:value="payload"
|
||||
label="Payload:"
|
||||
multiline
|
||||
rows="5"
|
||||
autosize
|
||||
placeholder="JSON payload"
|
||||
:validation="jsonInputValidation"
|
||||
/>
|
||||
</c-card>
|
||||
|
||||
<c-card :title="isSecret ? 'Token Secret' : 'Token Keys'" mb-2>
|
||||
<c-input-text v-if="isSecret" v-model:value="secret" />
|
||||
|
||||
<div v-if="!isSecret">
|
||||
<n-form-item label="Public Key (PEM):">
|
||||
<c-input-text
|
||||
v-model:value="publicKeyPEM"
|
||||
multiline
|
||||
rows="5"
|
||||
autosize
|
||||
/>
|
||||
</n-form-item>
|
||||
<n-form-item label="Private Key (PEM):">
|
||||
<c-input-text
|
||||
v-model:value="privateKeyPEM"
|
||||
multiline
|
||||
rows="5"
|
||||
autosize
|
||||
/>
|
||||
</n-form-item>
|
||||
|
||||
<n-divider />
|
||||
|
||||
<n-form-item label="Public Key (JWK):">
|
||||
<c-input-text
|
||||
v-model:value="publicKeyJWK"
|
||||
multiline
|
||||
rows="5"
|
||||
autosize
|
||||
/>
|
||||
</n-form-item>
|
||||
<n-form-item label="Private Key (JWK):">
|
||||
<c-input-text
|
||||
v-model:value="privateKeyJWK"
|
||||
multiline
|
||||
rows="5"
|
||||
autosize
|
||||
/>
|
||||
</n-form-item>
|
||||
</div>
|
||||
</c-card>
|
||||
|
||||
<c-card v-if="encodedJWT" title="Generated JWT Token:" mb-2>
|
||||
<textarea-copyable v-if="encodedJWT.token" :value="encodedJWT.token" word-wrap />
|
||||
<c-alert v-if="encodedJWT.error">
|
||||
{{ encodedJWT.error }}
|
||||
</c-alert>
|
||||
</c-card>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Key } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: 'JWT parser',
|
||||
name: translate('tools.jwt-parser.title'),
|
||||
path: '/jwt-parser',
|
||||
description: 'Parse and decode your JSON Web Token (jwt) and display its content.',
|
||||
description: translate('tools.jwt-parser.description'),
|
||||
keywords: [
|
||||
'jwt',
|
||||
'parser',
|
||||
|
||||
@@ -2,11 +2,7 @@ import jwtDecode, { type JwtHeader, type JwtPayload } from 'jwt-decode';
|
||||
import _ from 'lodash';
|
||||
import { ALGORITHM_DESCRIPTIONS, CLAIM_DESCRIPTIONS } from './jwt-parser.constants';
|
||||
|
||||
export { decodeJwt, getJwtAlgorithm };
|
||||
|
||||
function getJwtAlgorithm({ jwt }: { jwt: string }) {
|
||||
return jwtDecode<JwtHeader>(jwt, { header: true }).alg;
|
||||
}
|
||||
export { decodeJwt };
|
||||
|
||||
function decodeJwt({ jwt }: { jwt: string }) {
|
||||
const rawHeader = jwtDecode<JwtHeader>(jwt, { header: true });
|
||||
@@ -23,7 +19,7 @@ function decodeJwt({ jwt }: { jwt: string }) {
|
||||
|
||||
function parseClaims({ claim, value }: { claim: string; value: unknown }) {
|
||||
const claimDescription = CLAIM_DESCRIPTIONS[claim];
|
||||
const formattedValue = _.isPlainObject(value) ? JSON.stringify(value, null, 3) : _.toString(value);
|
||||
const formattedValue = _.isPlainObject(value) || _.isArray(value) ? JSON.stringify(value, null, 3) : _.toString(value);
|
||||
const friendlyValue = getFriendlyValue({ claim, value });
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import * as jose from 'jose';
|
||||
import JSON5 from 'json5';
|
||||
import { decodeJwt, getJwtAlgorithm } from './jwt-parser.service';
|
||||
import { decodeJwt } from './jwt-parser.service';
|
||||
import { useValidation } from '@/composable/validation';
|
||||
import { isNotThrowing } from '@/utils/boolean';
|
||||
import { withDefaultOnError } from '@/utils/defaults';
|
||||
@@ -28,41 +26,6 @@ const validation = useValidation({
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const secretOrPublicKey = ref('');
|
||||
const signatureVerification = computedAsync(async () => {
|
||||
const secretOrPublicKeyValue = secretOrPublicKey.value?.trim();
|
||||
if (!secretOrPublicKeyValue) {
|
||||
return { error: 'No secret or key provided' };
|
||||
}
|
||||
const jwt = rawJwt.value?.trim();
|
||||
if (!jwt) {
|
||||
return { error: 'No JWT token provided' };
|
||||
}
|
||||
try {
|
||||
const alg = getJwtAlgorithm({ jwt }) || 'unk';
|
||||
|
||||
if (secretOrPublicKeyValue.startsWith('{')) {
|
||||
const jwk = JSON5.parse(secretOrPublicKeyValue);
|
||||
const publicKey = await jose.importJWK(jwk, alg);
|
||||
|
||||
await jose.jwtVerify(jwt, publicKey);
|
||||
}
|
||||
else if (secretOrPublicKeyValue.includes('-----BEGIN PUBLIC KEY-----')) {
|
||||
const publicKey = await jose.importSPKI(secretOrPublicKeyValue, alg);
|
||||
await jose.jwtVerify(jwt, publicKey);
|
||||
}
|
||||
else {
|
||||
const secret = new TextEncoder().encode(secretOrPublicKeyValue);
|
||||
await jose.jwtVerify(jwt, secret);
|
||||
}
|
||||
|
||||
return { error: '' };
|
||||
}
|
||||
catch (e: any) {
|
||||
return { error: `Key or secret or verification error: ${e.toString()}` };
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -76,7 +39,7 @@ const signatureVerification = computedAsync(async () => {
|
||||
{{ section.title }}
|
||||
</th>
|
||||
<tr v-for="{ claim, claimDescription, friendlyValue, value } in decodedJWT[section.key]" :key="claim + value">
|
||||
<td class="claims">
|
||||
<td class="claims" style="vertical-align: top;">
|
||||
<span font-bold>
|
||||
{{ claim }}
|
||||
</span>
|
||||
@@ -84,7 +47,7 @@ const signatureVerification = computedAsync(async () => {
|
||||
({{ claimDescription }})
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<td style="word-wrap: break-word;word-break: break-all;">
|
||||
<span>{{ value }}</span>
|
||||
<span v-if="friendlyValue" ml-2 op-70>
|
||||
({{ friendlyValue }})
|
||||
@@ -94,21 +57,6 @@ const signatureVerification = computedAsync(async () => {
|
||||
</template>
|
||||
</tbody>
|
||||
</n-table>
|
||||
|
||||
<c-card title="Signature Validation">
|
||||
<c-input-text
|
||||
v-model:value="secretOrPublicKey" label="Secret or Public Key (SPKI or JWK)"
|
||||
placeholder="Put your secret or Public key here..." rows="5" multiline raw-text autofocus mb-3
|
||||
/>
|
||||
|
||||
<c-alert v-if="signatureVerification?.error">
|
||||
{{ signatureVerification.error }}
|
||||
</c-alert>
|
||||
|
||||
<n-alert v-if="!signatureVerification?.error" type="success">
|
||||
Signature verified
|
||||
</n-alert>
|
||||
</c-card>
|
||||
</c-card>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test.describe('Tool - Text to ASCII binary', () => {
|
||||
test.describe('Tool - Text to UTF-8 binary', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/text-to-binary');
|
||||
});
|
||||
|
||||
test('Has correct title', async ({ page }) => {
|
||||
await expect(page).toHaveTitle('Text to ASCII binary - IT Tools');
|
||||
await expect(page).toHaveTitle('Text to UTF-8 binary - IT Tools');
|
||||
});
|
||||
|
||||
test('Text to binary conversion', async ({ page }) => {
|
||||
@@ -17,7 +17,9 @@ test.describe('Tool - Text to ASCII binary', () => {
|
||||
});
|
||||
|
||||
test('Binary to text conversion', async ({ page }) => {
|
||||
await page.getByTestId('binary-to-text-input').fill('01101001 01110100 00101101 01110100 01101111 01101111 01101100 01110011');
|
||||
await page
|
||||
.getByTestId('binary-to-text-input')
|
||||
.fill('01101001 01110100 00101101 01110100 01101111 01101111 01101100 01110011');
|
||||
const text = await page.getByTestId('binary-to-text-output').inputValue();
|
||||
|
||||
expect(text).toEqual('it-tools');
|
||||
|
||||
@@ -1,32 +1,103 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { convertAsciiBinaryToText, convertTextToAsciiBinary } from './text-to-binary.models';
|
||||
import { convertTextToUtf8Binary, convertUtf8BinaryToText } from './text-to-binary.models';
|
||||
|
||||
describe('text-to-binary', () => {
|
||||
describe('convertTextToAsciiBinary', () => {
|
||||
it('a text string is converted to its ascii binary representation', () => {
|
||||
expect(convertTextToAsciiBinary('A')).toBe('01000001');
|
||||
expect(convertTextToAsciiBinary('hello')).toBe('01101000 01100101 01101100 01101100 01101111');
|
||||
expect(convertTextToAsciiBinary('')).toBe('');
|
||||
const utf8Tests = [
|
||||
{
|
||||
text: '文字',
|
||||
binary: '11100110 10010110 10000111 11100101 10101101 10010111',
|
||||
decimal: '',
|
||||
octal: '',
|
||||
hex: '',
|
||||
},
|
||||
{
|
||||
text: '💩',
|
||||
binary: '11110000 10011111 10010010 10101001',
|
||||
decimal: '',
|
||||
octal: '',
|
||||
hex: '',
|
||||
},
|
||||
];
|
||||
|
||||
describe('convertTextToUtf8Binary', () => {
|
||||
it('a text string is converted to its UTF-8 binary representation', () => {
|
||||
expect(convertTextToUtf8Binary('A')).toBe('01000001');
|
||||
expect(convertTextToUtf8Binary('A', { base: 8 })).toBe('0101');
|
||||
expect(convertTextToUtf8Binary('A', { base: 10 })).toBe('65');
|
||||
expect(convertTextToUtf8Binary('A', { base: 16 })).toBe('41');
|
||||
expect(convertTextToUtf8Binary('hello')).toBe('01101000 01100101 01101100 01101100 01101111');
|
||||
expect(convertTextToUtf8Binary('hello', { base: 8 })).toBe('0150 0145 0154 0154 0157');
|
||||
expect(convertTextToUtf8Binary('hello', { base: 10 })).toBe('104 101 108 108 111');
|
||||
expect(convertTextToUtf8Binary('hello', { base: 16 })).toBe('68 65 6c 6c 6f');
|
||||
expect(convertTextToUtf8Binary('')).toBe('');
|
||||
});
|
||||
it('the separator between octets can be changed', () => {
|
||||
expect(convertTextToAsciiBinary('hello', { separator: '' })).toBe('0110100001100101011011000110110001101111');
|
||||
expect(convertTextToUtf8Binary('hello', { separator: '' })).toBe('0110100001100101011011000110110001101111');
|
||||
expect(convertTextToUtf8Binary('hello', { separator: '-' })).toBe('01101000-01100101-01101100-01101100-01101111');
|
||||
expect(convertTextToUtf8Binary('hello', { separator: '-', base: 16 })).toBe('68-65-6c-6c-6f');
|
||||
});
|
||||
it('works with non-ASCII input', () => {
|
||||
for (const { text, binary } of utf8Tests) {
|
||||
const converted = convertTextToUtf8Binary(text);
|
||||
expect(converted).toBe(binary);
|
||||
}
|
||||
|
||||
expect(convertTextToUtf8Binary('💩 A', { base: 2 })).toBe('11110000 10011111 10010010 10101001 00100000 01000001');
|
||||
expect(convertTextToUtf8Binary('💩 A', { base: 8 })).toBe('0360 0237 0222 0251 040 0101');
|
||||
expect(convertTextToUtf8Binary('💩 A', { base: 10 })).toBe('240 159 146 169 32 65');
|
||||
expect(convertTextToUtf8Binary('💩 A', { base: 16 })).toBe('f0 9f 92 a9 20 41');
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertAsciiBinaryToText', () => {
|
||||
describe('convertUtf8BinaryToText', () => {
|
||||
it('an ascii binary string is converted to its text representation', () => {
|
||||
expect(convertAsciiBinaryToText('01101000 01100101 01101100 01101100 01101111')).toBe('hello');
|
||||
expect(convertAsciiBinaryToText('01000001')).toBe('A');
|
||||
expect(convertTextToAsciiBinary('')).toBe('');
|
||||
expect(convertUtf8BinaryToText('01101000 01100101 01101100 01101100 01101111')).toBe('hello');
|
||||
expect(convertUtf8BinaryToText('01101000 01100101 01101100 01101100 01101111', { base: 2 })).toBe('hello');
|
||||
expect(convertUtf8BinaryToText('0150 0145 0154 0154 0157', { base: 8 })).toBe('hello');
|
||||
expect(convertUtf8BinaryToText('104 101 108 108 111', { base: 10 })).toBe('hello');
|
||||
expect(convertUtf8BinaryToText('68 65 6c 6c 6f', { base: 16 })).toBe('hello');
|
||||
|
||||
expect(convertUtf8BinaryToText('11110000 10011111 10010010 10101001 00100000 01000001', { base: 2 })).toBe('💩 A');
|
||||
expect(convertUtf8BinaryToText('0360 0237 0222 0251 040 0101', { base: 8 })).toBe('💩 A');
|
||||
expect(convertUtf8BinaryToText('240 159 146 169 32 65', { base: 10 })).toBe('💩 A');
|
||||
expect(convertUtf8BinaryToText('f0 9f 92 a9 20 41', { base: 16 })).toBe('💩 A');
|
||||
|
||||
expect(convertUtf8BinaryToText('')).toBe('');
|
||||
|
||||
expect(convertUtf8BinaryToText('01000001')).toBe('A');
|
||||
expect(convertUtf8BinaryToText('0101', { base: 8 })).toBe('A');
|
||||
expect(convertUtf8BinaryToText('65', { base: 10 })).toBe('A');
|
||||
expect(convertUtf8BinaryToText('41', { base: 16 })).toBe('A');
|
||||
});
|
||||
|
||||
it('the given binary string is cleaned before conversion', () => {
|
||||
expect(convertAsciiBinaryToText(' 01000 001garbage')).toBe('A');
|
||||
it('the given string is cleaned before conversion', () => {
|
||||
expect(convertUtf8BinaryToText(' 01000 001garbage')).toBe('A');
|
||||
expect(convertUtf8BinaryToText(' 65garbage', { base: 10 })).toBe('A');
|
||||
expect(convertUtf8BinaryToText(' 41xxxx', { base: 16 })).toBe('A');
|
||||
});
|
||||
|
||||
it('throws an error if the given binary string as no complete octet', () => {
|
||||
expect(() => convertAsciiBinaryToText('010000011')).toThrow('Invalid binary string');
|
||||
expect(() => convertAsciiBinaryToText('1')).toThrow('Invalid binary string');
|
||||
it('throws an error if the given binary string is not an integer number of complete octets', () => {
|
||||
expect(() => convertUtf8BinaryToText('010000011')).toThrow('Invalid binary string');
|
||||
expect(() => convertUtf8BinaryToText('010000011 010000011')).toThrow('Invalid binary string');
|
||||
expect(() => convertUtf8BinaryToText('1')).toThrow('Invalid binary string');
|
||||
});
|
||||
|
||||
it('throws an error if the given binary string is not valid UTF-8', () => {
|
||||
expect(() => convertUtf8BinaryToText('11111111')).toThrow();
|
||||
});
|
||||
|
||||
it('the given string is cleaned from prefix before conversion', () => {
|
||||
expect(convertUtf8BinaryToText('0b01000001')).toBe('A');
|
||||
expect(convertUtf8BinaryToText('0x41', { base: 16 })).toBe('A');
|
||||
expect(convertUtf8BinaryToText('0x68 0x65 0x6c 0x6c 0x6f', { base: 16 })).toBe('hello');
|
||||
expect(convertUtf8BinaryToText('\\x68\\x65\\x6c\\x6c\\x6f', { base: 16 })).toBe('hello');
|
||||
});
|
||||
|
||||
it('works with non-ASCII input', () => {
|
||||
for (const { text, binary } of utf8Tests) {
|
||||
const reverted = convertUtf8BinaryToText(binary);
|
||||
expect(reverted).toBe(text);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,22 +1,67 @@
|
||||
export { convertTextToAsciiBinary, convertAsciiBinaryToText };
|
||||
export { convertTextToUtf8Binary, convertUtf8BinaryToText };
|
||||
|
||||
function convertTextToAsciiBinary(text: string, { separator = ' ' }: { separator?: string } = {}): string {
|
||||
return text
|
||||
.split('')
|
||||
.map(char => char.charCodeAt(0).toString(2).padStart(8, '0'))
|
||||
.join(separator);
|
||||
}
|
||||
export type EncodingBase = 2 | 8 | 10 | 16;
|
||||
|
||||
function convertAsciiBinaryToText(binary: string): string {
|
||||
const cleanBinary = binary.replace(/[^01]/g, '');
|
||||
|
||||
if (cleanBinary.length % 8) {
|
||||
throw new Error('Invalid binary string');
|
||||
function convertTextToUtf8Binary(text: string, { separator = ' ', base = 2 }: { separator?: string; base?: EncodingBase } = {}): string {
|
||||
if (!text?.trim()) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return cleanBinary
|
||||
.split(/(\d{8})/)
|
||||
.filter(Boolean)
|
||||
.map(binary => String.fromCharCode(Number.parseInt(binary, 2)))
|
||||
.join('');
|
||||
return [...new TextEncoder().encode(text)].map((char) => {
|
||||
const charInBase = char.toString(base);
|
||||
if (base === 2) {
|
||||
return charInBase.padStart(8, '0');
|
||||
}
|
||||
if (base === 8) {
|
||||
return `0${charInBase}`;
|
||||
}
|
||||
if (base === 16) {
|
||||
return charInBase.padStart(2, '0');
|
||||
}
|
||||
|
||||
return charInBase;
|
||||
}).join(separator);
|
||||
}
|
||||
|
||||
function convertUtf8BinaryToText(binary: string, { base = 2 }: { base?: EncodingBase } = {}): string {
|
||||
if (!binary?.trim()) {
|
||||
return '';
|
||||
}
|
||||
|
||||
let codepoints: number[] = [];
|
||||
if (base === 2) {
|
||||
const cleanBinary = binary.replace(/0b/g, '').replace(/[^01]/g, '').trim();
|
||||
|
||||
if (cleanBinary.length % 8) {
|
||||
throw new Error('Invalid binary string');
|
||||
}
|
||||
|
||||
codepoints = cleanBinary
|
||||
.split(/([01]{8})/)
|
||||
.filter(Boolean)
|
||||
.map(binary => Number.parseInt(binary, 2));
|
||||
}
|
||||
else if (base === 16) {
|
||||
const cleanBinary = binary.replace(/0x|\\x/g, '').replace(/[^0-9A-Fa-f]/g, '');
|
||||
|
||||
if (cleanBinary.length % 2) {
|
||||
throw new Error('Invalid hexadecimal string');
|
||||
}
|
||||
|
||||
codepoints = cleanBinary
|
||||
.split(/([0-9A-Fa-f]{2})/)
|
||||
.filter(Boolean)
|
||||
.map(binary => Number.parseInt(binary, 16));
|
||||
}
|
||||
else {
|
||||
const cleanBinary = binary.replace(/0o/g, '').replace(/[^\d\s]/g, '');
|
||||
codepoints = cleanBinary
|
||||
.split(/\s/)
|
||||
.filter(Boolean)
|
||||
.map(binary => Number.parseInt(binary, base));
|
||||
}
|
||||
|
||||
return new TextDecoder(undefined, { fatal: true }).decode(
|
||||
Uint8Array.from(codepoints),
|
||||
);
|
||||
}
|
||||
@@ -1,42 +1,95 @@
|
||||
<script setup lang="ts">
|
||||
import { convertAsciiBinaryToText, convertTextToAsciiBinary } from './text-to-binary.models';
|
||||
import { type EncodingBase, convertTextToUtf8Binary, convertUtf8BinaryToText } from './text-to-binary.models';
|
||||
import { withDefaultOnError } from '@/utils/defaults';
|
||||
import { useCopy } from '@/composable/copy';
|
||||
import { isNotThrowing } from '@/utils/boolean';
|
||||
import { useQueryParamOrStorage } from '@/composable/queryParams';
|
||||
|
||||
const base = useQueryParamOrStorage({ name: 'base', storageName: 'txt-bin:base', defaultValue: '2' });
|
||||
const inputText = ref('');
|
||||
const binaryFromText = computed(() => convertTextToAsciiBinary(inputText.value));
|
||||
const binaryFromText = computed(() => convertTextToUtf8Binary(inputText.value, { base: Number(base.value) as EncodingBase }));
|
||||
const { copy: copyBinary } = useCopy({ source: binaryFromText });
|
||||
|
||||
const inputBinary = ref('');
|
||||
const textFromBinary = computed(() => withDefaultOnError(() => convertAsciiBinaryToText(inputBinary.value), ''));
|
||||
const textFromBinary = computed(() => withDefaultOnError(() => convertUtf8BinaryToText(inputBinary.value, { base: Number(base.value) as EncodingBase }), ''));
|
||||
const inputBinaryValidationRules = [
|
||||
{
|
||||
validator: (value: string) => isNotThrowing(() => convertAsciiBinaryToText(value)),
|
||||
message: 'Binary should be a valid ASCII binary string with multiples of 8 bits',
|
||||
validator: (value: string) => isNotThrowing(() => convertUtf8BinaryToText(value)),
|
||||
message: 'Binary should be a valid UTF-8 binary string with multiples of 8 bits',
|
||||
},
|
||||
];
|
||||
const { copy: copyText } = useCopy({ source: textFromBinary });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card title="Text to ASCII binary">
|
||||
<c-input-text v-model:value="inputText" multiline placeholder="e.g. 'Hello world'" label="Enter text to convert to binary" autosize autofocus raw-text test-id="text-to-binary-input" />
|
||||
<c-input-text v-model:value="binaryFromText" label="Binary from your text" multiline raw-text readonly mt-2 placeholder="The binary representation of your text will be here" test-id="text-to-binary-output" />
|
||||
<div mt-2 flex justify-center>
|
||||
<c-button :disabled="!binaryFromText" @click="copyBinary()">
|
||||
Copy binary to clipboard
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
<div>
|
||||
<c-select
|
||||
v-model:value="base"
|
||||
label="Conversion Base:"
|
||||
label-position="left"
|
||||
mb-2
|
||||
:options="[
|
||||
{ value: '2', label: 'Binary' },
|
||||
{ value: '8', label: 'Octal' },
|
||||
{ value: '10', label: 'Decimal' },
|
||||
{ value: '16', label: 'Hexadecimal' },
|
||||
]"
|
||||
/>
|
||||
|
||||
<c-card title="ASCII binary to text">
|
||||
<c-input-text v-model:value="inputBinary" multiline placeholder="e.g. '01001000 01100101 01101100 01101100 01101111'" label="Enter binary to convert to text" autosize raw-text :validation-rules="inputBinaryValidationRules" test-id="binary-to-text-input" />
|
||||
<c-input-text v-model:value="textFromBinary" label="Text from your binary" multiline raw-text readonly mt-2 placeholder="The text representation of your binary will be here" test-id="binary-to-text-output" />
|
||||
<div mt-2 flex justify-center>
|
||||
<c-button :disabled="!textFromBinary" @click="copyText()">
|
||||
Copy text to clipboard
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
<c-card title="Text to UTF-8 binary">
|
||||
<c-input-text
|
||||
v-model:value="inputText"
|
||||
multiline
|
||||
placeholder="e.g. 'Hello world'"
|
||||
label="Enter text to convert to binary"
|
||||
autosize
|
||||
autofocus
|
||||
raw-text
|
||||
test-id="text-to-binary-input"
|
||||
/>
|
||||
<c-input-text
|
||||
v-model:value="binaryFromText"
|
||||
label="Binary from your text"
|
||||
multiline
|
||||
raw-text
|
||||
readonly
|
||||
mt-2
|
||||
placeholder="The binary representation of your text will be here"
|
||||
test-id="text-to-binary-output"
|
||||
/>
|
||||
<div mt-2 flex justify-center>
|
||||
<c-button :disabled="!binaryFromText" @click="copyBinary()">
|
||||
Copy binary to clipboard
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
|
||||
<c-card title="UTF-8 binary to text">
|
||||
<c-input-text
|
||||
v-model:value="inputBinary"
|
||||
multiline
|
||||
placeholder="e.g. '01001000 01100101 01101100 01101100 01101111'"
|
||||
label="Enter binary to convert to text"
|
||||
autosize
|
||||
raw-text
|
||||
:validation-rules="inputBinaryValidationRules"
|
||||
test-id="binary-to-text-input"
|
||||
/>
|
||||
<c-input-text
|
||||
v-model:value="textFromBinary"
|
||||
label="Text from your binary"
|
||||
multiline
|
||||
raw-text
|
||||
readonly
|
||||
mt-2
|
||||
placeholder="The text representation of your binary will be here"
|
||||
test-id="binary-to-text-output"
|
||||
/>
|
||||
<div mt-2 flex justify-center>
|
||||
<c-button :disabled="!textFromBinary" @click="copyText()">
|
||||
Copy text to clipboard
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
</div>
|
||||
</template>
|
||||
@@ -10,16 +10,18 @@ test.describe('Tool - Text to Unicode', () => {
|
||||
});
|
||||
|
||||
test('Text to unicode conversion', async ({ page }) => {
|
||||
await page.getByTestId('text-to-unicode-input').fill('it-tools');
|
||||
await page.getByTestId('text-to-unicode-input').fill('"it-tools" 文字');
|
||||
const unicode = await page.getByTestId('text-to-unicode-output').inputValue();
|
||||
|
||||
expect(unicode).toEqual('it-tools');
|
||||
// eslint-disable-next-line unicorn/escape-case
|
||||
expect(unicode).toEqual(String.raw`\u0022it-tools\u0022 \u6587\u5b57`);
|
||||
});
|
||||
|
||||
test('Unicode to text conversion', async ({ page }) => {
|
||||
await page.getByTestId('unicode-to-text-input').fill('it-tools');
|
||||
// eslint-disable-next-line unicorn/escape-case
|
||||
await page.getByTestId('unicode-to-text-input').fill(String.raw`\u0022it-tools\u0022 \u6587\u5b57`);
|
||||
const text = await page.getByTestId('unicode-to-text-output').inputValue();
|
||||
|
||||
expect(text).toEqual('it-tools');
|
||||
expect(text).toEqual('"it-tools" 文字');
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,18 @@ describe('text-to-unicode', () => {
|
||||
describe('convertTextToUnicode', () => {
|
||||
it('a text string is converted to unicode representation', () => {
|
||||
expect(convertTextToUnicode('A')).toBe('A');
|
||||
expect(convertTextToUnicode('linke the string convert to unicode')).toBe('linke the string convert to unicode');
|
||||
expect(convertTextToUnicode('💩 AĀ')).toBe('💩 AĀ');
|
||||
expect(convertTextToUnicode('💩 AĀ', { encoding: 'antiuni' })).toBe('\\u1f4a9\\u20\\u41\\u0100');
|
||||
expect(convertTextToUnicode('💩 AĀ', { encoding: 'css' })).toBe('\\01f4a9\\000020\\000041\\000100');
|
||||
expect(convertTextToUnicode('💩 AĀ', { encoding: 'htmldec' })).toBe('💩 AĀ');
|
||||
expect(convertTextToUnicode('💩 AĀ', { encoding: 'htmlhex' })).toBe('💩 AĀ');
|
||||
expect(convertTextToUnicode('💩 AĀ', { encoding: 'uniplus' })).toBe('U+1f4a9 U+00020 U+00041 U+00100');
|
||||
expect(convertTextToUnicode('💩 AĀ', { encoding: 'python' })).toBe('\\U1f4a9\\x20\\x41\\u0100');
|
||||
expect(convertTextToUnicode('💩 AĀ', { encoding: 'js' })).toBe('\\u{1f4a9}\\u0020\\u0041\\u0100');
|
||||
expect(convertTextToUnicode('💩 AĀ', { encoding: 'utf16' })).toBe('\\ud83d\\udca9\\u0020\\u0041\\u0100');
|
||||
expect(convertTextToUnicode('💩 hello AĀ', { skipAscii: true })).toBe('💩 hello AĀ');
|
||||
expect(convertTextToUnicode('linke the string convert to unicode')).toBe(
|
||||
'linke the string convert to unicode');
|
||||
expect(convertTextToUnicode('')).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -13,6 +24,16 @@ describe('text-to-unicode', () => {
|
||||
describe('convertUnicodeToText', () => {
|
||||
it('an unicode string is converted to its text representation', () => {
|
||||
expect(convertUnicodeToText('A')).toBe('A');
|
||||
expect(convertUnicodeToText('\\u1f4a9\\u20\\u41\\u0100')).toBe('💩 AĀ');
|
||||
expect(convertUnicodeToText('\\01f4a9\\000020\\000041\\000100')).toBe('💩 AĀ');
|
||||
expect(convertUnicodeToText('💩 AĀ')).toBe('💩 AĀ');
|
||||
expect(convertUnicodeToText('💩 AĀ')).toBe('💩 AĀ');
|
||||
expect(convertUnicodeToText('U+1f4a9 U+00020 U+00041 U+00100')).toBe('💩 AĀ');
|
||||
expect(convertUnicodeToText('\\U1f4a9\\x20\\x41\\u0100')).toBe('💩 AĀ');
|
||||
expect(convertUnicodeToText('\\u{1f4a9}\\u0020\\u0041\\u0100')).toBe('💩 AĀ');
|
||||
expect(convertUnicodeToText('\\ud83d\\udca9\\u0020\\u0041\\u0100')).toBe('💩 AĀ');
|
||||
expect(convertUnicodeToText('\\01f4a9 AĀ')).toBe('💩 AĀ');
|
||||
expect(convertUnicodeToText('💩 hello AĀ')).toBe('💩 hello AĀ');
|
||||
expect(convertUnicodeToText('linke the string convert to unicode')).toBe('linke the string convert to unicode');
|
||||
expect(convertUnicodeToText('')).toBe('');
|
||||
});
|
||||
|
||||
@@ -1,9 +1,66 @@
|
||||
function convertTextToUnicode(text: string): string {
|
||||
return text.split('').map(value => `&#${value.charCodeAt(0)};`).join('');
|
||||
export type Encoding = 'htmldec' | 'htmlhex' | 'uniplus' | 'antiuni' | 'css' | 'python' | 'js' | 'utf16';
|
||||
|
||||
const ALL_PRINTABLE_ASCII = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
|
||||
|
||||
function convertTextToUnicode(text: string, { encoding = 'htmldec', skipAscii = false }: { encoding?: Encoding; skipAscii?: boolean } = {}): string {
|
||||
let prefix: (value: number) => string;
|
||||
let suffix: (value: number) => string = () => '';
|
||||
let base = 16;
|
||||
let padding: (value: number) => number = () => 0;
|
||||
let separator = '';
|
||||
let codepoints = [...text];
|
||||
if (encoding === 'htmldec') {
|
||||
prefix = () => '&#';
|
||||
base = 10;
|
||||
suffix = () => ';';
|
||||
}
|
||||
else if (encoding === 'htmlhex') {
|
||||
prefix = () => '&#x';
|
||||
suffix = () => ';';
|
||||
}
|
||||
else if (encoding === 'uniplus') {
|
||||
prefix = () => 'U+';
|
||||
padding = () => 5;
|
||||
separator = ' ';
|
||||
}
|
||||
else if (encoding === 'antiuni') {
|
||||
prefix = () => '\\u';
|
||||
padding = (value: number) => value < 256 ? 2 : 4;
|
||||
}
|
||||
else if (encoding === 'utf16') {
|
||||
prefix = () => '\\u';
|
||||
padding = () => 4;
|
||||
codepoints = text.split('');
|
||||
}
|
||||
else if (encoding === 'python') {
|
||||
prefix = (value: number) => value < 256 ? '\\x' : (value < 65536 ? '\\u' : '\\U');
|
||||
padding = (value: number) => value < 256 ? 2 : 4;
|
||||
}
|
||||
else if (encoding === 'js') {
|
||||
prefix = (value: number) => value < 65536 ? '\\u' : '\\u{';
|
||||
suffix = (value: number) => value < 65536 ? '' : '}';
|
||||
padding = () => 4;
|
||||
}
|
||||
else if (encoding === 'css') {
|
||||
prefix = () => '\\';
|
||||
padding = () => 6;
|
||||
}
|
||||
|
||||
return codepoints.map((value) => {
|
||||
if (skipAscii && ALL_PRINTABLE_ASCII.includes(value)) {
|
||||
return value;
|
||||
}
|
||||
const charCode = value.codePointAt(0) || 0xFF;
|
||||
return `${prefix(charCode)}${charCode.toString(base).padStart(padding(charCode), '0')}${suffix(charCode)}`;
|
||||
}).join(separator);
|
||||
}
|
||||
|
||||
function convertUnicodeToText(unicodeStr: string): string {
|
||||
return unicodeStr.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec));
|
||||
return unicodeStr
|
||||
.replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(dec))
|
||||
.replace(/&#[xX]([0-9A-Fa-f]+);/g, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16)))
|
||||
.replace(/\\u\{([0-9A-Fa-f]+)\}/g, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16)))
|
||||
.replace(/(?:\\[uUx]|\\|\s*U\+)([0-9A-Fa-f]+)/g, (match, hex) => String.fromCodePoint(Number.parseInt(hex, 16))); // NOSONAR
|
||||
}
|
||||
|
||||
export { convertTextToUnicode, convertUnicodeToText };
|
||||
@@ -1,18 +1,46 @@
|
||||
<script setup lang="ts">
|
||||
import { convertTextToUnicode, convertUnicodeToText } from './text-to-unicode.service';
|
||||
import { type Encoding, convertTextToUnicode, convertUnicodeToText } from './text-to-unicode.service';
|
||||
import { useQueryParamOrStorage } from '@/composable/queryParams';
|
||||
import { useCopy } from '@/composable/copy';
|
||||
|
||||
const encoding = useQueryParamOrStorage({ name: 'enc', storageName: 'txt-uni:enc', defaultValue: 'htmldec' });
|
||||
const skipAscii = useQueryParamOrStorage({ name: 'skipAscii', storageName: 'txt-uni:asc', defaultValue: false });
|
||||
|
||||
const inputText = ref('');
|
||||
const unicodeFromText = computed(() => inputText.value.trim() === '' ? '' : convertTextToUnicode(inputText.value));
|
||||
const unicodeFromText = computed(() => inputText.value.trim() === ''
|
||||
? ''
|
||||
: convertTextToUnicode(inputText.value, { encoding: encoding.value as Encoding, skipAscii: skipAscii.value }));
|
||||
const { copy: copyUnicode } = useCopy({ source: unicodeFromText });
|
||||
|
||||
const inputUnicode = ref('');
|
||||
const textFromUnicode = computed(() => inputUnicode.value.trim() === '' ? '' : convertUnicodeToText(inputUnicode.value));
|
||||
const textFromUnicode = computed(() => inputUnicode.value.trim() === ''
|
||||
? ''
|
||||
: convertUnicodeToText(inputUnicode.value));
|
||||
const { copy: copyText } = useCopy({ source: textFromUnicode });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card title="Text to Unicode">
|
||||
<c-select
|
||||
v-model:value="encoding"
|
||||
label="Unicode encoding"
|
||||
:options="[
|
||||
{ value: 'htmldec', label: 'HTML Decimal (&#160;)' },
|
||||
{ value: 'htmlhex', label: 'HTML Hexadecimal (&#xA0;)' },
|
||||
{ value: 'uniplus', label: 'U+00A0' },
|
||||
{ value: 'antiuni', label: '\\u00A0' },
|
||||
{ value: 'css', label: 'CSS (\\0000A0)' },
|
||||
{ value: 'python', label: 'Python (\\xA0, \\u00A0, \\U100A0)' },
|
||||
{ value: 'js', label: 'Python (\\u00A0; \\u{100A0})' },
|
||||
{ value: 'utf16', label: 'UTF 16 (with surrogates)' },
|
||||
]"
|
||||
/>
|
||||
<n-form-item>
|
||||
<n-checkbox v-model:checked="skipAscii">
|
||||
Skip Ascii characters
|
||||
</n-checkbox>
|
||||
</n-form-item>
|
||||
|
||||
<c-input-text v-model:value="inputText" multiline placeholder="e.g. 'Hello Avengers'" label="Enter text to convert to unicode" autosize autofocus raw-text test-id="text-to-unicode-input" />
|
||||
<c-input-text v-model:value="unicodeFromText" label="Unicode from your text" multiline raw-text readonly mt-2 placeholder="The unicode representation of your text will be here" test-id="text-to-unicode-output" />
|
||||
<div mt-2 flex justify-center>
|
||||
|
||||
Reference in new issue
Block a user