Compare commits

..

7 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
24 changed files with 938 additions and 725 deletions

View File

@ -2,5 +2,6 @@
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"useTabs": false
"useTabs": false,
"trailingComma": "none"
}

View File

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

View File

@ -13,20 +13,20 @@ export default tseslint.config(
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
globals: globals.browser
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
'react-refresh': reactRefresh
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
{ allowConstantExport: true }
]
}
},
eslintConfigPrettier,
eslintPluginPrettierRecommended,
eslintPluginPrettierRecommended
)

View File

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

1168
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -21,7 +21,7 @@ export const Editor: FC = () => {
const rect = containerRef.current?.getBoundingClientRect()
ref.current?.layout({
width: rect?.width ?? 0,
height: rect?.height ?? 0,
height: rect?.height ?? 0
})
})
})
@ -54,7 +54,7 @@ export const Editor: FC = () => {
smoothScrolling: true,
cursorSmoothCaretAnimation: 'on',
cursorBlinking: 'smooth',
cursorStyle: 'line',
cursorStyle: 'line'
}}
theme="vs-dark"
/>

View File

@ -4,9 +4,9 @@ export const EditorValueState = atom({
key: 'editor_value',
default: JSON.stringify(
{
Hello: 'world!',
Hello: 'world!'
},
null,
2,
),
2
)
})

View File

@ -7,7 +7,7 @@ import Suika from '../Assets/favicon.webp'
export const LandingAnimation: FC = () => {
const [isVisible, setVisible] = useState(true)
const exitAnimation: TargetAndTransition = {
opacity: 0,
opacity: 0
}
useEffect(() => {

View File

@ -14,7 +14,7 @@ import {
TransformRadioOption,
TransformTextboxOption,
WrappedTransform,
WrappedTransformResult,
WrappedTransformResult
} from '../Transforms/Transform'
import { useLocalStorage } from '@uidotdev/usehooks'
import { AnimatePresence, motion } from 'framer-motion'
@ -30,11 +30,11 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
const [options, setOptions] = useState(transform.options)
const [closedToggle, setClosedToggle] = useLocalStorage(
`transform_closed__${transform.name}`,
false,
false
)
const [result, setResult] = useState<WrappedTransformResult>({
error: false,
value: '',
value: ''
})
const previewDisabled = value.length > 30000
@ -68,7 +68,7 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
setResult({
error: false,
value: '',
value: ''
})
}, [options, previewDisabled])
@ -77,7 +77,7 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
if (previewDisabled) {
setResult({
error: false,
value: '',
value: ''
})
return
}
@ -93,7 +93,7 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
(event: ChangeEvent<HTMLInputElement>) => {
options.set(option.key, {
...option,
value: event.target.checked,
value: event.target.checked
})
setOptions(new Map(options))
@ -104,7 +104,7 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
(event: ChangeEvent<HTMLInputElement>) => {
options.set(option.key, {
...option,
value: event.target.value,
value: event.target.value
})
setOptions(new Map(options))
@ -115,7 +115,7 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
(event: ChangeEvent<HTMLInputElement>) => {
options.set(option.key, {
...option,
value: parseInt(event.target.value),
value: parseInt(event.target.value)
})
setOptions(new Map(options))
@ -126,7 +126,7 @@ export const TransformGridItem: FC<TransformGridItemProp> = ({ transform }) => {
(event: ChangeEvent<HTMLInputElement>) => {
options.set(option.key, {
...option,
value: event.target.value,
value: event.target.value
})
setOptions(new Map(options))

View File

@ -2,10 +2,10 @@ import { Transform } from './Transform'
export const Base64DecodeTransform: Transform = {
name: 'base64d',
fn: async (v) => atob(v),
fn: async (v) => atob(v)
}
export const Base64EncodeTransform: Transform = {
name: 'base64e',
fn: async (v) => btoa(v),
fn: async (v) => btoa(v)
}

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

@ -28,8 +28,8 @@ export const DatetimeTransform: Transform = {
hour: date.getHours(),
minute: date.getMinutes(),
second: date.getSeconds(),
milli: date.getMilliseconds(),
}),
milli: date.getMilliseconds()
})
)
.join('\n')
@ -41,7 +41,7 @@ export const DatetimeTransform: Transform = {
type: 'RADIO',
key: 'f',
value: 'c',
radios: [{ value: 'c' }, { value: 'java' }],
},
],
radios: [{ value: 'c' }, { value: 'java' }]
}
]
}

View File

@ -1,82 +0,0 @@
// GzipCompressTransform.ts
import { Transform } from './Transform'
/**
* Compresses a string using Gzip and encodes the result in Base64.
* @param input - The input string to compress.
* @returns A promise that resolves to the Base64-encoded compressed string.
*/
const compressGzip = async (input: string): Promise<string> => {
// Check if CompressionStream is supported
if (typeof CompressionStream === 'undefined') {
throw new Error(
'CompressionStream API is not supported in this environment.',
)
}
// Encode the input string to a Uint8Array
const encoder = new TextEncoder()
const encoded = encoder.encode(input)
// Create a ReadableStream from the encoded data
const readable = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(encoded)
controller.close()
},
})
// Create a CompressionStream for Gzip
const compressionStream = new CompressionStream('gzip')
// Pipe the readable stream through the compression stream
const compressedStream = readable.pipeThrough(compressionStream)
// Collect the compressed chunks
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
}
// Concatenate all chunks into a single Uint8Array
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
}
// Convert the compressed data to a Base64 string
const base64String = arrayBufferToBase64(compressedData)
return base64String
}
/**
* Converts a Uint8Array to a Base64-encoded string.
* @param buffer - The Uint8Array to convert.
* @returns The Base64-encoded string.
*/
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

@ -17,5 +17,67 @@ const decompressGzip = async (base64: string) => {
export const GzipDecompressTransform: Transform = {
name: 'gzipd',
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

@ -9,7 +9,7 @@ export const JSONBeautifyTransform: Transform = {
? JSON.stringify(
JSON5.parse(v),
null,
(o.get('tab')?.value as number) ?? 2,
(o.get('tab')?.value as number) ?? 2
)
: v
.split('\n')
@ -17,34 +17,34 @@ export const JSONBeautifyTransform: Transform = {
JSON.stringify(
JSON5.parse(v2),
null,
(o.get('tab')?.value as number) ?? 2,
),
(o.get('tab')?.value as number) ?? 2
)
)
.join('\n'),
options: [
{
type: 'CHECKBOX',
key: 'multiline',
key: 'multiline'
},
{
type: 'INTBOX',
key: 'tab',
value: 2,
},
],
value: 2
}
]
}
export const JSONSimplifyTransform: Transform = {
name: 'jsonsmp',
fn: async (v) => JSON.stringify(JSON5.parse(v)),
fn: async (v) => JSON.stringify(JSON5.parse(v))
}
export const JSONEscapeTransform: Transform = {
name: 'jsonesc',
fn: async (v) => JSON.stringify(v),
fn: async (v) => JSON.stringify(v)
}
export const JSONUnescapeTransform: Transform = {
@ -56,5 +56,5 @@ export const JSONUnescapeTransform: Transform = {
if (typeof result !== 'string') throw new Error('Not JSON escaped')
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

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

View File

@ -1,19 +1,24 @@
import {
Base64DecodeTransform,
Base64EncodeTransform,
Base64EncodeTransform
} from './Base64Transforms'
import { DatetimeTransform } from './DatetimeTransforms'
import { GzipCompressTransform } from './GzipCompressTransform'
import { GzipDecompressTransform } from './GzipTransform'
import { GzipCompressTransform, GzipDecompressTransform } from './GzipTransform'
import {
JSONBeautifyTransform,
JSONEscapeTransform,
JSONSimplifyTransform,
JSONUnescapeTransform,
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 {
type: 'CHECKBOX'
@ -69,7 +74,7 @@ export interface WrappedTransform extends Omit<Transform, 'fn' | 'options'> {
fn: (
value: string,
options: Map<string, TransformOption>,
options: Map<string, TransformOption>
) => Promise<WrappedTransformResult>
options: Map<string, TransformOption>
@ -85,9 +90,9 @@ export const wrapTransform = (transform: Transform): WrappedTransform => ({
.catch((error) => ({ error: true, value: error.toString() })),
options: new Map<string, TransformOption>(
(transform.options ?? []).map((v) => [v.key, v]),
(transform.options ?? []).map((v) => [v.key, v])
),
wrapped: true,
wrapped: true
})
export const transforms: Transform[] = [
@ -103,6 +108,10 @@ export const transforms: Transform[] = [
JSONUnescapeTransform,
JSON2YAMLTransform,
YAML2JSONTransform,
PythonDictToJSONTransform,
JSONToPythonDictTransform,
GzipCompressTransform,
GzipDecompressTransform,
CurlTransform,
IWRETransform
]

View File

@ -9,9 +9,9 @@ export const URIDecodeTransform: Transform = {
options: [
{
type: 'CHECKBOX',
key: 'cmp',
},
],
key: 'cmp'
}
]
}
export const URIEncodeTransform: Transform = {
@ -23,7 +23,7 @@ export const URIEncodeTransform: Transform = {
options: [
{
type: 'CHECKBOX',
key: 'cmp',
},
],
key: 'cmp'
}
]
}

View File

@ -5,11 +5,11 @@ import JSON5 from 'json5'
export const YAML2JSONTransform: Transform = {
name: 'yaml2json',
fn: async (v) => JSON.stringify(YAML.parse(v)),
fn: async (v) => JSON.stringify(YAML.parse(v))
}
export const JSON2YAMLTransform: Transform = {
name: 'json2yaml',
fn: async (v) => YAML.stringify(JSON5.parse(v)),
fn: async (v) => YAML.stringify(JSON5.parse(v))
}

View File

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

1
src/vite-env.d.ts vendored
View File

@ -1,6 +1,5 @@
/// <reference types="vite/client" />
module 'strtime' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function strptime(string, string): Date
}

View File

@ -7,8 +7,8 @@ export default defineConfig({
css: {
preprocessorOptions: {
scss: {
api: 'modern-compiler', // or "modern"
},
},
},
api: 'modern-compiler' // or "modern"
}
}
}
})