Compare commits

..
Author SHA1 Message Date
ShareVB 8545fc6fa5 Merge remote-tracking branch 'origin/main' into feat/json-size 2024-09-29 21:17:55 +02:00
sharevb 3aa887ce54 feat(new tool): JSON Size Analyzer
Fix #450
2024-09-29 21:16:26 +02:00
Corentin THOMASSET 1c35ac3704 docs(author): updated author links (#1316) 2024-09-27 12:49:11 +00:00
Corentin Thomasset 72517002f3 refactor(regex-tester): better description 2024-09-27 10:40:56 +02:00
sharevbandCorentin THOMASSET f5c4ab19bc feat(new tool): Regex Tester (and Cheatsheet) (#1030)
* feat(new tool): Regex Tester

Fix https://github.com/CorentinTh/it-tools/issues/1007, https://github.com/CorentinTh/it-tools/issues/991, https://github.com/CorentinTh/it-tools/issues/936, https://github.com/CorentinTh/it-tools/issues/761, https://github.com/CorentinTh/it-tools/issues/649
https://github.com/CorentinTh/it-tools/issues/644, https://github.com/CorentinTh/it-tools/issues/554
https://github.com/CorentinTh/it-tools/issues/308

* fix: refactor to service + add regex diagram + ui enhancements

* fix: update queryParams

* fix: deps

* fix: svg style bug in @regexper/render

@regexper/render use a stylesheet in svg that cause bugs in whole site. So add regexper in a shadow root

* feat(new tool): added Regex Cheatsheet

* Update src/tools/regex-memo/index.ts

* Update src/tools/regex-tester/index.ts

---------

Co-authored-by: Corentin THOMASSET <corentin.thomasset74@gmail.com>
2024-09-20 18:39:40 +00:00
36 changed files with 1004 additions and 1123 deletions

No files matched your search

+1 -1
View File
@@ -117,7 +117,7 @@ Big thanks to all the people who have already contributed!
## Credits
Coded with ❤️ by [Corentin Thomasset](//corentin-thomasset.fr).
Coded with ❤️ by [Corentin Thomasset](https://corentin.tech?utm_source=it-tools&utm_medium=readme).
This project is continuously deployed using [vercel.com](https://vercel.com).
+11 -8
View File
@@ -73,7 +73,6 @@ declare module '@vue/runtime-core' {
DynamicValues: typeof import('./src/tools/benchmark-builder/dynamic-values.vue')['default']
Editor: typeof import('./src/tools/html-wysiwyg-editor/editor/editor.vue')['default']
EmailNormalizer: typeof import('./src/tools/email-normalizer/email-normalizer.vue')['default']
EmailParser: typeof import('./src/tools/email-parser/email-parser.vue')['default']
EmojiCard: typeof import('./src/tools/emoji-picker/emoji-card.vue')['default']
EmojiGrid: typeof import('./src/tools/emoji-picker/emoji-grid.vue')['default']
EmojiPicker: typeof import('./src/tools/emoji-picker/emoji-picker.vue')['default']
@@ -110,6 +109,7 @@ declare module '@vue/runtime-core' {
Ipv6UlaGenerator: typeof import('./src/tools/ipv6-ula-generator/ipv6-ula-generator.vue')['default']
JsonDiff: typeof import('./src/tools/json-diff/json-diff.vue')['default']
JsonMinify: typeof import('./src/tools/json-minify/json-minify.vue')['default']
JsonSizeAnalyzer: typeof import('./src/tools/json-size-analyzer/json-size-analyzer.vue')['default']
JsonToCsv: typeof import('./src/tools/json-to-csv/json-to-csv.vue')['default']
JsonToToml: typeof import('./src/tools/json-to-toml/json-to-toml.vue')['default']
JsonToXml: typeof import('./src/tools/json-to-xml/json-to-xml.vue')['default']
@@ -131,25 +131,25 @@ declare module '@vue/runtime-core' {
MetaTagGenerator: typeof import('./src/tools/meta-tag-generator/meta-tag-generator.vue')['default']
MimeTypes: typeof import('./src/tools/mime-types/mime-types.vue')['default']
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
NButton: typeof import('naive-ui')['NButton']
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']
NH1: typeof import('naive-ui')['NH1']
NH3: typeof import('naive-ui')['NH3']
NIcon: typeof import('naive-ui')['NIcon']
NInput: typeof import('naive-ui')['NInput']
NInputNumber: typeof import('naive-ui')['NInputNumber']
NLayout: typeof import('naive-ui')['NLayout']
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
NMenu: typeof import('naive-ui')['NMenu']
NRadio: typeof import('naive-ui')['NRadio']
NRadioGroup: typeof import('naive-ui')['NRadioGroup']
NScrollbar: typeof import('naive-ui')['NScrollbar']
NSpace: typeof import('naive-ui')['NSpace']
NTable: typeof import('naive-ui')['NTable']
NSlider: typeof import('naive-ui')['NSlider']
NSwitch: typeof import('naive-ui')['NSwitch']
NTree: typeof import('naive-ui')['NTree']
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']
OutlookParser: typeof import('./src/tools/outlook-parser/outlook-parser.vue')['default']
PasswordStrengthAnalyser: typeof import('./src/tools/password-strength-analyser/password-strength-analyser.vue')['default']
PdfSignatureChecker: typeof import('./src/tools/pdf-signature-checker/pdf-signature-checker.vue')['default']
PdfSignatureDetails: typeof import('./src/tools/pdf-signature-checker/components/pdf-signature-details.vue')['default']
@@ -157,6 +157,9 @@ declare module '@vue/runtime-core' {
PhoneParserAndFormatter: typeof import('./src/tools/phone-parser-and-formatter/phone-parser-and-formatter.vue')['default']
QrCodeGenerator: typeof import('./src/tools/qr-code-generator/qr-code-generator.vue')['default']
RandomPortGenerator: typeof import('./src/tools/random-port-generator/random-port-generator.vue')['default']
RegexMemo: typeof import('./src/tools/regex-memo/regex-memo.vue')['default']
'RegexMemo.content': typeof import('./src/tools/regex-memo/regex-memo.content.md')['default']
RegexTester: typeof import('./src/tools/regex-tester/regex-tester.vue')['default']
ResultRow: typeof import('./src/tools/ipv4-range-expander/result-row.vue')['default']
RomanNumeralConverter: typeof import('./src/tools/roman-numeral-converter/roman-numeral-converter.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink']
+1 -1
View File
@@ -38,7 +38,7 @@ about:
# Über IT-Tools
Diese wunderbare Website, erstellt mit ❤ von [Corentin
Thomasset](https://github.com/CorentinTh), sammelt nützliche Tools für
Thomasset](https://corentin.tech?utm_source=it-tools&utm_medium=about), sammelt nützliche Tools für
Entwickler und Menschen, die in der IT arbeiten. Wenn du sie nützlich
findest, teile sie gerne mit Personen, von denen du denkst, dass sie sie
ebenfalls nützlich finden könnten, und vergiss nicht, sie in deiner
+1 -1
View File
@@ -30,7 +30,7 @@ about:
content: >
# About IT-Tools
This wonderful website, made with ❤ by [Corentin Thomasset](https://github.com/CorentinTh) , aggregates useful tools for developer and people working in IT. If you find it useful, please feel free to share it to people you think may find it useful too and don't forget to bookmark it in your shortcut bar!
This wonderful website, made with ❤ by [Corentin Thomasset](https://corentin.tech?utm_source=it-tools&utm_medium=about) , aggregates useful tools for developer and people working in IT. If you find it useful, please feel free to share it to people you think may find it useful too and don't forget to bookmark it in your shortcut bar!
IT Tools is open-source (under the MIT license) and free, and will always be, but it costs me money to host and renew the domain name. If you want to support my work, and encourage me to add more tools, please consider supporting by [sponsoring me](https://www.buymeacoffee.com/cthmsst).
+3 -3
View File
@@ -30,7 +30,7 @@ about:
content: >
# Sobre IT-Tools
Este maravilloso sitio web, hecho con ❤ por [Corentin Thomasset](https://github.com/CorentinTh) , agrega herramientas útiles para desarrolladores y personas que trabajan en IT. Si lo encuentra útil, no dude en compartirlo con las personas que crea que también pueden encontrarlo útil y ¡no olvide marcarlo como favorito en su barra de accesos directos!
Este maravilloso sitio web, hecho con ❤ por [Corentin Thomasset](https://corentin.tech?utm_source=it-tools&utm_medium=about) , agrega herramientas útiles para desarrolladores y personas que trabajan en IT. Si lo encuentra útil, no dude en compartirlo con las personas que crea que también pueden encontrarlo útil y ¡no olvide marcarlo como favorito en su barra de accesos directos!
IT Tools es de código abierto (under the MIT license) y gratis, y siempre lo será, pero me cuesta dinero alojar y renovar el nombre de dominio. Si desea apoyar mi trabajo y animarme a agregar más herramientas, considere apoyarme a través de[sponsoring me](https://www.buymeacoffee.com/cthmsst).
@@ -39,7 +39,7 @@ about:
IT Tools está creado en Vue.js (Vue 3) con la biblioteca de componentes Naive UI y Vercel lo aloja y lo implementa continuamente. En algunas herramientas se utilizan bibliotecas de código abierto de terceros; puede encontrar la lista completa en [package.json](https://github.com/CorentinTh/it-tools/blob/main/package.json) archivo del repositorio.
## ¿Encontraste un error? ¿Falta una herramienta?
Si necesita una herramienta que actualmente no está presente aquí y cree que puede ser útil, puede enviar una solicitud de función en el [issues section](https://github.com/CorentinTh/it-tools/issues/new/choose) en el repositorio de GitHub.
Y si encontró un error o algo no funciona como se esperaba, presente un reporte de error en el [issues section](https://github.com/CorentinTh/it-tools/issues/new/choose) en el repositorio de GitHub.
@@ -68,4 +68,4 @@ tools:
math: Math
measurement: Measurement
text: Text
data: Data
data: Data
+1 -1
View File
@@ -29,7 +29,7 @@ about:
content: >
# À propos de IT-Tools
Ce merveilleux site, fait avec ❤ par [Corentin Thomasset](https://github.com/CorentinTh), regroupe des outils utiles pour les développeurs et les personnes travaillant dans l'informatique. Si vous le trouvez utile, n'hésitez pas à le partager et n'oubliez pas de le mettre dans vos favoris !
Ce merveilleux site, fait avec ❤ par [Corentin Thomasset](https://corentin.tech?utm_source=it-tools&utm_medium=about), regroupe des outils utiles pour les développeurs et les personnes travaillant dans l'informatique. Si vous le trouvez utile, n'hésitez pas à le partager et n'oubliez pas de le mettre dans vos favoris !
IT Tools est open-source (sous licence MIT) et gratuit, et le restera toujours, mais cela me coûte de l'argent pour l'héberger et renouveler le nom de domaine. Si vous voulez soutenir mon travail, et m'encourager à ajouter plus d'outils, n'hésitez pas à me [soutenir](https://www.buymeacoffee.com/cthmsst).
+1 -1
View File
@@ -30,7 +30,7 @@ about:
content: >
# Sobre o IT-Tools
Este site maravilhoso, feito com ❤ por [Corentin Thomasset](https://github.com/CorentinTh), junta ferramentas úteis para desenvolvedores e outras pessoas que trabalham com TI. Se você achar o site útil, fique à vontade para compartilhar com quem também possa gostar e não esqueça de salvar o bookmark na sua barra de atalhos!
Este site maravilhoso, feito com ❤ por [Corentin Thomasset](https://corentin.tech?utm_source=it-tools&utm_medium=about), junta ferramentas úteis para desenvolvedores e outras pessoas que trabalham com TI. Se você achar o site útil, fique à vontade para compartilhar com quem também possa gostar e não esqueça de salvar o bookmark na sua barra de atalhos!
O IT Tools é código aberto (sob a licença MIT), é gratuito, e sempre será, mas custa dinheiro para hospedar e renovar o domínio. Se quiser apoiar meu trabalho e me encorajar a adicionar mais ferramentas, por favor considere [ser patrocinador](https://www.buymeacoffee.com/cthmsst).
+1 -1
View File
@@ -30,7 +30,7 @@ about:
content: >
# Про IT-Tools
Цей чудовий вебсайт, створений з ❤ [Corentin Thomasset](https://github.com/CorentinTh), агрегує корисні інструменти для розробників і людей, які працюють в сфері IT. Якщо вам це корисно, будь ласка, поділіться цим з людьми, які, на вашу думку, також можуть знайти його корисним, і не забудьте додати його до закладок у вашій панелі швидкого доступу!
Цей чудовий вебсайт, створений з ❤ [Corentin Thomasset](https://corentin.tech?utm_source=it-tools&utm_medium=about), агрегує корисні інструменти для розробників і людей, які працюють в сфері IT. Якщо вам це корисно, будь ласка, поділіться цим з людьми, які, на вашу думку, також можуть знайти його корисним, і не забудьте додати його до закладок у вашій панелі швидкого доступу!
IT Tools є відкритим програмним забезпеченням (під ліцензією MIT) і безкоштовним, і завжди буде таким, але мені коштує гроші для хостингу і продовження доменного імені. Якщо ви хочете підтримати мою роботу і підтримати мене у додаванні нових інструментів, розгляньте можливість підтримки, [спонсоруючи мене](https://www.buymeacoffee.com/cthmsst).
+1 -1
View File
@@ -30,7 +30,7 @@ about:
content: >
# Về IT-Tools
Website tuyệt vời này, được tạo ra bằng ❤ bởi [Corentin Thomasset](https://github.com/CorentinTh), tổng hợp các công cụ hữu ích cho nhà phát triển và những người làm việc trong lĩnh vực IT. Nếu bạn thấy nó hữu ích, xin đừng ngần ngại chia sẻ cho những người mà bạn nghĩ sẽ thấy nó hữu ích và đừng quên đánh dấu nó trong thanh lối tắt của bạn!
Website tuyệt vời này, được tạo ra bằng ❤ bởi [Corentin Thomasset](https://corentin.tech?utm_source=it-tools&utm_medium=about), tổng hợp các công cụ hữu ích cho nhà phát triển và những người làm việc trong lĩnh vực IT. Nếu bạn thấy nó hữu ích, xin đừng ngần ngại chia sẻ cho những người mà bạn nghĩ sẽ thấy nó hữu ích và đừng quên đánh dấu nó trong thanh lối tắt của bạn!
IT Tools là mã nguồn mở (dưới giấy phép MIT) và miễn phí, và sẽ luôn như vậy, nhưng tôi phải trả tiền để lưu trữ và gia hạn tên miền. Nếu bạn muốn hỗ trợ công việc của tôi, và khích lệ tôi thêm nhiều công cụ hơn, hãy xem xét hỗ trợ bằng cách [tài trợ cho tôi](https://www.buymeacoffee.com/cthmsst).
+1 -1
View File
@@ -30,7 +30,7 @@ about:
content: >
# 关于 IT-Tools
IT-Tools 由 [Corentin Thomasset](https://github.com/CorentinTh) 用 ❤ 开发,汇集了对开发人员和 IT 从业者有用的工具。如果对您有帮助,请将其分享给您的朋友,并且添加到收藏夹中!
IT-Tools 由 [Corentin Thomasset](https://corentin.tech?utm_source=it-tools&utm_medium=about) 用 ❤ 开发,汇集了对开发人员和 IT 从业者有用的工具。如果对您有帮助,请将其分享给您的朋友,并且添加到收藏夹中!
IT-Tools 永久免费且开源(MIT 许可证),但需要资金用于托管和续订域名。如果您想支持我的工作,并鼓励我添加更多工具,请考虑通过 [赞助我](https://www.buymeacoffee.com/cthmsst) 进行支持。
+13 -15
View File
@@ -1,7 +1,14 @@
{
"name": "it-tools",
"version": "2024.5.13-a0bc346",
"packageManager": "pnpm@8.15.3",
"description": "Collection of handy online tools for developers, with great UX. ",
"author": "Corentin Th <corentin.thomasset74+it-tools@gmail.com> (https://corentin.tech)",
"license": "GNU GPLv3",
"repository": {
"type": "git",
"url": "https://github.com/CorentinTh/it-tools"
},
"keywords": [
"productivity",
"converter",
@@ -13,12 +20,6 @@
"developer-tools",
"developer-productivity"
],
"author": "Corentin Th <corentin.thomasset74+it-tools@gmail.com> (https://github.com/CorentinTh)",
"license": "GNU GPLv3",
"repository": {
"type": "git",
"url": "https://github.com/CorentinTh/it-tools"
},
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && NODE_OPTIONS=--max_old_space_size=4096 vite build",
@@ -37,14 +38,13 @@
"dependencies": {
"@it-tools/bip39": "^0.0.4",
"@it-tools/oggen": "^1.3.0",
"@kenjiuno/decompressrtf": "^0.1.4",
"@kenjiuno/msgreader": "^1.22.0",
"@regexper/render": "^1.0.0",
"@sindresorhus/slugify": "^2.2.1",
"@tiptap/pm": "2.1.6",
"@tiptap/starter-kit": "2.1.6",
"@tiptap/vue-3": "2.0.3",
"@types/markdown-it": "^13.0.7",
"@types/figlet": "^1.5.8",
"@types/markdown-it": "^13.0.7",
"@vicons/material": "^0.12.0",
"@vicons/tabler": "^0.12.0",
"@vueuse/core": "^10.3.0",
@@ -68,8 +68,8 @@
"highlight.js": "^11.7.0",
"iarna-toml-esm": "^3.0.5",
"ibantools": "^4.3.3",
"iconv-lite": "^0.6.3",
"js-base64": "^3.7.6",
"json-analyzer": "^1.2.2",
"json5": "^2.2.3",
"jwt-decode": "^3.1.2",
"libphonenumber-js": "^1.10.28",
@@ -86,9 +86,8 @@
"pdf-signature-reader": "^1.4.2",
"pinia": "^2.0.34",
"plausible-tracker": "^0.3.8",
"postal-mime": "^2.2.7",
"qrcode": "^1.5.1",
"rtf-stream-parser": "^3.8.0",
"randexp": "^0.5.3",
"sql-formatter": "^13.0.0",
"ua-parser-js": "^1.0.35",
"ulid": "^2.3.0",
@@ -98,6 +97,7 @@
"vue": "^3.3.4",
"vue-i18n": "^9.9.1",
"vue-router": "^4.1.6",
"vue-shadow-dom": "^4.2.0",
"vue-tsc": "^1.8.1",
"xml-formatter": "^3.3.2",
"xml-js": "^1.6.11",
@@ -141,13 +141,11 @@
"unplugin-icons": "^0.17.0",
"unplugin-vue-components": "^0.25.0",
"vite": "^4.4.9",
"vite-plugin-node-polyfills": "^0.22.0",
"vite-plugin-pwa": "^0.16.0",
"vite-plugin-vue-markdown": "^0.23.5",
"vite-svg-loader": "^4.0.0",
"vitest": "^0.34.0",
"workbox-window": "^7.0.0",
"zx": "^7.2.1"
},
"packageManager": "pnpm@8.15.3"
}
}
+97 -661
View File
File diff suppressed because it is too large. Load diff
+4 -38
View File
@@ -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>
+14 -15
View File
@@ -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 });
},
};
}
+32 -1
View File
@@ -1,7 +1,8 @@
import { useRouteQuery } from '@vueuse/router';
import { computed } from 'vue';
import { useStorage } from '@vueuse/core';
export { useQueryParam };
export { useQueryParam, useQueryParamOrStorage };
const transformers = {
number: {
@@ -16,6 +17,12 @@ const transformers = {
fromQuery: (value: string) => value.toLowerCase() === 'true',
toQuery: (value: boolean) => (value ? 'true' : 'false'),
},
object: {
fromQuery: (value: string) => {
return JSON.parse(value);
},
toQuery: (value: object) => JSON.stringify(value),
},
};
function useQueryParam<T>({ name, defaultValue }: { name: string; defaultValue: T }) {
@@ -33,3 +40,27 @@ function useQueryParam<T>({ name, defaultValue }: { name: string; defaultValue:
},
});
}
function useQueryParamOrStorage<T>({ name, storageName, defaultValue }: { name: string; storageName: string; defaultValue: T }) {
const type = typeof defaultValue;
const transformer = transformers[type as keyof typeof transformers] ?? transformers.string;
const storageRef = useStorage(storageName, defaultValue);
const proxyDefaultValue = transformer.toQuery(defaultValue as never);
const proxy = useRouteQuery(name, proxyDefaultValue);
const r = ref(defaultValue);
watch(r,
(value) => {
proxy.value = transformer.toQuery(value as never);
storageRef.value = value as never;
},
{ deep: true });
r.value = (proxy.value && proxy.value !== proxyDefaultValue
? transformer.fromQuery(proxy.value) as unknown as T
: storageRef.value as T) as never;
return r;
}
+18 -1
View File
@@ -3,9 +3,11 @@ import _ from 'lodash';
import { type Ref, reactive, watch } from 'vue';
type ValidatorReturnType = unknown;
type GetErrorMessageReturnType = string;
export interface UseValidationRule<T> {
validator: (value: T) => ValidatorReturnType
getErrorMessage?: (value: T) => GetErrorMessageReturnType
message: string
}
@@ -24,6 +26,15 @@ export function isFalsyOrHasThrown(cb: () => ValidatorReturnType): boolean {
}
}
export function getErrorMessageOrThrown(cb: () => GetErrorMessageReturnType): string {
try {
return cb() || '';
}
catch (e: any) {
return e.toString();
}
}
export interface ValidationAttrs {
feedback: string
validationStatus: string | undefined
@@ -61,7 +72,13 @@ export function useValidation<T>({
for (const rule of get(rules)) {
if (isFalsyOrHasThrown(() => rule.validator(source.value))) {
state.message = rule.message;
if (rule.getErrorMessage) {
const getErrorMessage = rule.getErrorMessage;
state.message = rule.message.replace('{0}', getErrorMessageOrThrown(() => getErrorMessage(source.value)));
}
else {
state.message = rule.message;
}
state.status = 'error';
}
}
+1 -1
View File
@@ -81,7 +81,7 @@ const tools = computed<ToolCategory[]>(() => [
</div>
<div>
© {{ new Date().getFullYear() }}
<c-link target="_blank" rel="noopener" href="https://github.com/CorentinTh">
<c-link target="_blank" rel="noopener" href="https://corentin.tech?utm_source=it-tools&utm_medium=footer">
Corentin Thomasset
</c-link>
</div>
+2
View File
@@ -3,6 +3,7 @@ import { createPinia } from 'pinia';
import { createHead } from '@vueuse/head';
import { registerSW } from 'virtual:pwa-register';
import shadow from 'vue-shadow-dom';
import { plausible } from './plugins/plausible.plugin';
import 'virtual:uno.css';
@@ -23,5 +24,6 @@ app.use(i18nPlugin);
app.use(router);
app.use(naive);
app.use(plausible);
app.use(shadow);
app.mount('#app');
-152
View File
@@ -1,152 +0,0 @@
<script setup lang="ts">
import PostalMime from 'postal-mime';
const inputType = ref<'file' | 'content'>('file');
const emailContent = ref('');
const fileInput = ref() as Ref<File | null>;
const error = ref('');
const parsedEmail = computedAsync(async () => {
const emailContentValue = emailContent.value;
const file = fileInput.value;
error.value = '';
try {
if (inputType.value === 'file' && file) {
return await PostalMime.parse(await file.arrayBuffer());
}
else if (inputType.value === 'content' && emailContentValue) {
return await PostalMime.parse(emailContentValue);
}
else {
return null;
}
}
catch (e: any) {
error.value = e.toString();
return null;
}
});
function downloadFile(data: ArrayBuffer, fileName: string, fileType: string) {
const blob = new Blob([data], { type: fileType || 'application/octet-stream' });
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = downloadUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(downloadUrl);
}
function onUpload(file: File) {
if (file) {
fileInput.value = file;
}
}
</script>
<template>
<div style="max-width: 600px;">
<c-card title="Input" mb-2>
<n-radio-group v-model:value="inputType" name="radiogroup" mb-2 flex justify-center>
<n-space>
<n-radio
value="file"
label="File"
/>
<n-radio
value="content"
label="Content"
/>
</n-space>
</n-radio-group>
<c-file-upload
v-if="inputType === 'file'"
title="Drag and drop EML file here, or click to select a file"
@file-upload="onUpload"
/>
<c-input-text
v-if="inputType === 'content'"
v-model:value="emailContent"
label="Email Content"
multiline
placeholder="Put your eml/email content here..."
rows="15"
mb-2
/>
</c-card>
<c-alert v-if="error">
{{ error }}
</c-alert>
<c-card v-if="!error && parsedEmail" title="Output">
<input-copyable v-if="fileInput?.name" label="File Name" :value="fileInput?.name" />
<input-copyable v-if="parsedEmail.date" label="Date" :value="parsedEmail.date" />
<input-copyable v-if="parsedEmail.from?.name" label="From (name)" :value="parsedEmail.from?.name" />
<input-copyable v-if="parsedEmail.from" label="From (address)" :value="parsedEmail.from?.address || parsedEmail.from" />
<input-copyable v-if="parsedEmail.to" label="To" :value="JSON.stringify(parsedEmail.to)" />
<input-copyable v-if="parsedEmail.cc" label="Cc" :value="JSON.stringify(parsedEmail.cc)" />
<input-copyable v-if="parsedEmail.bcc" label="Bcc" :value="JSON.stringify(parsedEmail.bcc)" />
<input-copyable v-if="parsedEmail.replyTo" label="Reply-To" :value="JSON.stringify(parsedEmail.replyTo)" />
<input-copyable v-if="parsedEmail.subject" label="Subject" :value="parsedEmail.subject" />
<c-card v-if="parsedEmail.text" title="Plain Content" mb-2>
<details>
<summary>See content</summary>
<textarea-copyable :value="parsedEmail.text" word-wrap />
</details>
</c-card>
<c-card v-if="parsedEmail.html" title="Html Content" mb-2>
<details>
<summary>See content</summary>
<textarea-copyable :value="parsedEmail.html" word-wrap />
</details>
</c-card>
<c-card v-if="parsedEmail?.attachments?.length" title="Attachments" mb-2>
<n-table>
<thead>
<tr>
<th scope="col">
Attachment
</th><th scope="col" />
</tr>
</thead>
<tbody>
<tr
v-for="(h, index) in parsedEmail.attachments || []"
:key="index"
>
<td>
{{ `${h.filename || h.contentId || 'noname'} (${h.mimeType}) / ${h.disposition}` }}
</td>
<td>
<c-button @click="downloadFile(h.content, h.filename || h.contentId || 'noname', h.mimeType)">
Download
</c-button>
</td>
</tr>
</tbody>
</n-table>
</c-card>
<input-copyable v-if="parsedEmail.messageId" label="Message Id" :value="parsedEmail.messageId" />
<input-copyable v-if="parsedEmail.inReplyTo" label="In Reply To" :value="parsedEmail.inReplyTo" />
<input-copyable v-if="parsedEmail.references" label="References" :value="parsedEmail.references" />
<input-copyable v-if="parsedEmail.deliveredTo" label="Delivered To" :value="parsedEmail.deliveredTo" />
<input-copyable v-if="parsedEmail.returnPath" label="Return Path" :value="parsedEmail.returnPath" />
<input-copyable v-if="parsedEmail.sender?.name" label="Sender (name)" :value="parsedEmail.sender?.name" />
<input-copyable v-if="parsedEmail.sender" label="Sender (address)" :value="parsedEmail.sender?.address || parsedEmail.sender" />
<c-card title="All Headers" mt-2>
<input-copyable
v-for="(h, index) in parsedEmail.headers || []"
:key="index"
:label="h.key"
:value="h.value"
/>
</c-card>
</c-card>
</div>
</template>
-12
View File
@@ -1,12 +0,0 @@
import { Mail } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Email Parser',
path: '/email-parser',
description: 'Parse and extract information from raw Email content',
keywords: ['email', 'parser', 'header', 'rfc2822', 'rfc5322', 'rfc822'],
component: () => import('./email-parser.vue'),
icon: Mail,
createdAt: new Date('2024-08-15'),
});
+7 -12
View File
@@ -2,8 +2,7 @@ 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 emailParser } from './email-parser';
import { tool as outlookParser } from './outlook-parser';
import { tool as jsonSizeAnalyzer } from './json-size-analyzer';
import { tool as asciiTextDrawer } from './ascii-text-drawer';
@@ -11,6 +10,8 @@ import { tool as textToUnicode } from './text-to-unicode';
import { tool as safelinkDecoder } from './safelink-decoder';
import { tool as xmlToJson } from './xml-to-json';
import { tool as jsonToXml } from './json-to-xml';
import { tool as regexTester } from './regex-tester';
import { tool as regexMemo } from './regex-memo';
import { tool as markdownToHtml } from './markdown-to-html';
import { tool as pdfSignatureChecker } from './pdf-signature-checker';
import { tool as numeronymGenerator } from './numeronym-generator';
@@ -151,6 +152,7 @@ export const toolsByCategory: ToolCategory[] = [
crontabGenerator,
jsonViewer,
jsonMinify,
jsonSizeAnalyzer,
jsonToCsv,
sqlPrettify,
chmodCalculator,
@@ -158,20 +160,13 @@ export const toolsByCategory: ToolCategory[] = [
xmlFormatter,
yamlViewer,
emailNormalizer,
regexTester,
regexMemo,
],
},
{
name: 'Network',
components: [
ipv4SubnetCalculator,
ipv4AddressConverter,
ipv4RangeExpander,
macAddressLookup,
macAddressGenerator,
ipv6UlaGenerator,
emailParser,
outlookParser,
],
components: [ipv4SubnetCalculator, ipv4AddressConverter, ipv4RangeExpander, macAddressLookup, macAddressGenerator, ipv6UlaGenerator],
},
{
name: 'Math',
+12
View File
@@ -0,0 +1,12 @@
import { FileAnalytics } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Json Size Analyzer',
path: '/json-size-analyzer',
description: 'Measure JSON nodes relative weights',
keywords: ['json', 'size', 'analyzer'],
component: () => import('./json-size-analyzer.vue'),
icon: FileAnalytics,
createdAt: new Date('2024-07-14'),
});
+13
View File
@@ -0,0 +1,13 @@
declare module 'json-analyzer' {
export default function analyze({
json,
verbose,
maxDepth,
target,
}: {
json: any,
verbose: boolean,
maxDepth: number,
target: string,
});
}
@@ -0,0 +1,113 @@
import { describe, expect, it } from 'vitest';
import { getJsonUsageTreeNodes } from './json-size-analyzer.service';
describe('json-size-analyzer', () => {
describe('getJsonUsageTreeNodes', () => {
it('return correct tree nodes structures', () => {
expect(getJsonUsageTreeNodes([{ a: [1, 2, 3] }, { b: 'a' }])).to.deep.eq({
children: [
{
children: [
{
children: [
{
children: [],
key: '$.[0].a.[0]',
label: '$.[0].a.[0]: 1 B(26 B gzip)',
},
{
children: [],
key: '$.[0].a.[1]',
label: '$.[0].a.[1]: 1 B(24 B gzip)',
},
{
children: [],
key: '$.[0].a.[2]',
label: '$.[0].a.[2]: 1 B(25 B gzip)',
},
],
key: '$.[0].a',
label: '$.[0].a: 7 B(35 B gzip) ; 28.000% of parent ; biggest child node: \'0\'',
},
],
key: '$.[0]',
label: '$.[0]: 13 B(43 B gzip) ; 52.000% of parent ; biggest child node: \'a\'',
},
{
children: [
{
children: [],
key: '$.[1].b',
label: '$.[1].b: 1 B(25 B gzip)',
},
],
key: '$.[1]',
label: '$.[1]: 9 B(34 B gzip) ; 36.000% of parent ; biggest child node: \'b\'',
},
],
key: '$',
label: '$: 25 B(61 B gzip) ; 100.00% of parent ; biggest child node: \'0\'',
});
expect(getJsonUsageTreeNodes({ a: { b: [1, 2, 3], c: 12 } })).to.deep.eq({
children: [
{
children: [
{
children: [
{
children: [],
key: '$.a.b.[0]',
label: '$.a.b.[0]: 1 B(26 B gzip)',
},
{
children: [],
key: '$.a.b.[1]',
label: '$.a.b.[1]: 1 B(24 B gzip)',
},
{
children: [],
key: '$.a.b.[2]',
label: '$.a.b.[2]: 1 B(25 B gzip)',
},
],
key: '$.a.b',
label: '$.a.b: 7 B(35 B gzip) ; 26.923% of parent ; biggest child node: \'0\'',
},
{
children: [],
key: '$.a.c',
label: '$.a.c: 2 B(24 B gzip)',
},
],
key: '$.a',
label: '$.a: 20 B(50 B gzip) ; 76.923% of parent ; biggest child node: \'b\'',
},
],
key: '$',
label: '$: 26 B(63 B gzip) ; 100.00% of parent ; biggest child node: \'a\'',
});
expect(getJsonUsageTreeNodes({ a: { b: 'azerty', c: 'ueop' } })).to.deep.eq({
children: [
{
children: [
{
children: [],
key: '$.a.b',
label: '$.a.b: 6 B(30 B gzip)',
},
{
children: [],
key: '$.a.c',
label: '$.a.c: 4 B(29 B gzip)',
},
],
key: '$.a',
label: '$.a: 25 B(51 B gzip) ; 80.645% of parent ; biggest child node: \'b\'',
},
],
key: '$',
label: '$: 31 B(61 B gzip) ; 100.00% of parent ; biggest child node: \'a\'',
});
});
});
});
@@ -0,0 +1,51 @@
import jsonAnalyzer from 'json-analyzer';
export interface Meta {
__meta__: {
size?: {
value: number
raw: string
gzip: string
}
number_of_childs?: number
parent_relative_percentage?: string
biggest_node_child: string
}
}
export type AnalysisNode = {
[key: string]: object & Meta
} & Meta;
export type TreeNode = {
key: string
label: string
children: Array<TreeNode>
} & Record<string, unknown>;
function getTreeNodes(obj: AnalysisNode, parentName: string): TreeNode {
const childNodes = Object.entries(obj)
.filter(([key, v]) => key !== '__meta__' && typeof v === 'object')
.map(([k, v]) => ({
key: (Number.isNaN(Number.parseInt(k, 10)) ? `.${k}` : `.[${k}]`),
value: v as AnalysisNode,
}));
const biggest_child_node = obj.__meta__.biggest_node_child ? ` ; biggest child node: '${obj.__meta__.biggest_node_child}'` : '';
const parent_relative_percentage = obj.__meta__.parent_relative_percentage ? ` ; ${obj.__meta__.parent_relative_percentage} of parent` : '';
return {
key: parentName,
label: obj.__meta__
? `${parentName}: ${obj.__meta__.size?.raw}(${obj.__meta__.size?.gzip} gzip)${parent_relative_percentage}${biggest_child_node}`
: parentName,
children: childNodes.map(childNode => getTreeNodes(childNode.value, parentName + childNode.key)),
};
}
export function getJsonUsageTreeNodes(jsonObj: any, maxDepth: number = 100, targetNode: string = ''): TreeNode {
const analysis = jsonAnalyzer({
json: jsonObj,
verbose: true,
maxDepth,
target: targetNode,
});
return getTreeNodes(analysis, '$');
}
@@ -0,0 +1,68 @@
<script setup lang="ts">
import JSON5 from 'json5';
import { getJsonUsageTreeNodes } from './json-size-analyzer.service';
import { useValidation } from '@/composable/validation';
const json = ref('{"a": 1, "b": [1,2,3]}');
const maxDepth = ref(100);
const target = ref('');
const jsonSizes = computed(() => {
const jsonObj = JSON5.parse(json.value);
if (!jsonObj) {
return null;
}
return [getJsonUsageTreeNodes(jsonObj, maxDepth.value - 1, target.value)];
});
const searchInAnalysis = ref('');
const jsonValidation = useValidation({
source: json,
rules: [
{
validator: (v) => {
return JSON5.parse(v);
},
message: 'Provided JSON is not valid.',
},
],
});
</script>
<template>
<div style="max-width: 600px;">
<c-card title="Input" mb-2>
<c-input-text
v-model:value="json"
label="JSON"
multiline
placeholder="Put your JSON data here..."
rows="5"
:validation="jsonValidation"
mb-2
/>
<n-form-item label="Max Depth:" label-placement="left">
<n-input-number v-model:value="maxDepth" :min="0" w-full />
</n-form-item>
<c-input-text
v-model:value="target"
label="Target Node"
placeholder="Where to start the analyze (ie, a[0].b.c)"
mb-2
/>
</c-card>
<c-card v-if="jsonSizes" title="Analysis">
<n-input v-model:value="searchInAnalysis" placeholder="Search in result" />
<n-tree
:show-irrelevant-nodes="false"
:pattern="searchInAnalysis"
:default-expand-all="true"
:data="jsonSizes"
block-line
/>
</c-card>
</div>
</template>
-12
View File
@@ -1,12 +0,0 @@
import { Mail } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Outlook MSG Parser',
path: '/outlook-parser',
description: 'Parse Outlook MSG Files',
keywords: ['outlook', 'email', 'msg', 'parser'],
component: () => import('./outlook-parser.vue'),
icon: Mail,
createdAt: new Date('2024-08-15'),
});
-182
View File
@@ -1,182 +0,0 @@
<script setup lang="ts">
import { Buffer } from 'node:buffer';
import MsgReader, { type FieldsData } from '@kenjiuno/msgreader';
import { getProps } from '@kenjiuno/msgreader/lib/Defs.js';
import { deEncapsulateSync } from 'rtf-stream-parser';
import { decompressRTF } from '@kenjiuno/decompressrtf';
import iconv from 'iconv-lite';
const fileInput = ref() as Ref<File | null>;
const error = ref('');
function getPropertyName(tag: string | undefined) {
if (!tag) {
return '';
}
const tagLower = tag.toLocaleLowerCase();
const prop = getProps().find(p => p.key?.toLocaleLowerCase() === tagLower);
if (!prop) {
return tag;
}
return `${prop.name} (${prop.area})`;
}
const parsedEmailRaw = computedAsync(async () => {
const file = fileInput.value;
error.value = '';
if (file == null) {
return null;
}
try {
const msg = new MsgReader(await file.arrayBuffer());
msg.parserConfig = {
includeRawProps: true,
};
return msg;
}
catch (e: any) {
error.value = e.toString();
return null;
}
});
const parsedEmail = computed(() => parsedEmailRaw.value?.getFileData());
const parsedRtf = computed(() => {
if (!parsedEmail.value?.compressedRtf) {
return { rtf: '', html: '' };
}
try {
const rtfBlob = decompressRTF(Array.from(parsedEmail.value?.compressedRtf));
const rtfText = iconv.decode(
Buffer.from(rtfBlob),
'latin1',
);
try {
return { rtf: rtfText, html: deEncapsulateSync(rtfText, { decode: iconv.decode })?.text };
}
catch (dex: any) {
return { rtf: rtfText, html: dex.toString() };
}
}
catch (ex: any) {
return { rtf: ex.toString(), html: '' };
}
});
function downloadFile(attachment: FieldsData) {
const attachmentData = parsedEmailRaw.value?.getAttachment(attachment);
if (!attachmentData) {
return;
}
const blob = new Blob([attachmentData.content], { type: 'application/octet-stream' });
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = downloadUrl;
a.download = attachmentData.fileName;
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(downloadUrl);
}
function onUpload(file: File) {
if (file) {
fileInput.value = file;
}
}
</script>
<template>
<div style="max-width: 600px;">
<c-card title="Input" mb-2>
<c-file-upload
title="Drag and drop MSG file here, or click to select a file"
@file-upload="onUpload"
/>
</c-card>
<c-alert v-if="error">
{{ error }}
</c-alert>
<c-card v-if="!error && parsedEmail" title="Output">
<input-copyable v-if="fileInput?.name" label="File Name" :value="fileInput?.name" />
<input-copyable v-if="parsedEmail.creationTime" label="Creation Date" :value="parsedEmail.creationTime" />
<input-copyable v-if="parsedEmail.clientSubmitTime" label="Submit Date" :value="parsedEmail.clientSubmitTime" />
<input-copyable v-if="parsedEmail.messageDeliveryTime" label="Delivery Date" :value="parsedEmail.messageDeliveryTime" />
<input-copyable v-if="parsedEmail.lastModificationTime" label="Last Mod. Date" :value="parsedEmail.lastModificationTime" />
<c-card title="Recipients" mt-2>
<input-copyable
v-for="(h, index) in parsedEmail.recipients || []"
:key="index"
:label="h.recipType || 'unk'"
:value="`${h.name}/${h.email}`"
/>
</c-card>
<input-copyable v-if="parsedEmail.subject" label="Subject" :value="parsedEmail.subject" />
<c-card v-if="parsedEmail.body" title="Plain Content" mb-2>
<details>
<summary>See content</summary>
<textarea-copyable :value="parsedEmail.body" />
</details>
</c-card>
<c-card v-if="parsedEmail.bodyHtml" title="Html Content" mb-2>
<details>
<summary>See content</summary>
<textarea-copyable :value="parsedEmail.bodyHtml" word-wrap />
</details>
</c-card>
<c-card v-if="parsedRtf.rtf || parsedRtf.html" title="RTF Content" mb-2>
<details>
<summary>See Raw RTF</summary>
<textarea-copyable :value="parsedRtf.rtf" word-wrap />
</details>
<details>
<summary>See RTF converted HTML</summary>
<textarea-copyable :value="parsedRtf.html" word-wrap />
</details>
</c-card>
<c-card v-if="parsedEmail?.attachments?.length" title="Attachments" mb-2>
<n-table>
<thead>
<tr>
<th scope="col">
Attachment
</th><th scope="col" />
</tr>
</thead>
<tbody>
<tr
v-for="(h, index) in parsedEmail.attachments || []"
:key="index"
>
<td>
{{ `${h.fileName || h.fileNameShort || 'noname'}` }}
</td>
<td>
<c-button @click="downloadFile(h)">
Download
</c-button>
</td>
</tr>
</tbody>
</n-table>
</c-card>
<input-copyable v-if="parsedEmail.messageId" label="Message Id" :value="parsedEmail.messageId" />
<input-copyable v-if="parsedEmail.senderName" label="Sender (name)" :value="parsedEmail.senderName" />
<input-copyable v-if="parsedEmail.senderEmail" label="Sender (email)" :value="parsedEmail.senderEmail" />
<c-card v-if="parsedEmail.headers" title="All Headers" mt-2>
<textarea-copyable :value="parsedEmail.headers" />
</c-card>
<c-card title="All RawProps" mt-2>
<input-copyable
v-for="(h, index) in parsedEmail.rawProps || []"
:key="index"
:label="h.propertyName || getPropertyName(h.propertyTag)"
:value="h.value"
/>
</c-card>
</c-card>
</div>
</template>
+12
View File
@@ -0,0 +1,12 @@
import { BrandJavascript } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Regex cheatsheet',
path: '/regex-memo',
description: 'Javascript Regex/Regular Expression cheatsheet',
keywords: ['regex', 'regular', 'expression', 'javascript', 'memo', 'cheatsheet'],
component: () => import('./regex-memo.vue'),
icon: BrandJavascript,
createdAt: new Date('2024-09-20'),
});
+121
View File
@@ -0,0 +1,121 @@
### Normal characters
Expression | Description
:--|:--
`.` or `[^\n\r]` | any character *excluding* a newline or carriage return
`[A-Za-z]` | alphabet
`[a-z]` | lowercase alphabet
`[A-Z]` | uppercase alphabet
`\d` or `[0-9]` | digit
`\D` or `[^0-9]` | non-digit
`_` | underscore
`\w` or `[A-Za-z0-9_]` | alphabet, digit or underscore
`\W` or `[^A-Za-z0-9_]` | inverse of `\w`
`\S` | inverse of `\s`
### Whitespace characters
Expression | Description
:--|:--
` ` | space
`\t` | tab
`\n` | newline
`\r` | carriage return
`\s` | space, tab, newline or carriage return
### Character set
Expression | Description
:--|:--
`[xyz]` | either `x`, `y` or `z`
`[^xyz]` | neither `x`, `y` nor `z`
`[1-3]` | either `1`, `2` or `3`
`[^1-3]` | neither `1`, `2` nor `3`
- Think of a character set as an `OR` operation on the single characters that are enclosed between the square brackets.
- Use `^` after the opening `[` to “negate” the character set.
- Within a character set, `.` means a literal period.
### Characters that require escaping
#### Outside a character set
Expression | Description
:--|:--
`\.` | period
`\^` | caret
`\$` | dollar sign
`\|` | pipe
`\\` | back slash
`\/` | forward slash
`\(` | opening bracket
`\)` | closing bracket
`\[` | opening square bracket
`\]` | closing square bracket
`\{` | opening curly bracket
`\}` | closing curly bracket
#### Inside a character set
Expression | Description
:--|:--
`\\` | back slash
`\]` | closing square bracket
- A `^` must be escaped only if it occurs immediately after the opening `[` of the character set.
- A `-` must be escaped only if it occurs between two alphabets or two digits.
### Quantifiers
Expression | Description
:--|:--
`{2}` | exactly 2
`{2,}` | at least 2
`{2,7}` | at least 2 but no more than 7
`*` | 0 or more
`+` | 1 or more
`?` | exactly 0 or 1
- The quantifier goes *after* the expression to be quantified.
### Boundaries
Expression | Description
:--|:--
`^` | start of string
`$` | end of string
`\b` | word boundary
- How word boundary matching works:
- At the beginning of the string if the first character is `\w`.
- Between two adjacent characters within the string, if the first character is `\w` and the second character is `\W`.
- At the end of the string if the last character is `\w`.
### Matching
Expression | Description
:--|:--
`foo\|bar` | match either `foo` or `bar`
`foo(?=bar)` | match `foo` if it’s before `bar`
`foo(?!bar)` | match `foo` if it’s *not* before `bar`
`(?<=bar)foo` | match `foo` if it’s after `bar`
`(?<!bar)foo` | match `foo` if it’s *not* after `bar`
### Grouping and capturing
Expression | Description
:--|:--
`(foo)` | capturing group; match and capture `foo`
`(?:foo)` | non-capturing group; match `foo` but *without* capturing `foo`
`(foo)bar\1` | `\1` is a backreference to the 1st capturing group; match `foobarfoo`
- Capturing groups are only relevant in the following methods:
- `string.match(regexp)`
- `string.matchAll(regexp)`
- `string.replace(regexp, callback)`
- `\N` is a backreference to the `Nth` capturing group. Capturing groups are numbered starting from 1.
## References and tools
- [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
- [RegExplained](https://leaverou.github.io/regexplained/)
+32
View File
@@ -0,0 +1,32 @@
<script setup lang="ts">
import { useThemeVars } from 'naive-ui';
import Memo from './regex-memo.content.md';
const themeVars = useThemeVars();
</script>
<template>
<div>
<Memo />
</div>
</template>
<style lang="less" scoped>
::v-deep(pre) {
margin: 0;
padding: 15px 22px;
background-color: v-bind('themeVars.cardColor');
border-radius: 4px;
overflow: auto;
}
::v-deep(table) {
border-collapse: collapse;
}
::v-deep(table), ::v-deep(td), ::v-deep(th) {
border: 1px solid v-bind('themeVars.textColor1');
padding: 5px;
}
::v-deep(a) {
color: v-bind('themeVars.textColor1');
}
</style>
+12
View File
@@ -0,0 +1,12 @@
import { Language } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Regex Tester',
path: '/regex-tester',
description: 'Test your regular expressions with sample text.',
keywords: ['regex', 'tester', 'sample', 'expression'],
component: () => import('./regex-tester.vue'),
icon: Language,
createdAt: new Date('2024-09-20'),
});
@@ -0,0 +1,106 @@
import { describe, expect, it } from 'vitest';
import { matchRegex } from './regex-tester.service';
const regexesData = [
{
regex: '',
text: '',
flags: '',
result: [],
},
{
regex: '.*',
text: '',
flags: '',
result: [],
},
{
regex: '',
text: 'aaa',
flags: '',
result: [],
},
{
regex: 'a',
text: 'baaa',
flags: '',
result: [
{
captures: [],
groups: [],
index: 1,
value: 'a',
},
],
},
{
regex: '(.)(?<g>r)',
text: 'azertyr',
flags: 'g',
result: [
{
captures: [
{
end: 3,
name: '1',
start: 2,
value: 'e',
},
{
end: 4,
name: '2',
start: 3,
value: 'r',
},
],
groups: [
{
end: 4,
name: 'g',
start: 3,
value: 'r',
},
],
index: 2,
value: 'er',
},
{
captures: [
{
end: 6,
name: '1',
start: 5,
value: 'y',
},
{
end: 7,
name: '2',
start: 6,
value: 'r',
},
],
groups: [
{
end: 7,
name: 'g',
start: 6,
value: 'r',
},
],
index: 5,
value: 'yr',
},
],
},
];
describe('regex-tester', () => {
for (const reg of regexesData) {
const { regex, text, flags, result: expected_result } = reg;
it(`Should matchRegex("${regex}","${text}","${flags}") return correct result`, async () => {
const result = matchRegex(regex, text, `${flags}d`);
expect(result).to.deep.equal(expected_result);
});
}
});
@@ -0,0 +1,61 @@
interface RegExpGroupIndices {
[name: string]: [number, number]
}
interface RegExpIndices extends Array<[number, number]> {
groups: RegExpGroupIndices
}
interface RegExpExecArrayWithIndices extends RegExpExecArray {
indices: RegExpIndices
}
interface GroupCapture {
name: string
value: string
start: number
end: number
};
export function matchRegex(regex: string, text: string, flags: string) {
// if (regex === '' || text === '') {
// return [];
// }
let lastIndex = -1;
const re = new RegExp(regex, flags);
const results = [];
let match = re.exec(text) as RegExpExecArrayWithIndices;
while (match !== null) {
if (re.lastIndex === lastIndex || match[0] === '') {
break;
}
const indices = match.indices;
const captures: Array<GroupCapture> = [];
Object.entries(match).forEach(([captureName, captureValue]) => {
if (captureName !== '0' && captureName.match(/\d+/)) {
captures.push({
name: captureName,
value: captureValue,
start: indices[Number(captureName)][0],
end: indices[Number(captureName)][1],
});
}
});
const groups: Array<GroupCapture> = [];
Object.entries(match.groups || {}).forEach(([groupName, groupValue]) => {
groups.push({
name: groupName,
value: groupValue,
start: indices.groups[groupName][0],
end: indices.groups[groupName][1],
});
});
results.push({
index: match.index,
value: match[0],
captures,
groups,
});
lastIndex = re.lastIndex;
match = re.exec(text) as RegExpExecArrayWithIndices;
}
return results;
}
+193
View File
@@ -0,0 +1,193 @@
<script setup lang="ts">
import RandExp from 'randexp';
import { render } from '@regexper/render';
import type { ShadowRootExpose } from 'vue-shadow-dom';
import { matchRegex } from './regex-tester.service';
import { useValidation } from '@/composable/validation';
import { useQueryParamOrStorage } from '@/composable/queryParams';
const regex = useQueryParamOrStorage({ name: 'regex', storageName: 'regex-tester:regex', defaultValue: '' });
const text = ref('');
const global = ref(true);
const ignoreCase = ref(false);
const multiline = ref(false);
const dotAll = ref(true);
const unicode = ref(true);
const unicodeSets = ref(false);
const visualizerSVG = ref<ShadowRootExpose>();
const regexValidation = useValidation({
source: regex,
rules: [
{
message: 'Invalid regex: {0}',
validator: value => new RegExp(value),
getErrorMessage: (value) => {
const _ = new RegExp(value);
return '';
},
},
],
});
const results = computed(() => {
let flags = 'd';
if (global.value) {
flags += 'g';
}
if (ignoreCase.value) {
flags += 'i';
}
if (multiline.value) {
flags += 'm';
}
if (dotAll.value) {
flags += 's';
}
if (unicode.value) {
flags += 'u';
}
else if (unicodeSets.value) {
flags += 'v';
}
try {
return matchRegex(regex.value, text.value, flags);
}
catch (_) {
return [];
}
});
const sample = computed(() => {
try {
const randexp = new RandExp(new RegExp(regex.value.replace(/\(\?\<[^\>]*\>/g, '(?:')));
return randexp.gen();
}
catch (_) {
return '';
}
});
watchEffect(
async () => {
const regexValue = regex.value;
// shadow root is required:
// @regexper/render append a <defs><style> that broke svg transparency of icons in the whole site
const visualizer = visualizerSVG.value?.shadow_root;
if (visualizer) {
while (visualizer.lastChild) {
visualizer.removeChild(visualizer.lastChild);
}
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
try {
await render(regexValue, svg);
}
catch (_) {
}
visualizer.appendChild(svg);
}
},
);
</script>
<template>
<div max-w-600px>
<c-card title="Regex" mb-1>
<c-input-text
v-model:value="regex"
label="Regex to test:"
placeholder="Put the regex to test"
multiline
rows="3"
:validation="regexValidation"
/>
<router-link target="_blank" to="/regex-memo" mb-1 mt-1>
See Regular Expression Cheatsheet
</router-link>
<n-space>
<n-checkbox v-model:checked="global">
<span title="Global search">Global search. (<code>g</code>)</span>
</n-checkbox>
<n-checkbox v-model:checked="ignoreCase">
<span title="Case-insensitive search">Case-insensitive search. (<code>i</code>)</span>
</n-checkbox>
<n-checkbox v-model:checked="multiline">
<span title="Allows ^ and $ to match next to newline characters.">Multiline(<code>m</code>)</span>
</n-checkbox>
<n-checkbox v-model:checked="dotAll">
<span title="Allows . to match newline characters.">Singleline(<code>s</code>)</span>
</n-checkbox>
<n-checkbox v-model:checked="unicode">
<span title="Unicode; treat a pattern as a sequence of Unicode code points.">Unicode(<code>u</code>)</span>
</n-checkbox>
<n-checkbox v-model:checked="unicodeSets">
<span title="An upgrade to the u mode with more Unicode features.">Unicode Sets (<code>v</code>)</span>
</n-checkbox>
</n-space>
<n-divider />
<c-input-text
v-model:value="text"
label="Text to match:"
placeholder="Put the text to match"
multiline
rows="5"
/>
</c-card>
<c-card title="Matches" mb-1 mt-3>
<n-table v-if="results?.length > 0">
<thead>
<tr>
<th scope="col">
Index in text
</th>
<th scope="col">
Value
</th>
<th scope="col">
Captures
</th>
<th scope="col">
Groups
</th>
</tr>
</thead>
<tbody>
<tr v-for="match of results" :key="match.index">
<td>{{ match.index }}</td>
<td>{{ match.value }}</td>
<td>
<ul>
<li v-for="capture in match.captures" :key="capture.name">
"{{ capture.name }}" = {{ capture.value }} [{{ capture.start }} - {{ capture.end }}]
</li>
</ul>
</td>
<td>
<ul>
<li v-for="group in match.groups" :key="group.name">
"{{ group.name }}" = {{ group.value }} [{{ group.start }} - {{ group.end }}]
</li>
</ul>
</td>
</tr>
</tbody>
</n-table>
<c-alert v-else>
No match
</c-alert>
</c-card>
<c-card title="Sample matching text" mt-3>
<pre style="white-space: pre-wrap; word-break: break-all;">{{ sample }}</pre>
</c-card>
<c-card title="Regex Diagram" style="overflow-x: scroll;" mt-3>
<shadow-root ref="visualizerSVG">
&#xa0;
</shadow-root>
</c-card>
</div>
</template>
-2
View File
@@ -15,7 +15,6 @@ import { VitePWA } from 'vite-plugin-pwa';
import markdown from 'vite-plugin-vue-markdown';
import svgLoader from 'vite-svg-loader';
import { configDefaults } from 'vitest/config';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
const baseUrl = process.env.BASE_URL ?? '/';
@@ -98,7 +97,6 @@ export default defineConfig({
resolvers: [NaiveUiResolver(), IconsResolver({ prefix: 'icon' })],
}),
Unocss(),
nodePolyfills(),
],
base: baseUrl,
resolve: {