Compare commits

..
Author SHA1 Message Date
ShareVB 7170450aba fix: better UI 2024-10-07 22:30:25 +02:00
sharevb e86e9212d5 feat(new tool): Bounce Email Parser
Parse SMTP bounce emails
2024-10-06 17:04:01 +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
23 changed files with 780 additions and 1050 deletions

No files matched your search

+5 -6
View File
@@ -20,6 +20,7 @@ declare module '@vue/runtime-core' {
Bcrypt: typeof import('./src/tools/bcrypt/bcrypt.vue')['default']
BenchmarkBuilder: typeof import('./src/tools/benchmark-builder/benchmark-builder.vue')['default']
Bip39Generator: typeof import('./src/tools/bip39-generator/bip39-generator.vue')['default']
BounceParser: typeof import('./src/tools/bounce-parser/bounce-parser.vue')['default']
CAlert: typeof import('./src/ui/c-alert/c-alert.vue')['default']
'CAlert.demo': typeof import('./src/ui/c-alert/c-alert.demo.vue')['default']
CameraRecorder: typeof import('./src/tools/camera-recorder/camera-recorder.vue')['default']
@@ -73,7 +74,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']
@@ -131,7 +131,6 @@ 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']
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
@@ -142,14 +141,11 @@ declare module '@vue/runtime-core' {
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']
NP: typeof import('naive-ui')['NP']
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']
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 +153,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']
+5 -7
View File
@@ -37,14 +37,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",
@@ -60,6 +59,7 @@
"crypto-js": "^4.1.1",
"date-fns": "^2.29.3",
"dompurify": "^3.0.6",
"email-bounce-parser-browser": "^1.1",
"email-normalizer": "^1.0.0",
"emojilib": "^3.0.10",
"figlet": "^1.7.0",
@@ -68,7 +68,6 @@
"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",
"json5": "^2.2.3",
"jwt-decode": "^3.1.2",
@@ -86,9 +85,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 +96,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,7 +140,6 @@
"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",
+57 -663
View File
File diff suppressed because it is too large. Load diff
BIN
View File
Binary file not shown.
+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';
}
}
+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');
+66
View File
@@ -0,0 +1,66 @@
<script setup lang="ts">
import EmailBounceParse from 'email-bounce-parser-browser';
const emailContent = ref('');
const parsedBounce = computed(() => {
try {
return { email: new EmailBounceParse().read(emailContent.value) };
}
catch (e: any) {
return { parsingError: e.toString() };
}
});
</script>
<template>
<div style="max-width: 600px;">
<c-card title="Input" mb-2>
<c-input-text
v-model:value="emailContent"
label="Bounce Email Textual Content"
multiline
placeholder="Put your email text content here..."
rows="15"
mb-2
/>
</c-card>
<c-card v-if="parsedBounce && emailContent" title="Output" mb-2>
<n-p v-if="parsedBounce.email?.email?.error" style="color: green" mb-2>
This mail is a bounce email
</n-p>
<n-p v-if="!parsedBounce.email?.email?.error" style="color: red" mb-2>
This mail is NOT a bounce email
</n-p>
<c-alert v-if="parsedBounce.parsingError" mb-2>
{{ parsedBounce.parsingError }}
</c-alert>
<input-copyable v-if="parsedBounce.email?.data?.recipient" label="Recipient" :value="parsedBounce.email?.data?.recipient" mb-2 />
<div v-if="parsedBounce.email?.email?.error">
<c-card title="Error" mb-2>
<input-copyable v-if="parsedBounce.email?.data?.command" label="Command" :value="parsedBounce.email?.data?.command" />
<input-copyable v-if="parsedBounce.email?.data?.error?.code?.basic || parsedBounce.email?.data?.error?.code?.enhanced" label="Code" :value="`${parsedBounce.email?.data?.error?.code?.basic}/${parsedBounce.email?.data?.error?.code?.enhanced}`" />
<input-copyable v-if="parsedBounce.email?.data?.error?.label" label="Label" :value="parsedBounce.email?.data?.error?.label" />
<input-copyable v-if="parsedBounce.email?.data?.error?.type" label="Type" :value="parsedBounce.email?.data?.error?.type" />
<input-copyable v-if="parsedBounce.email?.data?.error?.temporary" label="Temporary" :value="parsedBounce.email?.data?.error?.temporary" />
<input-copyable v-if="parsedBounce.email?.data?.error?.permanent" label="Permanent" :value="parsedBounce.email?.data?.error?.permanent" />
<input-copyable v-if="parsedBounce.email?.data?.error?.data?.type" label="Subtype" :value="parsedBounce.email?.data?.error?.data?.type" />
<input-copyable v-if="parsedBounce.email?.data?.error?.data?.blocked" label="Blocked" :value="parsedBounce.email?.data?.error?.data?.blocked" />
<input-copyable v-if="parsedBounce.email?.data?.error?.data?.spam" label="Spam" :value="parsedBounce.email?.data?.error?.data?.spam" />
</c-card>
<c-card v-if="parsedBounce.email?.data?.server?.hostname || parsedBounce.email?.data?.server?.ip" title="Server" mb-2>
<input-copyable v-if="parsedBounce.email?.data?.server?.hostname" label="Host" :value="parsedBounce.email?.data?.server?.hostname" />
<input-copyable v-if="parsedBounce.email?.data?.server?.ip" label="IP" :value="parsedBounce.email?.data?.server?.ip" />
<input-copyable v-if="parsedBounce.email?.data?.server?.port" label="Port" :value="parsedBounce.email?.data?.server?.port" />
</c-card>
<c-card title="Details" mb-2>
<textarea-copyable :value="JSON.stringify(parsedBounce.email?.data, null, 2)" />
</c-card>
<c-card title="Raw Error" mb-2>
<textarea-copyable :value="parsedBounce.email?.email?.error" word-wrap />
</c-card>
</div>
</c-card>
</div>
</template>
@@ -0,0 +1,36 @@
declare module "email-bounce-parser-browser" {
export default class EmailBounceParse {
read(emailContent: string): {
bounce: boolean
email?: {
body?: string
intro?: string
error?: string
}
data?: {
error?: {
code?: {
basic?: string
enhanced?:string
}
label?: string
type?: string
temporary?: boolean
permanent?: boolean
data?: {
type?: string
blocked?: boolean
spam?: boolean
}
}
recipient?:string
server?: {
hostname?: string
ip?: string
port?: string
}
command?: string
}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
import { Mailbox } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Bounce Email Parser',
path: '/bounce-parser',
description: 'Parse SMTP Bounce Emails',
keywords: ['bounce', 'email', 'smtp', 'parser'],
component: () => import('./bounce-parser.vue'),
icon: Mailbox,
createdAt: new Date('2024-08-15'),
});
-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 bounceParser } from './bounce-parser';
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';
@@ -137,6 +138,7 @@ export const toolsByCategory: ToolCategory[] = [
httpStatusCodes,
jsonDiff,
safelinkDecoder,
bounceParser,
],
},
{
@@ -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
@@ -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: 'Regex Tester',
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>
+3 -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: {
@@ -115,4 +113,7 @@ export default defineConfig({
build: {
target: 'esnext',
},
optimizeDeps: {
include: ['re2-wasm-embedded'], // optionally specify dependency name
},
});