Compare commits

...

9 Commits

Author SHA1 Message Date
70414baac0 feat: add iwre transformer
All checks were successful
/ deploy_site (push) Successful in 31s
2025-03-31 19:14:51 +09:00
2edc5171d9 feat: add curle transform
All checks were successful
/ deploy_site (push) Successful in 21s
2025-03-19 15:19:57 +09:00
f78c9cd655 chore: update deps and apply lint
All checks were successful
/ deploy_site (push) Successful in 22s
2025-03-19 15:10:18 +09:00
b01a3696a0 feat(regexp): add index and match indicator
All checks were successful
/ deploy_site (push) Successful in 23s
2025-02-01 10:06:13 +09:00
68fa9f64d7 fix: correct typo in README.md for string conversions
All checks were successful
/ deploy_site (push) Successful in 20s
2025-01-16 15:22:52 +09:00
52660afcba feat: add Python dictionary to JSON transforms and remove GzipCompressTransform
All checks were successful
/ deploy_site (push) Successful in 20s
- Introduced new transforms for converting Python dictionaries to JSON and vice versa in `PythonTransforms.ts`.
- Updated `README.md` to reflect the new transformations.
- Removed the `GzipCompressTransform.ts` file and integrated its functionality into `GzipTransform.ts`.
2025-01-16 14:33:41 +09:00
2fc8269442 chore: remove trailing comma
All checks were successful
/ deploy_site (push) Successful in 21s
2025-01-16 09:28:24 +09:00
05ff8493e4 chore: add prettier linter
All checks were successful
/ deploy_site (push) Successful in 23s
2025-01-16 09:16:14 +09:00
a22ea56b50 feat: add gzip encode ttransforms 2025-01-16 08:34:58 +09:00
29 changed files with 1244 additions and 821 deletions

7
.prettierrc Normal file
View File

@ -0,0 +1,7 @@
{
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"useTabs": false,
"trailingComma": "none"
}

View File

@ -1,5 +1,5 @@
# PTools # PTools
A collection of tools for string conversations A collection of tools for string conversions
## Demo ## Demo
* https://ptools.pmh.codes * https://ptools.pmh.codes
@ -13,3 +13,5 @@ A collection of tools for string conversations
* String Escaper/Unescaper * String Escaper/Unescaper
* JSON2YAML / YAML2JSON * JSON2YAML / YAML2JSON
* GZIP Zipped Base64 Unzipper * GZIP Zipped Base64 Unzipper
* Python Dictionary to JSON
* JSON to Python Dictionary

View File

@ -3,6 +3,8 @@ import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks' import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh' import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint' import tseslint from 'typescript-eslint'
import eslintConfigPrettier from 'eslint-config-prettier'
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended'
export default tseslint.config( export default tseslint.config(
{ ignores: ['dist'] }, { ignores: ['dist'] },
@ -11,18 +13,20 @@ export default tseslint.config(
files: ['**/*.{ts,tsx}'], files: ['**/*.{ts,tsx}'],
languageOptions: { languageOptions: {
ecmaVersion: 2020, ecmaVersion: 2020,
globals: globals.browser, globals: globals.browser
}, },
plugins: { plugins: {
'react-hooks': reactHooks, 'react-hooks': reactHooks,
'react-refresh': reactRefresh, 'react-refresh': reactRefresh
}, },
rules: { rules: {
...reactHooks.configs.recommended.rules, ...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [ 'react-refresh/only-export-components': [
'warn', 'warn',
{ allowConstantExport: true }, { allowConstantExport: true }
], ]
}, }
}, },
eslintConfigPrettier,
eslintPluginPrettierRecommended
) )

View File

@ -10,11 +10,11 @@
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@fontsource-variable/jetbrains-mono": "^5.1.1", "@fontsource-variable/jetbrains-mono": "^5.2.5",
"@monaco-editor/react": "^4.6.0", "@monaco-editor/react": "^4.7.0",
"@uidotdev/usehooks": "^2.4.1", "@uidotdev/usehooks": "^2.4.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"framer-motion": "^11.11.10", "framer-motion": "^11.18.2",
"json5": "^2.2.3", "json5": "^2.2.3",
"moment": "^2.30.1", "moment": "^2.30.1",
"normalize.css": "^8.0.1", "normalize.css": "^8.0.1",
@ -23,23 +23,26 @@
"react-tooltip": "^5.28.0", "react-tooltip": "^5.28.0",
"recoil": "^0.7.7", "recoil": "^0.7.7",
"strtime": "^1.1.2", "strtime": "^1.1.2",
"styled-components": "^6.1.13", "styled-components": "^6.1.16",
"yaml": "^2.6.0" "yaml": "^2.7.0"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.13.0", "@eslint/js": "^9.22.0",
"@types/react": "^18.3.11", "@types/react": "^18.3.18",
"@types/react-dom": "^18.3.1", "@types/react-dom": "^18.3.5",
"@vitejs/plugin-react-swc": "^3.5.0", "@vitejs/plugin-react-swc": "^3.8.0",
"eslint": "^9.13.0", "eslint": "^9.22.0",
"eslint-plugin-react-hooks": "^5.0.0", "eslint-config-prettier": "^10.1.1",
"eslint-plugin-react-refresh": "^0.4.13", "eslint-plugin-prettier": "^5.2.3",
"globals": "^15.11.0", "eslint-plugin-react-hooks": "^5.2.0",
"sass-embedded": "^1.80.4", "eslint-plugin-react-refresh": "^0.4.19",
"globals": "^15.15.0",
"monaco-editor": "^0.52.2",
"sass-embedded": "^1.86.0",
"sharp": "^0.33.5", "sharp": "^0.33.5",
"typescript": "~5.6.2", "typescript": "~5.6.3",
"typescript-eslint": "^8.10.0", "typescript-eslint": "^8.26.1",
"vite": "^5.4.9", "vite": "^5.4.14",
"vite-plugin-image-optimizer": "^1.1.8" "vite-plugin-image-optimizer": "^1.1.8"
} }
} }

1221
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
import { FC, ReactNode } from "react"; import { FC, ReactNode } from 'react'
import style from './style.module.scss' import style from './style.module.scss'
@ -6,7 +6,6 @@ interface AppLayoutProp {
children?: ReactNode children?: ReactNode
} }
export const AppLayout: FC<AppLayoutProp> = ({ children }) => export const AppLayout: FC<AppLayoutProp> = ({ children }) => (
<div className={style.container}> <div className={style.container}>{children}</div>
{children} )
</div>

View File

@ -1,11 +1,11 @@
import { FC } from "react"; import { FC } from 'react'
import { AppLayout } from "./AppLayout"; import { AppLayout } from './AppLayout'
import { Editor } from "../Editor"; import { Editor } from '../Editor'
import { TransformGrid } from "../TransformGrid"; import { TransformGrid } from '../TransformGrid'
export const App: FC = () => export const App: FC = () => (
<AppLayout> <AppLayout>
<Editor /> <Editor />
<TransformGrid /> <TransformGrid />
</AppLayout> </AppLayout>
)

View File

@ -1,4 +1,4 @@
import styled from "styled-components"; import styled from 'styled-components'
export const Button = styled.button` export const Button = styled.button`
border: none; border: none;

View File

@ -1,4 +1,4 @@
import styled from "styled-components"; import styled from 'styled-components'
export const Input = styled.input` export const Input = styled.input`
background-color: transparent; background-color: transparent;
@ -12,7 +12,7 @@ export const Input = styled.input`
width: 24px; width: 24px;
&[type=checkbox] { &[type='checkbox'] {
width: auto; width: auto;
} }

View File

@ -1,4 +1,4 @@
import styled from "styled-components"; import styled from 'styled-components'
export const TextArea = styled.textarea` export const TextArea = styled.textarea`
border: none; border: none;

View File

@ -1,15 +1,16 @@
import { createRef, FC, useEffect, useRef } from "react"; import { createRef, FC, useEffect, useRef } from 'react'
import { Editor as MonacoEditor } from "@monaco-editor/react"; import { Editor as MonacoEditor } from '@monaco-editor/react'
import { useRecoilState } from "recoil"; import { useRecoilState } from 'recoil'
import { EditorValueState } from "../GlobalStates/EditorValueState"; import { EditorValueState } from '../GlobalStates/EditorValueState'
import { motion } from "framer-motion"; import { motion } from 'framer-motion'
import { VERSION } from "../version"; import { VERSION } from '../version'
import { editor } from 'monaco-editor'
import style from "./style.module.scss"; import style from './style.module.scss'
export const Editor: FC = () => { export const Editor: FC = () => {
const [value, setValue] = useRecoilState(EditorValueState) const [value, setValue] = useRecoilState(EditorValueState)
const ref = useRef<any>() const ref = useRef<editor.IStandaloneCodeEditor>()
const containerRef = createRef<HTMLDivElement>() const containerRef = createRef<HTMLDivElement>()
useEffect(() => { useEffect(() => {
@ -24,7 +25,7 @@ export const Editor: FC = () => {
}) })
}) })
}) })
}, []) }, [containerRef])
return ( return (
<motion.div <motion.div
@ -32,33 +33,37 @@ export const Editor: FC = () => {
ref={containerRef} ref={containerRef}
transition={{ delay: 1.5 }} transition={{ delay: 1.5 }}
initial={{ opacity: 0 }} initial={{ opacity: 0 }}
animate={{ opacity: 1 }}> animate={{ opacity: 1 }}
>
<MonacoEditor <MonacoEditor
loading={<></>} loading={<></>}
value={value} value={value}
language="yaml" language="yaml"
onMount={(v) => ref.current = v} onMount={(v) => (ref.current = v)}
onChange={(v) => setValue(v ?? '')} onChange={(v) => setValue(v ?? '')}
options={{ options={{
automaticLayout: true, automaticLayout: true,
lineNumbersMinChars: 3, lineNumbersMinChars: 3,
minimap: { enabled: false }, minimap: { enabled: false },
theme: "vs-dark", theme: 'vs-dark',
fontSize: 24, fontSize: 24,
fontFamily: 'JetBrains Mono Variable', fontFamily: 'JetBrains Mono Variable',
fontLigatures: true, fontLigatures: true,
wordWrap: "on", wordWrap: 'on',
mouseWheelZoom: true, mouseWheelZoom: true,
smoothScrolling: true, smoothScrolling: true,
cursorSmoothCaretAnimation: 'on', cursorSmoothCaretAnimation: 'on',
cursorBlinking: 'smooth', cursorBlinking: 'smooth',
cursorStyle: 'line' cursorStyle: 'line'
}} }}
theme="vs-dark" /> theme="vs-dark"
/>
<div className={style.credit}> <div className={style.credit}>
<div className={style.creditstr}> <div className={style.creditstr}>
<p><b>The PTOOLS</b></p> <p>
<b>The PTOOLS</b>
</p>
<p>v2-{VERSION}</p> <p>v2-{VERSION}</p>
<p>&copy; Minhyeok Park</p> <p>&copy; Minhyeok Park</p>
</div> </div>

View File

@ -1,8 +1,12 @@
import { atom } from "recoil"; import { atom } from 'recoil'
export const EditorValueState = atom({ export const EditorValueState = atom({
key: 'editor_value', key: 'editor_value',
default: JSON.stringify({ default: JSON.stringify(
{
Hello: 'world!' Hello: 'world!'
}, null, 2) },
null,
2
)
}) })

View File

@ -1,4 +1,4 @@
import { FC, useEffect, useState } from "react"; import { FC, useEffect, useState } from 'react'
import { AnimatePresence, motion, TargetAndTransition } from 'framer-motion' import { AnimatePresence, motion, TargetAndTransition } from 'framer-motion'
import style from './style.module.scss' import style from './style.module.scss'

View File

@ -1,22 +1,21 @@
import { FC } from "react"; import { FC } from 'react'
import { motion } from "framer-motion"; import { motion } from 'framer-motion'
import style from './style.module.scss' import style from './style.module.scss'
import { TransformGridItem } from "../TransformGridItem"; import { TransformGridItem } from '../TransformGridItem'
import { transforms, wrapTransform } from "../Transforms/Transform"; import { transforms, wrapTransform } from '../Transforms/Transform'
export const TransformGrid: FC = () => export const TransformGrid: FC = () => (
<ul className={style.grid}> <ul className={style.grid}>
{transforms.map((transform, i) => {transforms.map((transform, i) => (
<motion.li <motion.li
key={i} key={i}
initial={{ opacity: 0 }} initial={{ opacity: 0 }}
animate={{ opacity: 1 }} animate={{ opacity: 1 }}
transition={{ delay: i * 0.1 + 1.5 }} > transition={{ delay: i * 0.1 + 1.5 }}
>
<TransformGridItem <TransformGridItem transform={wrapTransform(transform)} />
transform={wrapTransform(transform)}/>
</motion.li> </motion.li>
)} ))}
</ul> </ul>
)

View File

@ -1,11 +1,13 @@
import { ChangeEvent, FC, useEffect, useState } from "react"; // src/components/TransformGridItem.tsx
import { ChangeEvent, FC, useEffect, useState } from 'react'
import style from './style.module.scss' import style from './style.module.scss'
import { Button } from "../Components/Button"; import { Button } from '../Components/Button'
import { Input } from "../Components/Input"; import { Input } from '../Components/Input'
import { TextArea } from "../Components/TextArea"; // Remove TextArea import as it's no longer used
import clsx from "clsx"; import clsx from 'clsx'
import { useRecoilState } from "recoil"; import { useRecoilState } from 'recoil'
import { EditorValueState } from "../GlobalStates/EditorValueState"; import { EditorValueState } from '../GlobalStates/EditorValueState'
import { import {
TransformCheckboxOption, TransformCheckboxOption,
TransformIntboxOption, TransformIntboxOption,
@ -13,10 +15,11 @@ import {
TransformTextboxOption, TransformTextboxOption,
WrappedTransform, WrappedTransform,
WrappedTransformResult WrappedTransformResult
} from "../Transforms/Transform"; } from '../Transforms/Transform'
import { useLocalStorage } from "@uidotdev/usehooks"; import { useLocalStorage } from '@uidotdev/usehooks'
import { AnimatePresence, motion } from "framer-motion"; import { AnimatePresence, motion } from 'framer-motion'
import { Tooltip } from 'react-tooltip' import { Tooltip } from 'react-tooltip'
import { TextArea } from '../Components/TextArea'
interface TransformGridItemProp { interface TransformGridItemProp {
transform: WrappedTransform transform: WrappedTransform
@ -25,7 +28,10 @@ interface TransformGridItemProp {
export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => { export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
const [value, setValue] = useRecoilState(EditorValueState) const [value, setValue] = useRecoilState(EditorValueState)
const [options, setOptions] = useState(transform.options) const [options, setOptions] = useState(transform.options)
const [closedToggle, setClosedToggle] = useLocalStorage(`transform_closed__${transform.name}`, false) const [closedToggle, setClosedToggle] = useLocalStorage(
`transform_closed__${transform.name}`,
false
)
const [result, setResult] = useState<WrappedTransformResult>({ const [result, setResult] = useState<WrappedTransformResult>({
error: false, error: false,
value: '' value: ''
@ -41,27 +47,32 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
setResult(result) setResult(result)
return result return result
}) })
.catch((error) => {
setResult({ error: true, value: error.toString() })
return { error: true, value: error.toString() }
})
// trigger transform when value, option or closed state changed // Trigger transform when value, option or closed state changes
useEffect(() => { useEffect(() => {
if (previewDisabled) if (previewDisabled) return
return
triggerTransform() transform
}, [value, options, closed]) .fn(value, options)
.then(setResult.bind(this))
.catch((error) => setResult({ error: true, value: error.toString() }))
}, [value, options, closed, previewDisabled, transform])
// reset error state when option changed // Reset error state when options change
useEffect(() => { useEffect(() => {
if (!previewDisabled) if (!previewDisabled) return
return
setResult({ setResult({
error: false, error: false,
value: '' value: ''
}) })
}, [options]) }, [options, previewDisabled])
// forcely disable preview when value is longer than 30,000 chars // Force disable preview when value is longer than 30,000 chars
useEffect(() => { useEffect(() => {
if (previewDisabled) { if (previewDisabled) {
setResult({ setResult({
@ -71,13 +82,15 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
return return
} }
triggerTransform() transform
}, [value]) .fn(value, options)
.then(setResult.bind(this))
.catch((error) => setResult({ error: true, value: error.toString() }))
}, [value, previewDisabled, transform, options])
const onCheckboxOptionChanged = const onCheckboxOptionChanged =
(option: TransformCheckboxOption) => (option: TransformCheckboxOption) =>
(event: ChangeEvent<HTMLInputElement>) => { (event: ChangeEvent<HTMLInputElement>) => {
options.set(option.key, { options.set(option.key, {
...option, ...option,
value: event.target.checked value: event.target.checked
@ -86,11 +99,9 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
setOptions(new Map(options)) setOptions(new Map(options))
} }
const onTextboxOptionChanged = const onTextboxOptionChanged =
(option: TransformTextboxOption) => (option: TransformTextboxOption) =>
(event: ChangeEvent<HTMLInputElement>) => { (event: ChangeEvent<HTMLInputElement>) => {
options.set(option.key, { options.set(option.key, {
...option, ...option,
value: event.target.value value: event.target.value
@ -102,7 +113,6 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
const onIntboxOptionChanged = const onIntboxOptionChanged =
(option: TransformIntboxOption) => (option: TransformIntboxOption) =>
(event: ChangeEvent<HTMLInputElement>) => { (event: ChangeEvent<HTMLInputElement>) => {
options.set(option.key, { options.set(option.key, {
...option, ...option,
value: parseInt(event.target.value) value: parseInt(event.target.value)
@ -114,7 +124,6 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
const onRadioOptionChanged = const onRadioOptionChanged =
(option: TransformRadioOption) => (option: TransformRadioOption) =>
(event: ChangeEvent<HTMLInputElement>) => { (event: ChangeEvent<HTMLInputElement>) => {
options.set(option.key, { options.set(option.key, {
...option, ...option,
value: event.target.value value: event.target.value
@ -124,18 +133,15 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
} }
const onForwardButtonPressed = async () => { const onForwardButtonPressed = async () => {
const result = const result = await triggerTransform()
await triggerTransform()
if (result.error) if (result.error) return
return
setValue(result.value) setValue(result.value)
} }
const onLabelClicked = async () => { const onLabelClicked = async () => {
if (previewDisabled) if (previewDisabled) return
return
setClosedToggle(!closed) setClosedToggle(!closed)
} }
@ -144,22 +150,23 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
<div className={clsx(style.item, closed && style.closed)}> <div className={clsx(style.item, closed && style.closed)}>
<div className={style.toolbar}> <div className={style.toolbar}>
<div data-tooltip-id={`${transform.name}-tooltip`}> <div data-tooltip-id={`${transform.name}-tooltip`}>
<Button <Button disabled={result.error} onClick={onForwardButtonPressed}>
disabled={result.error}
onClick={onForwardButtonPressed}>
&lt;&lt;&lt; &lt;&lt;&lt;
</Button> </Button>
</div> </div>
<Tooltip className={style.error} id={`${transform.name}-tooltip`} place="bottom"> <Tooltip
className={style.error}
id={`${transform.name}-tooltip`}
place="bottom"
>
{previewDisabled && result.error && result.value} {previewDisabled && result.error && result.value}
</Tooltip> </Tooltip>
<h2 <h2
onClick={onLabelClicked} onClick={onLabelClicked}
className={clsx(style.name, previewDisabled && style.previewDisabled)}> className={clsx(style.name, previewDisabled && style.previewDisabled)}
>
{transform.name} {transform.name}
</h2> </h2>
@ -173,8 +180,10 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
<Input <Input
checked={option.value} checked={option.value}
onChange={onCheckboxOptionChanged(option)} onChange={onCheckboxOptionChanged(option)}
type="checkbox" /> type="checkbox"
</label>))} />
</label>
))}
{[...options.values()] {[...options.values()]
?.filter((v) => v.type === 'TEXTBOX') ?.filter((v) => v.type === 'TEXTBOX')
@ -185,9 +194,10 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
<Input <Input
value={option.value} value={option.value}
onChange={onTextboxOptionChanged(option)} onChange={onTextboxOptionChanged(option)}
type="text" /> type="text"
</label>))} />
</label>
))}
{[...options.values()] {[...options.values()]
?.filter((v) => v.type === 'INTBOX') ?.filter((v) => v.type === 'INTBOX')
@ -199,9 +209,10 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
min={1} min={1}
value={option.value} value={option.value}
onChange={onIntboxOptionChanged(option)} onChange={onIntboxOptionChanged(option)}
type="number" /> type="number"
</label>))} />
</label>
))}
{[...options.values()] {[...options.values()]
?.filter((v) => v.type === 'RADIO') ?.filter((v) => v.type === 'RADIO')
@ -209,7 +220,8 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
<div <div
key={i} key={i}
onChange={onRadioOptionChanged(option)} onChange={onRadioOptionChanged(option)}
className={style.optionItem}> className={style.optionItem}
>
{option.radios.map((radio, i2) => ( {option.radios.map((radio, i2) => (
<label key={i2}> <label key={i2}>
<p>{radio.label ?? radio.value}:</p> <p>{radio.label ?? radio.value}:</p>
@ -219,28 +231,31 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
name={option.key} name={option.key}
defaultChecked={radio.value === option.value} defaultChecked={radio.value === option.value}
value={radio.value} value={radio.value}
type="radio" /> type="radio"
/>
</label> </label>
))} ))}
</div>
</div>))} ))}
</div> </div>
</div> </div>
<AnimatePresence> <AnimatePresence>
{!closed && {!closed && (
<motion.div <motion.div
initial={{ height: 0 }} initial={{ height: 0 }}
animate={{ height: 200 }} animate={{ height: 200 }}
exit={{ height: 0 }} exit={{ height: 0 }}
className={style.output}> className={style.output}
>
<TextArea <TextArea
readOnly readOnly
value={result.value} value={result.value}
placeholder="(empty)" placeholder="(empty)"
className={clsx(result.error && style.error)} /> className={clsx(result.error && style.error)}
/>
</motion.div> </motion.div>
} )}
</AnimatePresence> </AnimatePresence>
</div> </div>
) )

View File

@ -1,4 +1,4 @@
import { Transform } from "./Transform"; import { Transform } from './Transform'
export const Base64DecodeTransform: Transform = { export const Base64DecodeTransform: Transform = {
name: 'base64d', name: 'base64d',

View File

@ -0,0 +1,49 @@
import { Transform } from './Transform'
export const CurlTransform: Transform = {
name: 'curle',
fn: async (v: string) => {
// Split the input into sections using blank lines as delimiters.
// The first section contains the request line and headers,
// and the remaining section(s) (if any) form the body.
const sections = v
.split(/\n\s*\n/)
.map((s) => s.trim())
.filter(Boolean)
if (sections.length === 0) return ''
// Process the first section (request line and headers)
const headerLines = sections[0]
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
if (headerLines.length === 0) return ''
// The first line is expected to be the request line, e.g., "POST https://test.example.com"
const [method, url] = headerLines[0].split(' ')
const curlParts: string[] = [`curl -X ${method.toUpperCase()} ${url}`]
// Process each header line (if any exist)
for (let i = 1; i < headerLines.length; i++) {
const line = headerLines[i]
// Find the first colon to split header name and value.
const colonIndex = line.indexOf(':')
if (colonIndex === -1) continue // Skip any lines that are not valid headers
const headerName = line.substring(0, colonIndex).trim()
const headerValue = line.substring(colonIndex + 1).trim()
curlParts.push(` -H "${headerName}: ${headerValue}"`)
}
// Process the body if one is provided (all sections after the first)
if (sections.length > 1) {
// Join remaining sections (in case there are multiple blank-line separations)
const body = sections.slice(1).join('\n\n').trim()
if (body) {
curlParts.push(` -d '${body}'`)
}
}
// Join the parts using backslashes to create a multi-line curl command.
return curlParts.join(' \\\n')
}
}

View File

@ -1,6 +1,6 @@
import { Transform } from "./Transform"; import { Transform } from './Transform'
import { strptime } from 'strtime' import { strptime } from 'strtime'
import moment from "moment"; import moment from 'moment'
export const DatetimeTransform: Transform = { export const DatetimeTransform: Transform = {
name: 'datetime', name: 'datetime',
@ -20,7 +20,8 @@ export const DatetimeTransform: Transform = {
throw new Error('Unknown Format') throw new Error('Unknown Format')
}) })
.map((date) => JSON.stringify({ .map((date) =>
JSON.stringify({
year: date.getFullYear(), year: date.getFullYear(),
month: date.getMonth() + 1, month: date.getMonth() + 1,
date: date.getDate(), date: date.getDate(),
@ -28,23 +29,19 @@ export const DatetimeTransform: Transform = {
minute: date.getMinutes(), minute: date.getMinutes(),
second: date.getSeconds(), second: date.getSeconds(),
milli: date.getMilliseconds() milli: date.getMilliseconds()
})) })
)
.join('\n') .join('\n')
return [ return [expression, samples, parsedSamples].join('\n\n')
expression,
samples,
parsedSamples
].join('\n\n')
}, },
options: [{ options: [
{
type: 'RADIO', type: 'RADIO',
key: 'f', key: 'f',
value: 'c', value: 'c',
radios: [ radios: [{ value: 'c' }, { value: 'java' }]
{ value: 'c' }, }
{ value: 'java' } ]
]
}]
} }

View File

@ -1,4 +1,4 @@
import { Transform } from "./Transform" import { Transform } from './Transform'
const decompressGzip = async (base64: string) => { const decompressGzip = async (base64: string) => {
const byteCharacters = atob(base64) const byteCharacters = atob(base64)
@ -7,10 +7,9 @@ const decompressGzip = async (base64: string) => {
for (let i = 0; i < byteCharacters.length; i++) for (let i = 0; i < byteCharacters.length; i++)
byteNumbers[i] = byteCharacters.charCodeAt(i) byteNumbers[i] = byteCharacters.charCodeAt(i)
const decompressedStream = const decompressedStream = new Blob([new Uint8Array(byteNumbers)])
new Blob([new Uint8Array(byteNumbers)])
.stream() .stream()
.pipeThrough(new DecompressionStream("gzip")) .pipeThrough(new DecompressionStream('gzip'))
return await new Response(decompressedStream).text() return await new Response(decompressedStream).text()
} }
@ -21,3 +20,64 @@ export const GzipDecompressTransform: Transform = {
fn: (v) => decompressGzip(v) fn: (v) => decompressGzip(v)
} }
const compressGzip = async (input: string): Promise<string> => {
if (typeof CompressionStream === 'undefined') {
throw new Error(
'CompressionStream API is not supported in this environment.'
)
}
const encoder = new TextEncoder()
const encoded = encoder.encode(input)
const readable = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(encoded)
controller.close()
}
})
const compressionStream = new CompressionStream('gzip')
const compressedStream = readable.pipeThrough(compressionStream)
const reader = compressedStream.getReader()
const chunks: Uint8Array[] = []
let done = false
while (!done) {
const { value, done: doneReading } = await reader.read()
if (value) {
chunks.push(value)
}
done = doneReading
}
const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0)
const compressedData = new Uint8Array(totalLength)
let offset = 0
for (const chunk of chunks) {
compressedData.set(chunk, offset)
offset += chunk.length
}
const base64String = arrayBufferToBase64(compressedData)
return base64String
}
const arrayBufferToBase64 = (buffer: Uint8Array): string => {
let binary = ''
for (let i = 0; i < buffer.length; i++) {
binary += String.fromCharCode(buffer[i])
}
return btoa(binary)
}
export const GzipCompressTransform: Transform = {
name: 'gzipc', // Unique identifier for the transform
fn: (v: string) => compressGzip(v),
options: [] // Add any options if needed
}

View File

@ -0,0 +1,58 @@
import { Transform } from './Transform'
export const IWRETransform: Transform = {
name: 'iwre',
fn: async (v: string) => {
// Split the input into sections using blank lines as delimiters.
const sections = v
.split(/\n\s*\n/)
.map((s) => s.trim())
.filter(Boolean)
if (sections.length === 0) return ''
// Process the first section (request line and headers)
const headerLines = sections[0]
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
if (headerLines.length === 0) return ''
// The first line should be something like "POST https://test.example.com"
const [method, url] = headerLines[0].split(' ')
const psParts: string[] = [
`Invoke-WebRequest -Uri "${url}" -Method ${method.toUpperCase()}`
]
// Build a headers object
const headers: { [key: string]: string } = {}
for (let i = 1; i < headerLines.length; i++) {
const line = headerLines[i]
const colonIndex = line.indexOf(':')
if (colonIndex === -1) continue // Skip lines that aren't valid headers
const headerName = line.substring(0, colonIndex).trim()
const headerValue = line.substring(colonIndex + 1).trim()
headers[headerName] = headerValue
}
if (Object.keys(headers).length > 0) {
// Build the header hashtable string for PowerShell using actual newlines.
const headerStr = Object.entries(headers)
.map(([key, value]) => ` "${key}" = "${value}"`)
.join('\n')
psParts.push(`-Headers @{\n${headerStr}\n}`)
}
// Process the body (if any)
if (sections.length > 1) {
const body = sections.slice(1).join('\n\n').trim()
if (body) {
// Escape single quotes by doubling them.
const escapedBody = body.replace(/'/g, "''")
psParts.push(`-Body '${escapedBody}'`)
}
}
// Join parts with PowerShell's line continuation character (backtick) and an actual newline.
return psParts.join(' `\n')
}
}

View File

@ -1,13 +1,26 @@
import JSON5 from 'json5' import JSON5 from 'json5'
import { Transform } from "./Transform"; import { Transform } from './Transform'
export const JSONBeautifyTransform: Transform = { export const JSONBeautifyTransform: Transform = {
name: 'jsonbtf', name: 'jsonbtf',
fn: async (v, o) => fn: async (v, o) =>
o.get('multiline')?.value === true o.get('multiline')?.value === true
? JSON.stringify(JSON5.parse(v), null, o.get('tab')?.value as number ?? 2) ? JSON.stringify(
: v.split('\n').map((v2) => JSON.stringify(JSON5.parse(v2), null, o.get('tab')?.value as number ?? 2)).join('\n'), JSON5.parse(v),
null,
(o.get('tab')?.value as number) ?? 2
)
: v
.split('\n')
.map((v2) =>
JSON.stringify(
JSON5.parse(v2),
null,
(o.get('tab')?.value as number) ?? 2
)
)
.join('\n'),
options: [ options: [
{ {
@ -25,15 +38,13 @@ export const JSONBeautifyTransform: Transform = {
export const JSONSimplifyTransform: Transform = { export const JSONSimplifyTransform: Transform = {
name: 'jsonsmp', name: 'jsonsmp',
fn: async (v) => fn: async (v) => JSON.stringify(JSON5.parse(v))
JSON.stringify(JSON5.parse(v))
} }
export const JSONEscapeTransform: Transform = { export const JSONEscapeTransform: Transform = {
name: 'jsonesc', name: 'jsonesc',
fn: async (v) => fn: async (v) => JSON.stringify(v)
JSON.stringify(v)
} }
export const JSONUnescapeTransform: Transform = { export const JSONUnescapeTransform: Transform = {
@ -42,8 +53,7 @@ export const JSONUnescapeTransform: Transform = {
fn: async (v) => { fn: async (v) => {
const result = JSON5.parse(v) const result = JSON5.parse(v)
if (typeof result !== 'string') if (typeof result !== 'string') throw new Error('Not JSON escaped')
throw new Error('Not JSON escaped')
return result return result
} }

View File

@ -0,0 +1,64 @@
import { Transform } from './Transform'
const pythonToJSON = (pythonStr: string): string => {
// Validate basic structure first before any replacements
if (!/^\s*(?:\{[\s\S]*\}|\[[\s\S]*\])\s*$/.test(pythonStr)) {
throw new Error('Invalid Python dictionary or array format')
}
// Perform all replacements in a single pass
return pythonStr.replace(/('|None\b|True\b|False\b)/g, (match) => {
switch (match) {
case "'":
return '"'
case 'None':
return 'null'
case 'True':
return 'true'
case 'False':
return 'false'
default:
return match
}
})
}
export const PythonDictToJSONTransform: Transform = {
name: 'py2json',
fn: async (v) => {
try {
// Validate the result is actually valid JSON
return JSON.stringify(JSON.parse(pythonToJSON(v)))
} catch {
throw new Error('Invalid Python dictionary or array format')
}
}
}
export const JSONToPythonDictTransform: Transform = {
name: 'json2py',
fn: async (v) => {
try {
// Validate and format in one step
return JSON.stringify(JSON.parse(v), null, 2).replace(
/("|\bnull\b|\btrue\b|\bfalse\b)/g,
(match) => {
switch (match) {
case '"':
return "'"
case 'null':
return 'None'
case 'true':
return 'True'
case 'false':
return 'False'
default:
return match
}
}
)
} catch {
throw new Error('Invalid JSON format')
}
}
}

View File

@ -1,4 +1,4 @@
import { Transform } from "./Transform"; import { Transform } from './Transform'
export const RegexpTransform: Transform = { export const RegexpTransform: Transform = {
name: 'regexp', name: 'regexp',
@ -8,14 +8,12 @@ export const RegexpTransform: Transform = {
const parsedSamples = samples const parsedSamples = samples
.split('\n') .split('\n')
.map((sample) => .map((sample) => regexp.exec(sample))
JSON.stringify(regexp.exec(sample)?.groups)) .map((sample, i) =>
`${i + 3}(${sample === null ? 'x' : 'o'}) ${JSON.stringify(sample?.groups) ?? ''}`.trimEnd()
)
.join('\n') .join('\n')
return [ return [expression, samples, parsedSamples].join('\n\n')
expression,
samples,
parsedSamples
].join('\n\n')
} }
} }

View File

@ -1,38 +1,51 @@
import { Base64DecodeTransform, Base64EncodeTransform } from "./Base64Transforms" import {
import { DatetimeTransform } from "./DatetimeTransforms" Base64DecodeTransform,
import { GzipDecompressTransform } from "./GzipTransform" Base64EncodeTransform
import { JSONBeautifyTransform, JSONEscapeTransform, JSONSimplifyTransform, JSONUnescapeTransform } from "./JSONTransforms" } from './Base64Transforms'
import { RegexpTransform } from "./RegexpTransform" import { DatetimeTransform } from './DatetimeTransforms'
import { URIDecodeTransform, URIEncodeTransform } from "./URITransforms" import { GzipCompressTransform, GzipDecompressTransform } from './GzipTransform'
import { JSON2YAMLTransform, YAML2JSONTransform } from "./YAMLTransforms" import {
JSONBeautifyTransform,
JSONEscapeTransform,
JSONSimplifyTransform,
JSONUnescapeTransform
} from './JSONTransforms'
import { RegexpTransform } from './RegexpTransform'
import { URIDecodeTransform, URIEncodeTransform } from './URITransforms'
import { JSON2YAMLTransform, YAML2JSONTransform } from './YAMLTransforms'
import {
PythonDictToJSONTransform,
JSONToPythonDictTransform
} from './PythonTransforms'
import { CurlTransform } from './CurlTransform'
import { IWRETransform } from './IWRTransform'
export interface TransformCheckboxOption { export interface TransformCheckboxOption {
type: 'CHECKBOX', type: 'CHECKBOX'
key: string, key: string
label?: string, label?: string
value?: boolean value?: boolean
} }
export interface TransformTextboxOption { export interface TransformTextboxOption {
type: 'TEXTBOX', type: 'TEXTBOX'
key: string, key: string
label?: string, label?: string
value?: string value?: string
} }
export interface TransformIntboxOption { export interface TransformIntboxOption {
type: 'INTBOX', type: 'INTBOX'
key: string, key: string
label?: string, label?: string
value?: number value?: number
} }
export interface TransformRadioOption { export interface TransformRadioOption {
type: 'RADIO', type: 'RADIO'
key: string, key: string
label?: string, label?: string
value?: string, value?: string
radios: { radios: {
label?: string label?: string
value: string value: string
@ -40,8 +53,10 @@ export interface TransformRadioOption {
} }
export type TransformOption = export type TransformOption =
TransformCheckboxOption | TransformTextboxOption | | TransformCheckboxOption
TransformIntboxOption | TransformRadioOption | TransformTextboxOption
| TransformIntboxOption
| TransformRadioOption
export interface Transform { export interface Transform {
name: string name: string
@ -55,10 +70,12 @@ export interface WrappedTransformResult {
} }
export interface WrappedTransform extends Omit<Transform, 'fn' | 'options'> { export interface WrappedTransform extends Omit<Transform, 'fn' | 'options'> {
wrapped: true, wrapped: true
fn: (value: string, options: Map<string, TransformOption>) => fn: (
Promise<WrappedTransformResult>, value: string,
options: Map<string, TransformOption>
) => Promise<WrappedTransformResult>
options: Map<string, TransformOption> options: Map<string, TransformOption>
} }
@ -67,11 +84,10 @@ export const wrapTransform = (transform: Transform): WrappedTransform => ({
...transform, ...transform,
fn: async (...args) => fn: async (...args) =>
await transform.fn(...args) await transform
.then((value) => .fn(...args)
({ error: false, value: value.toString() })) .then((value) => ({ error: false, value: value.toString() }))
.catch((error) => .catch((error) => ({ error: true, value: error.toString() })),
({ error: true, value: error.toString() })),
options: new Map<string, TransformOption>( options: new Map<string, TransformOption>(
(transform.options ?? []).map((v) => [v.key, v]) (transform.options ?? []).map((v) => [v.key, v])
@ -92,5 +108,10 @@ export const transforms: Transform[] = [
JSONUnescapeTransform, JSONUnescapeTransform,
JSON2YAMLTransform, JSON2YAMLTransform,
YAML2JSONTransform, YAML2JSONTransform,
GzipDecompressTransform PythonDictToJSONTransform,
JSONToPythonDictTransform,
GzipCompressTransform,
GzipDecompressTransform,
CurlTransform,
IWRETransform
] ]

View File

@ -1,29 +1,29 @@
import { Transform } from "./Transform"; import { Transform } from './Transform'
export const URIDecodeTransform: Transform = { export const URIDecodeTransform: Transform = {
name: 'urid', name: 'urid',
fn: async (v, o) => fn: async (v, o) =>
o.get('cmp')?.value === true o.get('cmp')?.value === true ? decodeURIComponent(v) : decodeURI(v),
? decodeURIComponent(v)
: decodeURI(v),
options: [{ options: [
{
type: 'CHECKBOX', type: 'CHECKBOX',
key: 'cmp' key: 'cmp'
}] }
]
} }
export const URIEncodeTransform: Transform = { export const URIEncodeTransform: Transform = {
name: 'urie', name: 'urie',
fn: async (v, o) => fn: async (v, o) =>
o.get('cmp')?.value === true o.get('cmp')?.value === true ? encodeURIComponent(v) : encodeURI(v),
? encodeURIComponent(v)
: encodeURI(v),
options: [{ options: [
{
type: 'CHECKBOX', type: 'CHECKBOX',
key: 'cmp' key: 'cmp'
}] }
]
} }

View File

@ -1,17 +1,15 @@
import { Transform } from "./Transform"; import { Transform } from './Transform'
import YAML from 'yaml' import YAML from 'yaml'
import JSON5 from 'json5' import JSON5 from 'json5'
export const YAML2JSONTransform: Transform = { export const YAML2JSONTransform: Transform = {
name: 'yaml2json', name: 'yaml2json',
fn: async (v) => fn: async (v) => JSON.stringify(YAML.parse(v))
JSON.stringify(YAML.parse(v))
} }
export const JSON2YAMLTransform: Transform = { export const JSON2YAMLTransform: Transform = {
name: 'json2yaml', name: 'json2yaml',
fn: async (v) => fn: async (v) => YAML.stringify(JSON5.parse(v))
YAML.stringify(JSON5.parse(v))
} }

View File

@ -21,3 +21,8 @@ input[type=number] {
appearance: textfield; appearance: textfield;
-moz-appearance: textfield; -moz-appearance: textfield;
} }
*::selection {
color: #212121;
background-color: #ff1696;
}

View File

@ -19,5 +19,5 @@ createRoot(document.getElementById('root')!).render(
<LandingAnimation /> <LandingAnimation />
</RecoilRoot> </RecoilRoot>
</StrictMode>, </StrictMode>
) )