Compare commits

..
Author SHA1 Message Date
ShareVB 63c842bdb3 feat(JSON to C#): update to add options from json2csharp.com
rootTypeName (choose root object name)
pascalCase (type and member names)
useFields (instead of properties)
useNullable (types)
addJsonProperty (Newtonsoft) and nullValueHandlingIgnore
addJsonPropertyName (System.Text.Json)
generateImmutableClasses
useRecordTypes
useReadonlyLists
2025-03-08 21:48:19 +01:00
sharevb 748126f207 feat(new tool): JSON to C# 2024-05-19 21:26:05 +02:00
54 changed files with 1199 additions and 1662 deletions

No files matched your search

+1 -4
View File
@@ -286,9 +286,6 @@
"watchTriggerable": true,
"watchWithFilter": true,
"whenever": true,
"toValue": true,
"injectLocal": true,
"provideLocal": true,
"useClipboardItems": true
"toValue": true
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

+2 -6
View File
@@ -1,8 +1,4 @@
<picture>
<source srcset="./.github/logo-dark.png" media="(prefers-color-scheme: light)">
<source srcset="./.github/logo-white.png" media="(prefers-color-scheme: dark)">
<img src="./.github/logo-dark.png" alt="logo">
</picture>
![logo](.github/logo.png)
Useful tools for developer and people working in IT. [Have a look !](https://it-tools.tech).
@@ -117,7 +113,7 @@ Big thanks to all the people who have already contributed!
## Credits
Coded with ❤️ by [Corentin Thomasset](https://corentin.tech?utm_source=it-tools&utm_medium=readme).
Coded with ❤️ by [Corentin Thomasset](//corentin-thomasset.fr).
This project is continuously deployed using [vercel.com](https://vercel.com).
-9
View File
@@ -36,7 +36,6 @@ declare global {
const h: typeof import('vue')['h']
const ignorableWatch: typeof import('@vueuse/core')['ignorableWatch']
const inject: typeof import('vue')['inject']
const injectLocal: typeof import('@vueuse/core')['injectLocal']
const isDefined: typeof import('@vueuse/core')['isDefined']
const isProxy: typeof import('vue')['isProxy']
const isReactive: typeof import('vue')['isReactive']
@@ -66,7 +65,6 @@ declare global {
const onUpdated: typeof import('vue')['onUpdated']
const pausableWatch: typeof import('@vueuse/core')['pausableWatch']
const provide: typeof import('vue')['provide']
const provideLocal: typeof import('@vueuse/core')['provideLocal']
const reactify: typeof import('@vueuse/core')['reactify']
const reactifyObject: typeof import('@vueuse/core')['reactifyObject']
const reactive: typeof import('vue')['reactive']
@@ -130,7 +128,6 @@ declare global {
const useBrowserLocation: typeof import('@vueuse/core')['useBrowserLocation']
const useCached: typeof import('@vueuse/core')['useCached']
const useClipboard: typeof import('@vueuse/core')['useClipboard']
const useClipboardItems: typeof import('@vueuse/core')['useClipboardItems']
const useCloned: typeof import('@vueuse/core')['useCloned']
const useColorMode: typeof import('@vueuse/core')['useColorMode']
const useConfirmDialog: typeof import('@vueuse/core')['useConfirmDialog']
@@ -329,7 +326,6 @@ declare module 'vue' {
readonly h: UnwrapRef<typeof import('vue')['h']>
readonly ignorableWatch: UnwrapRef<typeof import('@vueuse/core')['ignorableWatch']>
readonly inject: UnwrapRef<typeof import('vue')['inject']>
readonly injectLocal: UnwrapRef<typeof import('@vueuse/core')['injectLocal']>
readonly isDefined: UnwrapRef<typeof import('@vueuse/core')['isDefined']>
readonly isProxy: UnwrapRef<typeof import('vue')['isProxy']>
readonly isReactive: UnwrapRef<typeof import('vue')['isReactive']>
@@ -359,7 +355,6 @@ declare module 'vue' {
readonly onUpdated: UnwrapRef<typeof import('vue')['onUpdated']>
readonly pausableWatch: UnwrapRef<typeof import('@vueuse/core')['pausableWatch']>
readonly provide: UnwrapRef<typeof import('vue')['provide']>
readonly provideLocal: UnwrapRef<typeof import('@vueuse/core')['provideLocal']>
readonly reactify: UnwrapRef<typeof import('@vueuse/core')['reactify']>
readonly reactifyObject: UnwrapRef<typeof import('@vueuse/core')['reactifyObject']>
readonly reactive: UnwrapRef<typeof import('vue')['reactive']>
@@ -423,7 +418,6 @@ declare module 'vue' {
readonly useBrowserLocation: UnwrapRef<typeof import('@vueuse/core')['useBrowserLocation']>
readonly useCached: UnwrapRef<typeof import('@vueuse/core')['useCached']>
readonly useClipboard: UnwrapRef<typeof import('@vueuse/core')['useClipboard']>
readonly useClipboardItems: UnwrapRef<typeof import('@vueuse/core')['useClipboardItems']>
readonly useCloned: UnwrapRef<typeof import('@vueuse/core')['useCloned']>
readonly useColorMode: UnwrapRef<typeof import('@vueuse/core')['useColorMode']>
readonly useConfirmDialog: UnwrapRef<typeof import('@vueuse/core')['useConfirmDialog']>
@@ -616,7 +610,6 @@ declare module '@vue/runtime-core' {
readonly h: UnwrapRef<typeof import('vue')['h']>
readonly ignorableWatch: UnwrapRef<typeof import('@vueuse/core')['ignorableWatch']>
readonly inject: UnwrapRef<typeof import('vue')['inject']>
readonly injectLocal: UnwrapRef<typeof import('@vueuse/core')['injectLocal']>
readonly isDefined: UnwrapRef<typeof import('@vueuse/core')['isDefined']>
readonly isProxy: UnwrapRef<typeof import('vue')['isProxy']>
readonly isReactive: UnwrapRef<typeof import('vue')['isReactive']>
@@ -646,7 +639,6 @@ declare module '@vue/runtime-core' {
readonly onUpdated: UnwrapRef<typeof import('vue')['onUpdated']>
readonly pausableWatch: UnwrapRef<typeof import('@vueuse/core')['pausableWatch']>
readonly provide: UnwrapRef<typeof import('vue')['provide']>
readonly provideLocal: UnwrapRef<typeof import('@vueuse/core')['provideLocal']>
readonly reactify: UnwrapRef<typeof import('@vueuse/core')['reactify']>
readonly reactifyObject: UnwrapRef<typeof import('@vueuse/core')['reactifyObject']>
readonly reactive: UnwrapRef<typeof import('vue')['reactive']>
@@ -710,7 +702,6 @@ declare module '@vue/runtime-core' {
readonly useBrowserLocation: UnwrapRef<typeof import('@vueuse/core')['useBrowserLocation']>
readonly useCached: UnwrapRef<typeof import('@vueuse/core')['useCached']>
readonly useClipboard: UnwrapRef<typeof import('@vueuse/core')['useClipboard']>
readonly useClipboardItems: UnwrapRef<typeof import('@vueuse/core')['useClipboardItems']>
readonly useCloned: UnwrapRef<typeof import('@vueuse/core')['useCloned']>
readonly useColorMode: UnwrapRef<typeof import('@vueuse/core')['useColorMode']>
readonly useConfirmDialog: UnwrapRef<typeof import('@vueuse/core')['useConfirmDialog']>
+1 -41
View File
@@ -50,7 +50,6 @@ declare module '@vue/runtime-core' {
'CModal.demo': typeof import('./src/ui/c-modal/c-modal.demo.vue')['default']
CModalValue: typeof import('./src/ui/c-modal-value/c-modal-value.vue')['default']
'CModalValue.demo': typeof import('./src/ui/c-modal-value/c-modal-value.demo.vue')['default']
CodeHighlighter: typeof import('./src/tools/code-highlighter/code-highlighter.vue')['default']
CollapsibleToolMenu: typeof import('./src/components/CollapsibleToolMenu.vue')['default']
ColorConverter: typeof import('./src/tools/color-converter/color-converter.vue')['default']
ColoredCard: typeof import('./src/components/ColoredCard.vue')['default']
@@ -73,7 +72,6 @@ declare module '@vue/runtime-core' {
DockerRunToDockerComposeConverter: typeof import('./src/tools/docker-run-to-docker-compose-converter/docker-run-to-docker-compose-converter.vue')['default']
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']
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']
@@ -91,28 +89,17 @@ declare module '@vue/runtime-core' {
HttpStatusCodes: typeof import('./src/tools/http-status-codes/http-status-codes.vue')['default']
IbanValidatorAndParser: typeof import('./src/tools/iban-validator-and-parser/iban-validator-and-parser.vue')['default']
'IconMdi:brushVariant': typeof import('~icons/mdi/brush-variant')['default']
'IconMdi:contentCopy': typeof import('~icons/mdi/content-copy')['default']
'IconMdi:kettleSteamOutline': typeof import('~icons/mdi/kettle-steam-outline')['default']
IconMdiArrowDown: typeof import('~icons/mdi/arrow-down')['default']
IconMdiArrowRightBottom: typeof import('~icons/mdi/arrow-right-bottom')['default']
IconMdiCamera: typeof import('~icons/mdi/camera')['default']
IconMdiChevronDown: typeof import('~icons/mdi/chevron-down')['default']
IconMdiChevronRight: typeof import('~icons/mdi/chevron-right')['default']
IconMdiClose: typeof import('~icons/mdi/close')['default']
IconMdiContentCopy: typeof import('~icons/mdi/content-copy')['default']
IconMdiDeleteOutline: typeof import('~icons/mdi/delete-outline')['default']
IconMdiDownload: typeof import('~icons/mdi/download')['default']
IconMdiEye: typeof import('~icons/mdi/eye')['default']
IconMdiEyeOff: typeof import('~icons/mdi/eye-off')['default']
IconMdiHeart: typeof import('~icons/mdi/heart')['default']
IconMdiPause: typeof import('~icons/mdi/pause')['default']
IconMdiPlay: typeof import('~icons/mdi/play')['default']
IconMdiRecord: typeof import('~icons/mdi/record')['default']
IconMdiRefresh: typeof import('~icons/mdi/refresh')['default']
IconMdiSearch: typeof import('~icons/mdi/search')['default']
IconMdiTranslate: typeof import('~icons/mdi/translate')['default']
IconMdiTriangleDown: typeof import('~icons/mdi/triangle-down')['default']
IconMdiVideo: typeof import('~icons/mdi/video')['default']
InputCopyable: typeof import('./src/components/InputCopyable.vue')['default']
IntegerBaseConverter: typeof import('./src/tools/integer-base-converter/integer-base-converter.vue')['default']
Ipv4AddressConverter: typeof import('./src/tools/ipv4-address-converter/ipv4-address-converter.vue')['default']
@@ -121,9 +108,9 @@ 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']
JsonToCsharp: typeof import('./src/tools/json-to-csharp/json-to-csharp.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']
JsonToYaml: typeof import('./src/tools/json-to-yaml-converter/json-to-yaml.vue')['default']
JsonViewer: typeof import('./src/tools/json-viewer/json-viewer.vue')['default']
JwtParser: typeof import('./src/tools/jwt-parser/jwt-parser.vue')['default']
@@ -133,7 +120,6 @@ declare module '@vue/runtime-core' {
LoremIpsumGenerator: typeof import('./src/tools/lorem-ipsum-generator/lorem-ipsum-generator.vue')['default']
MacAddressGenerator: typeof import('./src/tools/mac-address-generator/mac-address-generator.vue')['default']
MacAddressLookup: typeof import('./src/tools/mac-address-lookup/mac-address-lookup.vue')['default']
MarkdownToHtml: typeof import('./src/tools/markdown-to-html/markdown-to-html.vue')['default']
MathEvaluator: typeof import('./src/tools/math-evaluator/math-evaluator.vue')['default']
MenuBar: typeof import('./src/tools/html-wysiwyg-editor/editor/menu-bar.vue')['default']
MenuBarItem: typeof import('./src/tools/html-wysiwyg-editor/editor/menu-bar-item.vue')['default']
@@ -141,42 +127,20 @@ declare module '@vue/runtime-core' {
MenuLayout: typeof import('./src/components/MenuLayout.vue')['default']
MetaTagGenerator: typeof import('./src/tools/meta-tag-generator/meta-tag-generator.vue')['default']
MimeTypes: typeof import('./src/tools/mime-types/mime-types.vue')['default']
NAlert: typeof import('naive-ui')['NAlert']
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
NButton: typeof import('naive-ui')['NButton']
NCheckbox: typeof import('naive-ui')['NCheckbox']
NCode: typeof import('naive-ui')['NCode']
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
NColorPicker: typeof import('naive-ui')['NColorPicker']
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDatePicker: typeof import('naive-ui')['NDatePicker']
NDivider: typeof import('naive-ui')['NDivider']
NDynamicInput: typeof import('naive-ui')['NDynamicInput']
NEllipsis: typeof import('naive-ui')['NEllipsis']
NForm: typeof import('naive-ui')['NForm']
NFormItem: typeof import('naive-ui')['NFormItem']
NGi: typeof import('naive-ui')['NGi']
NGrid: typeof import('naive-ui')['NGrid']
NH1: typeof import('naive-ui')['NH1']
NH2: typeof import('naive-ui')['NH2']
NH3: typeof import('naive-ui')['NH3']
NIcon: typeof import('naive-ui')['NIcon']
NImage: typeof import('naive-ui')['NImage']
NInputGroup: typeof import('naive-ui')['NInputGroup']
NInputGroupLabel: typeof import('naive-ui')['NInputGroupLabel']
NInputNumber: typeof import('naive-ui')['NInputNumber']
NLayout: typeof import('naive-ui')['NLayout']
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
NMenu: typeof import('naive-ui')['NMenu']
NProgress: typeof import('naive-ui')['NProgress']
NScrollbar: typeof import('naive-ui')['NScrollbar']
NSlider: typeof import('naive-ui')['NSlider']
NSpace: typeof import('naive-ui')['NSpace']
NSpin: typeof import('naive-ui')['NSpin']
NStatistic: typeof import('naive-ui')['NStatistic']
NSwitch: typeof import('naive-ui')['NSwitch']
NTable: typeof import('naive-ui')['NTable']
NTag: typeof import('naive-ui')['NTag']
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']
PasswordStrengthAnalyser: typeof import('./src/tools/password-strength-analyser/password-strength-analyser.vue')['default']
@@ -186,9 +150,6 @@ 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']
@@ -221,7 +182,6 @@ declare module '@vue/runtime-core' {
UuidGenerator: typeof import('./src/tools/uuid-generator/uuid-generator.vue')['default']
WifiQrCodeGenerator: typeof import('./src/tools/wifi-qr-code-generator/wifi-qr-code-generator.vue')['default']
XmlFormatter: typeof import('./src/tools/xml-formatter/xml-formatter.vue')['default']
XmlToJson: typeof import('./src/tools/xml-to-json/xml-to-json.vue')['default']
YamlToJson: typeof import('./src/tools/yaml-to-json-converter/yaml-to-json.vue')['default']
YamlToToml: typeof import('./src/tools/yaml-to-toml/yaml-to-toml.vue')['default']
YamlViewer: typeof import('./src/tools/yaml-viewer/yaml-viewer.vue')['default']
+1 -1
View File
@@ -38,7 +38,7 @@ about:
# Über IT-Tools
Diese wunderbare Website, erstellt mit ❤ von [Corentin
Thomasset](https://corentin.tech?utm_source=it-tools&utm_medium=about), sammelt nützliche Tools für
Thomasset](https://github.com/CorentinTh), 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://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!
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!
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://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!
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!
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://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 !
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 !
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://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!
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!
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://corentin.tech?utm_source=it-tools&utm_medium=about), агрегує корисні інструменти для розробників і людей, які працюють в сфері IT. Якщо вам це корисно, будь ласка, поділіться цим з людьми, які, на вашу думку, також можуть знайти його корисним, і не забудьте додати його до закладок у вашій панелі швидкого доступу!
Цей чудовий вебсайт, створений з ❤ [Corentin Thomasset](https://github.com/CorentinTh), агрегує корисні інструменти для розробників і людей, які працюють в сфері 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://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!
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!
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://corentin.tech?utm_source=it-tools&utm_medium=about) 用 ❤ 开发,汇集了对开发人员和 IT 从业者有用的工具。如果对您有帮助,请将其分享给您的朋友,并且添加到收藏夹中!
IT-Tools 由 [Corentin Thomasset](https://github.com/CorentinTh) 用 ❤ 开发,汇集了对开发人员和 IT 从业者有用的工具。如果对您有帮助,请将其分享给您的朋友,并且添加到收藏夹中!
IT-Tools 永久免费且开源(MIT 许可证),但需要资金用于托管和续订域名。如果您想支持我的工作,并鼓励我添加更多工具,请考虑通过 [赞助我](https://www.buymeacoffee.com/cthmsst) 进行支持。
+7 -18
View File
@@ -1,14 +1,7 @@
{
"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",
@@ -20,6 +13,12 @@
"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",
@@ -38,16 +37,14 @@
"dependencies": {
"@it-tools/bip39": "^0.0.4",
"@it-tools/oggen": "^1.3.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/figlet": "^1.5.8",
"@types/markdown-it": "^13.0.7",
"@vicons/material": "^0.12.0",
"@vicons/tabler": "^0.12.0",
"@vueuse/core": "^10.11.1",
"@vueuse/core": "^10.3.0",
"@vueuse/head": "^1.0.0",
"@vueuse/router": "^10.0.0",
"bcryptjs": "^2.4.3",
@@ -60,7 +57,6 @@
"crypto-js": "^4.1.1",
"date-fns": "^2.29.3",
"dompurify": "^3.0.6",
"email-normalizer": "^1.0.0",
"emojilib": "^3.0.10",
"figlet": "^1.7.0",
"figue": "^1.2.0",
@@ -68,12 +64,10 @@
"highlight.js": "^11.7.0",
"iarna-toml-esm": "^3.0.5",
"ibantools": "^4.3.3",
"js-base64": "^3.7.6",
"json5": "^2.2.3",
"jwt-decode": "^3.1.2",
"libphonenumber-js": "^1.10.28",
"lodash": "^4.17.21",
"markdown-it": "^14.0.0",
"marked": "^10.0.0",
"mathjs": "^11.9.1",
"mime-types": "^2.1.35",
@@ -86,9 +80,6 @@
"pinia": "^2.0.34",
"plausible-tracker": "^0.3.8",
"qrcode": "^1.5.1",
"randexp": "^0.5.3",
"regex": "^4.3.3",
"shiki": "^1.22.0",
"sql-formatter": "^13.0.0",
"ua-parser-js": "^1.0.35",
"ulid": "^2.3.0",
@@ -98,10 +89,8 @@
"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",
"yaml": "^2.2.1"
},
"devDependencies": {
+189 -416
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -48,7 +48,7 @@ const output = computed(() => transformer.value(input.value));
monospace
/>
<div overflow-auto>
<div>
<div mb-5px>
{{ outputLabel }}
</div>
-2
View File
@@ -7,7 +7,6 @@ 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 markdownHljs from 'highlight.js/lib/languages/markdown';
import { useCopy } from '@/composable/copy';
const props = withDefaults(
@@ -31,7 +30,6 @@ hljs.registerLanguage('html', xmlHljs);
hljs.registerLanguage('xml', xmlHljs);
hljs.registerLanguage('yaml', yamlHljs);
hljs.registerLanguage('toml', iniHljs);
hljs.registerLanguage('markdown', markdownHljs);
const { value, language, followHeightOf, copyPlacement, copyMessage } = toRefs(props);
const { height } = followHeightOf.value ? useElementSize(followHeightOf) : { height: ref(null) };
+1 -32
View File
@@ -1,5 +1,5 @@
// eslint-disable-next-line no-restricted-imports
import { useClipboard, useClipboardItems } from '@vueuse/core';
import { useClipboard } from '@vueuse/core';
import { useMessage } from 'naive-ui';
import type { MaybeRefOrGetter } from 'vue';
@@ -28,34 +28,3 @@ export function useCopy({ source, text = 'Copied to the clipboard', createToast
},
};
}
export function useCopyClipboardItems({ source, text = 'Copied to the clipboard', createToast = true }: { source?: MaybeRefOrGetter<Array<{ mime: string; content: string }>>; text?: string; createToast?: boolean } = {}) {
function toClipboardItem(item: { mime: string; content: string }) {
return new ClipboardItem({
[item.mime]: new Blob([item.content], { type: item.mime }),
});
}
const sourceClipboardItems = computed(() => (toValue(source) || []).map(toClipboardItem));
const { copy, copied, ...rest } = useClipboardItems({
source: sourceClipboardItems,
});
const message = useMessage();
return {
...rest,
isJustCopied: copied,
async copy(content?: { mime: string; content: string }[], { notificationMessage }: { notificationMessage?: string } = {}) {
if (source) {
await copy();
}
else {
await copy((content || []).map(toClipboardItem));
}
if (createToast) {
message.success(notificationMessage ?? text);
}
},
};
}
-21
View File
@@ -1,21 +0,0 @@
import _ from 'lodash';
function useDebouncedRef<T>(initialValue: T, delay: number, immediate: boolean = false) {
const state = ref(initialValue);
const debouncedRef = customRef((track, trigger) => ({
get() {
track();
return state.value;
},
set: _.debounce(
(value) => {
state.value = value;
trigger();
},
delay,
{ leading: immediate },
),
}));
return debouncedRef;
}
export default useDebouncedRef;
+19 -72
View File
@@ -1,13 +1,8 @@
import { extension as getExtensionFromMimeType, extension as getMimeTypeFromExtension } from 'mime-types';
import { extension as getExtensionFromMime } from 'mime-types';
import type { Ref } from 'vue';
import _ from 'lodash';
export {
getMimeTypeFromBase64,
getMimeTypeFromExtension, getExtensionFromMimeType,
useDownloadFileFromBase64, useDownloadFileFromBase64Refs,
previewImageFromBase64,
};
export { getMimeTypeFromBase64, useDownloadFileFromBase64 };
const commonMimeTypesSignatures = {
'JVBERi0': 'application/pdf',
@@ -41,78 +36,30 @@ function getFileExtensionFromMimeType({
defaultExtension?: string
}) {
if (mimeType) {
return getExtensionFromMimeType(mimeType) ?? defaultExtension;
return getExtensionFromMime(mimeType) ?? defaultExtension;
}
return defaultExtension;
}
function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }:
{ sourceValue: string; filename?: string; extension?: string; fileMimeType?: string }) {
if (sourceValue === '') {
throw new Error('Base64 string is empty');
}
const defaultExtension = extension ?? 'txt';
const { mimeType } = getMimeTypeFromBase64({ base64String: sourceValue });
let base64String = sourceValue;
if (!mimeType) {
const targetMimeType = fileMimeType ?? getMimeTypeFromExtension(defaultExtension);
base64String = `data:${targetMimeType};base64,${sourceValue}`;
}
const cleanExtension = extension ?? getFileExtensionFromMimeType(
{ mimeType, defaultExtension });
let cleanFileName = filename ?? `file.${cleanExtension}`;
if (extension && !cleanFileName.endsWith(`.${extension}`)) {
cleanFileName = `${cleanFileName}.${cleanExtension}`;
}
const a = document.createElement('a');
a.href = base64String;
a.download = cleanFileName;
a.click();
}
function useDownloadFileFromBase64(
{ source, filename, extension, fileMimeType }:
{ source: Ref<string>; filename?: string; extension?: string; fileMimeType?: string }) {
function useDownloadFileFromBase64({ source, filename }: { source: Ref<string>; filename?: string }) {
return {
download() {
downloadFromBase64({ sourceValue: source.value, filename, extension, fileMimeType });
if (source.value === '') {
throw new Error('Base64 string is empty');
}
const { mimeType } = getMimeTypeFromBase64({ base64String: source.value });
const base64String = mimeType
? source.value
: `data:text/plain;base64,${source.value}`;
const cleanFileName = filename ?? `file.${getFileExtensionFromMimeType({ mimeType })}`;
const a = document.createElement('a');
a.href = base64String;
a.download = cleanFileName;
a.click();
},
};
}
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 });
},
};
}
function previewImageFromBase64(base64String: string): HTMLImageElement {
if (base64String === '') {
throw new Error('Base64 string is empty');
}
const img = document.createElement('img');
img.src = base64String;
const container = document.createElement('div');
container.appendChild(img);
const previewContainer = document.getElementById('previewContainer');
if (previewContainer) {
previewContainer.innerHTML = '';
previewContainer.appendChild(container);
}
else {
throw new Error('Preview container element not found');
}
return img;
}
+1 -18
View File
@@ -3,11 +3,9 @@ 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
}
@@ -26,15 +24,6 @@ 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
@@ -72,13 +61,7 @@ export function useValidation<T>({
for (const rule of get(rules)) {
if (isFalsyOrHasThrown(() => rule.validator(source.value))) {
if (rule.getErrorMessage) {
const getErrorMessage = rule.getErrorMessage;
state.message = rule.message.replace('{0}', getErrorMessageOrThrown(() => getErrorMessage(source.value)));
}
else {
state.message = rule.message;
}
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://corentin.tech?utm_source=it-tools&utm_medium=footer">
<c-link target="_blank" rel="noopener" href="https://github.com/CorentinTh">
Corentin Thomasset
</c-link>
</div>
-2
View File
@@ -3,7 +3,6 @@ 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';
@@ -24,6 +23,5 @@ app.use(i18nPlugin);
app.use(router);
app.use(naive);
app.use(plausible);
app.use(shadow);
app.mount('#app');
@@ -2,19 +2,12 @@
import { useBase64 } from '@vueuse/core';
import type { Ref } from 'vue';
import { useCopy } from '@/composable/copy';
import { getExtensionFromMimeType, getMimeTypeFromBase64, previewImageFromBase64, useDownloadFileFromBase64Refs } from '@/composable/downloadBase64';
import { useDownloadFileFromBase64 } from '@/composable/downloadBase64';
import { useValidation } from '@/composable/validation';
import { isValidBase64 } from '@/utils/base64';
const fileName = ref('file');
const fileExtension = ref('');
const base64Input = ref('');
const { download } = useDownloadFileFromBase64Refs(
{
source: base64Input,
filename: fileName,
extension: fileExtension,
});
const { download } = useDownloadFileFromBase64({ source: base64Input });
const base64InputValidation = useValidation({
source: base64Input,
rules: [
@@ -25,35 +18,6 @@ const base64InputValidation = useValidation({
],
});
watch(
base64Input,
(newValue, _) => {
const { mimeType } = getMimeTypeFromBase64({ base64String: newValue });
if (mimeType) {
fileExtension.value = getExtensionFromMimeType(mimeType) || fileExtension.value;
}
},
);
function previewImage() {
if (!base64InputValidation.isValid) {
return;
}
try {
const image = previewImageFromBase64(base64Input.value);
image.style.maxWidth = '100%';
image.style.maxHeight = '400px';
const previewContainer = document.getElementById('previewContainer');
if (previewContainer) {
previewContainer.innerHTML = '';
previewContainer.appendChild(image);
}
}
catch (_) {
//
}
}
function downloadFile() {
if (!base64InputValidation.isValid) {
return;
@@ -80,24 +44,6 @@ async function onUpload(file: File) {
<template>
<c-card title="Base64 to file">
<n-grid cols="3" x-gap="12">
<n-gi span="2">
<c-input-text
v-model:value="fileName"
label="File Name"
placeholder="Download filename"
mb-2
/>
</n-gi>
<n-gi>
<c-input-text
v-model:value="fileExtension"
label="Extension"
placeholder="Extension"
mb-2
/>
</n-gi>
</n-grid>
<c-input-text
v-model:value="base64Input"
multiline
@@ -107,14 +53,7 @@ async function onUpload(file: File) {
mb-2
/>
<div flex justify-center py-2>
<div id="previewContainer" />
</div>
<div flex justify-center gap-3>
<c-button :disabled="base64Input === '' || !base64InputValidation.isValid" @click="previewImage()">
Preview image
</c-button>
<div flex justify-center>
<c-button :disabled="base64Input === '' || !base64InputValidation.isValid" @click="downloadFile()">
Download file
</c-button>
@@ -1,133 +0,0 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { bundledLanguagesInfo, createHighlighter } from 'shiki/bundle/full';
import { bundledThemesInfo } from 'shiki/themes';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { useCopy, useCopyClipboardItems } from '@/composable/copy';
const code = ref(`// Using 'typeof' to infer types
const person = { name: "Alice", age: 30 };
type PersonType = typeof person; // { name: string; age: number }
// 'satisfies' to ensure a type matches but allows more specific types
type Animal = { name: string };
const dog = { name: "Buddy", breed: "Golden Retriever" } satisfies Animal;
// Generics with 'extends' and default values
function identity<T extends number | string = string>(arg: T): T {
return arg;
}`);
const themes = ref<{ value: string; label: string }[]>(
bundledThemesInfo.map((item) => {
return {
value: item.id,
label: item.displayName,
};
}));
const langs = ref<{ value: string; label: string }[]>(
bundledLanguagesInfo.map(item => ({
value: item.id,
label: item.name,
})));
const currentTheme = useQueryParamOrStorage({ name: 'theme', storageName: 'code-highlighter:theme', defaultValue: 'dark-plus' });
const currentLang = useQueryParamOrStorage({ name: 'lang', storageName: 'code-highlighter:lang', defaultValue: 'typescript' });
const showLineNumbers = ref(false);
const formattedCodeHtml = computedAsync(async () => {
const currentThemeValue = currentTheme.value;
const currentLangValue = currentLang.value;
const codeValue = code.value;
const needLineNumbers = showLineNumbers.value;
const lineNumberWidth = Math.log10(codeValue.split('\n').length) + 2;
const highlighter = await createHighlighter(
{
langs: [currentLangValue],
themes: [currentThemeValue],
});
return highlighter.codeToHtml(codeValue, {
lang: currentLangValue,
theme: currentThemeValue,
transformers: [
{
postprocess(html: string) {
// when copied to clipboard and pasted to LibreOffice,
// formatting of first line is only kept if there is a line break before...
const ensureFirstLineFormattedWhenCopied
= (html: string) => html.replace('<code>', '<code>\n');
if (!needLineNumbers) {
return ensureFirstLineFormattedWhenCopied(html);
}
let lineNumber = 1;
return html.replace(/<span class="line/g, (m) => {
const lineNumberFormatted = (lineNumber++).toString().padStart(lineNumberWidth, ' ');
return `<span class="line-number" style="white-space-collapse: preserve">${lineNumberFormatted} </span>${m}`;
}).replace('<code>', '<code>\n');
},
},
],
});
});
const htmlClipboardItems = computed(() => [{
mime: 'text/html',
content: formattedCodeHtml.value,
}]);
const { copy: copyHtml } = useCopyClipboardItems({ source: htmlClipboardItems });
const { copy: copyText } = useCopy({ source: code });
</script>
<template>
<div>
<div mb-3 flex items-baseline gap-1>
<c-select
v-model:value="currentLang"
label="Language"
label-position="left"
searchable
:options="langs"
flex-1
/>
<c-select
v-model:value="currentTheme"
label="Theme"
label-position="left"
searchable
:options="themes"
flex-1
/>
</div>
<c-input-text
v-model:value="code"
label="Code snippet to format:"
multiline
placeholder="Put your code snippet here"
rows="5"
mb-3
/>
<div flex justify-center gap-2>
<n-form-item label="Show line numbers" label-placement="left">
<n-switch v-model:value="showLineNumbers" />
</n-form-item>
<c-button @click="copyHtml()">
Copy HTML Formatted
</c-button>
<c-button @click="copyText()">
Copy Code Text
</c-button>
</div>
<div v-html="formattedCodeHtml" /><!-- //NOSONAR -->
</div>
</template>
<style scoped>
::v-deep(.line-number) {
text-wrap: nowrap;
}
</style>
-12
View File
@@ -1,12 +0,0 @@
import { Code } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Code/Scripts Highlighter',
path: '/code-highlighter',
description: 'Highlight programming code fragments',
keywords: ['code', 'highlighter'],
component: () => import('./code-highlighter.vue'),
icon: Code,
createdAt: new Date('2024-08-15'),
});
@@ -1,65 +0,0 @@
<script setup lang="ts">
import { normalizeEmail } from 'email-normalizer';
import { withDefaultOnError } from '@/utils/defaults';
import { useCopy } from '@/composable/copy';
const emails = ref('');
const normalizedEmails = computed(() => {
if (!emails.value) {
return '';
}
return emails.value
.split('\n')
.map((email) => {
return withDefaultOnError(() => normalizeEmail({ email }), `Unable to parse email: ${email}`);
})
.join('\n');
});
const { copy } = useCopy({ source: normalizedEmails, text: 'Normalized emails copied to the clipboard', createToast: true });
</script>
<template>
<div>
<div class="mb-2">
Raw emails to normalize:
</div>
<c-input-text
v-model:value="emails"
placeholder="Put your emails here (one per line)..."
rows="3"
multiline
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"
autofocus
monospace
/>
<div class="mb-2 mt-4">
Normalized emails:
</div>
<c-input-text
:value="normalizedEmails"
placeholder="Normalized emails will appear here..."
rows="3"
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"
multiline
readonly
monospace
/>
<div class="mt-4 flex justify-center gap-2">
<c-button @click="emails = ''">
Clear emails
</c-button>
<c-button :disabled="!normalizedEmails" @click="copy()">
Copy normalized emails
</c-button>
</div>
</div>
</template>
-12
View File
@@ -1,12 +0,0 @@
import { Mail } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Email normalizer',
path: '/email-normalizer',
description: 'Normalize email addresses to a standard format for easier comparison. Useful for deduplication and data cleaning.',
keywords: ['email', 'normalizer'],
component: () => import('./email-normalizer.vue'),
icon: Mail,
createdAt: new Date('2024-08-15'),
});
+1 -2
View File
@@ -4,7 +4,6 @@ import emojiKeywords from 'emojilib';
import _ from 'lodash';
import type { EmojiInfo } from './emoji.types';
import { useFuzzySearch } from '@/composable/fuzzySearch';
import useDebouncedRef from '@/composable/debouncedref';
const escapeUnicode = ({ emoji }: { emoji: string }) => emoji.split('').map(unit => `\\u${unit.charCodeAt(0).toString(16).padStart(4, '0')}`).join('');
const getEmojiCodePoints = ({ emoji }: { emoji: string }) => emoji.codePointAt(0) ? `0x${emoji.codePointAt(0)?.toString(16)}` : undefined;
@@ -24,7 +23,7 @@ const emojisGroups: { emojiInfos: EmojiInfo[]; group: string }[] = _
.map((emojiInfos, group) => ({ group, emojiInfos }))
.value();
const searchQuery = useDebouncedRef('', 500);
const searchQuery = ref('');
const { searchResult } = useFuzzySearch({
search: searchQuery,
+2 -14
View File
@@ -1,18 +1,12 @@
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 codeHighlighter } from './code-highlighter';
import { tool as jsonToCsharp } from './json-to-csharp';
import { tool as asciiTextDrawer } from './ascii-text-drawer';
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';
import { tool as macAddressGenerator } from './mac-address-generator';
@@ -114,9 +108,7 @@ export const toolsByCategory: ToolCategory[] = [
listConverter,
tomlToJson,
tomlToYaml,
xmlToJson,
jsonToXml,
markdownToHtml,
jsonToCsharp,
],
},
{
@@ -158,10 +150,6 @@ export const toolsByCategory: ToolCategory[] = [
dockerRunToDockerComposeConverter,
xmlFormatter,
yamlViewer,
emailNormalizer,
codeHighlighter,
regexTester,
regexMemo,
],
},
{
+12
View File
@@ -0,0 +1,12 @@
import { CSharp } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'JSON to C#',
path: '/json-to-csharp',
description: 'Convert JSON data to C# type definition',
keywords: ['json', 'c#', 'csharp'],
component: () => import('./json-to-csharp.vue'),
icon: CSharp,
createdAt: new Date('2024-05-11'),
});
+102
View File
@@ -0,0 +1,102 @@
<script setup lang="ts">
import JSON5 from 'json5';
import json2csharp from './json2csharp';
import type { UseValidationRule } from '@/composable/validation';
import TextareaCopyable from '@/components/TextareaCopyable.vue';
import { withDefaultOnError } from '@/utils/defaults';
import { useQueryParamOrStorage } from '@/composable/queryParams';
const defaultValue = `{
a:"n",
arr: [1, 2],
nested: {
a:1,
b:"2"
}
}`;
const jsonInput = ref(defaultValue);
const pascalCase = useQueryParamOrStorage({ name: 'pascalcase', storageName: 'json-c#:pc', defaultValue: true });
const useFields = useQueryParamOrStorage({ name: 'fields', storageName: 'json-c#:fi', defaultValue: false });
const useNullable = useQueryParamOrStorage({ name: 'nullable', storageName: 'json-c#:null', defaultValue: false });
const addJsonProperty = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:jsp', defaultValue: false });
const nullValueHandlingIgnore = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:ign', defaultValue: true });
const addJsonPropertyName = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:jspp', defaultValue: true });
const generateImmutableClasses = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:imm', defaultValue: false });
const useRecordTypes = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:rec', defaultValue: true });
const useReadonlyLists = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:rdl', defaultValue: false });
const rootTypeName = useQueryParamOrStorage({ name: 'root', storageName: 'json-c#:rt', defaultValue: 'Root' });
const csharpOutput = computed(() => withDefaultOnError(
() => json2csharp({
src: JSON5.parse(jsonInput.value),
rootTypeName: rootTypeName.value,
pascalCase: pascalCase.value,
useFields: useFields.value,
useNullable: useNullable.value,
addJsonProperty: addJsonProperty.value,
nullValueHandlingIgnore: nullValueHandlingIgnore.value,
addJsonPropertyName: addJsonPropertyName.value,
generateImmutableClasses: generateImmutableClasses.value,
useRecordTypes: useRecordTypes.value,
useReadonlyLists: useReadonlyLists.value,
}), ''));
const rules: UseValidationRule<string>[] = [
{
validator: (v: string) => v === '' || JSON5.parse(v),
message: 'Provided JSON is not valid.',
},
];
</script>
<template>
<div>
<c-card title="JSON to C#">
<c-input-text
v-model:value="jsonInput"
multiline
placeholder="Put your json string here..."
rows="10"
label="JSON to C#"
:validation-rules="rules"
raw-text
mb-5
/>
<n-space justify="center">
<n-checkbox v-model:checked="pascalCase">
Use Pascal case
</n-checkbox>
<n-checkbox v-model:checked="useRecordTypes">
Use Record types
</n-checkbox>
<n-checkbox v-model:checked="generateImmutableClasses">
Generate Immutable classes
</n-checkbox>
<n-checkbox v-model:checked="useFields">
Use fields
</n-checkbox>
<n-checkbox v-model:checked="addJsonProperty">
Add JsonProperty attributes
</n-checkbox>
<n-checkbox v-model:checked="nullValueHandlingIgnore" :disabled="!addJsonProperty">
Use NullValueHandling.Ignore
</n-checkbox>
<n-checkbox v-model:checked="addJsonPropertyName">
Add JsonPropertyName attributes
</n-checkbox>
<n-checkbox v-model:checked="useNullable">
Use nullable types
</n-checkbox>
<n-checkbox v-model:checked="useReadonlyLists">
Use Readonly lists
</n-checkbox>
</n-space>
<c-input-text v-model:value="rootTypeName" label="Root type name" placeholder="Your root type name..." clearable raw-text mb-5 />
</c-card>
<c-card title="Your C# code" mt-2>
<TextareaCopyable
:value="csharpOutput"
language="csharp"
/>
</c-card>
</div>
</template>
@@ -0,0 +1,617 @@
import { describe, expect, it } from 'vitest';
import { getPrimitiveProp, isDate, json2classes, json2csharp } from './json2csharp';
// Test isDate function
describe('isDate', () => {
it('should return true for valid date strings', () => {
expect(isDate('2024-03-08')).toBe(true);
expect(isDate('2024-03-08T12:34:56Z')).toBe(true);
});
it('should return false for invalid date strings', () => {
expect(isDate('hello')).toBe(false);
expect(isDate('2024-13-08')).toBe(false); // Invalid month
expect(isDate('9999-99-99')).toBe(false); // Invalid format
});
});
// Test getPrimitiveProp function
describe('getPrimitiveProp', () => {
it('should return \'string\' type for non-date strings', () => {
expect(getPrimitiveProp('hello', 'testKey')).toEqual({
type: 'string',
name: 'testKey',
canBeNullable: false,
});
});
it('should return \'DateTime\' type for date strings', () => {
expect(getPrimitiveProp('2024-03-08', 'dateKey')).toEqual({
type: 'DateTime',
name: 'dateKey',
canBeNullable: true,
});
});
it('should return \'int\' for integers', () => {
expect(getPrimitiveProp(42, 'numberKey')).toEqual({
type: 'int',
name: 'numberKey',
canBeNullable: true,
});
});
it('should return \'double\' for floating point numbers', () => {
expect(getPrimitiveProp(3.14, 'floatKey')).toEqual({
type: 'double',
name: 'floatKey',
canBeNullable: true,
});
});
it('should return \'bool\' for boolean values', () => {
expect(getPrimitiveProp(true, 'boolKey')).toEqual({
type: 'bool',
name: 'boolKey',
canBeNullable: true,
});
});
it('should throw an error for unsupported types', () => {
expect(() => getPrimitiveProp({}, 'objKey')).toThrow('Unexpected key \'objKey\' of type object');
});
});
// Test json2classes function
describe('json2classes', () => {
it('should convert JSON to class definitions with custom root', () => {
const json = { name: 'John', age: 30 };
const result = json2classes(json, 'Main');
expect(result).to.deep.eq([
{
key: 'Main',
props: [
{ type: 'string', name: 'name', canBeNullable: false },
{ type: 'int', name: 'age', canBeNullable: true },
],
},
]);
});
it('should handle nested objects', () => {
const json = { user: { name: 'John' } };
const result = json2classes(json);
expect(result).to.deep.eq([
{ key: 'Root', props: [{ type: 'User', name: 'user' }] },
{ key: 'User', props: [{ type: 'string', name: 'name', canBeNullable: false }] },
]);
});
it('should handle arrays of primitives', () => {
const json = { numbers: [1, 2, 3] };
const result = json2classes(json);
expect(result).to.deep.eq([
{ key: 'Root', props: [{ type: 'int', name: 'numbers', isArray: true, canBeNullable: true }] },
]);
});
it('should handle arrays of objects', () => {
const json = { users: [{ name: 'John' }, { name: 'Jane' }] };
const result = json2classes(json);
expect(result).to.deep.eq([
{ key: 'Root', props: [{ type: 'UsersItem', name: 'users', isArray: true }] },
{ key: 'UsersItem', props: [{ type: 'string', name: 'name', canBeNullable: false }] },
]);
});
});
// Test json2csharp function
describe('json2csharp', () => {
const cleanTabs = (s: string) => s.replace(/\t/g, ' ');
it('should convert JSON to C# class with default options', () => {
const json = JSON.stringify({ name: 'John', age: 30 });
const result = cleanTabs(json2csharp({ src: json }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"name\")]
public string Name { get; set; }
[JsonPropertyName(\"age\")]
public int Age { get; set; }
}`);
});
it('should not change case if pascalCase option is false', () => {
const json = JSON.stringify({ test: { user_name: 'John' } });
const result = cleanTabs(json2csharp({ src: json, pascalCase: false }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"test\")]
public Test test { get; set; }
}
public class Test
{
[JsonPropertyName(\"user_name\")]
public string user_name { get; set; }
}`);
});
it('should handle when root is an array', () => {
const json = JSON.stringify([{ age: 30 }]);
const result = cleanTabs(json2csharp({ src: json, useNullable: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class RootItem
{
[JsonPropertyName(\"age\")]
public int? Age { get; set; }
}`);
});
it('should use nullable types if useNullable option is true', () => {
const json = JSON.stringify({ age: 30 });
const result = cleanTabs(json2csharp({ src: json, useNullable: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"age\")]
public int? Age { get; set; }
}`);
});
it('should add JsonProperty attributes if addJsonProperty is true', () => {
const json = JSON.stringify({ name: 'John' });
const result = cleanTabs(json2csharp({ src: json, addJsonProperty: true }));
expect(result).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
[JsonProperty(\"name\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"name\")]
public string Name { get; set; }
}`);
});
it('should add JsonPropertyName attributes if addJsonPropertyName is true', () => {
const json = JSON.stringify({ name: 'John' });
const result = cleanTabs(json2csharp({ src: json, addJsonPropertyName: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"name\")]
public string Name { get; set; }
}`);
});
it('should generate immutable classes if generateImmutableClasses is true', () => {
const json = JSON.stringify({ name: 'John' });
const result = cleanTabs(json2csharp({ src: json, generateImmutableClasses: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
public Root(
string name
){
this.Name = name;
}
[JsonPropertyName(\"name\")]
public string Name { get; }
}`);
});
it('should convert JSON with arrays into C# classes', () => {
const json = {
users: [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }],
};
expect(cleanTabs(json2csharp({ src: json }))).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"users\")]
public UsersItem[] Users { get; set; }
}
public class UsersItem
{
[JsonPropertyName(\"name\")]
public string Name { get; set; }
[JsonPropertyName(\"age\")]
public int Age { get; set; }
}`);
expect(cleanTabs(json2csharp({ src: json, useRecordTypes: true }))).toBe(`using System;
using System.Text.Json;
public record Root(
[property: JsonPropertyName(\"users\")]
UsersItem[] Users
);
public record UsersItem(
[property: JsonPropertyName(\"name\")]
string Name,
[property: JsonPropertyName(\"age\")]
int Age
);`);
expect(cleanTabs(json2csharp({ src: json, useRecordTypes: true, pascalCase: false, useReadonlyLists: true }))).toBe(`using System;
using System.Text.Json;
public record Root(
[property: JsonPropertyName(\"users\")]
IReadonlyList<UsersItem> users
);
public record UsersItem(
[property: JsonPropertyName(\"name\")]
string name,
[property: JsonPropertyName(\"age\")]
int age
);`);
});
it('should generate C# record types when useRecordTypes is true', () => {
const json = JSON.stringify({ name: 'John', age: 30 });
const result = cleanTabs(json2csharp({ src: json, useRecordTypes: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public record Root(
[property: JsonPropertyName(\"name\")]
string Name,
[property: JsonPropertyName(\"age\")]
int Age
);`);
});
it('should generate C# record types with attributes when useRecordTypes/addJsonProperty/addJsonPropertyName are true', () => {
const json = JSON.stringify({ name: 'John', age: 30 });
const result = cleanTabs(json2csharp({
src: json,
useRecordTypes: true,
addJsonProperty: true,
addJsonPropertyName: true,
}));
expect(result).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public record Root(
[property: JsonProperty(\"name\", NullValueHandling = NullValueHandling.Ignore)]
[property: JsonPropertyName(\"name\")]
string Name,
[property: JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
[property: JsonPropertyName(\"age\")]
int Age
);`);
});
it('should handle arrays of primitives', () => {
const json = JSON.stringify({ numbers: [1, 2, 3] });
const result = cleanTabs(json2csharp({ src: json }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"numbers\")]
public int[] Numbers { get; set; }
}`);
});
it('should handle arrays of objects with PascalCase enabled', () => {
const json = JSON.stringify({
items: [{ item_name: 'A', price: 10.5 }],
});
const result = cleanTabs(json2csharp({
src: json,
pascalCase: true,
addJsonProperty: true,
addJsonPropertyName: true,
}));
expect(result).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
[JsonProperty(\"items\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"items\")]
public ItemsItem[] Items { get; set; }
}
public class ItemsItem
{
[JsonProperty(\"item_name\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"item_name\")]
public string ItemName { get; set; }
[JsonProperty(\"price\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"price\")]
public double Price { get; set; }
}`);
});
it('should use nullable types for optional fields when useNullable is true', () => {
const json = JSON.stringify({ age: null, price: 10.5 });
const result = cleanTabs(json2csharp({ src: json, useNullable: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"age\")]
public Age Age { get; set; }
[JsonPropertyName(\"price\")]
public double? Price { get; set; }
}
public class Age
{
}`);
});
it('should use fields when useFields is true', () => {
const json = JSON.stringify({ age: 1, price: 10.5 });
const result = cleanTabs(json2csharp({ src: json, useFields: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"age\")]
public int Age;
[JsonPropertyName(\"price\")]
public double Price;
}`);
});
it('should add JsonProperty attributes when addJsonProperty is true', () => {
const json = JSON.stringify({ firstName: 'John', lastName: 'Doe' });
const result = cleanTabs(json2csharp({ src: json, addJsonProperty: true, nullValueHandlingIgnore: false }));
expect(result).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
[JsonProperty(\"firstName\")]
[JsonPropertyName(\"firstName\")]
public string FirstName { get; set; }
[JsonProperty(\"lastName\")]
[JsonPropertyName(\"lastName\")]
public string LastName { get; set; }
}`);
});
it('should add JsonProperty attributes when addJsonProperty and nullValueHandlingIgnore are true', () => {
const json = JSON.stringify({ firstName: 'John', lastName: 'Doe' });
const result = cleanTabs(json2csharp({ src: json, addJsonProperty: true, nullValueHandlingIgnore: true }));
expect(result).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
[JsonProperty(\"firstName\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"firstName\")]
public string FirstName { get; set; }
[JsonProperty(\"lastName\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"lastName\")]
public string LastName { get; set; }
}`);
});
it('should handle all types', () => {
const json = JSON.stringify({
id: 1, date: '2025-06-09', amount: 1.4, group: null, active: true, email: 'test@example.com',
});
const result = cleanTabs(json2csharp({ src: json }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"id\")]
public int Id { get; set; }
[JsonPropertyName(\"date\")]
public DateTime Date { get; set; }
[JsonPropertyName(\"amount\")]
public double Amount { get; set; }
[JsonPropertyName(\"group\")]
public Group Group { get; set; }
[JsonPropertyName(\"active\")]
public bool Active { get; set; }
[JsonPropertyName(\"email\")]
public string Email { get; set; }
}
public class Group
{
}`);
});
it('should use readonly lists when useReadonlyLists is true', () => {
const json = JSON.stringify({
items: [{ name: 'Item1' }, { name: 'Item2' }],
});
const result = cleanTabs(json2csharp({ src: json, useReadonlyLists: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"items\")]
public List<ItemsItem> Items { get; } = new List<ItemsItem>;
}
public class ItemsItem
{
[JsonPropertyName(\"name\")]
public string Name { get; set; }
}`);
});
it('should use immutable class properties when generateImmutableClasses is true', () => {
const json = JSON.stringify({ title: 'Book', pages: 300 });
const result = cleanTabs(json2csharp({ src: json, generateImmutableClasses: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
public Root(
string title,
int pages
){
this.Title = title;
this.Pages = pages;
}
[JsonPropertyName(\"title\")]
public string Title { get; }
[JsonPropertyName(\"pages\")]
public int Pages { get; }
}`);
});
it('should generate a combination of options correctly', () => {
const json = JSON.stringify({
people: [
{ first_name: 'John', age: 30 },
{ first_name: 'Jane', age: 25 },
],
});
expect(cleanTabs(json2csharp({
src: json,
pascalCase: true,
useNullable: true,
addJsonProperty: true,
generateImmutableClasses: true,
useRecordTypes: false,
useReadonlyLists: true,
}))).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
public Root(
List<PeopleItem> people
){
this.People = people;
}
[JsonProperty(\"people\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"people\")]
public List<PeopleItem> People { get; } = new List<PeopleItem>;
}
public class PeopleItem
{
public PeopleItem(
string firstName,
int? age
){
this.FirstName = firstName;
this.Age = age;
}
[JsonProperty(\"first_name\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"first_name\")]
public string FirstName { get; }
[JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"age\")]
public int? Age { get; }
}`);
expect(cleanTabs(json2csharp({
src: json,
pascalCase: true,
useNullable: true,
addJsonProperty: true,
addJsonPropertyName: true,
generateImmutableClasses: false,
useRecordTypes: false,
useReadonlyLists: true,
}))).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
[JsonProperty(\"people\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"people\")]
public List<PeopleItem> People { get; } = new List<PeopleItem>;
}
public class PeopleItem
{
[JsonProperty(\"first_name\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"first_name\")]
public string FirstName { get; set; }
[JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"age\")]
public int? Age { get; set; }
}`);
expect(cleanTabs(json2csharp({
src: json,
pascalCase: true,
useNullable: true,
addJsonProperty: true,
useRecordTypes: true,
useReadonlyLists: true,
}))).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public record Root(
[property: JsonProperty(\"people\", NullValueHandling = NullValueHandling.Ignore)]
[property: JsonPropertyName(\"people\")]
IReadonlyList<PeopleItem> People
);
public record PeopleItem(
[property: JsonProperty(\"first_name\", NullValueHandling = NullValueHandling.Ignore)]
[property: JsonPropertyName(\"first_name\")]
string FirstName,
[property: JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
[property: JsonPropertyName(\"age\")]
int? Age
);`);
});
});
+215
View File
@@ -0,0 +1,215 @@
import { camelCase as convertToCamelCase, pascalCase as convertToPascalCase } from 'change-case';
import JSON5 from 'json5';
function normalize(src: string, firstUpper = true) {
// return /^\d$/.test(src.charAt(0))
// ? `N${pascalCase(src)}`
// : pascalCase(src);
return /^\d$/.test(src.charAt(0))
? `N${src}`
: (firstUpper ? src.charAt(0).toUpperCase() + src.slice(1) : src);
}
export function isDate(src: string) {
return /^(\d{4})(-(0[1-9]|1[0-2])(-([12]\d|0[1-9]|3[01]))([T\s]((([01]\d|2[0-3])((:)[0-5]\d))([\:]\d+)?)?(:[0-5]\d([\.]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)$/.test(
src,
);
}
interface Prop { type: string; name: string; isArray?: boolean; canBeNullable?: boolean }
export function getPrimitiveProp(obj: any, key: string): Prop {
const type = typeof obj;
switch (type) {
case 'string':
// eslint-disable-next-line no-case-declarations
const isObjDate = isDate(obj);
return { type: isObjDate ? 'DateTime' : 'string', name: key, canBeNullable: isObjDate };
case 'number':
return { type: Number.isInteger(obj) ? 'int' : 'double', name: key, canBeNullable: true };
case 'boolean':
return { type: 'bool', name: key, canBeNullable: true };
default:
throw new Error(`Unexpected key '${key}' of type ${type}`);
}
}
interface ClassType { key: string; props: Array<Prop> }
function handleObject(
classes: Array<ClassType>,
obj: any,
key: string,
skip: boolean = false) {
const normalizedKey = normalize(key);
let target: ClassType = classes.find(x => x.key === normalizedKey) as never;
if (!target) {
target = { key: normalizedKey, props: [] };
if (!skip) {
classes.push(target);
}
}
if (obj != null) {
Object.keys(obj).forEach((k) => {
const keyName = Number.isNaN(Number(k)) ? k : `${normalizedKey}Item`;
let prop: Prop | null = null;
if (typeof obj[k] == 'object') {
if (Array.isArray(obj[k])) {
if (Array.from(obj[k]).length > 0) {
if (typeof obj[k][0] == 'object') {
handleObject(classes, obj[k], keyName, true);
prop = {
type: normalize(`${keyName}Item`),
name: keyName,
isArray: true,
};
}
else {
prop = getPrimitiveProp(obj[k][0], keyName);
prop.isArray = true;
}
}
}
else {
handleObject(classes, obj[k], keyName);
prop = { type: normalize(keyName), name: keyName };
}
}
else {
prop = getPrimitiveProp(obj[k], keyName);
}
if (prop && !target.props.some(x => x.name === prop?.name)) {
target.props.push(prop);
}
});
}
}
export function json2classes(src: object, rootTypeName: string = 'Root') {
const classes: Array<ClassType> = [];
handleObject(classes, src, rootTypeName);
return classes;
}
export function json2csharp(
{
src,
rootTypeName = 'Root',
pascalCase = true,
nullValueHandlingIgnore = true,
addJsonPropertyName = true,
useReadonlyLists,
useRecordTypes,
addJsonProperty,
generateImmutableClasses,
useFields,
useNullable,
}: {
src: any
rootTypeName?: string
pascalCase?: boolean
useFields?: boolean
useNullable?: boolean
addJsonProperty?: boolean
nullValueHandlingIgnore?: boolean
addJsonPropertyName?: boolean
generateImmutableClasses?: boolean
useRecordTypes?: boolean
useReadonlyLists?: boolean
}) {
const normalizeCase = (s: string) => {
const normalized = normalize(s, pascalCase);
return pascalCase ? convertToPascalCase(normalized) : normalized;
};
const getPropType = (p: Prop) => {
let type = p.type;
if (p.isArray) {
if (useReadonlyLists) {
type = useRecordTypes ? `IReadonlyList<${type}>` : `List<${type}>`;
}
else {
type = `${type}[]`;
}
}
const nullable = useNullable && p.canBeNullable ? '?' : '';
return { type, nullable };
};
const srcObj = typeof src === 'string' ? JSON5.parse(src) : src;
const classes = json2classes(
Array.isArray(srcObj) ? srcObj[0] : srcObj,
Array.isArray(srcObj) ? `${rootTypeName}Item` : rootTypeName);
let result = '';
result += 'using System;\n';
result += addJsonProperty ? 'using Newtonsoft.Json;\n' : '';
result += addJsonPropertyName ? 'using System.Text.Json;\n' : '';
result += '\n';
classes.forEach((c) => {
if (useRecordTypes) {
result += `public record ${normalizeCase(c.key)}(\n`;
}
else {
result += `public class ${normalizeCase(c.key)}\n`;
result += '{\n';
}
if (!useRecordTypes && generateImmutableClasses) {
result += `\tpublic ${normalizeCase(c.key)}(\n`;
c.props.forEach((p) => {
const propType = getPropType(p);
result += `\t\t${propType.type}${propType.nullable} ${convertToCamelCase(p.name)},\n`;
});
result = result.replace(/,\n$/, '\n');
result += '\t){\n';
c.props.forEach((p) => {
result += `\t\tthis.${normalizeCase(p.name)} = ${convertToCamelCase(p.name)};\n`;
});
result += '\t}\n\n';
}
c.props.forEach((p) => {
const scope = useRecordTypes ? 'property: ' : '';
if (addJsonProperty) {
if (nullValueHandlingIgnore) {
result += `\t[${scope}JsonProperty("${p.name}", NullValueHandling = NullValueHandling.Ignore)]\n`;
}
else {
result += `\t[${scope}JsonProperty("${p.name}")]\n`;
}
}
if (addJsonPropertyName) {
result += `\t[${scope}JsonPropertyName("${p.name}")]\n`;
}
const propType = getPropType(p);
if (useRecordTypes) {
result += `\t${propType.type}${propType.nullable} ${normalizeCase(p.name)},\n`;
}
else {
const newList = useReadonlyLists && p.isArray ? ` = new ${propType.type};` : '';
if (useFields) {
result += `\tpublic ${propType.type}${propType.nullable} ${normalizeCase(p.name)}${(newList || ';')}`;
}
else if (generateImmutableClasses || (p.isArray && useReadonlyLists)) {
result += `\tpublic ${propType.type}${propType.nullable} ${normalizeCase(p.name)} { get; }${newList}`;
}
else {
result += `\tpublic ${propType.type}${propType.nullable} ${normalizeCase(p.name)} { get; set; }${newList}`;
}
result += '\n';
}
});
if (useRecordTypes) {
result = result.replace(/,\n$/, '\n');
result += ');\n\n';
}
else {
result += '}\n\n';
}
});
return result.trim();
}
export default json2csharp;
-12
View File
@@ -1,12 +0,0 @@
import { Braces } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'JSON to XML',
path: '/json-to-xml',
description: 'Convert JSON to XML',
keywords: ['json', 'xml'],
component: () => import('./json-to-xml.vue'),
icon: Braces,
createdAt: new Date('2024-08-09'),
});
-32
View File
@@ -1,32 +0,0 @@
<script setup lang="ts">
import convert from 'xml-js';
import JSON5 from 'json5';
import { withDefaultOnError } from '@/utils/defaults';
import type { UseValidationRule } from '@/composable/validation';
const defaultValue = '{"a":{"_attributes":{"x":"1.234","y":"It\'s"}}}';
function transformer(value: string) {
return withDefaultOnError(() => {
return convert.js2xml(JSON5.parse(value), { compact: true });
}, '');
}
const rules: UseValidationRule<string>[] = [
{
validator: (v: string) => v === '' || JSON5.parse(v),
message: 'Provided JSON is not valid.',
},
];
</script>
<template>
<format-transformer
input-label="Your JSON content"
:input-default="defaultValue"
input-placeholder="Paste your JSON content here..."
output-label="Converted XML"
output-language="xml"
:transformer="transformer"
:input-validation-rules="rules"
/>
</template>
+2 -2
View File
@@ -39,7 +39,7 @@ const validation = useValidation({
{{ section.title }}
</th>
<tr v-for="{ claim, claimDescription, friendlyValue, value } in decodedJWT[section.key]" :key="claim + value">
<td class="claims" style="vertical-align: top;">
<td class="claims">
<span font-bold>
{{ claim }}
</span>
@@ -47,7 +47,7 @@ const validation = useValidation({
({{ claimDescription }})
</span>
</td>
<td style="word-wrap: break-word;word-break: break-all;">
<td>
<span>{{ value }}</span>
<span v-if="friendlyValue" ml-2 op-70>
({{ friendlyValue }})
@@ -2,7 +2,6 @@
import { generateLoremIpsum } from './lorem-ipsum-generator.service';
import { useCopy } from '@/composable/copy';
import { randIntFromInterval } from '@/utils/random';
import { computedRefreshable } from '@/composable/computedRefreshable';
const paragraphs = ref(1);
const sentences = ref([3, 8]);
@@ -10,7 +9,7 @@ const words = ref([8, 15]);
const startWithLoremIpsum = ref(true);
const asHTML = ref(false);
const [loremIpsumText, refreshLoremIpsum] = computedRefreshable(() =>
const loremIpsumText = computed(() =>
generateLoremIpsum({
paragraphCount: paragraphs.value,
asHTML: asHTML.value,
@@ -19,7 +18,6 @@ const [loremIpsumText, refreshLoremIpsum] = computedRefreshable(() =>
startWithLoremIpsum: startWithLoremIpsum.value,
}),
);
const { copy } = useCopy({ source: loremIpsumText, text: 'Lorem ipsum copied to the clipboard' });
</script>
@@ -43,13 +41,10 @@ const { copy } = useCopy({ source: loremIpsumText, text: 'Lorem ipsum copied to
<c-input-text :value="loremIpsumText" multiline placeholder="Your lorem ipsum..." readonly mt-5 rows="5" />
<div mt-5 flex justify-center gap-3>
<div mt-5 flex justify-center>
<c-button autofocus @click="copy()">
Copy
</c-button>
<c-button @click="refreshLoremIpsum">
Refresh
</c-button>
</div>
</c-card>
</template>
-12
View File
@@ -1,12 +0,0 @@
import { Markdown } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Markdown to HTML',
path: '/markdown-to-html',
description: 'Convert Markdown to Html and allow to print (as PDF)',
keywords: ['markdown', 'html', 'converter', 'pdf'],
component: () => import('./markdown-to-html.vue'),
icon: Markdown,
createdAt: new Date('2024-08-25'),
});
@@ -1,44 +0,0 @@
<script setup lang="ts">
import markdownit from 'markdown-it';
import TextareaCopyable from '@/components/TextareaCopyable.vue';
const inputMarkdown = ref('');
const outputHtml = computed(() => {
const md = markdownit();
return md.render(inputMarkdown.value);
});
function printHtml() {
const w = window.open();
if (w === null) {
return;
}
w.document.body.innerHTML = outputHtml.value;
w.print();
}
</script>
<template>
<div>
<c-input-text
v-model:value="inputMarkdown"
multiline raw-text
placeholder="Your Markdown content..."
rows="8"
autofocus
label="Your Markdown to convert:"
/>
<n-divider />
<n-form-item label="Output HTML:">
<TextareaCopyable :value="outputHtml" :word-wrap="true" language="html" />
</n-form-item>
<div flex justify-center>
<n-button @click="printHtml">
Print as PDF
</n-button>
</div>
</div>
</template>
-12
View File
@@ -1,12 +0,0 @@
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
@@ -1,121 +0,0 @@
### 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
@@ -1,32 +0,0 @@
<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
@@ -1,12 +0,0 @@
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'),
});
@@ -1,106 +0,0 @@
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);
});
}
});
@@ -1,61 +0,0 @@
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
@@ -1,193 +0,0 @@
<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>
-12
View File
@@ -1,12 +0,0 @@
import { Braces } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'XML to JSON',
path: '/xml-to-json',
description: 'Convert XML to JSON',
keywords: ['xml', 'json'],
component: () => import('./xml-to-json.vue'),
icon: Braces,
createdAt: new Date('2024-08-09'),
});
-32
View File
@@ -1,32 +0,0 @@
<script setup lang="ts">
import convert from 'xml-js';
import { isValidXML } from '../xml-formatter/xml-formatter.service';
import { withDefaultOnError } from '@/utils/defaults';
import type { UseValidationRule } from '@/composable/validation';
const defaultValue = '<a x="1.234" y="It\'s"/>';
function transformer(value: string) {
return withDefaultOnError(() => {
return JSON.stringify(convert.xml2js(value, { compact: true }), null, 2);
}, '');
}
const rules: UseValidationRule<string>[] = [
{
validator: isValidXML,
message: 'Provided XML is not valid.',
},
];
</script>
<template>
<format-transformer
input-label="Your XML content"
:input-default="defaultValue"
input-placeholder="Paste your XML content here..."
output-label="Converted JSON"
output-language="json"
:transformer="transformer"
:input-validation-rules="rules"
/>
</template>
+6 -7
View File
@@ -38,8 +38,7 @@ describe('base64 utils', () => {
it('should throw for incorrect base64 string', () => {
expect(() => base64ToText('a')).to.throw('Incorrect base64 string');
// should not really be false because trimming of space is now implied
// expect(() => base64ToText(' ')).to.throw('Incorrect base64 string');
expect(() => base64ToText(' ')).to.throw('Incorrect base64 string');
expect(() => base64ToText('é')).to.throw('Incorrect base64 string');
// missing final '='
expect(() => base64ToText('bG9yZW0gaXBzdW0')).to.throw('Incorrect base64 string');
@@ -57,17 +56,17 @@ describe('base64 utils', () => {
it('should return false for incorrect base64 string', () => {
expect(isValidBase64('a')).to.eql(false);
expect(isValidBase64(' ')).to.eql(false);
expect(isValidBase64('é')).to.eql(false);
expect(isValidBase64('data:text/plain;notbase64,YQ==')).to.eql(false);
// missing final '='
expect(isValidBase64('bG9yZW0gaXBzdW0')).to.eql(false);
});
it('should return true for untrimmed correct base64 string', () => {
expect(isValidBase64('bG9yZW0gaXBzdW0= ')).to.eql(true);
expect(isValidBase64(' LTE=')).to.eql(true);
expect(isValidBase64(' YQ== ')).to.eql(true);
expect(isValidBase64(' ')).to.eql(true);
it('should return false for untrimmed correct base64 string', () => {
expect(isValidBase64('bG9yZW0gaXBzdW0= ')).to.eql(false);
expect(isValidBase64(' LTE=')).to.eql(false);
expect(isValidBase64(' YQ== ')).to.eql(false);
});
});
+4 -7
View File
@@ -1,9 +1,7 @@
import { Base64 } from 'js-base64';
export { textToBase64, base64ToText, isValidBase64, removePotentialDataAndMimePrefix };
function textToBase64(str: string, { makeUrlSafe = false }: { makeUrlSafe?: boolean } = {}) {
const encoded = Base64.encode(str);
const encoded = window.btoa(str);
return makeUrlSafe ? makeUriSafe(encoded) : encoded;
}
@@ -18,7 +16,7 @@ function base64ToText(str: string, { makeUrlSafe = false }: { makeUrlSafe?: bool
}
try {
return Base64.decode(cleanStr);
return window.atob(cleanStr);
}
catch (_) {
throw new Error('Incorrect base64 string');
@@ -36,11 +34,10 @@ function isValidBase64(str: string, { makeUrlSafe = false }: { makeUrlSafe?: boo
}
try {
const reEncodedBase64 = Base64.fromUint8Array(Base64.toUint8Array(cleanStr));
if (makeUrlSafe) {
return removePotentialPadding(reEncodedBase64) === cleanStr;
return removePotentialPadding(window.btoa(window.atob(cleanStr))) === cleanStr;
}
return reEncodedBase64 === cleanStr.replace(/\s/g, '');
return window.btoa(window.atob(cleanStr)) === cleanStr;
}
catch (err) {
return false;
-3
View File
@@ -112,8 +112,5 @@ export default defineConfig({
},
build: {
target: 'esnext',
rollupOptions: {
external: ['regex'],
},
},
});