JSONPrism 2.0.0: Cloudflare Workers, TypeScript 7 and a full audit (#151)
- Web app moves to https://jsonprism.poli0981.dev on Cloudflare Workers (static assets + /api/turnstile/verify + /api/health), with security headers, redirects for the old /jsonPrism paths, previews for non-production branches and a production smoke workflow. GitHub Pages only redirects now. - Web-only Turnstile human check (server-verified, 7-day pass) and cookieless Web Analytics (after consent, opt-out, off under GPC); Privacy Policy and Terms 2.0, consent version 2. - Node 26, TypeScript 7 with the TS 6 API alias for typescript-eslint, dependencies on current majors (ends the ERESOLVE that kept main red). - Converter fixes: CSV columns, binary ZIP entries, MySQL backslash escaping, RESX/XML validity, BSON size, YAML quoting and alias limits, TOML nulls and big integers, JSON error positions, JSONL/BOM linting. - Web Worker conversion, faster editor, technical UI refresh with an Appearance menu and custom scrollbars, accessibility and i18n gaps. - Tauri least-privilege capabilities, hardened CSP, Tauri 2.12. - CI: SHA-pinned least-privilege workflows, SonarQube Cloud, Rust job, verifiable releases (SHA256SUMS + provenance); Dependabot grouping. - 864 tests (97% line coverage), SonarCloud quality gate passing; docs, legal and CLAUDE.md refreshed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f8263c3601
commit
532b5cfd82
242 files changed
+23289
-5897
No files matched your search
@@ -0,0 +1,3 @@
|
||||
# Copy to .dev.vars for `npm run cf:dev` / `npm run preview:cf`.
|
||||
# Cloudflare's documented always-pass test secret; real secrets live in the dashboard.
|
||||
TURNSTILE_SECRET=1x0000000000000000000000000000000AA
|
||||
@@ -6,6 +6,12 @@ labels: ['bug', 'needs-triage']
|
||||
assignees: []
|
||||
---
|
||||
|
||||
<!--
|
||||
Security vulnerabilities do NOT belong in a public issue. Report them
|
||||
privately through https://github.com/poli0981/jsonPrism/security/advisories/new
|
||||
or by email to security@poli0981.dev.
|
||||
-->
|
||||
|
||||
## Describe the bug
|
||||
|
||||
A clear description of what the bug is.
|
||||
@@ -13,13 +19,13 @@ A clear description of what the bug is.
|
||||
## To reproduce
|
||||
|
||||
1. Go to '...'
|
||||
2. Paste this JSON: '...'
|
||||
3. Pick format '...'
|
||||
2. Paste this input: '...'
|
||||
3. Pick format '...' and direction (JSON → format, or format → JSON where available)
|
||||
4. See error
|
||||
|
||||
## Sample JSON
|
||||
|
||||
Please provide a **minimal** JSON sample that triggers the bug:
|
||||
Please provide a **minimal** JSON sample (or source-format input, for format → JSON) that triggers the bug, with anything private removed:
|
||||
|
||||
```json
|
||||
{ "your": "sample here" }
|
||||
@@ -35,10 +41,20 @@ What actually happened. Include the error message and target format.
|
||||
|
||||
## Environment
|
||||
|
||||
- Browser: [e.g. Chrome 130, Firefox 132, Safari 18]
|
||||
- OS: [e.g. Windows 11, macOS 15, Ubuntu 24.04]
|
||||
- JSONPrism version: [e.g. 0.1.0 — check the footer]
|
||||
- Is this on the hosted version (poli0981.github.io/jsonPrism/) or local dev?
|
||||
- Platform: [Web / Windows / macOS / Linux / Android]
|
||||
- JSONPrism version: [e.g. 2.0.0 — see About → Build info]
|
||||
- Browser (web) or OS version (apps): [e.g. Firefox on Windows 11, Safari on macOS 15, Ubuntu 24.04, Android 15]
|
||||
- Where: [the website https://jsonprism.poli0981.dev / an installed release / a local dev build]
|
||||
|
||||
## Diagnostics
|
||||
|
||||
Optional but helpful: open **About → Build info → Copy diagnostics** in the
|
||||
app and paste the result below. It contains the version, commit, platform
|
||||
and recent log lines; check it for anything private before posting.
|
||||
|
||||
```text
|
||||
Paste diagnostics here
|
||||
```
|
||||
|
||||
## Screenshots
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ contact_links:
|
||||
about: Ask about usage, share workflows, or propose ideas before opening an issue.
|
||||
- name: Security vulnerability
|
||||
url: https://github.com/poli0981/jsonPrism/security/advisories/new
|
||||
about: Report security issues privately via GitHub Security Advisory (not in public issues).
|
||||
about: Report security issues privately via a GitHub Security Advisory, or email security@poli0981.dev. Never in a public issue.
|
||||
- name: Live demo
|
||||
url: https://poli0981.github.io/jsonPrism/
|
||||
url: https://jsonprism.poli0981.dev
|
||||
about: Try the latest deployed build in your browser before filing a bug.
|
||||
@@ -18,6 +18,12 @@ How would you like JSONPrism to handle it?
|
||||
|
||||
Other approaches you thought about, and why this one fits better.
|
||||
|
||||
## Platform
|
||||
|
||||
Where would you use it? [All / Web / Windows / macOS / Linux / Android]
|
||||
|
||||
Version you're on: [e.g. 2.0.0 — see About → Build info]
|
||||
|
||||
## Sample data (if applicable)
|
||||
|
||||
If your feature involves a specific JSON shape, paste a sample:
|
||||
@@ -35,8 +41,9 @@ expected output here
|
||||
## Scope check
|
||||
|
||||
- [ ] This fits the "one JSON → many formats" core mission
|
||||
- [ ] This can be done client-side (no server required)
|
||||
- [ ] This can be done on the user's device (no server required)
|
||||
- [ ] I have a real use case for this (not just hypothetical)
|
||||
- [ ] I checked the latest build at https://jsonprism.poli0981.dev and it doesn't do this yet
|
||||
|
||||
## Additional context
|
||||
|
||||
|
||||
@@ -3,12 +3,16 @@ Thanks for contributing to JSONPrism!
|
||||
|
||||
Please fill in the sections below. PRs missing required context (no summary,
|
||||
no test plan, off-topic preamble) may be closed without review.
|
||||
See CONTRIBUTING.md → "Auto-ignored cases" for what gets dismissed.
|
||||
See CONTRIBUTING.md → "Auto-ignored contributions" for what gets dismissed.
|
||||
|
||||
Fixing an undisclosed security vulnerability? Report it privately first
|
||||
(SECURITY.md: private advisory or security@poli0981.dev) instead of
|
||||
describing it in a public PR.
|
||||
-->
|
||||
|
||||
## Summary
|
||||
|
||||
<!-- 1–3 bullets describing WHAT changed and WHY. Link related issues. -->
|
||||
<!-- Required. 1–3 bullets describing WHAT changed and WHY. Link related issues. -->
|
||||
|
||||
-
|
||||
-
|
||||
@@ -17,33 +21,42 @@ Closes #
|
||||
|
||||
## Test plan
|
||||
|
||||
<!-- Markdown checklist of things you verified locally. -->
|
||||
<!--
|
||||
Required. These are the checks CI runs; tick what you ran locally.
|
||||
CI must pass before the PR can be merged.
|
||||
-->
|
||||
|
||||
- [ ] `npm run typecheck`
|
||||
- [ ] `npm run format:check`
|
||||
- [ ] `npm run lint`
|
||||
- [ ] `npm run knip`
|
||||
- [ ] `npm run typecheck`
|
||||
- [ ] `npm test`
|
||||
- [ ] `npm run build`
|
||||
- [ ] Manual smoke (describe what you clicked / loaded)
|
||||
- [ ] `npm run cf:check`
|
||||
- [ ] Rust changed: `cargo fmt --check` and `cargo clippy --all-targets --locked -- -D warnings` in `src-tauri/`
|
||||
- [ ] Manual smoke (describe what you clicked / loaded, and on which platform: Web / Windows / macOS / Linux / Android)
|
||||
|
||||
## Screenshots / recordings (UI changes only)
|
||||
|
||||
<!-- Drop images or short clips here. Required for any visual change. -->
|
||||
|
||||
## AI-assist disclosure
|
||||
## AI-assistance disclosure
|
||||
|
||||
<!--
|
||||
JSONPrism's maintainer uses AI co-authoring openly. If you used an AI tool to
|
||||
help write this PR, please note it briefly so reviewers can calibrate.
|
||||
Examples:
|
||||
- "Drafted with Claude Code (Opus 4.7, 1M context); reviewed each diff."
|
||||
- "No AI assistance."
|
||||
JSONPrism's maintainer uses AI co-authoring openly. If an AI tool helped
|
||||
with this PR (code, tests, docs or translations), say which tool and how
|
||||
you used it, so reviewers can calibrate. Either way, you are responsible
|
||||
for every line you submit.
|
||||
-->
|
||||
|
||||
-
|
||||
- [ ] No AI assistance.
|
||||
- [ ] AI-assisted. Tool(s) and how they were used:
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] My changes follow the conventions in [CLAUDE.md](../CLAUDE.md).
|
||||
- [ ] My changes follow the conventions in [CLAUDE.md](https://github.com/poli0981/jsonPrism/blob/main/CLAUDE.md) and [CONTRIBUTING.md](https://github.com/poli0981/jsonPrism/blob/main/CONTRIBUTING.md).
|
||||
- [ ] I added or updated tests where relevant.
|
||||
- [ ] I updated docs / i18n keys if user-visible strings changed.
|
||||
- [ ] New or changed UI strings are in all four locales (`en`, `vi`, `ja`, `zh-CN`) and the i18n parity test passes.
|
||||
- [ ] App code uses no ES2025 runtime APIs (Iterator helpers, `Set` methods, `Promise.try`, …).
|
||||
- [ ] I updated the docs and `CHANGELOG.md` (under `[Unreleased]`) for user-visible changes.
|
||||
- [ ] I did not include unrelated drive-by changes.
|
||||
+53
-35
@@ -1,65 +1,83 @@
|
||||
version: 2
|
||||
|
||||
# Dependency update schedule for JSONPrism.
|
||||
# Groups minor + patch bumps together to reduce PR churn; majors get their
|
||||
# own PR so they can be evaluated individually.
|
||||
# Weekly updates, grouped by package family so a family's majors land together:
|
||||
# a lone `eslint` major once left `npm ci` broken on main for four months.
|
||||
# A cooldown skips releases younger than a few days (security updates are exempt).
|
||||
|
||||
updates:
|
||||
# npm ecosystem (root package.json + lockfile)
|
||||
- package-ecosystem: npm
|
||||
directory: "/"
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
time: "08:00"
|
||||
time: '08:00'
|
||||
timezone: Asia/Ho_Chi_Minh
|
||||
open-pull-requests-limit: 10
|
||||
versioning-strategy: increase
|
||||
labels:
|
||||
- dependencies
|
||||
- npm
|
||||
cooldown:
|
||||
default-days: 3
|
||||
semver-major-days: 7
|
||||
labels: [dependencies, npm]
|
||||
ignore:
|
||||
# `typescript` is an alias for the TypeScript 6 API that typescript-eslint
|
||||
# needs; the compiler itself is TypeScript 7 (`@typescript/native`).
|
||||
- dependency-name: typescript
|
||||
versions: ['>=6.1.0']
|
||||
# @types/node follows the Node major in .nvmrc.
|
||||
- dependency-name: '@types/node'
|
||||
update-types: ['version-update:semver-major']
|
||||
groups:
|
||||
eslint:
|
||||
patterns: [eslint, '@eslint/*', typescript-eslint, 'eslint-plugin-*', globals]
|
||||
test:
|
||||
patterns: [vitest, '@vitest/*', jsdom, '@testing-library/*']
|
||||
react:
|
||||
patterns: [react, react-dom, '@types/react', '@types/react-dom', '@vitejs/plugin-react']
|
||||
build:
|
||||
patterns: [vite, tailwindcss, '@tailwindcss/*', tw-animate-css, prettier, 'prettier-plugin-*', knip]
|
||||
i18n:
|
||||
patterns: [i18next, react-i18next]
|
||||
tauri:
|
||||
patterns: ['@tauri-apps/*']
|
||||
codemirror:
|
||||
patterns: ['@codemirror/*', '@uiw/*', '@lezer/*']
|
||||
radix:
|
||||
patterns: ['@radix-ui/*']
|
||||
cloudflare:
|
||||
patterns: [wrangler, '@cloudflare/*', '@marsidev/react-turnstile']
|
||||
npm-minor-patch:
|
||||
applies-to: version-updates
|
||||
update-types:
|
||||
- minor
|
||||
- patch
|
||||
update-types: [minor, patch]
|
||||
|
||||
# GitHub Actions used in .github/workflows/
|
||||
- package-ecosystem: github-actions
|
||||
directory: "/"
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
time: "08:00"
|
||||
time: '08:00'
|
||||
timezone: Asia/Ho_Chi_Minh
|
||||
open-pull-requests-limit: 5
|
||||
labels:
|
||||
- dependencies
|
||||
- github-actions
|
||||
cooldown:
|
||||
default-days: 3
|
||||
labels: [dependencies, github-actions]
|
||||
groups:
|
||||
actions-minor-patch:
|
||||
applies-to: version-updates
|
||||
update-types:
|
||||
- minor
|
||||
- patch
|
||||
actions:
|
||||
patterns: ['*']
|
||||
|
||||
# Cargo ecosystem for the Tauri shell.
|
||||
# The Tauri shell. Keep the crate versions in step with the @tauri-apps npm packages.
|
||||
- package-ecosystem: cargo
|
||||
directory: "/src-tauri"
|
||||
directory: /src-tauri
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
time: "08:00"
|
||||
time: '08:00'
|
||||
timezone: Asia/Ho_Chi_Minh
|
||||
open-pull-requests-limit: 5
|
||||
labels:
|
||||
- dependencies
|
||||
- rust
|
||||
- tauri
|
||||
cooldown:
|
||||
default-days: 3
|
||||
semver-major-days: 7
|
||||
labels: [dependencies, rust, tauri]
|
||||
groups:
|
||||
tauri:
|
||||
patterns: ['tauri', 'tauri-*']
|
||||
cargo-minor-patch:
|
||||
applies-to: version-updates
|
||||
update-types:
|
||||
- minor
|
||||
- patch
|
||||
update-types: [minor, patch]
|
||||
@@ -0,0 +1,37 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>JSONPrism has moved</title>
|
||||
<meta name="robots" content="noindex" />
|
||||
<link rel="canonical" href="https://jsonprism.poli0981.dev/" />
|
||||
<!-- Without JavaScript, fall back to the new home page. -->
|
||||
<meta http-equiv="refresh" content="3; url=https://jsonprism.poli0981.dev/" />
|
||||
<script>
|
||||
(function () {
|
||||
// Drop the old project-site prefix; keep the rest of the path, the query and the hash.
|
||||
var path = location.pathname.replace(/^\/jsonprism(?=\/|$)/i, '') || '/';
|
||||
location.replace('https://jsonprism.poli0981.dev' + path + location.search + location.hash);
|
||||
})();
|
||||
</script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark light;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-family: system-ui, sans-serif;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<p>
|
||||
JSONPrism has moved to
|
||||
<a href="https://jsonprism.poli0981.dev/">jsonprism.poli0981.dev</a>.
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,37 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>JSONPrism has moved</title>
|
||||
<meta name="robots" content="noindex" />
|
||||
<link rel="canonical" href="https://jsonprism.poli0981.dev/" />
|
||||
<!-- Without JavaScript, fall back to the new home page. -->
|
||||
<meta http-equiv="refresh" content="3; url=https://jsonprism.poli0981.dev/" />
|
||||
<script>
|
||||
(function () {
|
||||
// Drop the old project-site prefix; keep the rest of the path, the query and the hash.
|
||||
var path = location.pathname.replace(/^\/jsonprism(?=\/|$)/i, '') || '/';
|
||||
location.replace('https://jsonprism.poli0981.dev' + path + location.search + location.hash);
|
||||
})();
|
||||
</script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark light;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-family: system-ui, sans-serif;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<p>
|
||||
JSONPrism has moved to
|
||||
<a href="https://jsonprism.poli0981.dev/">jsonprism.poli0981.dev</a>.
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,8 +1,8 @@
|
||||
name: Announce Release / Deploy in Discussions
|
||||
name: Announce Release in Discussions
|
||||
|
||||
# Create a Discussion post in the "Announcements" category when:
|
||||
# • a GitHub Release is published (tag-based deploys)
|
||||
# • the Deploy to GitHub Pages workflow finishes successfully
|
||||
# Create a Discussion post in the "Announcements" category when a GitHub
|
||||
# Release is published, or by hand. (Per-deploy posts were dropped: web deploys
|
||||
# now happen on every merge through Cloudflare Workers Builds.)
|
||||
#
|
||||
# Prerequisites (one-time manual setup):
|
||||
# 1. Enable Discussions in the repo Settings → Features.
|
||||
@@ -16,9 +16,6 @@ name: Announce Release / Deploy in Discussions
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_run:
|
||||
workflows: ["Deploy to GitHub Pages"]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
message:
|
||||
@@ -26,9 +23,7 @@ on:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
discussions: write
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: announce-discussion-${{ github.event_name }}
|
||||
@@ -37,12 +32,10 @@ concurrency:
|
||||
jobs:
|
||||
announce:
|
||||
name: Create Discussion post
|
||||
runs-on: ubuntu-latest
|
||||
# Skip when triggered by a failed deploy.
|
||||
if: >
|
||||
github.event_name == 'release'
|
||||
|| github.event_name == 'workflow_dispatch'
|
||||
|| (github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success')
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
discussions: write
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Resolve repository + category IDs
|
||||
@@ -82,8 +75,6 @@ jobs:
|
||||
RELEASE_TAG: ${{ github.event.release.tag_name || '' }}
|
||||
RELEASE_URL: ${{ github.event.release.html_url || '' }}
|
||||
RELEASE_BODY: ${{ github.event.release.body || '' }}
|
||||
DEPLOY_SHA: ${{ github.event.workflow_run.head_sha || '' }}
|
||||
DEPLOY_URL: ${{ github.event.workflow_run.html_url || '' }}
|
||||
DISPATCH_MSG: ${{ inputs.message || '' }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -97,11 +88,6 @@ jobs:
|
||||
title="Release ${RELEASE_TAG}"
|
||||
body="## ${RELEASE_TAG}${NL}${NL}${RELEASE_BODY}${NL}${NL}[View release →](${RELEASE_URL})"
|
||||
;;
|
||||
workflow_run)
|
||||
short_sha="${DEPLOY_SHA:0:7}"
|
||||
title="Deploy succeeded — ${short_sha}"
|
||||
body="Latest commit deployed to GitHub Pages.${NL}${NL}[Deploy run →](${DEPLOY_URL})"
|
||||
;;
|
||||
workflow_dispatch)
|
||||
title="Announcement"
|
||||
body="${DISPATCH_MSG}"
|
||||
|
||||
@@ -6,18 +6,21 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Existing release tag to re-announce"
|
||||
description: Existing release tag to re-announce
|
||||
required: true
|
||||
type: string
|
||||
|
||||
# Reusable announce-release.yml only needs `contents: read` to fetch
|
||||
# release metadata via the gh CLI.
|
||||
permissions:
|
||||
contents: read
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
announce:
|
||||
uses: poli0981/.github/.github/workflows/announce-release.yml@main
|
||||
permissions:
|
||||
contents: read
|
||||
uses: poli0981/.github/.github/workflows/announce-release.yml@c3e118a01d40e95b36b2c3466dc206638c11eb5a # main 2026-07-06
|
||||
with:
|
||||
tag_override: ${{ inputs.tag || '' }}
|
||||
secrets: inherit
|
||||
# Only the webhooks it needs, not every repository secret.
|
||||
secrets:
|
||||
DISCORD_RELEASES_WEBHOOK: ${{ secrets.DISCORD_RELEASES_WEBHOOK }}
|
||||
DISCORD_REPO_WEBHOOK: ${{ secrets.DISCORD_REPO_WEBHOOK }}
|
||||
DISCORD_PING_ROLE_ID: ${{ secrets.DISCORD_PING_ROLE_ID }}
|
||||
+131
-24
@@ -5,36 +5,41 @@ on:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
# Only superseded PR runs are cancelled; every commit on main gets a full run.
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
WRANGLER_SEND_METRICS: 'false'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Lint, typecheck, build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [22.x]
|
||||
|
||||
web:
|
||||
name: Web · lint, typecheck, test, build
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Setup Node ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# No dependency needs its install scripts (esbuild, workerd and the Tauri
|
||||
# CLI resolve their platform binaries at runtime), so none get to run.
|
||||
- name: Install dependencies
|
||||
run: npm ci --no-audit --no-fund
|
||||
run: npm ci --ignore-scripts --no-audit --no-fund
|
||||
|
||||
- name: Format check
|
||||
run: npm run format:check
|
||||
@@ -45,18 +50,120 @@ jobs:
|
||||
- name: Knip
|
||||
run: npm run knip
|
||||
|
||||
- name: Typecheck
|
||||
run: npm run typecheck
|
||||
- name: Typecheck (TypeScript 7)
|
||||
run: |
|
||||
npx tsc --version | grep -q '^Version 7\.' || { echo "::error::tsc is not TypeScript 7"; exit 1; }
|
||||
npm run typecheck
|
||||
|
||||
- name: Test
|
||||
run: npm test
|
||||
- name: Test with coverage
|
||||
run: npm run test:coverage
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
- name: Worker deploy dry run
|
||||
run: npm run cf:check
|
||||
|
||||
- name: Upload dist
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: dist
|
||||
path: dist
|
||||
retention-days: 7
|
||||
|
||||
- name: Upload coverage
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: coverage
|
||||
path: coverage/lcov.info
|
||||
retention-days: 7
|
||||
|
||||
sonar:
|
||||
name: SonarQube Cloud
|
||||
needs: web
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
# Empty for Dependabot and fork PRs, which get no secrets: skip, don't fail.
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
steps:
|
||||
- name: Skip without a token
|
||||
if: env.SONAR_TOKEN == ''
|
||||
run: echo "::notice::SONAR_TOKEN is not available to this run; skipping analysis."
|
||||
|
||||
- name: Checkout
|
||||
if: env.SONAR_TOKEN != ''
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
# Full history so new-code detection and blame work.
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Download coverage
|
||||
if: env.SONAR_TOKEN != ''
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: coverage
|
||||
path: coverage
|
||||
|
||||
- name: Scan
|
||||
if: env.SONAR_TOKEN != ''
|
||||
uses: SonarSource/sonarqube-scan-action@d209202bc7d53ff1cc128f7f907dac145c9d6ae9 # v8.3.0
|
||||
|
||||
rust:
|
||||
name: Tauri · fmt, clippy
|
||||
needs: web
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Linux build dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libssl-dev libgtk-3-dev
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci --ignore-scripts --no-audit --no-fund
|
||||
|
||||
# generate_context!() embeds the icons and the built frontend at compile time.
|
||||
- name: Generate icons
|
||||
run: npm run tauri:icon
|
||||
|
||||
- name: Download dist
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: dist
|
||||
path: dist
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master
|
||||
with:
|
||||
toolchain: stable
|
||||
components: clippy, rustfmt
|
||||
|
||||
- name: Cache Cargo
|
||||
uses: swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
workspaces: './src-tauri -> target'
|
||||
|
||||
- name: rustfmt
|
||||
working-directory: src-tauri
|
||||
run: cargo fmt --check
|
||||
|
||||
- name: Clippy
|
||||
working-directory: src-tauri
|
||||
run: cargo clippy --all-targets --locked -- -D warnings
|
||||
@@ -1,61 +0,0 @@
|
||||
name: Deploy to GitHub Pages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Setup Node 22
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22.x
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci --no-audit --no-fund
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
# SPA fallback so deep links (/jsonprism/about) work on GH Pages.
|
||||
- name: Copy index.html → 404.html
|
||||
run: cp dist/index.html dist/404.html
|
||||
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v6
|
||||
|
||||
- name: Upload Pages artifact
|
||||
uses: actions/upload-pages-artifact@v5
|
||||
with:
|
||||
path: dist
|
||||
|
||||
deploy:
|
||||
name: Deploy
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v5
|
||||
@@ -2,20 +2,16 @@ name: Notify CI Failures
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
# Subscribe only to the workflow we actually want failure notifications
|
||||
# for. The previous catch-all ("*") triggered this workflow on every
|
||||
# completion (deploy, release, notify itself), most of which immediately
|
||||
# skipped — adding noise to the Actions tab.
|
||||
workflows: ["CI"]
|
||||
workflows: ["CI", "Production smoke"]
|
||||
types: [completed]
|
||||
|
||||
# REQUIRED: declare permissions matching the reusable workflow's needs.
|
||||
# Reusable needs `actions: read` to inspect workflow_run details.
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@main
|
||||
secrets: inherit
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@c3e118a01d40e95b36b2c3466dc206638c11eb5a # main 2026-07-06
|
||||
secrets:
|
||||
DISCORD_CI_WEBHOOK: ${{ secrets.DISCORD_CI_WEBHOOK }}
|
||||
@@ -2,17 +2,16 @@ name: Notify Release Pipeline
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
# Subscribe only to release-pipeline workflows. The previous catch-all
|
||||
# ("*") triggered this workflow on every completion (including CI and
|
||||
# this workflow itself), most of which immediately skipped.
|
||||
workflows: ["Release Tauri bundles", "Deploy to GitHub Pages"]
|
||||
workflows: ["Release Tauri bundles"]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: poli0981/.github/.github/workflows/notify-release-pipeline.yml@main
|
||||
secrets: inherit
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
uses: poli0981/.github/.github/workflows/notify-release-pipeline.yml@c3e118a01d40e95b36b2c3466dc206638c11eb5a # main 2026-07-06
|
||||
secrets:
|
||||
DISCORD_RELEASE_PIPELINE_WEBHOOK: ${{ secrets.DISCORD_RELEASE_PIPELINE_WEBHOOK }}
|
||||
@@ -0,0 +1,45 @@
|
||||
name: Pages redirect
|
||||
|
||||
# GitHub Pages used to host the web app at poli0981.github.io/jsonPrism/. It now
|
||||
# serves only a redirect to https://jsonprism.poli0981.dev that keeps the path,
|
||||
# so old links from YouTube, Discord and READMEs still land on the right page.
|
||||
# Run it by hand after changing .github/pages-redirect/.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: Deploy redirect
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0
|
||||
|
||||
- name: Upload the redirect pages
|
||||
uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
|
||||
with:
|
||||
path: .github/pages-redirect
|
||||
|
||||
- name: Deploy
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1
|
||||
@@ -0,0 +1,64 @@
|
||||
name: Production smoke
|
||||
|
||||
# Cloudflare Workers Builds deploys every push to main to
|
||||
# https://jsonprism.poli0981.dev. This waits until the site serves the pushed
|
||||
# commit (index.html carries <meta name="jsonprism-commit">), then checks the
|
||||
# security headers, routing, redirects and the API. Failures reach Discord via
|
||||
# notify-ci-failure.yml.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: production-smoke
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
SITE: https://jsonprism.poli0981.dev
|
||||
UA: jsonprism-smoke (+https://github.com/poli0981/jsonPrism)
|
||||
|
||||
jobs:
|
||||
smoke:
|
||||
name: Check production
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
permissions: {}
|
||||
steps:
|
||||
- name: Wait for this commit to go live
|
||||
if: github.event_name == 'push'
|
||||
env:
|
||||
SHA: ${{ github.sha }}
|
||||
run: |
|
||||
want="${SHA:0:7}"
|
||||
for attempt in $(seq 1 60); do
|
||||
live=$(curl -fsS -A "$UA" --max-time 10 "$SITE/" | sed -n 's/.*<meta name="jsonprism-commit" content="\([0-9a-f]*\)".*/\1/p' | head -n 1 || true)
|
||||
if [ "$live" = "$want" ]; then
|
||||
echo "Production serves $live"
|
||||
exit 0
|
||||
fi
|
||||
echo "Attempt $attempt: live=${live:-unknown}, waiting for $want"
|
||||
sleep 15
|
||||
done
|
||||
echo "::error::Production did not serve $want within 15 minutes. Check Workers Builds in the Cloudflare dashboard."
|
||||
exit 1
|
||||
|
||||
- name: Check headers, routes and API
|
||||
run: |
|
||||
set -euo pipefail
|
||||
fail() { echo "::error::$1"; exit 1; }
|
||||
headers=$(curl -fsSI -A "$UA" "$SITE/")
|
||||
for expected in "content-security-policy: default-src 'self'" "strict-transport-security: max-age=" "x-content-type-options: nosniff" "x-frame-options: deny"; do
|
||||
grep -qi "^$expected" <<<"$headers" || fail "Missing header: $expected"
|
||||
done
|
||||
[ "$(curl -sS -A "$UA" -o /dev/null -w '%{http_code}' "$SITE/about")" = 200 ] || fail "/about is not served by the SPA fallback"
|
||||
old=$(curl -sS -A "$UA" -o /dev/null -w '%{http_code} %{redirect_url}' "$SITE/jsonPrism/about")
|
||||
[ "$old" = "301 $SITE/about" ] || fail "/jsonPrism/about gave '$old', expected a 301 to /about"
|
||||
[ "$(curl -fsS -A "$UA" "$SITE/api/health")" = '{"ok":true,"service":"jsonprism"}' ] || fail "/api/health is not healthy"
|
||||
curl -fsS -A "$UA" "$SITE/.well-known/security.txt" | grep -q '^Contact: mailto:security@poli0981.dev' || fail "security.txt is missing or stale"
|
||||
code=$(curl -sS -A "$UA" -o /dev/null -w '%{http_code}' -X POST -H 'Origin: https://example.com' -H 'Content-Type: application/json' --data '{"token":"x"}' "$SITE/api/turnstile/verify")
|
||||
[ "$code" = 403 ] || fail "/api/turnstile/verify answered $code to a foreign origin, expected 403"
|
||||
echo "Production checks passed."
|
||||
+221
-102
@@ -1,56 +1,121 @@
|
||||
name: Release Tauri bundles
|
||||
|
||||
# Builds the desktop bundles and the Android APK for a version tag into ONE
|
||||
# draft release, then adds SHA256SUMS.txt and build-provenance attestations.
|
||||
# The maintainer publishes the draft, which triggers the announcements.
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Existing version tag to (re)build, e.g. v2.0.0
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: release-${{ inputs.tag || github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
TAG: ${{ inputs.tag || github.ref_name }}
|
||||
|
||||
jobs:
|
||||
# Create the draft release ONCE, up front, so every platform in the matrix
|
||||
# below uploads into the same release. Previously each matrix job ran
|
||||
# tauri-action's "find or create release" concurrently; with no release yet,
|
||||
# they raced to create it and produced duplicate drafts that split the assets
|
||||
# (Linux bundles in one draft, macOS/Windows in another). A single
|
||||
# pre-created release referenced by `releaseId` removes the race.
|
||||
verify:
|
||||
name: Verify tag and tests
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
outputs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
- name: Validate tag format
|
||||
run: |
|
||||
[[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "::error::'$TAG' is not a version tag"; exit 1; }
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: refs/tags/${{ env.TAG }}
|
||||
persist-credentials: false
|
||||
|
||||
- name: Check the tag matches the app version
|
||||
id: version
|
||||
run: |
|
||||
version=$(node -p "require('./package.json').version")
|
||||
cargo_version=$(sed -n 's/^version = "\(.*\)"$/\1/p' src-tauri/Cargo.toml | head -n 1)
|
||||
[ "$TAG" = "v$version" ] || { echo "::error::Tag $TAG does not match package.json version $version"; exit 1; }
|
||||
[ "$cargo_version" = "$version" ] || { echo "::error::Cargo.toml version $cargo_version does not match $version"; exit 1; }
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci --ignore-scripts --no-audit --no-fund
|
||||
|
||||
- name: Test
|
||||
run: npm test
|
||||
|
||||
# One draft for the whole matrix: parallel "find or create" calls used to
|
||||
# race and split the assets across duplicate drafts.
|
||||
create-release:
|
||||
name: Create draft release
|
||||
runs-on: ubuntu-latest
|
||||
needs: verify
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: write
|
||||
outputs:
|
||||
release_id: ${{ steps.create-release.outputs.result }}
|
||||
release_id: ${{ steps.release.outputs.result }}
|
||||
steps:
|
||||
- name: Create draft release
|
||||
id: create-release
|
||||
uses: actions/github-script@v9
|
||||
- name: Create or reuse the draft
|
||||
id: release
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const tag = context.ref.replace('refs/tags/', '').replace('refs/heads/', '');
|
||||
const tag = process.env.TAG;
|
||||
const { owner, repo } = context.repo;
|
||||
const releases = await github.paginate(github.rest.repos.listReleases, { owner, repo, per_page: 100 });
|
||||
const existing = releases.find((r) => r.tag_name === tag);
|
||||
if (existing) {
|
||||
if (!existing.draft) throw new Error(`Release ${tag} is already published; delete it or tag a new version.`);
|
||||
core.info(`Reusing draft ${existing.id}`);
|
||||
return existing.id;
|
||||
}
|
||||
const { data } = await github.rest.repos.createRelease({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
owner,
|
||||
repo,
|
||||
tag_name: tag,
|
||||
name: `JSONPrism ${tag}`,
|
||||
body: [
|
||||
'Native desktop builds for Windows, macOS, and Linux, plus an Android APK (sideload, Android 12+).',
|
||||
'',
|
||||
'Android: download the `.apk`, then enable "install unknown apps" for your browser/file manager to sideload.',
|
||||
'',
|
||||
'See the [CHANGELOG](https://github.com/poli0981/jsonPrism/blob/main/CHANGELOG.md) for details.',
|
||||
].join('\n'),
|
||||
draft: true,
|
||||
prerelease: false,
|
||||
prerelease: tag.includes('-'),
|
||||
body: [
|
||||
'Native builds for Windows, macOS (universal) and Linux, plus an Android APK (sideload, Android 12+). The web app runs at https://jsonprism.poli0981.dev.',
|
||||
'',
|
||||
'Verify a download with `sha256sum -c SHA256SUMS.txt --ignore-missing`, or check its build provenance with `gh attestation verify <file> --repo poli0981/jsonPrism`.',
|
||||
'',
|
||||
'Android: download the `.apk`, then allow "install unknown apps" for your browser or file manager.',
|
||||
'',
|
||||
`See the [CHANGELOG](https://github.com/${owner}/${repo}/blob/${tag}/CHANGELOG.md) for details.`,
|
||||
].join('\n'),
|
||||
});
|
||||
return data.id;
|
||||
|
||||
build:
|
||||
desktop:
|
||||
name: Build · ${{ matrix.platform.name }}
|
||||
needs: create-release
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
timeout-minutes: 40
|
||||
|
||||
timeout-minutes: 45
|
||||
permissions:
|
||||
contents: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -61,118 +126,108 @@ jobs:
|
||||
- name: macOS (universal)
|
||||
runner: macos-14
|
||||
args: '--target universal-apple-darwin'
|
||||
# The oldest supported Ubuntu keeps the AppImage/deb glibc floor low.
|
||||
- name: Linux
|
||||
runner: ubuntu-22.04
|
||||
args: ''
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: refs/tags/${{ env.TAG }}
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Linux build dependencies
|
||||
if: matrix.platform.runner == 'ubuntu-22.04'
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
libwebkit2gtk-4.1-dev \
|
||||
libappindicator3-dev \
|
||||
librsvg2-dev \
|
||||
patchelf \
|
||||
libssl-dev \
|
||||
libgtk-3-dev
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libssl-dev libgtk-3-dev
|
||||
|
||||
- name: Setup Node 22
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 22.x
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
- name: Setup Rust (stable)
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master
|
||||
with:
|
||||
# macOS universal2 build needs both aarch64 + x86_64 targets installed.
|
||||
targets: ${{ matrix.platform.runner == 'macos-14' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
|
||||
toolchain: stable
|
||||
# The universal macOS bundle needs both Apple targets.
|
||||
targets: ${{ runner.os == 'macOS' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
|
||||
|
||||
- name: Cache Cargo build artifacts
|
||||
uses: swatinem/rust-cache@v2
|
||||
- name: Cache Cargo
|
||||
uses: swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
workspaces: './src-tauri -> target'
|
||||
key: ${{ matrix.platform.runner }}
|
||||
|
||||
- name: Install npm dependencies
|
||||
run: npm ci --no-audit --no-fund
|
||||
- name: Install dependencies
|
||||
run: npm ci --ignore-scripts --no-audit --no-fund
|
||||
|
||||
- name: Generate icons (Linux & macOS)
|
||||
if: matrix.platform.runner != 'windows-latest'
|
||||
- name: Generate icons
|
||||
run: npm run tauri:icon
|
||||
|
||||
- name: Generate icons (Windows)
|
||||
if: matrix.platform.runner == 'windows-latest'
|
||||
run: npm run tauri:icon
|
||||
shell: pwsh
|
||||
|
||||
- name: Build, sign, and upload to release
|
||||
uses: tauri-apps/tauri-action@v0
|
||||
- name: Build and upload to the draft
|
||||
uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # action-v1.0.0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
with:
|
||||
# Upload into the single draft created by the create-release job above
|
||||
# instead of finding/creating one per matrix job (which caused
|
||||
# duplicate drafts + split assets). The maintainer un-drafts manually.
|
||||
releaseId: ${{ needs.create-release.outputs.release_id }}
|
||||
args: ${{ matrix.platform.args }}
|
||||
|
||||
# Android is built separately: tauri-action does not build mobile targets, so
|
||||
# this job drives the Tauri CLI directly (Java + Android SDK/NDK + Rust android
|
||||
# targets), signs with the release keystore from secrets, and uploads the
|
||||
# universal APK into the same draft release as the desktop bundles.
|
||||
#
|
||||
# Requires these repository secrets (see docs/TAURI-NOTES.md):
|
||||
# ANDROID_KEYSTORE_BASE64 base64 of upload-keystore.jks
|
||||
# ANDROID_KEYSTORE_PASSWORD the keystore (store) password
|
||||
# ANDROID_KEY_PASSWORD the key password (optional; defaults to store password)
|
||||
# ANDROID_KEY_ALIAS the key alias (optional; defaults to "upload")
|
||||
# tauri-action builds desktop targets only; Android drives the Tauri CLI
|
||||
# directly and signs with the release keystore (see docs/TAURI-NOTES.md):
|
||||
# ANDROID_KEYSTORE_BASE64, ANDROID_KEYSTORE_PASSWORD,
|
||||
# ANDROID_KEY_PASSWORD (optional), ANDROID_KEY_ALIAS (optional, "upload").
|
||||
android:
|
||||
name: Build · Android (APK)
|
||||
needs: create-release
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 40
|
||||
needs: [verify, create-release]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: refs/tags/${{ env.TAG }}
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Java 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
|
||||
- name: Setup Android SDK
|
||||
uses: android-actions/setup-android@v4
|
||||
uses: android-actions/setup-android@be39fa834029ff78f1a44aa3bb0819b8fc2bd8fd # v4.0.4
|
||||
|
||||
- name: Install SDK platform + NDK
|
||||
- name: Install SDK platform and NDK
|
||||
run: |
|
||||
sdkmanager "platforms;android-36" "ndk;27.2.12479018"
|
||||
echo "NDK_HOME=$ANDROID_HOME/ndk/27.2.12479018" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Setup Rust (stable) + Android targets
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
- name: Setup Rust with Android targets
|
||||
uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master
|
||||
with:
|
||||
toolchain: stable
|
||||
targets: aarch64-linux-android,armv7-linux-androideabi,i686-linux-android,x86_64-linux-android
|
||||
|
||||
- name: Cache Cargo build artifacts
|
||||
uses: swatinem/rust-cache@v2
|
||||
- name: Cache Cargo
|
||||
uses: swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
workspaces: './src-tauri -> target'
|
||||
key: android
|
||||
|
||||
- name: Setup Node 22
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 22.x
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
- name: Install npm dependencies
|
||||
run: npm ci --no-audit --no-fund
|
||||
- name: Install dependencies
|
||||
run: npm ci --ignore-scripts --no-audit --no-fund
|
||||
|
||||
- name: Generate icons
|
||||
run: npm run tauri:icon
|
||||
@@ -185,7 +240,7 @@ jobs:
|
||||
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
run: |
|
||||
if [ -z "$ANDROID_KEYSTORE_BASE64" ]; then
|
||||
echo "::error::ANDROID_KEYSTORE_BASE64 secret is not set — cannot sign the release APK."
|
||||
echo "::error::ANDROID_KEYSTORE_BASE64 is not set; cannot sign the release APK."
|
||||
exit 1
|
||||
fi
|
||||
KEYSTORE_PATH="$RUNNER_TEMP/upload-keystore.jks"
|
||||
@@ -200,22 +255,86 @@ jobs:
|
||||
- name: Build signed universal APK
|
||||
run: npm run tauri -- android build --apk
|
||||
|
||||
- name: Upload APK to release
|
||||
uses: actions/github-script@v9
|
||||
- name: Upload the APK to the draft
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
env:
|
||||
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
|
||||
VERSION: ${{ needs.verify.outputs.version }}
|
||||
with:
|
||||
script: |
|
||||
const fs = require('fs');
|
||||
const tag = context.ref.replace('refs/tags/', '').replace('refs/heads/', '');
|
||||
const fs = require('node:fs');
|
||||
const { owner, repo } = context.repo;
|
||||
const releaseId = Number(process.env.RELEASE_ID);
|
||||
const dir = 'src-tauri/gen/android/app/build/outputs/apk/universal/release';
|
||||
const apks = fs.readdirSync(dir).filter((f) => f.endsWith('.apk'));
|
||||
if (apks.length === 0) throw new Error(`No APK found in ${dir}`);
|
||||
const src = `${dir}/${apks[0]}`;
|
||||
const name = `JSONPrism-${tag}-android-universal.apk`;
|
||||
if (apks.length !== 1) throw new Error(`Expected one APK in ${dir}, found: ${apks.join(', ') || 'none'}`);
|
||||
// Same naming scheme as the desktop bundles.
|
||||
const name = `JSONPrism_${process.env.VERSION}_android-universal.apk`;
|
||||
const assets = await github.paginate(github.rest.repos.listReleaseAssets, { owner, repo, release_id: releaseId });
|
||||
for (const old of assets.filter((a) => a.name === name)) {
|
||||
await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: old.id });
|
||||
}
|
||||
await github.rest.repos.uploadReleaseAsset({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: ${{ needs.create-release.outputs.release_id }},
|
||||
owner,
|
||||
repo,
|
||||
release_id: releaseId,
|
||||
name,
|
||||
data: fs.readFileSync(src),
|
||||
data: fs.readFileSync(`${dir}/${apks[0]}`),
|
||||
});
|
||||
core.info(`Uploaded ${name}`);
|
||||
|
||||
checksums:
|
||||
name: Checksums and provenance
|
||||
needs: [create-release, desktop, android]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
attestations: write
|
||||
steps:
|
||||
- name: Download the draft's assets
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
|
||||
run: |
|
||||
mkdir assets
|
||||
gh api --paginate "repos/$GITHUB_REPOSITORY/releases/$RELEASE_ID/assets" \
|
||||
--jq '.[] | select(.name != "SHA256SUMS.txt") | [.id, .name] | @tsv' |
|
||||
while IFS=$'\t' read -r id name; do
|
||||
gh api -H 'Accept: application/octet-stream' "repos/$GITHUB_REPOSITORY/releases/assets/$id" > "assets/$name"
|
||||
done
|
||||
ls -l assets
|
||||
|
||||
- name: Write SHA256SUMS.txt
|
||||
working-directory: assets
|
||||
run: |
|
||||
sha256sum -- * > ../SHA256SUMS.txt
|
||||
cat ../SHA256SUMS.txt
|
||||
|
||||
- name: Attest build provenance
|
||||
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
|
||||
with:
|
||||
subject-path: assets/*
|
||||
|
||||
- name: Upload SHA256SUMS.txt to the draft
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
env:
|
||||
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
|
||||
with:
|
||||
script: |
|
||||
const fs = require('node:fs');
|
||||
const { owner, repo } = context.repo;
|
||||
const releaseId = Number(process.env.RELEASE_ID);
|
||||
const name = 'SHA256SUMS.txt';
|
||||
const assets = await github.paginate(github.rest.repos.listReleaseAssets, { owner, repo, release_id: releaseId });
|
||||
for (const old of assets.filter((a) => a.name === name)) {
|
||||
await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: old.id });
|
||||
}
|
||||
await github.rest.repos.uploadReleaseAsset({
|
||||
owner,
|
||||
repo,
|
||||
release_id: releaseId,
|
||||
name,
|
||||
data: fs.readFileSync(name),
|
||||
});
|
||||
core.info(`Uploaded ${name} from ${src}`);
|
||||
@@ -53,3 +53,11 @@ coverage
|
||||
*.tsbuildinfo
|
||||
|
||||
.claude/
|
||||
|
||||
# Cloudflare Workers (wrangler)
|
||||
.wrangler/
|
||||
.dev.vars
|
||||
.dev.vars.*
|
||||
!.dev.vars.example
|
||||
# Generated by `npm run cf:types` (wrangler types) — regenerate, don't commit.
|
||||
worker-configuration.d.ts
|
||||
@@ -8,6 +8,80 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
|
||||
|
||||
No unreleased changes at this time. Future work tracked in `docs/ROADMAP.md` under "Beyond".
|
||||
|
||||
## [2.0.0] — 2026-10-22
|
||||
|
||||
A new home, a hardened toolchain and a full audit. The web app moves to **<https://jsonprism.poli0981.dev>** on Cloudflare Workers; the old GitHub Pages address redirects there, keeping the path. Because the website now uses Cloudflare services, the Privacy Policy and Terms are at version 2.0 and **everyone is asked to accept them again** (`CONSENT_VERSION` 2).
|
||||
|
||||
### Added
|
||||
|
||||
- **Cloudflare Workers hosting.** `wrangler.jsonc` serves `dist/` as static assets with an SPA fallback on the custom domain; only `/api/*` runs Worker code (`worker/`). Cloudflare Workers Builds deploys every push to `main` and publishes a Worker Preview for other branches (`previews` block). New scripts: `cf:types`, `cf:check` (deploy dry run, also in CI) and `preview:cf` (`wrangler dev` on port 8787; `wrangler.jsonc` builds first). See `docs/DEPLOYMENT.md`.
|
||||
- **Edge security headers** in `public/_headers`: a strict CSP, HSTS, `nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy`, `Permissions-Policy`, COOP, and immutable caching for hashed assets. `public/_redirects` 301s the old `/jsonPrism/*` paths. Also new: `robots.txt`, `sitemap.xml`, `/.well-known/security.txt`, an Open Graph image and canonical URLs.
|
||||
- **Cloudflare Turnstile human check (web only).** Runs inside the Consent Gate and is verified server-side by `POST /api/turnstile/verify` (same-origin check, JSON only, 4 KB body cap, per-client rate limit, siteverify with retry and hostname/action/age checks, no visitor IP sent). A pass is remembered for 7 days. A rejected token keeps the gate closed; if Cloudflare cannot be reached the user may continue after a warning, since conversion never needs the network. `GET /api/health` reports Worker health.
|
||||
- **Cloudflare Web Analytics (web only, cookieless).** Loaded only on the production hostname, after consent, while the new Appearance toggle is on; it starts off when the browser sends Global Privacy Control.
|
||||
- **Appearance menu** replacing the theme toggle: light / dark / system theme, **hide scrollbars** (scrolling still works) and, on the web, the analytics switch. Custom thin scrollbars everywhere, including the editors.
|
||||
- **Web Worker conversion.** Inputs over 256 KB and every batch job convert off the main thread (`src/lib/convert-worker.ts`, `convert-client.ts`), with cancellation and a main-thread fallback only if the worker cannot load.
|
||||
- **Logging and diagnostics.** `src/lib/logger.ts` keeps the last 200 log lines in memory (never sent anywhere) and catches global errors; About → **Copy diagnostics** copies version, commit, platform and recent logs for bug reports.
|
||||
- **CSV `escapeFormulae` option** (off by default) that prefixes cells starting with `=`, `+`, `-`, `@`, a tab or a carriage return with `'`, so spreadsheet apps don't run them as formulas.
|
||||
- **Precision warning** when the input contains integers beyond 2^53, which JavaScript cannot represent exactly.
|
||||
- **Release integrity.** Releases include `SHA256SUMS.txt` and GitHub build-provenance attestations (`gh attestation verify`).
|
||||
- **Production smoke workflow** that waits for each merge to go live and checks headers, routing, redirects and the API.
|
||||
- Per-route page titles, build commit in the header and About page, and the Android-friendly `viewport-fit=cover` with safe-area padding.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Toolchain.** Node.js 26 (`.nvmrc`, `engines >=26`). **TypeScript 7** native compiler (`@typescript/native` provides `tsc`; `typescript` is an alias for the TS 6 API that typescript-eslint still needs), target ES2025 while app code keeps the ES2023 library so the Android WebView 111 / macOS 12 floors hold. Separate tsconfigs for app, tests, config files and the Worker. Vite 8 `codeSplitting.groups` replaces the deprecated `advancedChunks`.
|
||||
- **Dependencies to current majors**: React 19.3, React Router 8 (`react-router` only), i18next 26 / react-i18next 17, js-yaml 5, lucide-react 1, tailwind-merge 3, react-dropzone 20, Vitest 5, jsdom 30, ESLint 10, eslint-plugin-react-hooks 7 (React Compiler rules), wrangler 4, Tauri 2.12. `npm audit` reports no vulnerabilities.
|
||||
- **"Technical" UI refresh, same layout.** Blueprint grid, mono labels, corner ticks, separate light and dark prism colours (light-theme text now meets 4.5:1 contrast), success/warning tokens, a terminal-style status bar (state, bytes in → out, time, encoding), animated icons behind `prefers-reduced-motion`, and headings in Geist (Instrument Serif lacked Vietnamese glyphs). Format chips that don't suit the detected shape get a dashed border instead of faded text. The theme is applied before first paint (`public/theme-init.js`), so there is no flash.
|
||||
- **Consent Gate.** Also shown on macOS and Linux desktop (only the Windows installer has its own license page); legal links point at the exact commit of the build; the app renders behind the gate instead of a blank page.
|
||||
- **Faster typing.** One layout rendered at a time, stable editor extensions (no reconfiguration per keystroke), deferred live conversion, a virtualised read-only CodeMirror for output, batched batch-progress updates and streaming ZIP creation.
|
||||
- **Tauri bundles carry no web-only code.** The analytics beacon and the Turnstile widget are compiled out of desktop and Android builds instead of only being switched off at runtime.
|
||||
- **Tauri permissions narrowed.** The static file scope is now Documents, Downloads and Desktop (previously all of `$HOME`); files you pick or drop are added at runtime. Dotfiles never match scope globs, unused permissions (`os`, `set-title`, `write-text-file`, message dialogs) are gone, and the app CSP adds `object-src 'none'`, `base-uri`, `form-action` and `frame-ancestors`. The version now comes from `package.json`; Android `versionCode` 20000 and `allowBackup="false"`.
|
||||
- **Keyboard shortcuts.** Ctrl/⌘+S downloads, Ctrl/⌘+, opens settings; Ctrl/⌘+K (clear) is removed because it hijacked the browser's search. Shortcuts ignore key repeat, IME composition and open dialogs.
|
||||
- **Internationalisation.** Japanese and Simplified Chinese gained 27 missing strings, unused keys were removed, remaining hard-coded strings (including CodeMirror's search and lint panels) are translated, and a test keeps the four locales in sync.
|
||||
- **CI and releases.** Actions pinned to commit SHAs, least-privilege permissions, `npm ci --ignore-scripts`, a TypeScript 7 guard, coverage, a Rust `fmt`/`clippy` job and SonarQube Cloud analysis. Releases check that the tag matches the app version, run the tests first, build into a single draft and name the APK `JSONPrism_<version>_android-universal.apk`. Notification workflows pass only the secrets they need to pinned reusable workflows, and GitHub Discussions no longer receive a post for every deploy. Dependabot groups related packages (majors included) and waits a few days before proposing new releases.
|
||||
- **Documentation and legal.** Privacy Policy and Terms 2.0, refreshed Disclaimer, Security policy (2.x supported, Worker and edge in scope), Code of Conduct, contributing guide, third-party notices, new `docs/DEPLOYMENT.md`, and project contacts at `@poli0981.dev`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **CSV** used only the first row's keys as columns, silently dropping fields that appeared later; columns are now the union across rows. Reverse parsing turns only canonical numbers into numbers (no more `007` → `7` or dates guessed), and keys like `__proto__` are stored safely.
|
||||
- **Batch ZIP** stored base64 text for BSON, CBOR and MessagePack; it now contains the real bytes. Pressing *Process* a second time no longer wipes earlier results, cancelling returns unfinished files to the queue, and duplicate output names are made unique case-insensitively.
|
||||
- **SQL INSERT**: MySQL string literals escape backslashes (a `\'` payload could break out of the string), MSSQL uses `N'…'` and `NVARCHAR`, `CREATE TABLE` types are inferred from all rows (`BIGINT`, `DECIMAL(38, 0)` for huge integers), dotted table names are quoted per part, and MSSQL batches are capped at its 1000-row limit.
|
||||
- **RESX** reverse keeps values such as `"007"` as strings, validates the XML and rejects `DOCTYPE`; output always includes the resheaders, encodes carriage returns and replaces characters XML cannot carry.
|
||||
- **XML** produced invalid documents for keys that are not valid element names; names are now sanitised (the original kept in a `key` attribute), nested arrays are wrapped, control characters replaced, root/item names validated and every result checked with a validator.
|
||||
- **BSON** documents over 16 MiB were silently truncated; they now return a clear error.
|
||||
- **YAML** `quoteStyle` had no effect; it works again with js-yaml 5. Alias and merge-key bombs are capped, and empty input reports an error instead of `undefined`.
|
||||
- **TOML** reports `null` values with their path (or omits them, by option), keeps integers beyond 2^53 exact and sorts keys deterministically.
|
||||
- **JSONL** tolerates a BOM and reports real line numbers, blank lines included.
|
||||
- **JSON errors** show the correct line and column in Chromium, Firefox and WebKit.
|
||||
- The editor inserted the text of dropped files itself, racing the file loader; file drops now go only to the drop zone. An empty editor is no longer flagged as invalid JSON, JSONL typed in the → JSON direction is checked line by line instead of being marked invalid, and a leading byte-order mark is accepted like the converter accepts it.
|
||||
- File sizes just under 1 MiB showed as "1024.0 KB".
|
||||
- **Download** and Ctrl/⌘+S reported success on Android without saving; desktop and Android now use the native save dialog.
|
||||
- Native open dialogs filter by conversion direction and accept `.yml`, `.ndjson` and `.markdown`; a drag-and-drop listener could leak when the component unmounted early.
|
||||
- Route errors now reset when you navigate away, and a stale tab that fails to load a chunk after a deploy reloads once instead of breaking.
|
||||
- Stored options and formats are validated, so corrupt `localStorage` can no longer crash the app; blocked storage is tolerated everywhere.
|
||||
- Accessibility: live regions for errors, status and batch progress; accessible names for the editors; `aria-pressed` on toggle groups; touch targets of at least 24 px; `<html lang>` follows the interface language.
|
||||
|
||||
### Removed
|
||||
|
||||
- The GitHub Pages deployment (`deploy.yml`, `public/404.html` and the SPA redirect script). Pages now serves only a redirect page (`pages-redirect.yml`, run by hand).
|
||||
- `react-router-dom`, `@fontsource/instrument-serif`, `@types/js-yaml` and the unused `os` plugin (`@tauri-apps/plugin-os`, `tauri-plugin-os`).
|
||||
|
||||
### Security
|
||||
|
||||
- Fixed the MySQL backslash escaping flaw in the SQL converter (see Fixed) and the XML/RESX output issues that could yield malformed documents.
|
||||
- Narrowed the desktop file-system scope and permissions, disabled Android backups and tightened both CSPs (see Changed).
|
||||
- Resolved the open npm Dependabot alerts by upgrading react-router, js-yaml, undici, postcss, smol-toml, brace-expansion, source-map-js and vitest.
|
||||
|
||||
### Tests
|
||||
|
||||
- **864 tests in 92 files** (up from 215), 97% line and 91% branch coverage: regression tests for every fix above, a contract test that feeds hostile input to every converter, component tests for the whole UI (Testing Library + user-event, with a fake Turnstile widget and Tauri IPC mocks), hook, store and storage tests, the Web Worker client, locale parity, and Worker tests for the verify endpoint and router. Vitest runs two projects (`app` in jsdom, `worker` in Node) and reports coverage to SonarQube Cloud, whose quality gate now passes.
|
||||
|
||||
## [1.7.2] — 2026-06-16
|
||||
|
||||
### Fixed
|
||||
|
||||
- **External links open on Android.** Links tapped in the Android app — the Consent Gate's legal links, the footer and About links — did nothing: `@tauri-apps/plugin-shell`'s `open()` has no URL handler on Android and failed with "os error 2". `openExternal()` now uses `@tauri-apps/plugin-opener`'s `openUrl()`, which hands the URL to the system browser through `Intent.ACTION_VIEW`. The shell plugin, its capability and its npm package were removed. Verified on an Android 13 emulator. `bundle.android.versionCode` 10702.
|
||||
|
||||
## [1.7.1] — 2026-06-16
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -4,111 +4,151 @@ Guidance for Claude (and other AI assistants) working on this repository.
|
||||
|
||||
## Project context
|
||||
|
||||
**JSONPrism** is a client-side JSON converter web app. Single JSON input → many formats (JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown table, SQL INSERT). Deployed to GitHub Pages; later wrapped in Tauri 2 as a desktop app.
|
||||
**JSONPrism** converts one JSON input into 12 formats (JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack) and parses six of them (JSONL, CSV, TSV, YAML, TOML, RESX) back. Conversion always runs on the user's device. It ships as:
|
||||
|
||||
The maintainer is **Kokone** ([@poli0981](https://github.com/poli0981)). Audience: developer community on the open-source Discord server + YouTube viewers who watch indie/visual-novel gameplay and occasionally want a quick devtool.
|
||||
- a web app at <https://jsonprism.poli0981.dev>, served by the Cloudflare Worker `jsonprism` (static assets + a tiny `/api/*` Worker), deployed by Cloudflare Workers Builds on every push to `main`;
|
||||
- native apps built with Tauri 2: Windows, macOS, Linux and Android (sideload APK).
|
||||
|
||||
**Project phase**: Phase 0 scaffold complete. Phase 1 polishes the four working converters and adds CodeMirror. Phase 2 implements XML/TOML/Markdown/SQL and the Tauri build. Phase 3 implements RESX.
|
||||
GitHub Pages (`poli0981.github.io/jsonPrism`) now only redirects to the new domain.
|
||||
|
||||
The maintainer is **Kokone** ([@poli0981](https://github.com/poli0981)). Audience: the developer community on the open-source Discord server plus YouTube viewers who watch indie/visual-novel gameplay and occasionally want a quick devtool.
|
||||
|
||||
**Current release**: 2.0.0. See [`docs/ROADMAP.md`](docs/ROADMAP.md) for what is next.
|
||||
|
||||
## Stack — exact versions matter
|
||||
|
||||
- **Node.js** 22.x LTS (minimum 22.0.0; enforced in `package.json` `engines`)
|
||||
- **React** 19.x (uses new JSX transform, `use()` hook, ref-as-prop)
|
||||
- **TypeScript** 5.7+ (strict mode; `verbatimModuleSyntax`; `erasableSyntaxOnly`)
|
||||
- **Vite** 6.x (ES2022 target, `@tailwindcss/vite` plugin)
|
||||
- **Tailwind CSS** v4 (new `@theme inline` syntax in CSS, NOT `tailwind.config.ts`)
|
||||
- **shadcn/ui** New York style, neutral base, configured in `components.json`
|
||||
- **ESLint** v9 flat config + `typescript-eslint` v8
|
||||
- **Prettier** 3.x with `prettier-plugin-tailwindcss`
|
||||
- **Node.js** 26 (`.nvmrc`; `engines.node` >= 26.0.0). npm 11; nothing needs dependency install scripts (CI runs `npm ci --ignore-scripts`).
|
||||
- **TypeScript 7** (native compiler) — `@typescript/native` (`npm:typescript@^7`) provides `tsc`. The `typescript` package is an alias for `@typescript/typescript6` and exists only because typescript-eslint needs the TS 6 API; don't "fix" the alias. Remove it once TS 7.1 ships an API and typescript-eslint supports it.
|
||||
- Strict mode, `verbatimModuleSyntax`, `erasableSyntaxOnly` (no enums, no parameter properties), no `baseUrl` (TS 7 rejects it; `paths` only), `types` listed explicitly per tsconfig (TS 7 defaults to `[]`).
|
||||
- `target` ES2025, but app `lib` is ES2023: **don't use ES2025 runtime APIs** (Iterator helpers, Set methods, `Promise.try`, `RegExp.escape`…). The floors are Android WebView Chromium 111 and macOS 12 WebKit.
|
||||
- tsconfigs: `tsconfig.app.json` (browser code), `tsconfig.test.json` (tests, Node types), `tsconfig.node.json` (config files), `tsconfig.worker.json` (Worker; types from `wrangler types`).
|
||||
- **React** 19.3 (new JSX transform, `use()`, ref-as-prop, `<title>` hoisting), **React Router** 8 (`react-router` only).
|
||||
- **Vite** 8 (Rolldown + Oxc). Chunks are split with `build.rollupOptions.output.codeSplitting.groups` (the old `manualChunks`/`advancedChunks` forms are deprecated). Leave `build.target` at the default; an ES-year target also raises the CSS target.
|
||||
- **Tailwind CSS** v4 (`@theme inline` in CSS, no `tailwind.config.ts`), **shadcn/ui** New York style in `components.json`.
|
||||
- **ESLint** 10 flat config (`defineConfig`) + typescript-eslint 8, eslint-plugin-react-hooks 7 (React Compiler rules: no setState in effects, no components defined during render, pure render), react-refresh.
|
||||
- **Prettier** 3 with `prettier-plugin-tailwindcss`, **Knip**, **Vitest** 5 (projects: `app` = jsdom, `worker` = node).
|
||||
- **Cloudflare**: wrangler 4, `wrangler.jsonc`, Worker code in `worker/`.
|
||||
|
||||
Do not propose downgrading or "modernizing" to deprecated patterns.
|
||||
|
||||
## Tauri 2 desktop wrapper
|
||||
## Web platform (Cloudflare)
|
||||
|
||||
JSONPrism is shipped as both a web app (GitHub Pages) and a native desktop app (Tauri 2 bundles). The same React UI runs in both contexts.
|
||||
- `wrangler.jsonc`: static assets from `dist/` with SPA fallback; only `/api/*` runs the Worker (`run_worker_first`). Bindings: `ASSETS`, `VERIFY_LIMITER` (rate limit), var `ALLOWED_HOSTNAMES`, secret `TURNSTILE_SECRET` (dashboard; locally `.dev.vars`, copied from `.dev.vars.example`).
|
||||
- `worker/index.ts` may only have a **default export** — workerd treats every named export of the entry module as an entrypoint and refuses to start. Put shared code in other modules (`worker/verify.ts`, `worker/turnstile.ts`, `worker/http.ts`).
|
||||
- Worker logs are structured (`logEvent`) and must never contain IPs, tokens or user content.
|
||||
- `public/_headers` holds the CSP and security headers; `public/_redirects` maps the old `/jsonPrism/*` paths. Adding any third-party script, style, font or connection means updating the CSP there (and the Tauri CSP in `tauri.conf.json` if it applies to the apps).
|
||||
- `wrangler dev` rewrites the request URL and `Origin` to the production route; the verify endpoint relaxes its origin check only under Cloudflare's test secret.
|
||||
- Local preview of the real edge setup: `npm run preview:cf` (http://localhost:8787). `npm run cf:check` is the deploy dry run CI uses.
|
||||
|
||||
**Runtime detection**: `isTauri()` from `src/lib/tauri.ts` is the single source of truth. The web bundle never imports Tauri modules statically — they're behind dynamic imports gated by `isTauri()` so tree-shaking keeps web builds clean.
|
||||
## Web-only services
|
||||
|
||||
**When to branch on `isTauri()`**:
|
||||
Turnstile and Web Analytics exist **only in the web build** — never in Tauri builds, never in `npm run dev` (Turnstile can be forced with `VITE_TURNSTILE_DEV=1`).
|
||||
|
||||
- File dialogs: web uses hidden `<input type="file">`; Tauri uses `plugin-dialog`
|
||||
- Save .zip: web uses Blob URL download; Tauri uses native save dialog + `plugin-fs.writeFile`
|
||||
- Drag-drop from File Explorer / Finder: web uses `react-dropzone`; Tauri uses `tauri://drag-drop` event via `useTauriDragDrop`
|
||||
- **Turnstile** (`src/lib/turnstile.ts`, `src/components/common/HumanCheck.tsx`, `worker/verify.ts`): runs in the Consent Gate, verified server-side, remembered 7 days. Rejected token → gate stays closed. Cloudflare unreachable → let the user continue after a warning (conversion never needs the network). Keep the action name in sync between client and Worker.
|
||||
- **Web Analytics** (`src/lib/analytics.ts`): injected only on the production hostname, after consent, while the Appearance toggle is on (default off under Global Privacy Control).
|
||||
- Changing what the website collects means updating `PRIVACY.md` and bumping `CONSENT_VERSION` in `src/lib/consent-storage.ts` so users accept again.
|
||||
|
||||
**Don't branch on `isTauri()`** for things that work in both: clipboard, in-memory operations, the converters themselves. Keep the Tauri-specific code at the I/O boundary.
|
||||
## Tauri 2 apps
|
||||
|
||||
**Adding a new Tauri-only command**: declare in `src-tauri/src/lib.rs` with `#[tauri::command]`, register in `invoke_handler!`, expose a typed wrapper in `src/lib/tauri.ts` using `invoke()`. Update the capability JSON if it needs new permissions.
|
||||
The same React UI runs in the browser and in Tauri (desktop + Android).
|
||||
|
||||
**Icon updates**: edit `src-tauri/icons/icon.svg` (1024×1024 canvas) then run `npm run tauri:icon`. The generated PNG/ICO/ICNS files are gitignored — CI regenerates them per build.
|
||||
**Runtime detection**: `isTauri()` from `src/lib/tauri.ts`, backed by the build-time `__IS_TAURI_BUILD__`, `__IS_ANDROID_BUILD__` and `__TAURI_PLATFORM__` defines. The web bundle never imports Tauri modules statically — they sit behind dynamic imports guarded by these flags so tree-shaking keeps them out of the web build.
|
||||
|
||||
**Permission model**: Tauri 2 uses capability files. Edits to `src-tauri/capabilities/default.json` change which APIs the main window can call. Default capability already grants dialog, fs (scoped to `$HOME`, `$DOCUMENT`, `$DOWNLOAD`, `$DESKTOP`), os, and shell:open.
|
||||
**When to branch on the platform**:
|
||||
|
||||
**Bundling**: `npm run tauri:build` produces the platform bundle of whatever OS you're on. For cross-platform releases, push a `v*` tag — `.github/workflows/release.yml` matrix-builds for Windows, macOS Intel/ARM, and Linux.
|
||||
- File dialogs: web uses a hidden `<input type="file">`; Tauri uses `nativeOpenFiles()` (`plugin-dialog`).
|
||||
- Saving output or a `.zip`: web uses a Blob download (`src/lib/download.ts`); Tauri uses `nativeSaveBlob()` (save dialog + `plugin-fs.writeFile`).
|
||||
- Drag-drop from the OS: web uses `react-dropzone`; Tauri uses the `tauri://drag-drop` event via `useTauriDragDrop`.
|
||||
- External links: `openExternal()` (the Android WebView ignores `target="_blank"`).
|
||||
- Consent Gate: shown on web, Android, macOS and Linux; Windows skips it because the installer's license page (`src-tauri/license.rtf`) already asks.
|
||||
|
||||
**Velopack note**: PhantomMAC uses Velopack for `.exe` deltas; JSONPrism uses Tauri's native bundler instead. Don't mix the two — Tauri's bundler produces `.msi` + `.exe` (NSIS) for Windows which covers the same ground.
|
||||
**Don't branch** for things that work everywhere: clipboard, in-memory work, the converters. Keep platform code at the I/O boundary.
|
||||
|
||||
**Adding a Tauri command**: declare it in `src-tauri/src/lib.rs` with `#[tauri::command]`, register it in `generate_handler!`, expose a typed wrapper in `src/lib/tauri.ts` using `invoke()`, and grant only the permissions it needs.
|
||||
|
||||
**Permission model**: `src-tauri/capabilities/default.json` is least-privilege — `core:default`, `opener:default`, dialog open/save, fs read-text/write/stat. The static fs scope is `$DOCUMENT`, `$DOWNLOAD`, `$DESKTOP`; files the user picks in a dialog or drops on the window are added to the scope at runtime by the plugins. `plugins.fs.requireLiteralLeadingDot` is `true`, so globs never match dotfiles. Don't widen the scope to `$HOME/**`.
|
||||
|
||||
**Versions**: `tauri.conf.json` reads the version from `package.json`. On a release bump `package.json`, `src-tauri/Cargo.toml` (+ `Cargo.lock`) and `bundle.android.versionCode` (MAJOR*10000 + MINOR*100 + PATCH). The release workflow refuses a tag that doesn't match.
|
||||
|
||||
**Icons**: edit `src-tauri/icons/icon.svg` (1024×1024) and run `npm run tauri:icon`. Generated PNG/ICO/ICNS files are gitignored; CI regenerates them. Revert unintended changes it makes under `src-tauri/gen/android/`.
|
||||
|
||||
**Bundling**: `npm run tauri:build` builds for the current OS. Releases come from pushing a `vX.Y.Z` tag: `.github/workflows/release.yml` builds Windows, macOS universal, Linux and Android into one draft release with `SHA256SUMS.txt` and provenance attestations.
|
||||
|
||||
**Velopack note**: PhantomMAC uses Velopack for `.exe` deltas; JSONPrism uses Tauri's native bundler (`.msi` + NSIS `.exe`). Don't mix the two.
|
||||
|
||||
## Code style — non-negotiable
|
||||
|
||||
- **Pure functions for converters**. Each converter is a pure, synchronous module implementing the `Converter<TOptions>` interface in `src/converters/types.ts`. No I/O, no DOM access, no global state.
|
||||
- **Errors as values**. Converters return `{ ok: true, output } | { ok: false, error }`. Never throw across converter boundaries.
|
||||
- **No `any`**. Use `unknown` for JSON values and narrow with type guards. The only sanctioned `any` is in `registry.ts` for the heterogeneous record type — keep it there.
|
||||
- **Type-only imports**: `import type { Converter } from './types'`. Enforced by ESLint rule `consistent-type-imports`.
|
||||
- **Use the `@/*` path alias** for imports inside `src/`. Don't write `../../lib/utils`.
|
||||
- **Tailwind class order**: rely on `prettier-plugin-tailwindcss` — never hand-sort.
|
||||
- **Don't fight the theme system**. Use the CSS variables (`--color-prism-*`, `bg-background`, etc.) instead of hard-coded hex.
|
||||
- **i18n everything user-facing**. Hard-coded English strings in components are a bug. Add to both `en.json` and `vi.json`.
|
||||
- **Pure functions for converters**. Each converter is a pure, synchronous module implementing `Converter<TOptions>` from `src/converters/types.ts`. No I/O, no DOM, no global state.
|
||||
- **Errors as values**. Converters return `{ ok: true, output } | { ok: false, error }`. Never throw across converter boundaries; callers go through `safeConvert`/`safeReverse` in `registry.ts`, which also catch the unexpected. Turn caught values into messages with `errorMessage()` from `src/lib/errors.ts`.
|
||||
- **Untrusted keys**: build objects from parsed input with `defineOwn()` (`src/lib/json.ts`) so `__proto__` stays a plain key; sort keys with `compareOrdinal`.
|
||||
- **No `any`**. Use `unknown` and narrow. The only sanctioned `any` is the heterogeneous record in `registry.ts`.
|
||||
- **Type-only imports**: `import type { Converter } from './types'` (ESLint `consistent-type-imports`).
|
||||
- **Use the `@/*` path alias** inside `src/`.
|
||||
- **Tailwind class order**: rely on `prettier-plugin-tailwindcss`; never hand-sort.
|
||||
- **Don't fight the theme system**. Use the tokens (`--color-prism-*`, `--color-success`, `--color-warning`, `bg-background`, …), which have separate light and dark values. No hard-coded hex. Animations go behind `motion-safe:`.
|
||||
- **i18n everything user-facing** in all four locales: `en.json`, `vi.json`, `ja.json`, `zh-CN.json` (`src/i18n/__tests__/locales.test.ts` enforces key parity). Libraries return error *codes*; components translate them.
|
||||
- **Logging**: use `createLogger(scope)` from `src/lib/logger.ts`, not `console.*` (ESLint warns). Logs stay in memory and feed About → Copy diagnostics; never log user content.
|
||||
- **Heavy work off the main thread**: conversions of large inputs and batch jobs go through `src/lib/convert-client.ts` (Web Worker); keep `convert-worker.ts` free of DOM access.
|
||||
|
||||
## File layout — where things go
|
||||
|
||||
```
|
||||
src/
|
||||
├── app/ # Top-level App component + routes
|
||||
├── app/ # App component + routes
|
||||
├── components/
|
||||
│ ├── ui/ # shadcn components — generated by CLI, don't hand-edit
|
||||
│ ├── layout/ # Header, Footer, theme/language toggles
|
||||
│ ├── layout/ # Header, Footer, AppearanceMenu, Layout
|
||||
│ ├── converter/ # The workspace UI
|
||||
│ └── common/ # Reusable bits not specific to converters
|
||||
│ └── common/ # Reusable bits (ConsentGate, HumanCheck, error states…)
|
||||
├── converters/ # ONE file per format. Self-contained.
|
||||
├── hooks/ # React hooks
|
||||
├── i18n/ # i18next setup + locales
|
||||
├── lib/ # Pure utilities: detect, theme, sample, utils
|
||||
├── lib/ # Pure utilities and platform glue
|
||||
├── pages/ # Route components
|
||||
└── styles/ # globals.css ONLY — no per-component CSS files
|
||||
├── stores/ # Zustand stores (workspace, batch, consent, preferences)
|
||||
├── styles/ # globals.css ONLY — no per-component CSS files
|
||||
└── test/ # Vitest setup
|
||||
worker/ # Cloudflare Worker (its own runtime and tsconfig)
|
||||
public/ # Static files incl. _headers, _redirects, .well-known/
|
||||
src-tauri/ # Tauri shell (Rust), capabilities, Android project
|
||||
```
|
||||
|
||||
If you find yourself wanting to add a new top-level folder, stop and reconsider.
|
||||
If you find yourself wanting another top-level folder, stop and reconsider.
|
||||
|
||||
## Adding a new converter — checklist
|
||||
|
||||
1. Create `src/converters/myformat.ts` exporting `myFormatConverter` (camelCase).
|
||||
2. Implement the `Converter<MyFormatOptions>` interface. Return errors as values.
|
||||
3. Add the format ID to the `FormatId` union in `src/converters/types.ts`.
|
||||
4. Register in `src/converters/registry.ts` (both `CONVERTERS` and `ALL_FORMATS`).
|
||||
5. Add `formats.myformat` label to BOTH `src/i18n/locales/en.json` AND `src/i18n/locales/vi.json`.
|
||||
6. If introducing a new parsing library, add it to `vite.config.ts` `manualChunks.parsers` so it splits cleanly.
|
||||
7. Update the format table in `README.md` and `README.vi.md`.
|
||||
8. Update `docs/ROADMAP.md` to mark the phase done.
|
||||
9. Write unit tests (Phase 1+ when Vitest lands).
|
||||
1. Create `src/converters/myformat.ts` exporting `myFormatConverter`.
|
||||
2. Implement `Converter<MyFormatOptions>`, including `meta.extension` (plus `altExtensions` for aliases such as `yml`, and `binary` for byte formats). Return errors as values.
|
||||
3. Add the ID to the `FormatId` union in `src/converters/types.ts`.
|
||||
4. Register it in `src/converters/registry.ts` (`CONVERTERS` and `ALL_FORMATS`).
|
||||
5. Add `formats.myformat` (and any option labels) to all four locale files.
|
||||
6. A new parsing library gets its own `p-*` group in `vite.config.ts` `codeSplitting.groups`.
|
||||
7. Add regression tests under `src/converters/__tests__/`; the contract test runs every converter against hostile input automatically.
|
||||
8. Update the format tables in `README.md` and `README.vi.md`, `THIRD-PARTY.md` for new dependencies, and `docs/ROADMAP.md`.
|
||||
|
||||
## Pitfalls observed in the wild
|
||||
|
||||
- **Don't put options inside the converter call signature**. Options are passed separately so the UI can introspect `defaultOptions` to render a settings panel.
|
||||
- **Don't use `JSON.parse` directly in components**. Always go through `parseJsonInput` in `src/lib/detect.ts` so error positions surface uniformly.
|
||||
- **CSV nested values**: stringify nested objects as JSON by default (`nestedStrategy: 'json'`). The `flatten` strategy is alpha — keep it but don't make it default.
|
||||
- **YAML force-quoting**: js-yaml's `forceQuotes` only works in conjunction with `quotingType`. Leaving one undefined produces unquoted output. Tested.
|
||||
- **GitHub Pages basename**: production builds use base `/jsonprism/`. The router uses `import.meta.env.PROD` to switch basename. Do not hard-code.
|
||||
- **Tailwind v4 dark mode**: uses the new `@custom-variant dark (&:is(.dark *));` syntax. The `.dark` class on `<html>` triggers all dark-mode variants. Don't add `darkMode: 'class'` configs — that's v3 syntax.
|
||||
- **Options live outside the converter call signature**. They are passed separately so the UI can introspect `defaultOptions`/the option schema; stored options are validated against that schema (`src/lib/options-storage.ts`).
|
||||
- **Don't use `JSON.parse` directly in components**. Go through `parseJsonInput` in `src/lib/detect.ts` so error positions and the precision-loss warning surface uniformly.
|
||||
- **CSV nested values**: stringify nested objects as JSON by default (`nestedStrategy: 'json'`). `flatten` is alpha — keep it, don't make it default. Columns are the union of keys across rows.
|
||||
- **YAML quoting** (js-yaml 5): `quoteStyle` picks the quote character and `forceQuotes` must be `true` for it to apply; `'auto'` means no forced quotes. Tested.
|
||||
- **Binary formats** (BSON, CBOR, MessagePack) produce text (base64/hex) for display; downloads and ZIPs must contain the decoded bytes.
|
||||
- **Base path**: the web build is served from `/` on its own domain. Don't reintroduce a `/jsonPrism/` base or router basename.
|
||||
- **Tailwind v4 dark mode**: `@custom-variant dark (&:is(.dark *));`. The `.dark` class on `<html>` (set before paint by `public/theme-init.js`) drives it. Don't add `darkMode: 'class'` configs.
|
||||
- **Inline scripts are blocked by the CSP**. Early page logic goes in a file under `public/` (like `theme-init.js`).
|
||||
|
||||
## Commands the maintainer actually runs
|
||||
|
||||
```bash
|
||||
npm run dev # 99% of the time
|
||||
npm run typecheck # before pushing
|
||||
npm run lint # CI does this anyway
|
||||
npm run build # to verify production output
|
||||
npm run dev # 99% of the time
|
||||
npm run typecheck # before pushing (tsc -b + the Worker)
|
||||
npm run lint # CI does this anyway
|
||||
npm test # Vitest, app + worker projects
|
||||
npm run build # verify production output
|
||||
npm run preview:cf # the real Cloudflare setup on http://localhost:8787
|
||||
```
|
||||
|
||||
Format check happens automatically via Prettier in CI. The maintainer typically uses **WebStorm** (JetBrains license), so Prettier and ESLint run on save.
|
||||
CI (`.github/workflows/ci.yml`) also runs `format:check`, `knip`, coverage, `cf:check`, SonarQube Cloud and `cargo fmt`/`clippy`. The maintainer typically uses **WebStorm** (JetBrains license), so Prettier and ESLint run on save.
|
||||
|
||||
## Communication preferences
|
||||
|
||||
@@ -117,8 +157,8 @@ Format check happens automatically via Prettier in CI. The maintainer typically
|
||||
- When proposing changes, show the diff or full file; don't just describe.
|
||||
- Match the file-naming and patterns already established (`*Converter`, `useFoo`, kebab-case for files, PascalCase for components).
|
||||
- The maintainer dislikes excessive emoji; reserve them for status indicators in docs (✅ 🔜 📋).
|
||||
- When unsure between two equally-valid approaches, pick one and explain briefly — don't ask which the maintainer prefers unless it's a meaningful tradeoff.
|
||||
- When unsure between two equally valid approaches, pick one and explain briefly — don't ask which the maintainer prefers unless it's a meaningful tradeoff.
|
||||
|
||||
## Roadmap reference
|
||||
|
||||
See [`docs/ROADMAP.md`](docs/ROADMAP.md) for the canonical phase plan. Update it as work lands.
|
||||
See [`docs/ROADMAP.md`](docs/ROADMAP.md) for the canonical phase plan and [`docs/DEPLOYMENT.md`](docs/DEPLOYMENT.md) for hosting and releases. Update them as work lands.
|
||||
+15
-7
@@ -1,6 +1,7 @@
|
||||
# Code of Conduct
|
||||
|
||||
This project adopts the **[Contributor Covenant, v2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/)** verbatim.
|
||||
This project adopts the **[Contributor Covenant, v2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/)** by reference: its full text is
|
||||
JSONPrism's Code of Conduct.
|
||||
|
||||
In short:
|
||||
|
||||
@@ -9,14 +10,21 @@ In short:
|
||||
- Assume good intent, but don't tolerate bad behavior.
|
||||
- Keep discussion focused on the project.
|
||||
|
||||
The maintainer ([@poli0981](https://github.com/poli0981)) is responsible
|
||||
for enforcement. Reports of misconduct can be sent through:
|
||||
The maintainer, Kokone ([@poli0981](https://github.com/poli0981)), is
|
||||
responsible for enforcement. Report misconduct by email to
|
||||
**[code@poli0981.dev](mailto:code@poli0981.dev)**, with links to the
|
||||
issues, comments or messages concerned if you can.
|
||||
|
||||
- A [private Discussion](https://github.com/poli0981/jsonPrism/discussions) addressed to the maintainer, or
|
||||
- Email via the address on the GitHub profile.
|
||||
Content on GitHub that breaks GitHub's own rules, including anything
|
||||
posted by the maintainer, can also be reported to GitHub directly:
|
||||
see [Reporting abuse or spam](https://docs.github.com/en/communities/maintaining-your-safety-on-github/reporting-abuse-or-spam).
|
||||
|
||||
Reports are handled confidentially. Possible outcomes include: a warning,
|
||||
a temporary ban, or a permanent ban from the repository.
|
||||
Reports are handled confidentially. Following the Covenant's enforcement
|
||||
guidelines, possible outcomes are a private correction, a warning, a
|
||||
temporary ban, or a permanent ban from the repository.
|
||||
|
||||
Security vulnerabilities are not conduct reports; see
|
||||
[SECURITY.md](SECURITY.md).
|
||||
|
||||
For the full text — definitions, scope, enforcement guidelines — see the
|
||||
[Contributor Covenant 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/).
|
||||
+177
-40
@@ -2,83 +2,214 @@
|
||||
|
||||
Thanks for considering a contribution! JSONPrism is an open-source project under Apache License 2.0.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
| Tool | Version | Notes |
|
||||
|---|---|---|
|
||||
| **Node.js** | 26 | Pinned in [`.nvmrc`](.nvmrc), so `nvm use` (or `fnm use`) picks it up. `engines.node` is `>=26.0.0`. |
|
||||
| **npm** | 11 | Ships with Node 26. |
|
||||
| **Rust** | latest stable (Tauri 2.12 needs ≥ 1.90) | Only for the desktop / Android shell in `src-tauri/`. |
|
||||
|
||||
The OS packages needed for Tauri builds are listed under "Desktop app"
|
||||
and "Android app" in [README.md](README.md).
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
git clone https://github.com/poli0981/jsonPrism.git
|
||||
cd jsonprism
|
||||
npm install
|
||||
cd jsonPrism
|
||||
npm ci
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Open <http://localhost:5173>.
|
||||
|
||||
npm 11 may block or warn about dependency install scripts. That is
|
||||
expected: nothing in this project needs them, and CI installs with
|
||||
`npm ci --ignore-scripts`.
|
||||
|
||||
Desktop and Android shells (Tauri 2):
|
||||
|
||||
```bash
|
||||
npm run tauri:dev # desktop window around the dev server
|
||||
npm run tauri:android:dev # Android emulator or device
|
||||
```
|
||||
|
||||
## Before opening a PR
|
||||
|
||||
1. **Run the checks locally**:
|
||||
1. **Run the same checks as CI**. If any fails, your PR can't be merged:
|
||||
|
||||
```bash
|
||||
npm run format
|
||||
npm run lint
|
||||
npm run knip
|
||||
npm run typecheck
|
||||
npm run build
|
||||
npm run format:check # Prettier (fix with: npm run format)
|
||||
npm run lint # ESLint (many issues fix with: npm run lint:fix)
|
||||
npm run knip # unused files, exports and dependencies
|
||||
npm run typecheck # TypeScript 7: app, tests, config files, Worker
|
||||
npm test # Vitest (CI runs npm run test:coverage)
|
||||
npm run build # production web build into dist/
|
||||
npm run cf:check # Worker deploy dry run; needs dist/ from the build
|
||||
```
|
||||
|
||||
CI runs all of these. If any fails, your PR can't be merged.
|
||||
If you changed `src-tauri/`, CI also runs `cargo fmt --check` and
|
||||
`cargo clippy --all-targets --locked -- -D warnings` in that folder.
|
||||
Run `npm run tauri:icon` and `npm run build` first: the Rust build
|
||||
embeds the generated icons and `dist/`.
|
||||
|
||||
2. **Match the project style.** Read [`CLAUDE.md`](CLAUDE.md) for non-negotiable conventions (converter shape, error handling, i18n requirements).
|
||||
2. **Match the project style.** Read [`CLAUDE.md`](CLAUDE.md) for the
|
||||
non-negotiable code conventions (converter shape, error handling, i18n
|
||||
requirements). For tool versions, `package.json` and this file are
|
||||
authoritative.
|
||||
|
||||
3. **Keep PRs focused.** One feature or one fix per PR. Refactors as separate PRs.
|
||||
|
||||
4. **Write a clear PR description**: what changed, why, screenshots if UI.
|
||||
4. **Fill in the [PR template](.github/PULL_REQUEST_TEMPLATE.md)**: what
|
||||
changed, why, how you tested it, screenshots if UI, and whether AI
|
||||
tools helped.
|
||||
|
||||
## Toolchain notes
|
||||
|
||||
### TypeScript 7 and the TS 6 alias
|
||||
|
||||
JSONPrism type-checks and builds with **TypeScript 7**, the native
|
||||
compiler. Two TypeScript packages are installed side by side on purpose:
|
||||
|
||||
| `package.json` entry | Installs | Used for |
|
||||
|---|---|---|
|
||||
| `@typescript/native` | `typescript@7` | The `tsc` binary: `npm run typecheck` and `npm run build` |
|
||||
| `typescript` | `@typescript/typescript6` | The TypeScript 6 API (binary `tsc6`) that typescript-eslint and editors load |
|
||||
|
||||
Why: TypeScript 7.0 ships no JavaScript API yet, and typescript-eslint 8
|
||||
only supports `typescript` below 6.1. Leave the alias as it is (Dependabot
|
||||
ignores it from 6.1 on). It goes away once TypeScript 7.1 ships an API
|
||||
that typescript-eslint supports.
|
||||
|
||||
- **`npm run typecheck` is the source of truth.** CI also checks that
|
||||
`tsc` really is TypeScript 7. Diagnostics from an editor running the
|
||||
TS 6 language service can occasionally differ; the command line wins.
|
||||
- **WebStorm**: in *Settings → Languages & Frameworks → TypeScript*, point
|
||||
the TypeScript package at `node_modules/typescript` (the TS 6 API), or
|
||||
use the TypeScript 7 native preview as described in JetBrains' docs.
|
||||
- TS 7 rules to remember: no `baseUrl` (use `paths`), `types` defaults to
|
||||
`[]` so every tsconfig lists its own, and `erasableSyntaxOnly` rules out
|
||||
enums, runtime namespaces and constructor parameter properties.
|
||||
- Projects: `tsconfig.app.json` (browser code), `tsconfig.test.json`
|
||||
(tests, Node types), `tsconfig.node.json` (Vite / Vitest config) and
|
||||
`tsconfig.worker.json` (Cloudflare Worker).
|
||||
|
||||
### No ES2025 runtime APIs in app code
|
||||
|
||||
TypeScript targets ES2025, but `tsconfig.app.json` deliberately includes
|
||||
only the **ES2023** library. Do not use ES2025 runtime APIs in `src/`:
|
||||
Iterator helpers, the new `Set` methods, `Promise.try`, `RegExp.escape`
|
||||
and the like. The Android WebView floor (Chromium 111) and macOS 12
|
||||
WebKit don't have them, and the compiler rejects them on purpose. Leave
|
||||
Vite's `build.target` at its default too. The Worker in `worker/` runs on
|
||||
Cloudflare's runtime and is not bound by this rule.
|
||||
|
||||
### Tests
|
||||
|
||||
- `npm test` runs Vitest once, in two projects: `app` (jsdom) for
|
||||
`src/**/*.test.{ts,tsx}` and `worker` (Node) for `worker/**/*.test.ts`.
|
||||
- `npm run test:watch` re-runs on change. `npm run test:coverage` adds V8
|
||||
coverage in `coverage/` (CI feeds `lcov.info` to SonarQube Cloud).
|
||||
- Tests live in `__tests__/` folders next to the code they cover. Add a
|
||||
regression test with a bug fix where you can.
|
||||
|
||||
## Cloudflare Worker (web build)
|
||||
|
||||
The website is served by a Cloudflare Worker configured in
|
||||
[`wrangler.jsonc`](wrangler.jsonc). Only `/api/*` runs Worker code;
|
||||
everything else is static files from `dist/`. The code lives in
|
||||
[`worker/`](worker/):
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `worker/index.ts` | Router. The entry module must only have a **default export**: workerd treats named exports as entrypoints. |
|
||||
| `worker/verify.ts` | `POST /api/turnstile/verify`: same-origin check, JSON only, body size cap, rate limit |
|
||||
| `worker/turnstile.ts` | Cloudflare siteverify call: timeout, one retry, hostname / action / age checks |
|
||||
| `worker/http.ts` | JSON responses with strict headers, structured logs |
|
||||
|
||||
Worker logs must never contain IP addresses, tokens or user content.
|
||||
|
||||
To run it locally:
|
||||
|
||||
```bash
|
||||
cp .dev.vars.example .dev.vars # Cloudflare's always-pass Turnstile test secret
|
||||
npm run preview:cf # wrangler dev on http://localhost:8787 (builds first)
|
||||
```
|
||||
|
||||
`wrangler.jsonc` runs `npm run build` before every `wrangler dev`, deploy and
|
||||
dry run, so `preview:cf` always serves a fresh build.
|
||||
|
||||
- `.dev.vars` is gitignored. Never commit real secrets; production secrets
|
||||
live in the Cloudflare dashboard.
|
||||
- `npm run cf:types` regenerates the gitignored `worker-configuration.d.ts`
|
||||
after you change bindings in `wrangler.jsonc` (`npm run typecheck` does
|
||||
this too).
|
||||
- The Turnstile human check is off in `npm run dev` unless you set
|
||||
`VITE_TURNSTILE_DEV=1`. On localhost the app uses Cloudflare's test
|
||||
sitekey.
|
||||
- Nobody deploys by hand: Cloudflare Workers Builds deploys every push to
|
||||
`main`. `npm run cf:check` is the deploy dry run CI uses. Hosting, secrets,
|
||||
rollback and releases are described in [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md).
|
||||
|
||||
## Ways to contribute
|
||||
|
||||
### 🐛 Bug reports
|
||||
### Bug reports
|
||||
|
||||
Use the [Bug Report](https://github.com/poli0981/jsonPrism/issues/new?template=bug_report.md) template. Include:
|
||||
|
||||
- Browser + OS
|
||||
- Platform (Web / Windows / macOS / Linux / Android) and browser or OS version
|
||||
- JSONPrism version (*About → Build info*), or the output of *Copy diagnostics* on the same page
|
||||
- Steps to reproduce
|
||||
- Sample JSON that triggers the bug (minimal, please)
|
||||
- Sample JSON that triggers the bug (minimal, please, and nothing private)
|
||||
- Expected vs actual output
|
||||
|
||||
### 💡 Feature requests
|
||||
Security vulnerabilities never go in a public issue. See [SECURITY.md](SECURITY.md).
|
||||
|
||||
### Feature requests
|
||||
|
||||
Use the [Feature Request](https://github.com/poli0981/jsonPrism/issues/new?template=feature_request.md) template. We prioritize features that:
|
||||
|
||||
- Fit the "one JSON → many formats" core mission
|
||||
- Don't require server-side processing (we're client-only by design)
|
||||
- Run entirely on the user's device (conversion never touches a server)
|
||||
- Have a clear use case from a real workflow
|
||||
|
||||
### 🌍 Translations
|
||||
### Translations
|
||||
|
||||
Currently bundled: **English**, **Tiếng Việt**, **日本語**, **简体中文**.
|
||||
Non-English locales are AI-generated and not professionally reviewed —
|
||||
see [DISCLAIMER.md](DISCLAIMER.md). Native-speaker corrections are very
|
||||
welcome.
|
||||
Currently bundled: **English** (`en`), **Tiếng Việt** (`vi`), **日本語**
|
||||
(`ja`), **简体中文** (`zh-CN`). The Japanese and Simplified Chinese
|
||||
locales, and parts of the Vietnamese one, are AI-generated and not
|
||||
professionally reviewed; see [DISCLAIMER.md](DISCLAIMER.md).
|
||||
Native-speaker corrections are very welcome.
|
||||
|
||||
Every user-facing string goes through i18next, so a new or changed string
|
||||
means editing **all four** files in `src/i18n/locales/`. The parity test
|
||||
(`src/i18n/__tests__/locales.test.ts`, part of `npm test` and CI) fails
|
||||
when a locale is missing a key or has an extra one, changes a
|
||||
`{{variable}}`, or leaves a value empty. If you aren't confident in a
|
||||
translation, say so in the PR.
|
||||
|
||||
To add a new language:
|
||||
|
||||
1. Copy `src/i18n/locales/en.json` to `src/i18n/locales/<your-locale>.json`
|
||||
2. Translate every value
|
||||
3. Register in `src/i18n/index.ts`
|
||||
4. Add to the `supportedLngs` array
|
||||
5. Add the language to `LanguageSwitcher.tsx`
|
||||
1. Copy `src/i18n/locales/en.json` to `src/i18n/locales/<locale>.json` and translate every value (keep `{{variables}}` unchanged)
|
||||
2. Import it in `src/i18n/index.ts` and add it to `resources` and `SUPPORTED_LANGUAGES`
|
||||
3. Add it to `LANGUAGES` in `src/components/common/LanguageSwitcher.tsx`
|
||||
4. Add it to the `describe.each` list in `src/i18n/__tests__/locales.test.ts`
|
||||
5. If Cloudflare Turnstile supports the language, map it in `turnstileLanguage()` in `src/lib/turnstile.ts`
|
||||
6. Open a PR
|
||||
|
||||
### ➕ Adding a new converter
|
||||
### Adding a new converter
|
||||
|
||||
See the **"Adding a new converter — checklist"** section in [`CLAUDE.md`](CLAUDE.md).
|
||||
|
||||
Briefly:
|
||||
|
||||
1. New file `src/converters/myformat.ts` implementing `Converter<TOptions>`
|
||||
2. Register in `registry.ts` and `types.ts`
|
||||
3. Add i18n labels (EN + VI minimum)
|
||||
4. Update README format tables
|
||||
5. Mark roadmap entry done
|
||||
1. New file `src/converters/myformat.ts` implementing `Converter<TOptions>` (pure, errors as values)
|
||||
2. Add the ID to `FormatId` in `types.ts` and register the converter in `registry.ts`
|
||||
3. Add `formats.myformat` labels to all four locales
|
||||
4. Add tests in `src/converters/__tests__/` (`contract.test.ts` already runs every registered converter against the errors-as-values contract)
|
||||
5. New parsing library? Give it its own `p-*` entry in the `codeSplitting.groups` list in `vite.config.ts`
|
||||
6. Update the format tables in `README.md` and `README.vi.md`, the roadmap entry in `docs/ROADMAP.md`, and `CHANGELOG.md`
|
||||
|
||||
## Commit messages
|
||||
|
||||
@@ -87,11 +218,15 @@ We follow a relaxed version of [Conventional Commits](https://www.conventionalco
|
||||
```
|
||||
feat(converter): add TOML converter with smol-toml
|
||||
fix(csv): escape pipes in cell values
|
||||
perf(batch): convert large inputs in a Web Worker
|
||||
docs: clarify Tauri build steps
|
||||
chore(deps): bump react to 19.1
|
||||
build(deps): bump react to 19.3
|
||||
ci: pin actions to full commit SHAs
|
||||
```
|
||||
|
||||
Prefixes: `feat`, `fix`, `docs`, `refactor`, `test`, `chore`, `style`.
|
||||
Prefixes: `feat`, `fix`, `perf`, `refactor`, `docs`, `test`, `build`
|
||||
(dependencies, bundling, toolchain), `ci` (GitHub Actions workflows),
|
||||
`chore`, `style`.
|
||||
|
||||
## Auto-ignored contributions
|
||||
|
||||
@@ -108,11 +243,11 @@ closed without review:
|
||||
- **Behavior / language violating GitHub's policy** — harassment, hate
|
||||
speech, doxxing, NSFW content, etc.
|
||||
- **Off-topic preamble**, e.g. "Chào buổi sáng, hôm nay là 1 ngày trời
|
||||
đẹp…" or any greeting/filler that doesn't immediately address the
|
||||
issue. Get to the point: what's wrong, what's the expected behavior,
|
||||
what reproduces it.
|
||||
- **PRs without a meaningful description** or test plan. See the PR
|
||||
template — sections marked required are required.
|
||||
đẹp…" ("Good morning, what a lovely day…") or any greeting/filler that
|
||||
doesn't immediately address the issue. Get to the point: what's wrong,
|
||||
what's the expected behavior, what reproduces it.
|
||||
- **PRs without a meaningful description** or test plan. The Summary and
|
||||
Test plan sections of the PR template are required.
|
||||
|
||||
These rules exist because this is a one-person + AI-assisted project
|
||||
(see [DISCLAIMER.md](DISCLAIMER.md)); time spent triaging low-effort
|
||||
@@ -124,7 +259,9 @@ This project adopts the [Contributor Covenant v2.1](CODE_OF_CONDUCT.md).
|
||||
Be kind. Assume good faith. Disagreements about technical choices are
|
||||
fine; personal attacks and harassment are not.
|
||||
|
||||
Reports to the maintainer via the [private Security Advisory flow](https://github.com/poli0981/jsonPrism/security/advisories/new) for sensitive matters, or a private GitHub Discussion otherwise.
|
||||
Report conduct concerns to the maintainer at **code@poli0981.dev**.
|
||||
Security vulnerabilities are not conduct reports: follow
|
||||
[SECURITY.md](SECURITY.md) (private advisory or security@poli0981.dev).
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+41
-32
@@ -1,62 +1,71 @@
|
||||
# Disclaimer
|
||||
|
||||
**Last updated**: 2026-05-13
|
||||
**Last updated**: 2026-10-22
|
||||
|
||||
## Project status
|
||||
|
||||
JSONPrism is a **one-person open-source project** maintained by
|
||||
[@poli0981](https://github.com/poli0981) (Kokone), written with substantial
|
||||
AI assistance. It is published under the Apache 2.0 License and the source
|
||||
is available on GitHub.
|
||||
JSONPrism is a **one-person open-source project** maintained by poli0981
|
||||
(Kokone, [@poli0981](https://github.com/poli0981)), written with
|
||||
substantial AI assistance. It is published under the Apache 2.0 License
|
||||
and the source is available on GitHub.
|
||||
|
||||
It is **not** a commercial product. There is no SLA, no support contract,
|
||||
It is **not** a commercial product. There is no SLA, no support contract
|
||||
and no warranty. See the `LICENSE` file for the exact legal text — the
|
||||
Apache 2.0 disclaimer-of-warranty clause applies in full.
|
||||
|
||||
## Quality expectations
|
||||
|
||||
- The maintainer aims for production-grade quality but does not guarantee
|
||||
bug-free behavior, performance, or correctness for any particular input.
|
||||
bug-free behaviour, performance or correctness for any particular input.
|
||||
- Each conversion is implemented to a reasonable interpretation of the
|
||||
target spec, but edge cases (especially around lossy formats like XML
|
||||
and Markdown) may differ from other tools you've used.
|
||||
- If you rely on JSONPrism for a critical workflow, please verify the
|
||||
output yourself.
|
||||
target format, but edge cases (especially in lossy formats such as XML,
|
||||
CSV and Markdown) may differ from other tools you have used.
|
||||
- If you rely on JSONPrism for a critical workflow, verify the output
|
||||
yourself.
|
||||
|
||||
## AI-assisted code & translations
|
||||
## AI-assisted code and translations
|
||||
|
||||
This project openly uses AI tools during development:
|
||||
|
||||
- **Claude Chat** + **Claude Code (Opus 4.7, 1M context)** — used for
|
||||
drafting code, refactoring, writing tests, generating translations,
|
||||
and reviewing PRs.
|
||||
- All AI-generated code is reviewed by the maintainer before being
|
||||
merged. Errors that slip through are bugs — please report them via
|
||||
- **Claude Chat** and **Claude Code** — Claude Opus 4.7 and 4.8 for the 1.x
|
||||
releases, Claude Opus 5.5 for 2.0 — used for drafting code,
|
||||
refactoring, writing tests and documentation, generating translations
|
||||
and reviewing changes.
|
||||
- All AI-generated code is reviewed by the maintainer before it is merged.
|
||||
Errors that slip through are bugs — please report them via
|
||||
[GitHub Issues](https://github.com/poli0981/jsonPrism/issues).
|
||||
|
||||
### Translations
|
||||
|
||||
Non-English locales (currently Vietnamese, Japanese, Simplified Chinese)
|
||||
are produced primarily by AI translation. They are **not professionally
|
||||
reviewed**. Subtle wording, technical jargon, or idiomatic phrasings may
|
||||
be inaccurate.
|
||||
Non-English locales (Vietnamese, Japanese, Simplified Chinese) are
|
||||
produced primarily by AI translation. They are **not professionally
|
||||
reviewed**, so wording, technical terms or idioms may be inaccurate.
|
||||
|
||||
If you are a native speaker and spot a translation issue, a PR or a
|
||||
Discussion post is very welcome. See the `disclaimer.translation` i18n
|
||||
key — it surfaces this disclaimer to users at runtime.
|
||||
If you are a native speaker and spot a translation issue, a pull request
|
||||
or a Discussion post is very welcome.
|
||||
|
||||
## Third-party services
|
||||
|
||||
The website relies on Cloudflare for hosting, the Turnstile human check
|
||||
and cookieless Web Analytics (see [PRIVACY.md](PRIVACY.md)). Their
|
||||
availability is outside the maintainer's control: if Cloudflare cannot
|
||||
be reached, the website lets you continue after a warning, because
|
||||
conversion itself never needs the network. The desktop and Android apps
|
||||
do not depend on these services.
|
||||
|
||||
## What this means in practice
|
||||
|
||||
- Do not feed JSONPrism sensitive data and then ship the output to
|
||||
production without checking it.
|
||||
- Do not assume that round-tripping JSON → format → JSON is byte-perfect
|
||||
for lossy formats (XML, SQL, Markdown — the app marks these by not
|
||||
exposing a reverse converter).
|
||||
- Pin a specific JSONPrism version if you depend on its behavior; future
|
||||
- Do not feed JSONPrism sensitive data and ship the output to production
|
||||
without checking it.
|
||||
- Do not assume that a round trip JSON → format → JSON is byte-perfect for
|
||||
lossy formats. Only JSONL, CSV, TSV, YAML, TOML and RESX convert back
|
||||
to JSON at all.
|
||||
- Pin a specific JSONPrism version if you depend on its behaviour; future
|
||||
releases may change defaults.
|
||||
|
||||
## Reporting concerns
|
||||
|
||||
- Bugs: [GitHub Issues](https://github.com/poli0981/jsonPrism/issues)
|
||||
- Security: [Private Security Advisory](https://github.com/poli0981/jsonPrism/security/advisories/new)
|
||||
- Translation accuracy: GitHub Discussions
|
||||
- Security: [SECURITY.md](SECURITY.md)
|
||||
- Translation accuracy: [GitHub Discussions](https://github.com/poli0981/jsonPrism/discussions)
|
||||
- Legal: legal@poli0981.dev
|
||||
+24
-5
@@ -1,18 +1,36 @@
|
||||
# Maintainers
|
||||
|
||||
| Name | GitHub | Scope |
|
||||
|---|---|---|
|
||||
| Kokone | [@poli0981](https://github.com/poli0981) | Solo maintainer — code review, releases, translations review, community |
|
||||
| Name | GitHub | Contact | Scope |
|
||||
|---|---|---|---|
|
||||
| Kokone | [@poli0981](https://github.com/poli0981) | [code@poli0981.dev](mailto:code@poli0981.dev) | Solo maintainer — code review, releases, translations review, community |
|
||||
|
||||
JSONPrism is co-authored with AI tooling — see [DISCLAIMER.md](DISCLAIMER.md)
|
||||
for details. The maintainer is the single point of human review for every
|
||||
merged PR.
|
||||
|
||||
## Responsibilities
|
||||
|
||||
- **Code review** — reviews and merges every PR, including AI-assisted
|
||||
changes and the weekly grouped Dependabot updates, and doesn't merge on
|
||||
red CI.
|
||||
- **Releases** — tags `v*` releases; `release.yml` builds the Windows,
|
||||
macOS, Linux and Android packages into a draft GitHub Release with
|
||||
`SHA256SUMS.txt` and build-provenance attestations, which the maintainer
|
||||
reviews and publishes. The website deploys itself from `main` through
|
||||
Cloudflare Workers Builds.
|
||||
- **Translations review** — the AI-generated Japanese and Simplified
|
||||
Chinese strings and the partly AI-generated Vietnamese ones.
|
||||
- **Community** — issues, Discussions and the Discord server, and
|
||||
enforcement of the [Code of Conduct](CODE_OF_CONDUCT.md). Vulnerability
|
||||
reports are triaged as described in [SECURITY.md](SECURITY.md).
|
||||
|
||||
## Contact
|
||||
|
||||
- Bug reports & feature requests: [GitHub Issues](https://github.com/poli0981/jsonPrism/issues)
|
||||
- Discussion / Q&A: [GitHub Discussions](https://github.com/poli0981/jsonPrism/discussions)
|
||||
- Security: [Private Security Advisory](https://github.com/poli0981/jsonPrism/security/advisories/new)
|
||||
- Community chat: [Discord](https://discord.gg/2aNR3aVt)
|
||||
- Project, maintainer & Code of Conduct: [code@poli0981.dev](mailto:code@poli0981.dev)
|
||||
- Security: [Private Security Advisory](https://github.com/poli0981/jsonPrism/security/advisories/new) or [security@poli0981.dev](mailto:security@poli0981.dev) — never a public issue
|
||||
|
||||
## Becoming a maintainer
|
||||
|
||||
@@ -20,7 +38,8 @@ JSONPrism is small-by-design. Additional maintainers may be added when a
|
||||
contributor has demonstrated:
|
||||
|
||||
- Multiple high-quality merged PRs.
|
||||
- Familiarity with the conventions in [CLAUDE.md](CLAUDE.md).
|
||||
- Familiarity with the conventions in [CLAUDE.md](CLAUDE.md) and
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
- Willingness to review others' PRs and respond to issues.
|
||||
|
||||
Until then, the project runs as a single-maintainer indie project.
|
||||
+154
-48
@@ -1,72 +1,178 @@
|
||||
# Privacy policy
|
||||
# Privacy Policy
|
||||
|
||||
**Last updated**: 2026-05-13
|
||||
**Version**: 2.0 · **Effective**: 2026-10-22 · Replaces the policy of 2026-05-13.
|
||||
|
||||
## Short version
|
||||
|
||||
**JSONPrism does not collect, transmit, or store your data on any server.**
|
||||
Everything happens in your browser (or inside the Tauri desktop bundle).
|
||||
There is no analytics, no telemetry, no tracking, no account system, no
|
||||
"cloud sync." This page exists to explain what *does* happen locally and
|
||||
why.
|
||||
- **Your data stays on your device.** JSON, files and output are converted
|
||||
in your browser or in the desktop/Android app. They are never uploaded,
|
||||
and JSONPrism has no account system, no cloud sync and no error reporting.
|
||||
- **The website** (<https://jsonprism.poli0981.dev>) is hosted on
|
||||
Cloudflare. It runs a quick Cloudflare Turnstile human check when you
|
||||
first open it (and again every 7 days), and it counts page views with
|
||||
Cloudflare Web Analytics, which uses no cookies. You can switch the
|
||||
analytics off under **Appearance**; it starts off if your browser sends
|
||||
[Global Privacy Control](https://globalprivacycontrol.org/).
|
||||
- **The desktop and Android apps** make no network requests of their own
|
||||
and use none of the Cloudflare services.
|
||||
|
||||
## What we run on
|
||||
## Who is responsible
|
||||
|
||||
| Surface | Hosting | What it can see |
|
||||
JSONPrism is an open-source project maintained by one person, poli0981
|
||||
(Kokone), who is the controller for the processing described here.
|
||||
Privacy questions and requests: **privacy@poli0981.dev**.
|
||||
|
||||
## What happens on each surface
|
||||
|
||||
| Surface | Hosting / runtime | What leaves your device |
|
||||
|---|---|---|
|
||||
| Web app | [GitHub Pages](https://pages.github.com/) (static hosting only) | Standard request logs at the GitHub layer — IP, user-agent, requested asset. JSONPrism has no server code with access to those. |
|
||||
| Desktop app | Tauri 2 bundle, runs locally | No network calls from app code. Only the OS file dialogs you trigger. |
|
||||
| Website | Cloudflare Workers (static files plus a small API for the human check) | Standard HTTP request data needed to deliver the site; the Turnstile check; anonymous page-view metrics if analytics is on. Never the data you convert. |
|
||||
| Windows, macOS, Linux app | Tauri 2, runs locally | Nothing from app code. Links you click open in your browser. |
|
||||
| Android app | Tauri 2 in the system WebView | Nothing from app code. Links you tap open in your browser. |
|
||||
|
||||
Neither surface phones home about how you use the app.
|
||||
### Hosting (website)
|
||||
|
||||
## What we store locally
|
||||
Cloudflare, Inc. serves the website and processes the data every web
|
||||
request carries (IP address, user agent, requested URL, time, TLS details)
|
||||
to deliver pages and protect the service against abuse. JSONPrism's own
|
||||
server code handles only the human-check API (`/api/turnstile/verify`)
|
||||
and a health check. For that API it records structured events — outcome,
|
||||
HTTP status, the Cloudflare data centre code, duration and Turnstile error
|
||||
codes — in Cloudflare Workers Logs, kept for 7 days. These events never
|
||||
contain IP addresses, Turnstile tokens or anything you convert. The API is
|
||||
rate limited per client by Cloudflare; the client key is not stored by
|
||||
JSONPrism.
|
||||
|
||||
The app uses `localStorage` to remember your preferences across reloads.
|
||||
These keys are written by JSONPrism:
|
||||
### Human check (website)
|
||||
|
||||
| Key | What it stores |
|
||||
[Cloudflare Turnstile](https://www.cloudflare.com/products/turnstile/)
|
||||
tells people and bots apart without puzzles. When the check runs, your
|
||||
browser loads Cloudflare's script from `challenges.cloudflare.com`, which
|
||||
collects signals such as your IP address, TLS fingerprint, user agent and
|
||||
the site key, as described in Cloudflare's
|
||||
[Turnstile Privacy Addendum](https://www.cloudflare.com/turnstile-privacy-policy/).
|
||||
JSONPrism's server then sends the resulting one-time token — not your IP
|
||||
address — to Cloudflare's verification API. If the check passes, your
|
||||
browser stores the expiry time (`jsonprism.humanCheck`) and is not asked
|
||||
again for 7 days.
|
||||
|
||||
### Web Analytics (website, optional)
|
||||
|
||||
[Cloudflare Web Analytics](https://www.cloudflare.com/web-analytics/)
|
||||
counts page views and measures load performance (page path, referrer,
|
||||
browser and device type, timing metrics). It sets no cookies, uses no
|
||||
local storage and, according to Cloudflare, does not collect or use
|
||||
visitors' personal data. JSONPrism loads it only on the production
|
||||
website, only after you have accepted the terms, and only while
|
||||
**Appearance → Anonymous usage analytics** is on. The setting starts off
|
||||
when your browser sends Global Privacy Control, and turning it off takes
|
||||
effect from your next visit.
|
||||
|
||||
### Desktop and Android apps
|
||||
|
||||
- No telemetry, no analytics, no Turnstile, no update checks.
|
||||
- Files reach the app only when you pick them in a system dialog or drop
|
||||
them onto the window. The app can read files you choose and write only
|
||||
where you choose to save; its static file access is limited to your
|
||||
Documents, Downloads and Desktop folders and never includes hidden
|
||||
files such as `~/.ssh`
|
||||
(see [`src-tauri/capabilities/default.json`](src-tauri/capabilities/default.json)).
|
||||
- The Android app declares the `INTERNET` permission because the Tauri
|
||||
WebView runtime requires it; JSONPrism's code makes no network requests.
|
||||
Android backups of the app's data are disabled.
|
||||
|
||||
## What is stored on your device
|
||||
|
||||
The app keeps these entries in your browser's (or the app WebView's)
|
||||
`localStorage`. They never leave your device.
|
||||
|
||||
| Key | Contents |
|
||||
|---|---|
|
||||
| `jsonprism.theme` | `light` / `dark` / `system` |
|
||||
| `jsonprism.lang` | UI language code (`en` / `vi` / `ja` / `zh-CN`) |
|
||||
| `jsonprism.selected_format` | The target format chip you last selected |
|
||||
| `jsonprism.direction` | Conversion direction (`forward` / `reverse`) |
|
||||
| `jsonprism.options.<format>` | Per-format options (e.g. CSV header on/off) |
|
||||
| `jsonprism.consent` | That you accepted the License / Terms / Privacy / Disclaimer (acceptance flag + version + timestamp). Web only — the desktop app gates this in its installer. |
|
||||
| `jsonprism.consent` | That you accepted the License, Terms, Privacy Policy and Disclaimer: flag, policy version, time |
|
||||
| `jsonprism.humanCheck` | Website only: when the passed human check expires |
|
||||
| `jsonprism.prefs` | Appearance preferences: hide scrollbars, anonymous analytics on/off |
|
||||
| `jsonprism.theme` | `light`, `dark` or `system` |
|
||||
| `jsonprism.lang` | Interface language (`en`, `vi`, `ja`, `zh-CN`) |
|
||||
| `jsonprism.selected_format` | The target format you last selected |
|
||||
| `jsonprism.direction` | Conversion direction |
|
||||
| `jsonprism.options.<format>` | Your options for each format |
|
||||
|
||||
That is the entire on-disk footprint. Clearing your browser's site data
|
||||
removes everything. Nothing leaves your device.
|
||||
`sessionStorage` briefly holds `jsonprism.preloadReload` (when the app
|
||||
last reloaded itself after a new release). Clearing the site's data, or
|
||||
uninstalling the app, removes all of it.
|
||||
|
||||
The app also keeps its most recent 200 log lines in memory, for
|
||||
**About → Copy diagnostics**. They are never sent anywhere; the button
|
||||
copies them to your clipboard, together with the version, commit and
|
||||
platform, so you can choose to paste them into a bug report.
|
||||
|
||||
## What JSONPrism never does
|
||||
|
||||
- No analytics SDK (no Google Analytics, no Plausible, no PostHog, etc.).
|
||||
- No remote error reporting (no Sentry, no Rollbar).
|
||||
- No CDN that proxies your content — assets are served directly from
|
||||
GitHub Pages.
|
||||
- No login or account.
|
||||
- No "cloud" backup, no clipboard upload, no diff-sharing.
|
||||
- Upload, store or inspect what you convert.
|
||||
- Use cookies, advertising or cross-site tracking.
|
||||
- Sell or share personal information.
|
||||
- Load fonts or scripts from third parties other than the two Cloudflare
|
||||
services above (fonts are bundled with the app).
|
||||
- Report errors to a remote service.
|
||||
|
||||
## Tauri desktop specifics
|
||||
## Legal bases (EU/EEA, UK)
|
||||
|
||||
- The Tauri bundle has filesystem access scoped to `$HOME`, `$DOCUMENT`,
|
||||
`$DOWNLOAD`, `$DESKTOP` only (see [`src-tauri/capabilities/default.json`](src-tauri/capabilities/default.json)).
|
||||
- Drag-and-drop files come from the OS — JSONPrism reads their contents
|
||||
in-process and never writes them anywhere unless you explicitly hit
|
||||
"Download .zip" or "Save".
|
||||
- The OS may write window-position / window-size metadata on shutdown
|
||||
(handled by Tauri, not by JSONPrism code).
|
||||
- Hosting, security, abuse prevention and the human check: legitimate
|
||||
interests in running a public website safely (GDPR Art. 6(1)(f)).
|
||||
- Anonymous page-view statistics: legitimate interest in understanding,
|
||||
in aggregate, how the website is used, with an easy opt-out and Global
|
||||
Privacy Control honoured (Art. 6(1)(f)).
|
||||
- Preferences stored on your device: strictly necessary to provide the
|
||||
features you use.
|
||||
|
||||
## Third-party fonts
|
||||
You may object to processing based on legitimate interests at any time by
|
||||
writing to privacy@poli0981.dev; for analytics, switching it off in
|
||||
Appearance is enough.
|
||||
|
||||
The web build loads three fonts from Google Fonts via `<link rel="preconnect">`:
|
||||
## International transfers
|
||||
|
||||
- Geist (body)
|
||||
- Instrument Serif (display)
|
||||
- JetBrains Mono (code)
|
||||
Cloudflare operates worldwide, so request data may be processed outside
|
||||
your country, including in the United States. Cloudflare is certified
|
||||
under the EU-U.S. Data Privacy Framework (and its UK and Swiss
|
||||
extensions) and its data processing addendum includes the EU Standard
|
||||
Contractual Clauses. See [Cloudflare's privacy policy](https://www.cloudflare.com/privacypolicy/).
|
||||
|
||||
Google Fonts can see your IP when your browser fetches the font files.
|
||||
The Tauri build inlines these fonts and never makes the request.
|
||||
## Retention
|
||||
|
||||
## Questions
|
||||
- Data on your device: until you clear it; the human check expires after
|
||||
7 days, and acceptance is asked again whenever this policy's version
|
||||
changes.
|
||||
- Workers Logs for the human-check API: 7 days.
|
||||
- Request processing and analytics data held by Cloudflare: according to
|
||||
Cloudflare's own retention schedules; Web Analytics shows aggregated
|
||||
figures only.
|
||||
|
||||
Open a [GitHub Discussion](https://github.com/poli0981/jsonPrism/discussions) if anything here is unclear.
|
||||
For security-relevant reports, use the [private Security Advisory flow](https://github.com/poli0981/jsonPrism/security/advisories/new).
|
||||
## Your rights
|
||||
|
||||
Depending on where you live (for example under the GDPR, UK GDPR or the
|
||||
California CCPA/CPRA) you may have the right to access, correct, delete,
|
||||
restrict or object to the processing of personal data about you, to data
|
||||
portability, and to lodge a complaint with your data protection
|
||||
authority. JSONPrism itself holds no personal data about you beyond what
|
||||
Cloudflare processes on its behalf, so most requests are best served by
|
||||
clearing the site's data; for anything else write to
|
||||
privacy@poli0981.dev and you will get an answer within 30 days. JSONPrism
|
||||
does not sell or share personal information and honours Global Privacy
|
||||
Control.
|
||||
|
||||
## Children
|
||||
|
||||
JSONPrism is a developer tool and is not directed at children under 13
|
||||
(or under the age of digital consent where you live).
|
||||
|
||||
## Changes to this policy
|
||||
|
||||
Changes are listed in [CHANGELOG.md](CHANGELOG.md). When this policy
|
||||
changes materially its version number increases, and the app asks you to
|
||||
accept it again before you continue.
|
||||
|
||||
## Contact
|
||||
|
||||
- Privacy: privacy@poli0981.dev
|
||||
- Security vulnerabilities: see [SECURITY.md](SECURITY.md)
|
||||
- Everything else: [GitHub Issues](https://github.com/poli0981/jsonPrism/issues)
|
||||
@@ -4,19 +4,19 @@
|
||||
|
||||
**Disperse JSON into many formats.**
|
||||
|
||||
One JSON input. Multi-target formats. Fully in your browser.
|
||||
One JSON input. Multi-target formats. Fully on your device.
|
||||
|
||||
[](https://github.com/poli0981/jsonPrism/actions/workflows/ci.yml)
|
||||
[](https://github.com/poli0981/jsonPrism/actions/workflows/deploy.yml)
|
||||
[](https://sonarcloud.io/summary/new_code?id=poli0981_jsonPrism)
|
||||
[](LICENSE)
|
||||
|
||||
[Live demo](https://poli0981.github.io/jsonPrism/) · [Tiếng Việt](README.vi.md) · [Roadmap](docs/ROADMAP.md)
|
||||
[Web app](https://jsonprism.poli0981.dev) · [Downloads](https://github.com/poli0981/jsonPrism/releases/latest) · [Tiếng Việt](README.vi.md) · [Roadmap](docs/ROADMAP.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
JSONPrism is a refracting tool for developers. It takes a single JSON input and disperses it into many target formats — like white light through a prism. **Everything runs client-side**, so your data never leaves your device.
|
||||
JSONPrism is a refracting tool for developers. It takes a single JSON input and disperses it into many target formats — like white light through a prism. **Conversion runs entirely on your device** — in the browser, the desktop app or the Android app — so your data never leaves it.
|
||||
|
||||
## Target formats
|
||||
|
||||
@@ -35,41 +35,119 @@ JSONPrism is a refracting tool for developers. It takes a single JSON input and
|
||||
| CBOR | `.cbor` | ✅ Phase 4 | — |
|
||||
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
|
||||
|
||||
Twelve formats. Six of them — JSONL, CSV, TSV, YAML, TOML and RESX — also convert back to JSON; in that direction `.ndjson`, `.tab` and `.yml` files are accepted too. SQL `INSERT` speaks standard SQL, PostgreSQL, MySQL, SQLite and MSSQL. BSON, CBOR and MessagePack are binary: the output panel shows them as base64 or hex text, and downloads are real binary files.
|
||||
|
||||
## Features
|
||||
|
||||
- **Client-side only** — no server, no telemetry, no upload. Your JSON stays in your browser.
|
||||
- **On-device conversion** — no upload, no conversion server. What you paste, type or open stays on your device; see [Privacy](#privacy) for the few services the website itself uses.
|
||||
- **Fast first paint** — routes and the CodeMirror editor are lazy-loaded, and vendor/parser code is split into small per-feature chunks, so the browser only downloads what you actually use.
|
||||
- **Batch processing** — up to 500 files at once (Phase 2).
|
||||
- **Smooth with large inputs** — inputs over 256 KB and every batch run convert in a Web Worker, so typing and scrolling stay responsive.
|
||||
- **Batch processing** — up to 500 files at once, downloaded as a single `.zip` (binary formats as real binary files).
|
||||
- **Smart shape detection** — recognizes flat objects, arrays of objects, scalars; suggests the best target format.
|
||||
- **Per-format options** — pretty-print, indentation, dialect (for SQL), alignment (for Markdown), and more.
|
||||
- **Dark + light themes** — Prism Spectrum palette with violet / cyan / amber / rose accents.
|
||||
- **Light, dark or system theme** — Prism Spectrum palette with violet / cyan / amber / rose accents on a technical, blueprint-grid look. The Appearance menu can also hide scrollbars.
|
||||
- **Responsive — designed for viewports ≥ 360 × 640.** Smaller screens still work but may feel cramped; on mobile, Input and Output use a Tabs UI to give each panel full height. See [`docs/tested-viewports.md`](docs/tested-viewports.md) for the full device test matrix.
|
||||
- **EN + VI** — bilingual interface out of the box. More languages welcome.
|
||||
- **Tauri desktop build** — drag-and-drop file workflow, offline-first (Phase 2 milestone).
|
||||
- **4 UI languages** — English, Tiếng Việt, 日本語 and 简体中文. The Japanese and Chinese translations are AI-generated; fixes from native speakers are welcome.
|
||||
- **Desktop and Android apps** — Tauri 2 builds for Windows, macOS, Linux and Android with native file dialogs and drag-and-drop. They work fully offline.
|
||||
|
||||
## Privacy
|
||||
|
||||
- **Your data stays on your device.** Every build converts locally; nothing you paste, type or open is uploaded. Settings and workspace state live in `localStorage` and are never sent anywhere.
|
||||
- **The website** ([jsonprism.poli0981.dev](https://jsonprism.poli0981.dev)) **adds three Cloudflare services**, none of which sees what you convert:
|
||||
- **Hosting** — Cloudflare serves the site and, like any host, processes request logs (IP address, user agent) for delivery and security.
|
||||
- **Turnstile** — a quick human check, about once a week (a passed check is remembered for 7 days). If Cloudflare can't be reached you can continue after a warning, because conversion never needs the network.
|
||||
- **Web Analytics** — cookieless, anonymous page-view counts, loaded only after you accept the Terms and Privacy Policy. Turn it off under **Appearance → Anonymous usage analytics**; it is off by default when your browser sends Global Privacy Control.
|
||||
- **The desktop and Android apps use none of these** — no analytics, no human check, no network requests except links you open yourself.
|
||||
|
||||
Details: [`PRIVACY.md`](PRIVACY.md).
|
||||
|
||||
## Tech stack
|
||||
|
||||
- **Vite 8** + **React 19** + **TypeScript 5.7**
|
||||
- **Vite 8** + **React 19.3** + **TypeScript 7** (native compiler; the `typescript` dependency is a TS 6 alias kept only for typescript-eslint)
|
||||
- **Tailwind CSS v4** + **shadcn/ui** (New York style, neutral base)
|
||||
- **CodeMirror 6** for the input editor (Phase 1 polish)
|
||||
- **PapaParse**, **js-yaml**, **smol-toml**, **fast-xml-parser** for parsing/serialization
|
||||
- **i18next** for translations, **Zustand** for state, **Sonner** for toasts
|
||||
- **Tauri 2** wrapper (Phase 2)
|
||||
- **CodeMirror 6** for the input editor and the read-only output view
|
||||
- **PapaParse**, **js-yaml**, **smol-toml**, **fast-xml-parser**, **bson**, **cbor-x**, **@msgpack/msgpack** for parsing/serialization; **fflate** for batch `.zip` files
|
||||
- **i18next** for translations, **Zustand** for state, **React Router 8** for routing, **Sonner** for toasts
|
||||
- **Vitest** + Testing Library for tests
|
||||
- **Node.js 26** for the toolchain
|
||||
- **Cloudflare Workers** hosts the web app (static assets plus a small Worker for `/api/*`)
|
||||
- **Tauri 2.12** for the desktop (Windows, macOS, Linux) and Android apps
|
||||
|
||||
## Quick start
|
||||
|
||||
**Requirements**: Node.js **22 LTS** or newer.
|
||||
**Requirements**: Node.js **26** (pinned in `.nvmrc`).
|
||||
|
||||
```bash
|
||||
git clone https://github.com/poli0981/jsonPrism.git
|
||||
cd jsonprism
|
||||
cd jsonPrism
|
||||
nvm use # picks Node 26 from .nvmrc
|
||||
npm install
|
||||
npm run dev # http://localhost:5173
|
||||
```
|
||||
|
||||
The Turnstile human check is off in `npm run dev` (set `VITE_TURNSTILE_DEV=1` to try it). To run the production build the way Cloudflare serves it — static assets plus the Worker:
|
||||
|
||||
```bash
|
||||
cp .dev.vars.example .dev.vars # Cloudflare's always-pass Turnstile test secret
|
||||
npm run preview:cf # build + wrangler dev on http://localhost:8787
|
||||
```
|
||||
|
||||
### Scripts
|
||||
|
||||
| Script | What it does |
|
||||
| --- | --- |
|
||||
| `npm run dev` | Start Vite dev server with HMR |
|
||||
| `npm run build` | Type-check, then build for production into `dist/` |
|
||||
| `npm run preview` | Preview the built site locally (Vite) |
|
||||
| `npm run lint` | Run ESLint |
|
||||
| `npm run lint:fix` | Run ESLint with autofix |
|
||||
| `npm run typecheck` | Type-check the app, tests, config files and Worker (TypeScript 7), no emit |
|
||||
| `npm run knip` | Find unused files, exports and dependencies |
|
||||
| `npm run format` | Format with Prettier |
|
||||
| `npm run format:check` | Check formatting (CI uses this) |
|
||||
| `npm test` | Run the Vitest suite once |
|
||||
| `npm run test:watch` | Run Vitest in watch mode |
|
||||
| `npm run test:coverage` | Run the tests with a coverage report (CI uses this) |
|
||||
| `npm run cf:types` | Regenerate the Worker's binding types |
|
||||
| `npm run cf:check` | Dry-run the Cloudflare deploy (`wrangler deploy --dry-run`; CI runs it too) |
|
||||
| `npm run preview:cf` | Serve a fresh build and the Worker with `wrangler dev` on http://localhost:8787 |
|
||||
| `npm run tauri:dev` | Desktop app in dev mode (Vite + Tauri window with hot reload) |
|
||||
| `npm run tauri:build` | Native desktop bundles for the current OS |
|
||||
| `npm run tauri:icon` | Render `src-tauri/icons/icon.svg` into every icon size |
|
||||
| `npm run tauri:android:dev` | Android app on a device or emulator |
|
||||
| `npm run tauri:android:build` | Universal Android APK |
|
||||
|
||||
### shadcn/ui components
|
||||
|
||||
The `components.json` is preconfigured. Add components on demand:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add button input textarea tabs select card dialog sheet \
|
||||
dropdown-menu switch badge progress tooltip sonner resizable
|
||||
```
|
||||
|
||||
## Desktop app (Tauri 2)
|
||||
|
||||
JSONPrism also ships as a native desktop app via Tauri 2. The app uses the same React UI, with native OS dialogs and drag-drop hooked into the existing batch flow.
|
||||
JSONPrism also ships as a native desktop app via Tauri 2. The app uses the same React UI, with native OS dialogs and drag-drop hooked into the existing batch flow. It works fully offline: no analytics, no human check, and no network requests except links you open yourself.
|
||||
|
||||
### Download (users)
|
||||
|
||||
Get the bundle for your OS from the [latest release](https://github.com/poli0981/jsonPrism/releases/latest):
|
||||
|
||||
| OS | Files | Requirement |
|
||||
| --- | --- | --- |
|
||||
| **Windows** | `.msi` or NSIS `-setup.exe` | WebView2 runtime (preinstalled on Windows 11) |
|
||||
| **macOS** | universal `.dmg` (Apple Silicon + Intel) | macOS **12** or newer |
|
||||
| **Linux** | `.deb`, `.rpm` or `.AppImage` | Built on Ubuntu 22.04 — needs Ubuntu 22.04 or a similarly recent distro |
|
||||
|
||||
The desktop bundles aren't code-signed yet, so Windows SmartScreen or macOS Gatekeeper may warn the first time you open them. Releases from v2.0.0 on also carry `SHA256SUMS.txt` and GitHub build-provenance attestations, so you can check a download before running it:
|
||||
|
||||
```bash
|
||||
sha256sum -c SHA256SUMS.txt --ignore-missing
|
||||
gh attestation verify <file> --repo poli0981/jsonPrism
|
||||
```
|
||||
|
||||
### Build (developers)
|
||||
|
||||
**Additional requirements**:
|
||||
|
||||
@@ -77,7 +155,7 @@ JSONPrism also ships as a native desktop app via Tauri 2. The app uses the same
|
||||
- **Platform build deps**:
|
||||
- **Windows**: Visual Studio Build Tools (C++ workload) + WebView2 (preinstalled on Windows 11)
|
||||
- **macOS**: Xcode Command Line Tools (`xcode-select --install`)
|
||||
- **Linux**: `libwebkit2gtk-4.1-dev`, `libappindicator3-dev`, `librsvg2-dev`, `patchelf`, `libssl-dev`
|
||||
- **Linux**: `libwebkit2gtk-4.1-dev`, `libappindicator3-dev`, `librsvg2-dev`, `patchelf`, `libssl-dev`, `libgtk-3-dev`
|
||||
|
||||
**Generate icons once** (uses Tauri's CLI to render the SVG to PNG/ICO/ICNS):
|
||||
|
||||
@@ -101,9 +179,9 @@ Output:
|
||||
|
||||
- Windows → `src-tauri/target/release/bundle/msi/*.msi` + `nsis/*-setup.exe`
|
||||
- macOS → `src-tauri/target/release/bundle/dmg/*.dmg` + `macos/*.app`
|
||||
- Linux → `src-tauri/target/release/bundle/appimage/*.AppImage` + `deb/*.deb`
|
||||
- Linux → `src-tauri/target/release/bundle/appimage/*.AppImage` + `deb/*.deb` + `rpm/*.rpm`
|
||||
|
||||
**Automated releases**: pushing a `v*` tag triggers `.github/workflows/release.yml`, which builds for all platforms in parallel and creates a draft GitHub release.
|
||||
**Automated releases**: pushing a `v*` tag runs `.github/workflows/release.yml`. It checks that the tag matches the version in `package.json` and `src-tauri/Cargo.toml`, runs the tests, builds the Windows, macOS (universal) and Linux bundles plus the Android APK into **one** draft GitHub release, then adds `SHA256SUMS.txt` and build-provenance attestations. The maintainer publishes the draft.
|
||||
|
||||
## Android app (Tauri 2)
|
||||
|
||||
@@ -117,14 +195,15 @@ JSONPrism also ships as an Android app you sideload from a `.apk`. Same React UI
|
||||
| **System WebView** | **Chromium 111+** (Android System WebView / Chrome). Kept current by the Play Store on most devices; a much older WebView renders the layout incorrectly — update "Android System WebView" and Chrome from the Play Store if the UI looks broken. |
|
||||
| **CPU / ABI** | arm64-v8a, armeabi-v7a, x86, or x86_64 — the single universal APK runs on all of them (modern phones are arm64-v8a) |
|
||||
| **RAM** | 2 GB minimum; 4 GB recommended for large or batch (up to 500 files) conversions |
|
||||
| **Storage** | ~27 MB to download; ~100 MB free recommended (install + temporary working files) |
|
||||
| **Storage** | ~100 MB free recommended (install + temporary working files) |
|
||||
| **Network** | None — the app runs fully offline and sends nothing off the device |
|
||||
|
||||
### Install (users)
|
||||
|
||||
1. Download `JSONPrism-<version>-android-universal.apk` from the [Releases](https://github.com/poli0981/jsonPrism/releases) page.
|
||||
2. Open it; Android will ask you to allow "install unknown apps" for your browser/file manager — enable it, then install.
|
||||
3. Needs Android 12+. The app runs fully offline.
|
||||
1. Download `JSONPrism_<version>_android-universal.apk` from the [latest release](https://github.com/poli0981/jsonPrism/releases/latest).
|
||||
2. Optionally check it against `SHA256SUMS.txt` or with `gh attestation verify` (see [Download (users)](#download-users)).
|
||||
3. Open it; Android will ask you to allow "install unknown apps" for your browser/file manager — enable it, then install.
|
||||
4. Needs Android 12+. The app runs fully offline.
|
||||
|
||||
### Build (developers)
|
||||
|
||||
@@ -151,29 +230,7 @@ npm run tauri:android:build
|
||||
|
||||
Output: `src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk`. Release signing is read from `src-tauri/gen/android/keystore.properties` (gitignored); without it the APK builds unsigned. See [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md) for keystore setup and the CI signing secrets.
|
||||
|
||||
**Automated releases**: the same `v*` tag also runs the `android` job in `release.yml`, which signs the APK with the keystore from repository secrets and attaches it to the draft release.
|
||||
|
||||
### Scripts
|
||||
|
||||
| Script | What it does |
|
||||
| --------------------- | --------------------------------------------- |
|
||||
| `npm run dev` | Start Vite dev server with HMR |
|
||||
| `npm run build` | Production build to `dist/` |
|
||||
| `npm run preview` | Preview the built site locally |
|
||||
| `npm run lint` | Run ESLint |
|
||||
| `npm run lint:fix` | Run ESLint with autofix |
|
||||
| `npm run typecheck` | TypeScript type-check, no emit |
|
||||
| `npm run format` | Format with Prettier |
|
||||
| `npm run format:check`| Check formatting (CI uses this) |
|
||||
|
||||
### shadcn/ui components
|
||||
|
||||
The `components.json` is preconfigured. Add components on demand:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add button input textarea tabs select card dialog sheet \
|
||||
dropdown-menu switch badge progress tooltip sonner resizable
|
||||
```
|
||||
**Automated releases**: the same `v*` tag also runs the `android` job in `release.yml`, which signs the APK with the keystore from repository secrets and attaches it to the draft release as `JSONPrism_<version>_android-universal.apk`.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -182,30 +239,34 @@ src/
|
||||
├── app/ # Router + global providers
|
||||
├── components/
|
||||
│ ├── ui/ # shadcn components (added on demand)
|
||||
│ ├── layout/ # Header, Footer, ThemeToggle
|
||||
│ ├── converter/ # Workspace, panels, format picker
|
||||
│ └── common/ # ErrorBoundary, LanguageSwitcher
|
||||
│ ├── layout/ # Header, Footer, AppearanceMenu
|
||||
│ ├── converter/ # Workspace, panels, format picker, batch
|
||||
│ └── common/ # ConsentGate, HumanCheck, error boundaries, LanguageSwitcher
|
||||
├── converters/ # One module per target format
|
||||
│ ├── types.ts # Converter interface
|
||||
│ ├── registry.ts # Lookup table
|
||||
│ └── *.ts # Per-format implementations
|
||||
├── hooks/ # Custom hooks
|
||||
├── i18n/ # Translations (en, vi)
|
||||
├── lib/ # detect, theme, utils, sample
|
||||
├── pages/ # Home, About
|
||||
├── i18n/ # Translations (en, vi, ja, zh-CN)
|
||||
├── lib/ # detect, conversion + Web Worker, batch, theme, logger, utils
|
||||
├── pages/ # Home, About, error pages
|
||||
├── stores/ # Zustand stores (workspace, batch, consent, preferences)
|
||||
├── styles/ # globals.css (Tailwind + theme tokens)
|
||||
└── main.tsx
|
||||
```
|
||||
|
||||
Outside `src/`: `worker/` is the Cloudflare Worker (`/api/health` and `/api/turnstile/verify`, configured in `wrangler.jsonc`), and `src-tauri/` is the Tauri 2 shell for the desktop and Android apps.
|
||||
|
||||
### Adding a new format
|
||||
|
||||
Each format is a self-contained module implementing the `Converter` interface:
|
||||
|
||||
```ts
|
||||
import type { Converter } from './types';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
|
||||
interface MyFormatOptions {
|
||||
indent: 2 | 4;
|
||||
indent: number;
|
||||
}
|
||||
|
||||
export const myFormatConverter: Converter<MyFormatOptions> = {
|
||||
@@ -218,18 +279,23 @@ export const myFormatConverter: Converter<MyFormatOptions> = {
|
||||
ready: true,
|
||||
},
|
||||
defaultOptions: { indent: 2 },
|
||||
// Drives the auto-generated settings panel.
|
||||
optionSchema: [
|
||||
{ type: 'integer', key: 'indent', labelKey: 'options.myformat.indent', min: 0, max: 8 },
|
||||
],
|
||||
convert({ data }, options) {
|
||||
try {
|
||||
const output = serialize(data, options);
|
||||
return { ok: true, output };
|
||||
} catch (err) {
|
||||
return { ok: false, error: (err as Error).message };
|
||||
return { ok: false, error: errorMessage(err) };
|
||||
}
|
||||
},
|
||||
// Optional: reverse({ text }, options) parses the format back to JSON.
|
||||
};
|
||||
```
|
||||
|
||||
Then register it in `src/converters/registry.ts` and add label keys to `src/i18n/locales/*.json`.
|
||||
Then add the id to the `FormatId` union in `src/converters/types.ts`, register the converter in `src/converters/registry.ts` (`CONVERTERS` and `ALL_FORMATS`), and add its label keys to all four files in `src/i18n/locales/` — a parity test fails when a locale is missing a key.
|
||||
|
||||
See [`docs/ROADMAP.md`](docs/ROADMAP.md) for the full phase plan.
|
||||
|
||||
@@ -239,17 +305,31 @@ Pull requests welcome — please read [`CONTRIBUTING.md`](CONTRIBUTING.md) first
|
||||
|
||||
For bug reports and feature requests, use [GitHub Issues](https://github.com/poli0981/jsonPrism/issues). For security vulnerabilities, use the [private Security Advisory flow](https://github.com/poli0981/jsonPrism/security/advisories/new).
|
||||
|
||||
## Contact
|
||||
|
||||
| Address | For |
|
||||
| --- | --- |
|
||||
| [security@poli0981.dev](mailto:security@poli0981.dev) | Vulnerability reports (the [private Security Advisory flow](https://github.com/poli0981/jsonPrism/security/advisories/new) is preferred) |
|
||||
| [privacy@poli0981.dev](mailto:privacy@poli0981.dev) | Privacy requests |
|
||||
| [legal@poli0981.dev](mailto:legal@poli0981.dev) | Terms, licensing and other legal questions |
|
||||
| [copyright@poli0981.dev](mailto:copyright@poli0981.dev) | Copyright and takedown notices |
|
||||
| [code@poli0981.dev](mailto:code@poli0981.dev) | The project and its maintainer; Code of Conduct reports |
|
||||
| [sponsor@poli0981.dev](mailto:sponsor@poli0981.dev) | Sponsorship |
|
||||
|
||||
Bug reports and feature requests belong in [GitHub Issues](https://github.com/poli0981/jsonPrism/issues), not email.
|
||||
|
||||
## Project docs
|
||||
|
||||
| Doc | What's in it |
|
||||
|---|---|
|
||||
| [`PRIVACY.md`](PRIVACY.md) | Offline-first, localStorage-only, no telemetry. |
|
||||
| [`PRIVACY.md`](PRIVACY.md) | What stays on your device, and the web-only Cloudflare services (hosting, Turnstile, Web Analytics). |
|
||||
| [`TERMS.md`](TERMS.md) | ToS / EULA — acceptable use, license inheritance, user data ownership. |
|
||||
| [`SECURITY.md`](SECURITY.md) | How to report vulnerabilities; response SLAs. |
|
||||
| [`DISCLAIMER.md`](DISCLAIMER.md) | One-person + AI-assisted project; no warranty. |
|
||||
| [`THIRD-PARTY.md`](THIRD-PARTY.md) | Every dependency: version, license, link. |
|
||||
| [`MAINTAINERS.md`](MAINTAINERS.md) | Who's responsible for what. |
|
||||
| [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md) | Contributor Covenant v2.1. |
|
||||
| [`CHANGELOG.md`](CHANGELOG.md) | Release notes for every version. |
|
||||
| [`docs/ROADMAP.md`](docs/ROADMAP.md) | Phase plan, current status. |
|
||||
| [`docs/pc_spec.md`](docs/pc_spec.md) · [`docs/dev_env.md`](docs/dev_env.md) | Maintainer's hardware + toolchain. |
|
||||
| [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md) | Tauri build / process notes. |
|
||||
@@ -269,17 +349,21 @@ Hang out, ask questions, or follow updates:
|
||||
## Acknowledgements
|
||||
|
||||
Substantial parts of JSONPrism's code, tests, translations, and docs
|
||||
were drafted with **Claude Chat** and **Claude Code (Opus 4.7, 1M
|
||||
context)**. See [DISCLAIMER.md](DISCLAIMER.md) for the full AI-assist
|
||||
disclosure. Translation quality for non-English locales is best-effort
|
||||
and contributions from native speakers are welcomed.
|
||||
were drafted with AI assistance: **Claude Chat** and **Claude Code
|
||||
(Opus 4.7, 1M context)** for v1.x, and **Claude Code (Opus 5.5)** for
|
||||
v2.0.0. See [DISCLAIMER.md](DISCLAIMER.md) for the full AI-assist
|
||||
disclosure. The Japanese and Simplified Chinese translations, and parts
|
||||
of the Vietnamese one, are AI-generated and best-effort; contributions
|
||||
from native speakers are welcomed.
|
||||
|
||||
## Sponsorship
|
||||
|
||||
If JSONPrism is useful to you, consider sponsoring the maintainer via
|
||||
any of the channels in [`.github/FUNDING.yml`](.github/FUNDING.yml):
|
||||
GitHub Sponsors, Ko-fi, Buy Me a Coffee, Patreon, or PayPal.
|
||||
If JSONPrism is useful to you, consider sponsoring the maintainer,
|
||||
poli0981 (Kokone), via any of the channels in
|
||||
[`.github/FUNDING.yml`](.github/FUNDING.yml): GitHub Sponsors, Ko-fi,
|
||||
Buy Me a Coffee, Patreon, or PayPal. For sponsorship enquiries, email
|
||||
[sponsor@poli0981.dev](mailto:sponsor@poli0981.dev).
|
||||
|
||||
## License
|
||||
|
||||
[Apache License 2.0](LICENSE) — © 2026 Kokone ([@poli0981](https://github.com/poli0981)).
|
||||
[Apache License 2.0](LICENSE) — © 2026 [poli0981](https://github.com/poli0981) (Kokone).
|
||||
+149
-66
@@ -4,19 +4,19 @@
|
||||
|
||||
**Tán sắc JSON ra nhiều định dạng.**
|
||||
|
||||
Một JSON đầu vào. Đa định dạng đích. Chạy hoàn toàn trong trình duyệt.
|
||||
Một JSON đầu vào. Đa định dạng đích. Chạy hoàn toàn trên thiết bị của bạn.
|
||||
|
||||
[](https://github.com/poli0981/jsonPrism/actions/workflows/ci.yml)
|
||||
[](https://github.com/poli0981/jsonPrism/actions/workflows/deploy.yml)
|
||||
[](https://sonarcloud.io/summary/new_code?id=poli0981_jsonPrism)
|
||||
[](LICENSE)
|
||||
|
||||
[Bản demo](https://poli0981.github.io/jsonPrism/) · [English](README.md) · [Lộ trình](docs/ROADMAP.md)
|
||||
[Ứng dụng web](https://jsonprism.poli0981.dev) · [Tải về](https://github.com/poli0981/jsonPrism/releases/latest) · [English](README.md) · [Lộ trình](docs/ROADMAP.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
JSONPrism là công cụ "tán sắc" cho developer. Nhận một JSON đầu vào và phân tách ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính. **Mọi thứ chạy client-side**, dữ liệu của bạn không bao giờ rời khỏi máy.
|
||||
JSONPrism là công cụ "tán sắc" cho developer. Nhận một JSON đầu vào và phân tách ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính. **Việc chuyển đổi diễn ra hoàn toàn trên thiết bị của bạn** — trong trình duyệt, app desktop hay app Android — nên dữ liệu không bao giờ rời khỏi máy.
|
||||
|
||||
## Định dạng hỗ trợ
|
||||
|
||||
@@ -35,41 +35,119 @@ JSONPrism là công cụ "tán sắc" cho developer. Nhận một JSON đầu v
|
||||
| CBOR | `.cbor` | ✅ Phase 4 | — |
|
||||
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
|
||||
|
||||
Tổng cộng 12 định dạng. Sáu trong số đó — JSONL, CSV, TSV, YAML, TOML và RESX — còn chuyển ngược được về JSON; ở chiều này app cũng nhận file `.ndjson`, `.tab` và `.yml`. SQL `INSERT` hỗ trợ SQL chuẩn, PostgreSQL, MySQL, SQLite và MSSQL. BSON, CBOR và MessagePack là định dạng nhị phân: panel output hiển thị chúng dưới dạng text base64 hoặc hex, còn file tải về là binary thật.
|
||||
|
||||
## Tính năng
|
||||
|
||||
- **Chạy hoàn toàn client-side** — không server, không telemetry, không upload. JSON của bạn ở lại trong trình duyệt.
|
||||
- **Chuyển đổi ngay trên thiết bị** — không upload, không có server chuyển đổi. Những gì bạn dán, gõ hay mở đều ở lại trên máy; xem phần [Quyền riêng tư](#quyền-riêng-tư) để biết vài dịch vụ mà riêng website sử dụng.
|
||||
- **Khởi động nhanh** — route và editor CodeMirror được lazy-load, mã vendor/parser tách thành nhiều chunk nhỏ theo tính năng, nên trình duyệt chỉ tải đúng phần bạn dùng.
|
||||
- **Xử lý batch** — tới 500 file cùng lúc (Phase 2).
|
||||
- **Mượt cả với input lớn** — input trên 256 KB và mọi lượt xử lý batch đều chạy trong Web Worker, nên gõ phím và cuộn trang vẫn mượt.
|
||||
- **Xử lý batch** — tới 500 file cùng lúc, tải về gọn trong một file `.zip` (định dạng nhị phân là binary thật).
|
||||
- **Phát hiện shape thông minh** — nhận diện flat object, mảng object, scalar; gợi ý format đích phù hợp.
|
||||
- **Tuỳ chọn theo từng format** — pretty-print, indentation, dialect (SQL), alignment (Markdown), v.v.
|
||||
- **Theme sáng/tối** — bảng màu Prism Spectrum với violet / cyan / amber / rose.
|
||||
- **Theme sáng, tối hoặc theo hệ thống** — bảng màu Prism Spectrum với violet / cyan / amber / rose trên phong cách "kỹ thuật" với nền lưới kiểu bản vẽ (blueprint). Menu Giao diện còn có tuỳ chọn ẩn thanh cuộn.
|
||||
- **Responsive — tối ưu cho viewport ≥ 360 × 640.** Màn hình nhỏ hơn vẫn dùng được nhưng có thể chật; trên mobile, Input và Output dùng Tabs UI để mỗi panel có toàn bộ chiều cao. Xem [`docs/tested-viewports.md`](docs/tested-viewports.md) cho ma trận thiết bị đã kiểm thử.
|
||||
- **Đa ngôn ngữ EN + VI** — sẵn sàng từ ngày đầu. Hoan nghênh thêm ngôn ngữ khác.
|
||||
- **Bản desktop Tauri** — drag-and-drop file, hoạt động offline (mốc Phase 2).
|
||||
- **4 ngôn ngữ giao diện** — English, Tiếng Việt, 日本語 và 简体中文. Bản tiếng Nhật và tiếng Trung do AI dịch; rất hoan nghênh người bản ngữ góp ý chỉnh sửa.
|
||||
- **App desktop và Android** — bản Tauri 2 cho Windows, macOS, Linux và Android, có dialog chọn file native và drag-and-drop. Chạy hoàn toàn offline.
|
||||
|
||||
## Quyền riêng tư
|
||||
|
||||
- **Dữ liệu của bạn ở lại trên thiết bị.** Mọi bản build đều chuyển đổi ngay trên máy; những gì bạn dán, gõ hay mở không bao giờ bị tải lên. Cài đặt và trạng thái workspace được lưu trong `localStorage` và không gửi đi đâu cả.
|
||||
- **Riêng website** ([jsonprism.poli0981.dev](https://jsonprism.poli0981.dev)) **dùng thêm ba dịch vụ của Cloudflare**, và không dịch vụ nào thấy nội dung bạn chuyển đổi:
|
||||
- **Hosting** — Cloudflare phục vụ trang web và, như mọi nhà cung cấp hosting, xử lý log request (địa chỉ IP, user agent) để phân phối nội dung và bảo mật.
|
||||
- **Turnstile** — bước xác minh nhanh, khoảng mỗi tuần một lần (xác minh thành công được ghi nhớ 7 ngày). Nếu không kết nối được tới Cloudflare, bạn vẫn có thể tiếp tục sau một cảnh báo, vì việc chuyển đổi không bao giờ cần mạng.
|
||||
- **Web Analytics** — đếm lượt xem trang ẩn danh, không dùng cookie, chỉ được tải sau khi bạn chấp nhận Điều khoản và Chính sách quyền riêng tư. Tắt tại **Giao diện → Thống kê truy cập ẩn danh**; mặc định tắt nếu trình duyệt gửi tín hiệu Global Privacy Control.
|
||||
- **App desktop và Android không dùng dịch vụ nào trong số này** — không analytics, không bước xác minh, không request mạng nào ngoài các link bạn tự mở.
|
||||
|
||||
Chi tiết: [`PRIVACY.md`](PRIVACY.md).
|
||||
|
||||
## Tech stack
|
||||
|
||||
- **Vite 8** + **React 19** + **TypeScript 5.7**
|
||||
- **Vite 8** + **React 19.3** + **TypeScript 7** (compiler native; dependency `typescript` là alias TS 6, chỉ giữ lại cho typescript-eslint)
|
||||
- **Tailwind CSS v4** + **shadcn/ui** (style New York, base neutral)
|
||||
- **CodeMirror 6** cho editor đầu vào (Phase 1 polish)
|
||||
- **PapaParse**, **js-yaml**, **smol-toml**, **fast-xml-parser** để parse/serialize
|
||||
- **i18next** cho dịch thuật, **Zustand** cho state, **Sonner** cho toast
|
||||
- **Tauri 2** wrapper (Phase 2)
|
||||
- **CodeMirror 6** cho editor đầu vào và khung output chỉ đọc
|
||||
- **PapaParse**, **js-yaml**, **smol-toml**, **fast-xml-parser**, **bson**, **cbor-x**, **@msgpack/msgpack** để parse/serialize; **fflate** để đóng gói file `.zip` khi xử lý batch
|
||||
- **i18next** cho dịch thuật, **Zustand** cho state, **React Router 8** cho routing, **Sonner** cho toast
|
||||
- **Vitest** + Testing Library cho test
|
||||
- **Node.js 26** cho toolchain
|
||||
- **Cloudflare Workers** host bản web (static assets kèm một Worker nhỏ cho `/api/*`)
|
||||
- **Tauri 2.12** cho app desktop (Windows, macOS, Linux) và Android
|
||||
|
||||
## Bắt đầu nhanh
|
||||
|
||||
**Yêu cầu**: Node.js **22 LTS** trở lên.
|
||||
**Yêu cầu**: Node.js **26** (ghim trong `.nvmrc`).
|
||||
|
||||
```bash
|
||||
git clone https://github.com/poli0981/jsonPrism.git
|
||||
cd jsonprism
|
||||
cd jsonPrism
|
||||
nvm use # chọn Node 26 theo .nvmrc
|
||||
npm install
|
||||
npm run dev # http://localhost:5173
|
||||
```
|
||||
|
||||
Bước xác minh Turnstile tắt khi chạy `npm run dev` (đặt `VITE_TURNSTILE_DEV=1` nếu muốn thử). Để chạy bản build production giống cách Cloudflare phục vụ — static assets kèm Worker:
|
||||
|
||||
```bash
|
||||
cp .dev.vars.example .dev.vars # secret test của Cloudflare Turnstile, luôn pass
|
||||
npm run preview:cf # build + wrangler dev tại http://localhost:8787
|
||||
```
|
||||
|
||||
### Các script
|
||||
|
||||
| Script | Chức năng |
|
||||
| --- | --- |
|
||||
| `npm run dev` | Chạy Vite dev server với HMR |
|
||||
| `npm run build` | Type-check rồi build production vào `dist/` |
|
||||
| `npm run preview` | Xem trước bản build trên máy local (Vite) |
|
||||
| `npm run lint` | Chạy ESLint |
|
||||
| `npm run lint:fix` | Chạy ESLint với autofix |
|
||||
| `npm run typecheck` | Type-check app, test, file config và Worker (TypeScript 7), không emit |
|
||||
| `npm run knip` | Tìm file, export và dependency không dùng đến |
|
||||
| `npm run format` | Format bằng Prettier |
|
||||
| `npm run format:check` | Kiểm tra format (CI dùng cái này) |
|
||||
| `npm test` | Chạy bộ test Vitest một lần |
|
||||
| `npm run test:watch` | Chạy Vitest ở chế độ watch |
|
||||
| `npm run test:coverage` | Chạy test kèm báo cáo coverage (CI dùng cái này) |
|
||||
| `npm run cf:types` | Tạo lại type cho các binding của Worker |
|
||||
| `npm run cf:check` | Chạy thử deploy lên Cloudflare (`wrangler deploy --dry-run`; CI cũng chạy) |
|
||||
| `npm run preview:cf` | Build mới rồi chạy site + Worker bằng `wrangler dev` tại http://localhost:8787 |
|
||||
| `npm run tauri:dev` | Chạy app desktop ở dev mode (Vite + cửa sổ Tauri có hot reload) |
|
||||
| `npm run tauri:build` | Build bundle desktop native cho OS đang dùng |
|
||||
| `npm run tauri:icon` | Render `src-tauri/icons/icon.svg` ra mọi kích thước icon |
|
||||
| `npm run tauri:android:dev` | Chạy app Android trên thiết bị hoặc emulator |
|
||||
| `npm run tauri:android:build` | Build APK Android universal |
|
||||
|
||||
### Components shadcn/ui
|
||||
|
||||
`components.json` đã được cấu hình sẵn. Thêm component theo nhu cầu:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add button input textarea tabs select card dialog sheet \
|
||||
dropdown-menu switch badge progress tooltip sonner resizable
|
||||
```
|
||||
|
||||
## Bản desktop (Tauri 2)
|
||||
|
||||
JSONPrism cũng có bản desktop native qua Tauri 2. App dùng cùng React UI, với dialog OS native và drag-drop tích hợp vào batch flow hiện có.
|
||||
JSONPrism cũng có bản desktop native qua Tauri 2. App dùng cùng React UI, với dialog OS native và drag-drop tích hợp vào batch flow hiện có. App chạy hoàn toàn offline: không analytics, không bước xác minh, không request mạng nào ngoài các link bạn tự mở.
|
||||
|
||||
### Tải về (người dùng)
|
||||
|
||||
Tải bundle cho hệ điều hành của bạn từ [bản release mới nhất](https://github.com/poli0981/jsonPrism/releases/latest):
|
||||
|
||||
| Hệ điều hành | File | Yêu cầu |
|
||||
| --- | --- | --- |
|
||||
| **Windows** | `.msi` hoặc NSIS `-setup.exe` | WebView2 runtime (cài sẵn trên Windows 11) |
|
||||
| **macOS** | `.dmg` universal (Apple Silicon + Intel) | macOS **12** trở lên |
|
||||
| **Linux** | `.deb`, `.rpm` hoặc `.AppImage` | Build trên Ubuntu 22.04 — cần Ubuntu 22.04 hoặc distro mới tương đương |
|
||||
|
||||
Bản desktop chưa được ký số (code signing), nên Windows SmartScreen hoặc macOS Gatekeeper có thể cảnh báo ở lần mở đầu tiên. Từ v2.0.0, mỗi bản release đều kèm `SHA256SUMS.txt` và build-provenance attestation của GitHub để bạn kiểm tra file trước khi chạy:
|
||||
|
||||
```bash
|
||||
sha256sum -c SHA256SUMS.txt --ignore-missing
|
||||
gh attestation verify <file> --repo poli0981/jsonPrism
|
||||
```
|
||||
|
||||
### Build (lập trình viên)
|
||||
|
||||
**Yêu cầu thêm**:
|
||||
|
||||
@@ -77,7 +155,7 @@ JSONPrism cũng có bản desktop native qua Tauri 2. App dùng cùng React UI,
|
||||
- **Build deps theo platform**:
|
||||
- **Windows**: Visual Studio Build Tools (workload C++) + WebView2 (cài sẵn trên Windows 11)
|
||||
- **macOS**: Xcode Command Line Tools (`xcode-select --install`)
|
||||
- **Linux**: `libwebkit2gtk-4.1-dev`, `libappindicator3-dev`, `librsvg2-dev`, `patchelf`, `libssl-dev`
|
||||
- **Linux**: `libwebkit2gtk-4.1-dev`, `libappindicator3-dev`, `librsvg2-dev`, `patchelf`, `libssl-dev`, `libgtk-3-dev`
|
||||
|
||||
**Generate icon một lần** (dùng Tauri CLI render SVG ra PNG/ICO/ICNS):
|
||||
|
||||
@@ -101,9 +179,9 @@ Output:
|
||||
|
||||
- Windows → `src-tauri/target/release/bundle/msi/*.msi` + `nsis/*-setup.exe`
|
||||
- macOS → `src-tauri/target/release/bundle/dmg/*.dmg` + `macos/*.app`
|
||||
- Linux → `src-tauri/target/release/bundle/appimage/*.AppImage` + `deb/*.deb`
|
||||
- Linux → `src-tauri/target/release/bundle/appimage/*.AppImage` + `deb/*.deb` + `rpm/*.rpm`
|
||||
|
||||
**Release tự động**: push tag `v*` sẽ trigger `.github/workflows/release.yml`, build cho tất cả platform song song và tạo draft GitHub release.
|
||||
**Release tự động**: push tag `v*` sẽ chạy `.github/workflows/release.yml`: kiểm tra tag khớp với version trong `package.json` và `src-tauri/Cargo.toml`, chạy test, build bundle Windows, macOS (universal), Linux cùng APK Android vào **một** draft GitHub release, rồi thêm `SHA256SUMS.txt` và build-provenance attestation. Maintainer sẽ publish draft đó.
|
||||
|
||||
## Bản Android (Tauri 2)
|
||||
|
||||
@@ -117,14 +195,15 @@ JSONPrism còn có bản Android để bạn sideload từ file `.apk`. Cùng Re
|
||||
| **System WebView** | **Chromium 111+** (Android System WebView / Chrome). Đa số máy được Play Store cập nhật sẵn; WebView quá cũ sẽ render giao diện sai — nếu UI bị vỡ, hãy cập nhật "Android System WebView" và Chrome trong Play Store. |
|
||||
| **CPU / ABI** | arm64-v8a, armeabi-v7a, x86 hoặc x86_64 — một file APK universal chạy được trên tất cả (máy hiện đại là arm64-v8a) |
|
||||
| **RAM** | Tối thiểu 2 GB; khuyến nghị 4 GB cho file lớn hoặc xử lý hàng loạt (tối đa 500 file) |
|
||||
| **Dung lượng** | ~27 MB để tải; nên có ~100 MB trống (cài đặt + file tạm khi làm việc) |
|
||||
| **Dung lượng** | Nên có ~100 MB trống (cài đặt + file tạm khi làm việc) |
|
||||
| **Mạng** | Không cần — app chạy hoàn toàn offline, không gửi gì ra ngoài |
|
||||
|
||||
### Cài đặt (người dùng)
|
||||
|
||||
1. Tải `JSONPrism-<version>-android-universal.apk` từ trang [Releases](https://github.com/poli0981/jsonPrism/releases).
|
||||
2. Mở file; Android sẽ hỏi cho phép "cài app không rõ nguồn" cho trình duyệt/trình quản lý file — bật lên rồi cài.
|
||||
3. Cần Android 12+. App chạy hoàn toàn offline.
|
||||
1. Tải `JSONPrism_<version>_android-universal.apk` từ [bản release mới nhất](https://github.com/poli0981/jsonPrism/releases/latest).
|
||||
2. Nếu muốn, đối chiếu file với `SHA256SUMS.txt` hoặc kiểm tra bằng `gh attestation verify` (xem [Tải về (người dùng)](#tải-về-người-dùng)).
|
||||
3. Mở file; Android sẽ hỏi cho phép "cài app không rõ nguồn" cho trình duyệt/trình quản lý file — bật lên rồi cài.
|
||||
4. Cần Android 12+. App chạy hoàn toàn offline.
|
||||
|
||||
### Build (lập trình viên)
|
||||
|
||||
@@ -151,29 +230,7 @@ npm run tauri:android:build
|
||||
|
||||
Output: `src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk`. Thông tin ký lấy từ `src-tauri/gen/android/keystore.properties` (gitignored); thiếu file này thì APK build ra chưa ký. Xem [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md) để biết cách tạo keystore và các secret ký trong CI.
|
||||
|
||||
**Release tự động**: cùng tag `v*` cũng chạy job `android` trong `release.yml`, ký APK bằng keystore từ repository secrets và đính vào draft release.
|
||||
|
||||
### Các script
|
||||
|
||||
| Script | Chức năng |
|
||||
| --------------------- | ---------------------------------------- |
|
||||
| `npm run dev` | Chạy Vite dev server với HMR |
|
||||
| `npm run build` | Build production vào `dist/` |
|
||||
| `npm run preview` | Xem trước bản build trên máy local |
|
||||
| `npm run lint` | Chạy ESLint |
|
||||
| `npm run lint:fix` | Chạy ESLint với autofix |
|
||||
| `npm run typecheck` | Type-check TypeScript, không emit |
|
||||
| `npm run format` | Format bằng Prettier |
|
||||
| `npm run format:check`| Kiểm tra format (CI dùng cái này) |
|
||||
|
||||
### Components shadcn/ui
|
||||
|
||||
`components.json` đã được cấu hình sẵn. Thêm component theo nhu cầu:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add button input textarea tabs select card dialog sheet \
|
||||
dropdown-menu switch badge progress tooltip sonner resizable
|
||||
```
|
||||
**Release tự động**: cùng tag `v*` cũng chạy job `android` trong `release.yml`, ký APK bằng keystore từ repository secrets và đính vào draft release với tên `JSONPrism_<version>_android-universal.apk`.
|
||||
|
||||
## Kiến trúc
|
||||
|
||||
@@ -182,30 +239,34 @@ src/
|
||||
├── app/ # Router + providers
|
||||
├── components/
|
||||
│ ├── ui/ # shadcn components (thêm theo nhu cầu)
|
||||
│ ├── layout/ # Header, Footer, ThemeToggle
|
||||
│ ├── converter/ # Workspace, panels, format picker
|
||||
│ └── common/ # ErrorBoundary, LanguageSwitcher
|
||||
│ ├── layout/ # Header, Footer, AppearanceMenu
|
||||
│ ├── converter/ # Workspace, panels, format picker, batch
|
||||
│ └── common/ # ConsentGate, HumanCheck, error boundary, LanguageSwitcher
|
||||
├── converters/ # Một module cho mỗi định dạng đích
|
||||
│ ├── types.ts # Interface Converter
|
||||
│ ├── registry.ts # Bảng tra cứu
|
||||
│ └── *.ts # Cài đặt theo từng format
|
||||
├── hooks/ # Custom hooks
|
||||
├── i18n/ # Dịch thuật (en, vi)
|
||||
├── lib/ # detect, theme, utils, sample
|
||||
├── pages/ # Home, About
|
||||
├── i18n/ # Dịch thuật (en, vi, ja, zh-CN)
|
||||
├── lib/ # detect, chuyển đổi + Web Worker, batch, theme, logger, utils
|
||||
├── pages/ # Home, About, trang lỗi
|
||||
├── stores/ # Zustand store (workspace, batch, consent, preferences)
|
||||
├── styles/ # globals.css (Tailwind + theme tokens)
|
||||
└── main.tsx
|
||||
```
|
||||
|
||||
Ngoài `src/`: `worker/` là Cloudflare Worker (`/api/health` và `/api/turnstile/verify`, cấu hình trong `wrangler.jsonc`), còn `src-tauri/` là phần vỏ Tauri 2 cho app desktop và Android.
|
||||
|
||||
### Thêm định dạng mới
|
||||
|
||||
Mỗi format là một module độc lập, cài đặt interface `Converter`:
|
||||
|
||||
```ts
|
||||
import type { Converter } from './types';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
|
||||
interface MyFormatOptions {
|
||||
indent: 2 | 4;
|
||||
indent: number;
|
||||
}
|
||||
|
||||
export const myFormatConverter: Converter<MyFormatOptions> = {
|
||||
@@ -218,38 +279,57 @@ export const myFormatConverter: Converter<MyFormatOptions> = {
|
||||
ready: true,
|
||||
},
|
||||
defaultOptions: { indent: 2 },
|
||||
// Drives the auto-generated settings panel.
|
||||
optionSchema: [
|
||||
{ type: 'integer', key: 'indent', labelKey: 'options.myformat.indent', min: 0, max: 8 },
|
||||
],
|
||||
convert({ data }, options) {
|
||||
try {
|
||||
const output = serialize(data, options);
|
||||
return { ok: true, output };
|
||||
} catch (err) {
|
||||
return { ok: false, error: (err as Error).message };
|
||||
return { ok: false, error: errorMessage(err) };
|
||||
}
|
||||
},
|
||||
// Optional: reverse({ text }, options) parses the format back to JSON.
|
||||
};
|
||||
```
|
||||
|
||||
Sau đó đăng ký nó trong `src/converters/registry.ts` và thêm label key vào `src/i18n/locales/*.json`.
|
||||
Sau đó thêm id vào union `FormatId` trong `src/converters/types.ts`, đăng ký converter trong `src/converters/registry.ts` (`CONVERTERS` và `ALL_FORMATS`), và thêm label key vào cả bốn file trong `src/i18n/locales/` — test parity sẽ fail nếu một ngôn ngữ thiếu key.
|
||||
|
||||
Xem [`docs/ROADMAP.md`](docs/ROADMAP.md) để biết kế hoạch phase đầy đủ.
|
||||
|
||||
## Đóng góp
|
||||
|
||||
Welcome pull request — vui lòng đọc [`CONTRIBUTING.md`](CONTRIBUTING.md) trước. PR thuộc nhóm **auto-ignored** (code đáng ngờ, lan man không vào vấn đề, không mô tả…) sẽ bị đóng không review.
|
||||
Rất hoan nghênh pull request — vui lòng đọc [`CONTRIBUTING.md`](CONTRIBUTING.md) trước. PR thuộc nhóm **auto-ignored** (code đáng ngờ, lan man không vào vấn đề, không mô tả…) sẽ bị đóng không review.
|
||||
|
||||
Báo bug hoặc đề xuất tính năng tại [GitHub Issues](https://github.com/poli0981/jsonPrism/issues). Vấn đề bảo mật vui lòng dùng [Security Advisory riêng tư](https://github.com/poli0981/jsonPrism/security/advisories/new).
|
||||
|
||||
## Liên hệ
|
||||
|
||||
| Địa chỉ | Dùng cho |
|
||||
| --- | --- |
|
||||
| [security@poli0981.dev](mailto:security@poli0981.dev) | Báo lỗ hổng bảo mật (ưu tiên dùng [Security Advisory riêng tư](https://github.com/poli0981/jsonPrism/security/advisories/new)) |
|
||||
| [privacy@poli0981.dev](mailto:privacy@poli0981.dev) | Yêu cầu liên quan đến quyền riêng tư |
|
||||
| [legal@poli0981.dev](mailto:legal@poli0981.dev) | Điều khoản, giấy phép và các vấn đề pháp lý khác |
|
||||
| [copyright@poli0981.dev](mailto:copyright@poli0981.dev) | Thông báo bản quyền và yêu cầu gỡ bỏ (takedown) |
|
||||
| [code@poli0981.dev](mailto:code@poli0981.dev) | Về project và maintainer; báo cáo vi phạm Quy tắc ứng xử |
|
||||
| [sponsor@poli0981.dev](mailto:sponsor@poli0981.dev) | Tài trợ |
|
||||
|
||||
Báo bug và đề xuất tính năng vui lòng gửi qua [GitHub Issues](https://github.com/poli0981/jsonPrism/issues), không gửi qua email.
|
||||
|
||||
## Tài liệu project
|
||||
|
||||
| Doc | Nội dung |
|
||||
|---|---|
|
||||
| [`PRIVACY.md`](PRIVACY.md) | Offline-first, chỉ localStorage, không telemetry. |
|
||||
| [`PRIVACY.md`](PRIVACY.md) | Những gì ở lại trên thiết bị, và các dịch vụ Cloudflare chỉ dùng cho website (hosting, Turnstile, Web Analytics). |
|
||||
| [`TERMS.md`](TERMS.md) | ToS / EULA — acceptable use, kế thừa giấy phép, quyền sở hữu dữ liệu. |
|
||||
| [`SECURITY.md`](SECURITY.md) | Cách report vulnerability, SLA. |
|
||||
| [`DISCLAIMER.md`](DISCLAIMER.md) | Project 1 người + AI-assisted, không bảo hành. |
|
||||
| [`THIRD-PARTY.md`](THIRD-PARTY.md) | Mỗi dependency: version, giấy phép, link. |
|
||||
| [`MAINTAINERS.md`](MAINTAINERS.md) | Ai chịu trách nhiệm gì. |
|
||||
| [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md) | Contributor Covenant v2.1. |
|
||||
| [`CHANGELOG.md`](CHANGELOG.md) | Ghi chú phát hành của từng phiên bản. |
|
||||
| [`docs/ROADMAP.md`](docs/ROADMAP.md) | Phase plan, trạng thái hiện tại. |
|
||||
| [`docs/i18n/vi/pc_spec.md`](docs/i18n/vi/pc_spec.md) · [`docs/i18n/vi/dev_env.md`](docs/i18n/vi/dev_env.md) | Phần cứng + toolchain của maintainer. |
|
||||
| [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md) | Ghi chú Tauri build / process. |
|
||||
@@ -269,17 +349,20 @@ Trò chuyện, hỏi đáp, hoặc theo dõi cập nhật:
|
||||
## Ghi nhận
|
||||
|
||||
Phần lớn code, test, bản dịch và tài liệu của JSONPrism được draft với
|
||||
**Claude Chat** và **Claude Code (Opus 4.7, 1M context)**. Xem
|
||||
[DISCLAIMER.md](DISCLAIMER.md) để biết chi tiết về AI-assist. Chất lượng
|
||||
bản dịch ngôn ngữ ngoài tiếng Anh là best-effort — rất hoan nghênh
|
||||
đóng góp từ người bản ngữ.
|
||||
sự hỗ trợ của AI: **Claude Chat** và **Claude Code (Opus 4.7, 1M
|
||||
context)** cho v1.x, **Claude Code (Opus 5.5)** cho v2.0.0. Xem
|
||||
[DISCLAIMER.md](DISCLAIMER.md) để biết chi tiết về AI-assist. Bản dịch
|
||||
tiếng Nhật, tiếng Trung giản thể và một phần bản tiếng Việt do AI tạo,
|
||||
chất lượng ở mức best-effort — rất hoan nghênh đóng góp từ người bản ngữ.
|
||||
|
||||
## Tài trợ
|
||||
|
||||
Nếu JSONPrism hữu ích cho bạn, hãy cân nhắc tài trợ maintainer qua một
|
||||
trong các kên trong [`.github/FUNDING.yml`](.github/FUNDING.yml):
|
||||
GitHub Sponsors, Ko-fi, Buy Me a Coffee, Patreon hoặc PayPal.
|
||||
Nếu JSONPrism hữu ích cho bạn, hãy cân nhắc tài trợ maintainer
|
||||
poli0981 (Kokone) qua một trong các kênh trong
|
||||
[`.github/FUNDING.yml`](.github/FUNDING.yml): GitHub Sponsors, Ko-fi,
|
||||
Buy Me a Coffee, Patreon hoặc PayPal. Liên hệ về tài trợ qua email
|
||||
[sponsor@poli0981.dev](mailto:sponsor@poli0981.dev).
|
||||
|
||||
## Giấy phép
|
||||
|
||||
[Apache License 2.0](LICENSE) — © 2026 Kokone ([@poli0981](https://github.com/poli0981)).
|
||||
[Apache License 2.0](LICENSE) — © 2026 [poli0981](https://github.com/poli0981) (Kokone).
|
||||
+51
-29
@@ -3,12 +3,13 @@
|
||||
## Supported versions
|
||||
|
||||
JSONPrism follows [Semantic Versioning](https://semver.org/). Only the
|
||||
latest minor of the current major receives security fixes.
|
||||
latest release of the current major version receives security fixes; the
|
||||
website always runs the latest code on `main`.
|
||||
|
||||
| Version | Supported |
|
||||
|---|---|
|
||||
| 1.x | ✅ |
|
||||
| < 1.0 | ❌ |
|
||||
| 2.x | ✅ |
|
||||
| < 2.0 | ❌ |
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
@@ -18,51 +19,72 @@ Use GitHub's private vulnerability reporting:
|
||||
|
||||
→ <https://github.com/poli0981/jsonPrism/security/advisories/new>
|
||||
|
||||
This routes the report directly to the maintainer through a private
|
||||
channel. You can include a proof-of-concept, suggested fix, and your
|
||||
disclosure timeline preference.
|
||||
This reaches the maintainer through a private channel. Include a
|
||||
proof of concept, a suggested fix if you have one, and your preferred
|
||||
disclosure timeline.
|
||||
|
||||
If GitHub's private reporting is unavailable for any reason, contact
|
||||
[@poli0981](https://github.com/poli0981) via the email listed on the
|
||||
GitHub profile.
|
||||
If you cannot use GitHub, email **security@poli0981.dev**. The same
|
||||
contacts are published in
|
||||
[`/.well-known/security.txt`](https://jsonprism.poli0981.dev/.well-known/security.txt).
|
||||
|
||||
## Response expectations
|
||||
|
||||
JSONPrism is a one-person open-source project (see
|
||||
[DISCLAIMER.md](DISCLAIMER.md)). Response times are best-effort:
|
||||
[DISCLAIMER.md](DISCLAIMER.md)). Response times are best effort:
|
||||
|
||||
| Severity | Initial response | Fix released |
|
||||
|---|---|---|
|
||||
| Critical (RCE, data exfil, auth bypass) | within 48h | best-effort patch ASAP |
|
||||
| High (information disclosure, persistent XSS) | within 7 days | next release |
|
||||
| Critical (code execution, data exfiltration, supply-chain compromise) | within 48 h | as soon as possible |
|
||||
| High (information disclosure, persistent XSS, CSP bypass) | within 7 days | next release |
|
||||
| Medium / Low | within 30 days | next minor release |
|
||||
|
||||
For the **client-side, no-server** nature of JSONPrism, "critical" issues
|
||||
are realistically: malicious-input parsing crashes that lead to RCE
|
||||
inside the Tauri WebView, supply-chain compromise of a dependency, or
|
||||
prototype-pollution-style flaws in a converter that affects downstream
|
||||
consumers of the output.
|
||||
Conversion runs entirely on the user's device, so realistic critical
|
||||
issues are: malicious input that achieves code execution in the browser
|
||||
or the Tauri WebView, a compromised dependency, a converter flaw that
|
||||
produces output dangerous to downstream consumers (for example SQL or
|
||||
CSV injection beyond what the options document), or a weakness in the
|
||||
website's edge configuration.
|
||||
|
||||
## Scope
|
||||
|
||||
In scope:
|
||||
- Vulnerabilities in `src/` (React app, converters, batch processor).
|
||||
- Vulnerabilities in `src-tauri/` (Rust shell, plugin config, CSP).
|
||||
- Vulnerabilities introduced by build tooling that end up in the
|
||||
published bundle (`dist/` on GitHub Pages, Tauri release artifacts).
|
||||
- Auth/identity vulnerabilities — not applicable; the app has no
|
||||
accounts, no server, no telemetry.
|
||||
|
||||
- `src/` — the React app, converters and batch processor.
|
||||
- `worker/` — the Cloudflare Worker (`/api/turnstile/verify`,
|
||||
`/api/health`): origin checks, rate limiting, request validation.
|
||||
- Website edge configuration: `public/_headers` (CSP and security
|
||||
headers), `public/_redirects`, `wrangler.jsonc`.
|
||||
- `src-tauri/` — the Rust shell, capabilities, file-system scope and CSP.
|
||||
- Build and release tooling whose output ships to users: the website
|
||||
build, Tauri release artifacts and `.github/workflows/`.
|
||||
|
||||
Out of scope:
|
||||
- GitHub Pages or GitHub Actions platform issues — report to GitHub.
|
||||
- WebView2 / WebKitGTK / WKWebView host bugs — report to Microsoft /
|
||||
the GTK / Apple WebKit teams. JSONPrism inherits whatever is on the
|
||||
|
||||
- Cloudflare, GitHub Pages or GitHub Actions platform issues — report them
|
||||
to Cloudflare or GitHub.
|
||||
- WebView2 / WebKitGTK / WKWebView / Android System WebView bugs — report
|
||||
them to their vendors. JSONPrism uses whatever is installed on the
|
||||
user's system.
|
||||
- Issues that require an attacker to already have local code execution
|
||||
on the user's machine.
|
||||
- Turnstile bypasses that only affect Cloudflare's challenge itself.
|
||||
- Attacks that require existing local code execution on the user's
|
||||
machine.
|
||||
- Missing best-practice headers with no demonstrable impact.
|
||||
|
||||
## Verifying releases
|
||||
|
||||
Every GitHub release includes `SHA256SUMS.txt` and build-provenance
|
||||
attestations generated in GitHub Actions:
|
||||
|
||||
```bash
|
||||
sha256sum -c SHA256SUMS.txt --ignore-missing
|
||||
gh attestation verify JSONPrism_2.0.0_x64-setup.exe --repo poli0981/jsonPrism
|
||||
```
|
||||
|
||||
The desktop installers are not yet code-signed, so Windows SmartScreen
|
||||
and macOS Gatekeeper may warn on first launch.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
Reporters are credited in the published advisory unless they request
|
||||
Reporters are credited in the published advisory unless they ask
|
||||
otherwise. Contributors of accepted fixes are credited in the release
|
||||
notes.
|
||||
@@ -1,122 +1,146 @@
|
||||
# Terms of Service / EULA
|
||||
|
||||
**Last updated**: 2026-05-13
|
||||
**Version**: 2.0 · **Effective**: 2026-10-22 · Replaces the terms of 2026-05-13.
|
||||
|
||||
JSONPrism is a one-person, AI-assisted open-source project published by
|
||||
[@poli0981](https://github.com/poli0981) under the [Apache License 2.0](LICENSE).
|
||||
This page sets out the terms under which you may use the website, the
|
||||
desktop application, the source repository, and any associated assets
|
||||
(collectively, "JSONPrism").
|
||||
poli0981 (Kokone, [@poli0981](https://github.com/poli0981)) under the
|
||||
[Apache License 2.0](LICENSE). These terms cover the website, the desktop
|
||||
and Android applications, the source repository and associated assets
|
||||
(together, "JSONPrism").
|
||||
|
||||
By using JSONPrism in any form, you agree to the terms below. If you do
|
||||
not agree, stop using it.
|
||||
By using JSONPrism in any form you agree to these terms. If you do not
|
||||
agree, stop using it.
|
||||
|
||||
---
|
||||
|
||||
## 1. Acceptance
|
||||
|
||||
Accessing the web app at <https://poli0981.github.io/jsonPrism/>,
|
||||
running the Tauri desktop bundle, cloning or downloading the repository,
|
||||
or otherwise interacting with the project constitutes acceptance of
|
||||
these terms.
|
||||
Using the web app at <https://jsonprism.poli0981.dev>, installing or
|
||||
running the desktop or Android app, cloning or downloading the repository,
|
||||
or otherwise interacting with the project means you accept these terms.
|
||||
The apps ask you to confirm this on first launch (the Windows installer
|
||||
does so on its license page) and again whenever these terms or the
|
||||
[Privacy Policy](PRIVACY.md) change materially.
|
||||
|
||||
You must be at least 13 years old, or the age of digital consent where
|
||||
you live, to use JSONPrism.
|
||||
|
||||
## 2. GitHub Terms of Service
|
||||
|
||||
The repository, issues, discussions, releases, and pull requests are
|
||||
hosted on GitHub. You agree to use them in compliance with:
|
||||
The repository, issues, discussions, releases and pull requests are
|
||||
hosted on GitHub. Using them means complying with:
|
||||
|
||||
- [GitHub Terms of Service](https://docs.github.com/en/site-policy/github-terms/github-terms-of-service)
|
||||
- [GitHub Acceptable Use Policies](https://docs.github.com/en/site-policy/acceptable-use-policies/github-acceptable-use-policies)
|
||||
- [GitHub Privacy Statement](https://docs.github.com/en/site-policy/privacy-policies/github-general-privacy-statement)
|
||||
|
||||
Behavior that violates GitHub's platform rules is also a violation of
|
||||
these terms.
|
||||
Behaviour that violates GitHub's rules also violates these terms.
|
||||
|
||||
## 3. License inheritance
|
||||
## 3. License
|
||||
|
||||
JSONPrism source code is licensed under the
|
||||
[Apache License, Version 2.0](LICENSE). You may use, modify, and
|
||||
redistribute the code subject to that license — most importantly, you
|
||||
must preserve copyright notices and the license text in distributions.
|
||||
JSONPrism's source code is licensed under the
|
||||
[Apache License, Version 2.0](LICENSE). You may use, study, modify and
|
||||
redistribute it under that license; in particular you must keep the
|
||||
copyright notices and the license text in your distributions. Nothing in
|
||||
these terms restricts rights the Apache License grants you.
|
||||
|
||||
The project consumes third-party libraries with their own licenses. See
|
||||
[THIRD-PARTY.md](THIRD-PARTY.md) for the full list. When redistributing
|
||||
JSONPrism or a derivative, you are responsible for satisfying the terms
|
||||
of every upstream dependency.
|
||||
The project uses third-party libraries, fonts and services with their own
|
||||
licenses and terms, listed in [THIRD-PARTY.md](THIRD-PARTY.md). When you
|
||||
redistribute JSONPrism or a derivative, you are responsible for meeting
|
||||
the terms of every upstream component.
|
||||
|
||||
## 4. No warranty / limitation of liability
|
||||
## 4. Third-party services (website only)
|
||||
|
||||
The website is hosted on Cloudflare and uses Cloudflare Turnstile for a
|
||||
human check and Cloudflare Web Analytics for anonymous page-view counts,
|
||||
as described in the [Privacy Policy](PRIVACY.md). Cloudflare provides
|
||||
these services under its own terms and
|
||||
[privacy policy](https://www.cloudflare.com/privacypolicy/). The desktop
|
||||
and Android apps do not use them.
|
||||
|
||||
## 5. No warranty and limitation of liability
|
||||
|
||||
JSONPrism is provided **"AS IS"**, without warranty of any kind, express
|
||||
or implied, including (but not limited to) warranties of merchantability,
|
||||
fitness for a particular purpose, and non-infringement. The maintainer
|
||||
is not liable for any claim, damages, or other liability arising from
|
||||
your use of the software.
|
||||
or implied, including warranties of merchantability, fitness for a
|
||||
particular purpose and non-infringement. To the maximum extent permitted
|
||||
by law, the maintainer is not liable for any claim, damages or other
|
||||
liability arising from your use of JSONPrism, including data loss or
|
||||
incorrect conversions. Check converted output before you rely on it.
|
||||
|
||||
This restates the disclaimer in the Apache 2.0 license — see
|
||||
[DISCLAIMER.md](DISCLAIMER.md) for the project's own framing of the
|
||||
"one-person + AI-assisted" reality.
|
||||
This restates the disclaimer in the Apache License; see
|
||||
[DISCLAIMER.md](DISCLAIMER.md) for the project's own account of what
|
||||
"one person plus AI assistance" means in practice.
|
||||
|
||||
## 5. User data ownership
|
||||
## 6. Your data
|
||||
|
||||
You own everything you paste, drop, type, or generate in JSONPrism.
|
||||
You own everything you paste, drop, type or generate in JSONPrism.
|
||||
|
||||
- The maintainer does not receive, store, transmit, or analyze your
|
||||
input or output. The web build is a static GitHub Pages deploy with no
|
||||
server-side code; the desktop bundle runs entirely on your machine.
|
||||
- The only on-disk footprint is a small set of `localStorage` preferences
|
||||
(theme, language, selected format, direction, per-format options) —
|
||||
documented in [PRIVACY.md](PRIVACY.md).
|
||||
- You are responsible for the legality of the data you feed in. If you
|
||||
paste copyrighted, classified, or otherwise restricted data, the
|
||||
responsibility is yours.
|
||||
- The maintainer does not receive, store, transmit or analyse your input
|
||||
or output. Conversion runs on your device in every version.
|
||||
- What the apps keep on your device, and what the website's hosting and
|
||||
services process, is documented in [PRIVACY.md](PRIVACY.md).
|
||||
- You are responsible for having the right to use the data you feed in.
|
||||
|
||||
## 6. Acceptable use
|
||||
## 7. Acceptable use
|
||||
|
||||
You may not:
|
||||
You must not:
|
||||
|
||||
- Use JSONPrism, the repository, or its assets to facilitate activity
|
||||
that violates applicable law in your jurisdiction or the jurisdiction
|
||||
where the data was sourced.
|
||||
- Process **regulated personal data** (PHI, PCI, biometric, etc.) on the
|
||||
publicly hosted web build. If your environment requires such handling,
|
||||
build the Tauri desktop bundle yourself from source and run it
|
||||
air-gapped.
|
||||
- Submit pull requests or content that the maintainer determines
|
||||
contains hidden malicious code, obfuscated payloads, or supply-chain
|
||||
attack vectors. See [CONTRIBUTING.md](CONTRIBUTING.md) "Auto-ignored
|
||||
cases" for the enforcement rules — repeat offenders are banned from
|
||||
the repository.
|
||||
- Reverse-engineer the Tauri desktop bundle's capability scope to bypass
|
||||
the filesystem / dialog / shell restrictions configured in
|
||||
`src-tauri/capabilities/default.json`. This is enforced by Tauri's
|
||||
runtime; circumventing it is a violation of these terms.
|
||||
- Misrepresent JSONPrism as an official, certified, or guaranteed
|
||||
product. It is a one-person indie project (see
|
||||
[MAINTAINERS.md](MAINTAINERS.md)).
|
||||
- Use JSONPrism, the repository or its assets to facilitate activity that
|
||||
is unlawful where you are or where the data comes from.
|
||||
- Process **regulated personal data** (health, payment card, biometric
|
||||
data and the like) on the hosted website. If your environment requires
|
||||
such handling, use the desktop app or build JSONPrism from source and
|
||||
run it in your own controlled environment.
|
||||
- Attack, overload, probe for vulnerabilities without following
|
||||
[SECURITY.md](SECURITY.md), or disrupt the website or its API, or try
|
||||
to bypass or automate its human check.
|
||||
- Submit pull requests or other content that hides malicious code,
|
||||
obfuscated payloads or supply-chain attacks. See
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md) for how such contributions are
|
||||
handled; repeat offenders are blocked from the repository.
|
||||
- Present JSONPrism as an official, certified or guaranteed product. It
|
||||
is a one-person indie project (see [MAINTAINERS.md](MAINTAINERS.md)).
|
||||
|
||||
## 7. Trademarks
|
||||
## 8. Trademarks
|
||||
|
||||
"JSONPrism" and the prism logo are project marks of the maintainer.
|
||||
You may reference the project, but do not imply official endorsement of
|
||||
your derivative product without prior written permission.
|
||||
"JSONPrism" and the prism logo identify this project. You may refer to
|
||||
the project, but do not use the name or logo in a way that suggests the
|
||||
maintainer made or endorses your product or modified build without prior
|
||||
written permission.
|
||||
|
||||
## 8. Modifications
|
||||
## 9. Copyright complaints
|
||||
|
||||
The maintainer may update these terms. Material changes are recorded in
|
||||
[CHANGELOG.md](CHANGELOG.md) under the corresponding release. Continued
|
||||
use after a change constitutes acceptance of the updated terms.
|
||||
The website hosts no user content. If you believe material in the
|
||||
repository or the apps infringes your copyright, write to
|
||||
**copyright@poli0981.dev** with the material concerned, the work you
|
||||
claim it infringes and your contact details. Content on GitHub
|
||||
(issues, discussions, pull requests) is also subject to
|
||||
[GitHub's DMCA process](https://docs.github.com/en/site-policy/content-removal-policies/dmca-takedown-policy).
|
||||
|
||||
## 9. Termination
|
||||
## 10. Changes
|
||||
|
||||
The maintainer may, at any time and at sole discretion, restrict access
|
||||
to the repository or block contributions from a user whose behavior
|
||||
violates these terms or [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md). Such
|
||||
restrictions do not revoke the Apache 2.0 license already granted on
|
||||
existing distributions.
|
||||
The maintainer may update these terms. Changes are listed in
|
||||
[CHANGELOG.md](CHANGELOG.md) under the release that introduces them, and
|
||||
material changes increase the version number above and are presented for
|
||||
acceptance in the apps. Continuing to use JSONPrism after a change means
|
||||
you accept the updated terms.
|
||||
|
||||
## 10. Contact
|
||||
## 11. Termination
|
||||
|
||||
- General contact: see [MAINTAINERS.md](MAINTAINERS.md).
|
||||
- Security: see [SECURITY.md](SECURITY.md) for the private vulnerability
|
||||
reporting flow.
|
||||
- Privacy questions: see [PRIVACY.md](PRIVACY.md).
|
||||
The maintainer may at any time restrict access to the website or the
|
||||
repository, or block contributions from anyone whose behaviour violates
|
||||
these terms or the [Code of Conduct](CODE_OF_CONDUCT.md). This does not
|
||||
revoke the Apache License already granted for existing distributions.
|
||||
|
||||
## 12. Severability
|
||||
|
||||
If any provision of these terms is held unenforceable, the rest remain in
|
||||
effect. Not enforcing a provision does not waive it.
|
||||
|
||||
## 13. Contact
|
||||
|
||||
- Legal and licensing: legal@poli0981.dev
|
||||
- Copyright: copyright@poli0981.dev
|
||||
- Privacy: privacy@poli0981.dev ([PRIVACY.md](PRIVACY.md))
|
||||
- Security: [SECURITY.md](SECURITY.md)
|
||||
- Project and maintainer: [MAINTAINERS.md](MAINTAINERS.md)
|
||||
+149
-90
@@ -1,16 +1,20 @@
|
||||
# Third-party notice
|
||||
|
||||
JSONPrism is built on top of open-source libraries. This page lists each
|
||||
direct dependency, the version pinned in [`package.json`](package.json) and
|
||||
[`src-tauri/Cargo.toml`](src-tauri/Cargo.toml), the upstream license, and a
|
||||
link to the project.
|
||||
direct dependency declared in [`package.json`](package.json) and
|
||||
[`src-tauri/Cargo.toml`](src-tauri/Cargo.toml), the exact version used by
|
||||
**JSONPrism 2.0.0**, the upstream license, and a link to the project. It
|
||||
also lists the third-party services the website uses.
|
||||
|
||||
Versions reflect the `^` semver range — exact installed versions appear
|
||||
in [`package-lock.json`](package-lock.json) and `src-tauri/Cargo.lock`.
|
||||
Versions are the ones locked in [`package-lock.json`](package-lock.json)
|
||||
and [`src-tauri/Cargo.lock`](src-tauri/Cargo.lock); the manifests declare
|
||||
semver ranges. License identifiers (SPDX) are copied from each package's
|
||||
own `package.json` or `Cargo.toml`. Transitive dependencies are listed in
|
||||
the lockfiles.
|
||||
|
||||
If you are bundling JSONPrism into a derived work, the Apache 2.0
|
||||
license inherited from the upstream packages requires that you reproduce
|
||||
the relevant notices. This file is a starting point.
|
||||
If you are bundling JSONPrism into a derived work, these licenses (MIT,
|
||||
ISC, BSD, Apache-2.0, OFL-1.1) require that you keep the upstream
|
||||
copyright and license notices. This file is a starting point.
|
||||
|
||||
---
|
||||
|
||||
@@ -18,120 +22,164 @@ the relevant notices. This file is a starting point.
|
||||
|
||||
| Package | Version | License | Link |
|
||||
|---|---|---|---|
|
||||
| `react` | ^19.0.0 | MIT | [react.dev](https://react.dev/) |
|
||||
| `react-dom` | ^19.0.0 | MIT | [react.dev](https://react.dev/) |
|
||||
| `react-router-dom` | ^7.0.0 | MIT | [reactrouter.com](https://reactrouter.com/) |
|
||||
| `tailwindcss` | ^4.0.0 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
|
||||
| `tw-animate-css` | ^1.2.0 | MIT | [github.com/Wombosvideo/tw-animate-css](https://github.com/Wombosvideo/tw-animate-css) |
|
||||
| `tailwind-merge` | ^2.5.0 | MIT | [github.com/dcastil/tailwind-merge](https://github.com/dcastil/tailwind-merge) |
|
||||
| `class-variance-authority` | ^0.7.0 | Apache-2.0 | [cva.style](https://cva.style/) |
|
||||
| `clsx` | ^2.1.0 | MIT | [github.com/lukeed/clsx](https://github.com/lukeed/clsx) |
|
||||
| `@radix-ui/react-dialog` | ^1.1.0 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
|
||||
| `@radix-ui/react-slot` | ^1.1.0 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
|
||||
| `@radix-ui/react-switch` | ^1.1.0 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
|
||||
| `@radix-ui/react-tabs` | ^1.1.0 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
|
||||
| `lucide-react` | ^0.460.0 | ISC | [lucide.dev](https://lucide.dev/) |
|
||||
| `sonner` | ^2.0.7 | MIT | [sonner.emilkowal.ski](https://sonner.emilkowal.ski/) |
|
||||
| `react-dropzone` | ^14.3.0 | MIT | [react-dropzone.js.org](https://react-dropzone.js.org/) |
|
||||
| `react` | 19.3.1 | MIT | [react.dev](https://react.dev/) |
|
||||
| `react-dom` | 19.3.1 | MIT | [react.dev](https://react.dev/) |
|
||||
| `react-router` | 8.5.0 | MIT | [reactrouter.com](https://reactrouter.com/) |
|
||||
| `tailwindcss` (devDep) | 4.3.3 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
|
||||
| `tw-animate-css` (devDep) | 1.4.0 | MIT | [github.com/Wombosvideo/tw-animate-css](https://github.com/Wombosvideo/tw-animate-css) |
|
||||
| `tailwind-merge` | 3.7.0 | MIT | [github.com/dcastil/tailwind-merge](https://github.com/dcastil/tailwind-merge) |
|
||||
| `class-variance-authority` | 0.7.1 | Apache-2.0 | [cva.style](https://cva.style/) |
|
||||
| `clsx` | 2.1.1 | MIT | [github.com/lukeed/clsx](https://github.com/lukeed/clsx) |
|
||||
| `@radix-ui/react-dialog` | 1.3.1 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
|
||||
| `@radix-ui/react-slot` | 1.5.0 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
|
||||
| `@radix-ui/react-switch` | 1.4.1 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
|
||||
| `@radix-ui/react-tabs` | 1.2.1 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
|
||||
| `lucide-react` | 1.61.0 | ISC | [lucide.dev](https://lucide.dev/) |
|
||||
| `sonner` | 2.0.8 | MIT | [sonner.emilkowal.ski](https://sonner.emilkowal.ski/) |
|
||||
| `react-dropzone` | 20.1.4 | MIT | [react-dropzone.js.org](https://react-dropzone.js.org/) |
|
||||
|
||||
The component patterns under `src/components/ui/` are generated from
|
||||
**[shadcn/ui](https://ui.shadcn.com/)** (MIT) — copied into the repo, not
|
||||
installed as a runtime dependency.
|
||||
installed as a runtime dependency. `tailwindcss` and `tw-animate-css` are
|
||||
build-time packages whose generated CSS ships in the bundle.
|
||||
|
||||
## Code editor
|
||||
|
||||
| Package | Version | License | Link |
|
||||
|---|---|---|---|
|
||||
| `@uiw/react-codemirror` | ^4.23.0 | MIT | [uiwjs.github.io/react-codemirror](https://uiwjs.github.io/react-codemirror/) |
|
||||
| `@codemirror/state` | ^6.4.0 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/view` | ^6.34.0 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/language` | ^6.10.0 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lang-json` | ^6.0.0 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lang-yaml` | ^6.1.3 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lang-xml` | ^6.1.0 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lang-markdown` | ^6.5.0 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lang-sql` | ^6.10.0 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/legacy-modes` | ^6.5.2 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lint` | ^6.8.0 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@lezer/highlight` | ^1.2.0 | MIT | [lezer.codemirror.net](https://lezer.codemirror.net/) |
|
||||
| `@uiw/react-codemirror` | 4.25.12 | MIT | [uiwjs.github.io/react-codemirror](https://uiwjs.github.io/react-codemirror/) |
|
||||
| `@codemirror/state` | 6.7.6 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/view` | 6.43.15 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/language` | 6.13.1 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lang-json` | 6.0.2 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lang-yaml` | 6.1.3 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lang-xml` | 6.1.0 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lang-markdown` | 6.5.2 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lang-sql` | 6.10.0 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/legacy-modes` | 6.5.5 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@codemirror/lint` | 6.9.7 | MIT | [codemirror.net](https://codemirror.net/) |
|
||||
| `@lezer/highlight` | 1.2.5 | MIT | [lezer.codemirror.net](https://lezer.codemirror.net/) |
|
||||
|
||||
## Parsers / serialization
|
||||
|
||||
| Package | Version | License | Link |
|
||||
|---|---|---|---|
|
||||
| `papaparse` | ^5.4.0 | MIT | [papaparse.com](https://www.papaparse.com/) |
|
||||
| `js-yaml` | ^4.1.0 | MIT | [github.com/nodeca/js-yaml](https://github.com/nodeca/js-yaml) |
|
||||
| `smol-toml` | ^1.3.0 | BSD-3-Clause | [github.com/squirrelchat/smol-toml](https://github.com/squirrelchat/smol-toml) |
|
||||
| `fast-xml-parser` | ^5.8.0 | MIT | [github.com/NaturalIntelligence/fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) |
|
||||
| `bson` | ^7.2.0 | Apache-2.0 | [github.com/mongodb/js-bson](https://github.com/mongodb/js-bson) |
|
||||
| `cbor-x` | ^1.6.4 | MIT | [github.com/kriszyp/cbor-x](https://github.com/kriszyp/cbor-x) |
|
||||
| `@msgpack/msgpack` | ^3.1.3 | ISC | [msgpack.org/javascript](https://msgpack.org/) |
|
||||
| `fflate` | ^0.8.2 | MIT | [github.com/101arrowz/fflate](https://github.com/101arrowz/fflate) |
|
||||
| `papaparse` | 5.7.0 | MIT | [papaparse.com](https://www.papaparse.com/) |
|
||||
| `js-yaml` | 5.5.0 | MIT | [github.com/nodeca/js-yaml](https://github.com/nodeca/js-yaml) |
|
||||
| `smol-toml` | 1.9.1 | BSD-3-Clause | [github.com/squirrelchat/smol-toml](https://github.com/squirrelchat/smol-toml) |
|
||||
| `fast-xml-parser` | 5.11.2 | MIT | [github.com/NaturalIntelligence/fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) |
|
||||
| `bson` | 7.3.3 | Apache-2.0 | [github.com/mongodb/js-bson](https://github.com/mongodb/js-bson) |
|
||||
| `cbor-x` | 1.6.8 | MIT | [github.com/kriszyp/cbor-x](https://github.com/kriszyp/cbor-x) |
|
||||
| `@msgpack/msgpack` | 3.1.3 | ISC | [msgpack.org](https://msgpack.org/) |
|
||||
| `fflate` | 0.8.3 | MIT | [github.com/101arrowz/fflate](https://github.com/101arrowz/fflate) |
|
||||
|
||||
## State & i18n
|
||||
|
||||
| Package | Version | License | Link |
|
||||
|---|---|---|---|
|
||||
| `zustand` | ^5.0.0 | MIT | [github.com/pmndrs/zustand](https://github.com/pmndrs/zustand) |
|
||||
| `i18next` | ^23.0.0 | MIT | [i18next.com](https://www.i18next.com/) |
|
||||
| `react-i18next` | ^15.0.0 | MIT | [react.i18next.com](https://react.i18next.com/) |
|
||||
| `i18next-browser-languagedetector` | ^8.0.0 | MIT | [github.com/i18next/i18next-browser-languageDetector](https://github.com/i18next/i18next-browser-languageDetector) |
|
||||
| `zustand` | 5.0.16 | MIT | [github.com/pmndrs/zustand](https://github.com/pmndrs/zustand) |
|
||||
| `i18next` | 26.5.5 | MIT | [i18next.com](https://www.i18next.com/) |
|
||||
| `react-i18next` | 17.1.1 | MIT | [react.i18next.com](https://react.i18next.com/) |
|
||||
| `i18next-browser-languagedetector` | 8.2.1 | MIT | [github.com/i18next/i18next-browser-languageDetector](https://github.com/i18next/i18next-browser-languageDetector) |
|
||||
|
||||
## Tauri (desktop)
|
||||
## Cloudflare (web build)
|
||||
|
||||
| Package | Version | License | Link |
|
||||
|---|---|---|---|
|
||||
| `@tauri-apps/api` | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-dialog` | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-fs` | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-opener` | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-os` | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/cli` (devDep) | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@marsidev/react-turnstile` | 1.6.3 | MIT | [github.com/marsidev/react-turnstile](https://github.com/marsidev/react-turnstile) |
|
||||
| `wrangler` (devDep) | 4.151.3 | MIT OR Apache-2.0 | [github.com/cloudflare/workers-sdk](https://github.com/cloudflare/workers-sdk) |
|
||||
|
||||
### Rust crates (`src-tauri/Cargo.toml`)
|
||||
`@marsidev/react-turnstile` renders the Turnstile widget on the website
|
||||
only. `wrangler` runs, type-checks and deploys the Worker in `worker/`.
|
||||
The services themselves are covered under
|
||||
[Third-party services](#third-party-services-web-build-only).
|
||||
|
||||
## Tauri (desktop and Android)
|
||||
|
||||
| Package | Version | License | Link |
|
||||
|---|---|---|---|
|
||||
| `@tauri-apps/api` | 2.12.4 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-dialog` | 2.8.3 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-fs` | 2.7.1 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-opener` | 2.7.2 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/cli` (devDep) | 2.12.4 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
|
||||
### Rust crates (`src-tauri/Cargo.lock`)
|
||||
|
||||
| Crate | Version | License | Link |
|
||||
|---|---|---|---|
|
||||
| `tauri` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri](https://crates.io/crates/tauri) |
|
||||
| `tauri-build` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-build](https://crates.io/crates/tauri-build) |
|
||||
| `tauri-plugin-dialog` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-dialog](https://crates.io/crates/tauri-plugin-dialog) |
|
||||
| `tauri-plugin-fs` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-fs](https://crates.io/crates/tauri-plugin-fs) |
|
||||
| `tauri-plugin-opener` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-opener](https://crates.io/crates/tauri-plugin-opener) |
|
||||
| `tauri-plugin-os` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-os](https://crates.io/crates/tauri-plugin-os) |
|
||||
| `tauri-plugin-single-instance` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-single-instance](https://crates.io/crates/tauri-plugin-single-instance) |
|
||||
| `serde` | 1 | Apache-2.0 OR MIT | [serde.rs](https://serde.rs/) |
|
||||
| `serde_json` | 1 | Apache-2.0 OR MIT | [github.com/serde-rs/json](https://github.com/serde-rs/json) |
|
||||
| `tauri` | 2.12.5 | Apache-2.0 OR MIT | [crates.io/crates/tauri](https://crates.io/crates/tauri) |
|
||||
| `tauri-build` (build dependency) | 2.7.4 | Apache-2.0 OR MIT | [crates.io/crates/tauri-build](https://crates.io/crates/tauri-build) |
|
||||
| `tauri-plugin-dialog` | 2.8.3 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-dialog](https://crates.io/crates/tauri-plugin-dialog) |
|
||||
| `tauri-plugin-fs` | 2.7.1 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-fs](https://crates.io/crates/tauri-plugin-fs) |
|
||||
| `tauri-plugin-opener` | 2.7.2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-opener](https://crates.io/crates/tauri-plugin-opener) |
|
||||
| `tauri-plugin-single-instance` (desktop only) | 2.5.4 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-single-instance](https://crates.io/crates/tauri-plugin-single-instance) |
|
||||
| `serde` | 1.0.229 | MIT OR Apache-2.0 | [serde.rs](https://serde.rs/) |
|
||||
| `serde_json` | 1.0.154 | MIT OR Apache-2.0 | [github.com/serde-rs/json](https://github.com/serde-rs/json) |
|
||||
|
||||
## Build tooling
|
||||
|
||||
Development dependencies: used to build, lint and test JSONPrism, not
|
||||
shipped in the app.
|
||||
|
||||
| Package | Version | License | Link |
|
||||
|---|---|---|---|
|
||||
| `vite` | ^8.0.0 | MIT | [vite.dev](https://vite.dev/) |
|
||||
| `@vitejs/plugin-react` | ^6.0.0 | MIT | [github.com/vitejs/vite-plugin-react](https://github.com/vitejs/vite-plugin-react) |
|
||||
| `@tailwindcss/vite` | ^4.0.0 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
|
||||
| `typescript` | ^5.7.0 | Apache-2.0 | [typescriptlang.org](https://www.typescriptlang.org/) |
|
||||
| `eslint` | ^9.15.0 | MIT | [eslint.org](https://eslint.org/) |
|
||||
| `typescript-eslint` | ^8.15.0 | MIT, BSD-2-Clause | [typescript-eslint.io](https://typescript-eslint.io/) |
|
||||
| `eslint-plugin-react-hooks` | ^5.0.0 | MIT | [github.com/facebook/react](https://github.com/facebook/react) |
|
||||
| `eslint-plugin-react-refresh` | ^0.4.0 | MIT | [github.com/ArnaudBarre/eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) |
|
||||
| `prettier` | ^3.4.0 | MIT | [prettier.io](https://prettier.io/) |
|
||||
| `prettier-plugin-tailwindcss` | ^0.6.0 | MIT | [github.com/tailwindlabs/prettier-plugin-tailwindcss](https://github.com/tailwindlabs/prettier-plugin-tailwindcss) |
|
||||
| `vitest` | ^4.1.6 | MIT | [vitest.dev](https://vitest.dev/) |
|
||||
| `@vitest/coverage-v8` | ^4.1.6 | MIT | [vitest.dev](https://vitest.dev/) |
|
||||
| `@testing-library/react` | ^16.1.0 | MIT | [testing-library.com](https://testing-library.com/) |
|
||||
| `@testing-library/jest-dom` | ^6.6.0 | MIT | [testing-library.com](https://testing-library.com/) |
|
||||
| `@testing-library/user-event` | ^14.5.0 | MIT | [testing-library.com](https://testing-library.com/) |
|
||||
| `jsdom` | ^29.0.0 | MIT | [github.com/jsdom/jsdom](https://github.com/jsdom/jsdom) |
|
||||
| `knip` | ^6.14.1 | ISC | [knip.dev](https://knip.dev/) |
|
||||
| `globals` | ^14.0.0 | MIT | [github.com/sindresorhus/globals](https://github.com/sindresorhus/globals) |
|
||||
| `vite` | 8.3.5 | MIT | [vite.dev](https://vite.dev/) |
|
||||
| `@vitejs/plugin-react` | 6.1.2 | MIT | [github.com/vitejs/vite-plugin-react](https://github.com/vitejs/vite-plugin-react) |
|
||||
| `@tailwindcss/vite` | 4.3.3 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
|
||||
| `@typescript/native` (alias of `typescript@^7`) | 7.0.2 | Apache-2.0 | [typescriptlang.org](https://www.typescriptlang.org/) |
|
||||
| `typescript` (alias of `@typescript/typescript6`, wraps TypeScript 6.0.3) | 6.0.2 | Apache-2.0 | [typescriptlang.org](https://www.typescriptlang.org/) |
|
||||
| `eslint` | 10.13.0 | MIT | [eslint.org](https://eslint.org/) |
|
||||
| `@eslint/js` | 10.0.1 | MIT | [eslint.org](https://eslint.org/) |
|
||||
| `typescript-eslint` | 8.72.0 | MIT | [typescript-eslint.io](https://typescript-eslint.io/) |
|
||||
| `eslint-plugin-react-hooks` | 7.1.1 | MIT | [github.com/facebook/react](https://github.com/facebook/react) |
|
||||
| `eslint-plugin-react-refresh` | 0.5.7 | MIT | [github.com/ArnaudBarre/eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) |
|
||||
| `globals` | 17.13.0 | MIT | [github.com/sindresorhus/globals](https://github.com/sindresorhus/globals) |
|
||||
| `prettier` | 3.9.10 | MIT | [prettier.io](https://prettier.io/) |
|
||||
| `prettier-plugin-tailwindcss` | 0.8.1 | MIT | [github.com/tailwindlabs/prettier-plugin-tailwindcss](https://github.com/tailwindlabs/prettier-plugin-tailwindcss) |
|
||||
| `knip` | 6.42.1 | ISC | [knip.dev](https://knip.dev/) |
|
||||
| `vitest` | 5.0.5 | MIT | [vitest.dev](https://vitest.dev/) |
|
||||
| `@vitest/coverage-v8` | 5.0.5 | MIT | [vitest.dev](https://vitest.dev/) |
|
||||
| `jsdom` | 30.1.3 | MIT | [github.com/jsdom/jsdom](https://github.com/jsdom/jsdom) |
|
||||
| `@testing-library/react` | 16.3.3 | MIT | [testing-library.com](https://testing-library.com/) |
|
||||
| `@testing-library/dom` | 10.4.2 | MIT | [testing-library.com](https://testing-library.com/) |
|
||||
| `@testing-library/jest-dom` | 7.0.1 | MIT | [testing-library.com](https://testing-library.com/) |
|
||||
| `@testing-library/user-event` | 14.6.8 | MIT | [testing-library.com](https://testing-library.com/) |
|
||||
| `@types/node` | 26.6.5 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
|
||||
| `@types/papaparse` | 5.5.2 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
|
||||
| `@types/react` | 19.3.0 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
|
||||
| `@types/react-dom` | 19.3.0 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
|
||||
|
||||
## Fonts
|
||||
|
||||
Served via Google Fonts on the web build, inlined into Tauri build:
|
||||
Both fonts are self-hosted: the [Fontsource](https://fontsource.org/)
|
||||
packages below bundle the font files into the build, so neither the
|
||||
website nor the apps request fonts from Google Fonts or any other CDN.
|
||||
|
||||
- **Geist** — SIL Open Font License 1.1 — [vercel.com/font](https://vercel.com/font)
|
||||
- **Instrument Serif** — SIL Open Font License 1.1 — [github.com/Instrument/instrument-serif](https://github.com/Instrument/instrument-serif)
|
||||
- **JetBrains Mono** — SIL Open Font License 1.1 — [jetbrains.com/lp/mono](https://www.jetbrains.com/lp/mono/)
|
||||
| Package | Version | License | Link |
|
||||
|---|---|---|---|
|
||||
| `@fontsource-variable/geist` | 5.3.0 | OFL-1.1 | [fontsource.org/fonts/geist](https://fontsource.org/fonts/geist) |
|
||||
| `@fontsource-variable/jetbrains-mono` | 5.3.0 | OFL-1.1 | [fontsource.org/fonts/jetbrains-mono](https://fontsource.org/fonts/jetbrains-mono) |
|
||||
|
||||
- **Geist** (headings and body text) — SIL Open Font License 1.1 — [vercel.com/font](https://vercel.com/font)
|
||||
- **JetBrains Mono** (code and labels) — SIL Open Font License 1.1 — [jetbrains.com/lp/mono](https://www.jetbrains.com/lp/mono/)
|
||||
|
||||
## Third-party services (web build only)
|
||||
|
||||
The website at <https://jsonprism.poli0981.dev> uses the Cloudflare
|
||||
services below. The desktop (Windows, macOS, Linux) and Android apps don't
|
||||
include any of them. The JSON you convert never reaches them: conversion
|
||||
runs on your device.
|
||||
|
||||
| Service | What JSONPrism uses it for | What it processes | Documentation |
|
||||
|---|---|---|---|
|
||||
| **Cloudflare Workers** | Hosting: serves the site from `dist/` and runs the small Worker in `worker/` for `/api/*` (Turnstile verification, health check). | Standard request data (IP address, user agent, requested URL) to deliver and protect the site. The Worker's own logs contain no IP addresses, tokens or user content. | [developers.cloudflare.com/workers](https://developers.cloudflare.com/workers/) |
|
||||
| **Cloudflare Turnstile** | Human check inside the first-launch consent screen, verified server-side by the Worker. A pass is remembered on the device for 7 days. | Browser signals collected by Cloudflare's widget script to tell people from bots. The Worker does not send the visitor's IP address when it verifies a token. | [developers.cloudflare.com/turnstile](https://developers.cloudflare.com/turnstile/) · [Turnstile Privacy Addendum](https://www.cloudflare.com/turnstile-privacy-policy/) |
|
||||
| **Cloudflare Web Analytics** | Cookieless page-view counts. Loaded only on the production site, only after the consent screen is accepted, and only while *Appearance → Anonymous usage analytics* is on (off by default when the browser sends Global Privacy Control). | Page path, referrer, browser and device type, and load-performance timings. No cookies or local storage; never editor content. | [developers.cloudflare.com/web-analytics](https://developers.cloudflare.com/web-analytics/) |
|
||||
|
||||
Cloudflare processes this data under the
|
||||
[Cloudflare Privacy Policy](https://www.cloudflare.com/privacypolicy/).
|
||||
How JSONPrism itself handles data is described in [PRIVACY.md](PRIVACY.md).
|
||||
|
||||
## Icon
|
||||
|
||||
@@ -139,8 +187,19 @@ The JSONPrism brand icon at `src-tauri/icons/icon.svg` is original
|
||||
artwork by Kokone, licensed under the same Apache 2.0 terms as the rest
|
||||
of the project.
|
||||
|
||||
## Acknowledgements
|
||||
## AI assistance
|
||||
|
||||
Substantial portions of JSONPrism's code, tests, translations, and docs
|
||||
were drafted with **Claude Chat** + **Claude Code (Opus 4.7, 1M
|
||||
context)** from Anthropic. See [DISCLAIMER.md](DISCLAIMER.md).
|
||||
were drafted with AI assistance from Anthropic: **Claude Chat** +
|
||||
**Claude Code** with Claude Opus 4.7 and 4.8 for the 1.x releases, and
|
||||
**Claude Code** with Claude Opus 5.5 for 2.0.0. The Japanese and Simplified
|
||||
Chinese translations, and parts of the Vietnamese one, are AI-generated.
|
||||
The maintainer reviews every change before it is merged. See
|
||||
[DISCLAIMER.md](DISCLAIMER.md).
|
||||
|
||||
## Copyright and takedown
|
||||
|
||||
If you believe JSONPrism uses your work without a compatible license or
|
||||
proper attribution, or a notice on this page is missing or wrong, write to
|
||||
**copyright@poli0981.dev**. [TERMS.md](TERMS.md) describes what to include
|
||||
in a copyright complaint.
|
||||
@@ -0,0 +1,356 @@
|
||||
# Deployment
|
||||
|
||||
Maintainer guide for the web app at https://jsonprism.poli0981.dev and for the
|
||||
desktop / Android releases. Contributors don't need any of this: local setup is
|
||||
in [dev_env.md](dev_env.md), Tauri details in [TAURI-NOTES.md](TAURI-NOTES.md).
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Task | How |
|
||||
| --- | --- |
|
||||
| Deploy the web app | Merge or push to `main`. Cloudflare Workers Builds deploys it. |
|
||||
| Check a deploy | GitHub Actions → **Production smoke** (runs on every push to `main`). |
|
||||
| Roll back the web app | Dashboard → `jsonprism` Worker → **Deployments**, or `npx wrangler rollback`. |
|
||||
| Preview locally | `npm run preview:cf` → http://localhost:8787 |
|
||||
| Rotate the Turnstile secret | Rotate it on the widget, then update `TURNSTILE_SECRET` on the Worker. |
|
||||
| Ship desktop + Android builds | Bump the versions, push a `vX.Y.Z` tag, publish the draft release. |
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
browser ──► jsonprism.poli0981.dev (Cloudflare Worker "jsonprism")
|
||||
├─ /api/* → worker/index.ts ──► Turnstile siteverify
|
||||
└─ everything → static assets from dist/
|
||||
else (_headers, _redirects, SPA fallback to index.html)
|
||||
```
|
||||
|
||||
- One Cloudflare Worker, **`jsonprism`** (Workers Paid plan), configured in
|
||||
`wrangler.jsonc`.
|
||||
- **Static assets**: the Vite build in `dist/`, served by Workers Static Assets
|
||||
with `not_found_handling: "single-page-application"`.
|
||||
- **Worker code** runs only for `/api/*` (`run_worker_first: ["/api/*"]`).
|
||||
Conversion never happens on the server.
|
||||
|
||||
| Route | Code | Response |
|
||||
| --- | --- | --- |
|
||||
| `POST /api/turnstile/verify` | `worker/verify.ts`, `worker/turnstile.ts` | Verifies a Turnstile token — see [Turnstile](#turnstile). |
|
||||
| `GET /api/health` | `worker/index.ts` | `{"ok":true,"service":"jsonprism"}` |
|
||||
| any other `/api/*` | `worker/index.ts` | JSON 404 |
|
||||
|
||||
- `worker/index.ts` may only have a default export: workerd treats every named
|
||||
export of the entry module as an entrypoint. Put helpers in other modules.
|
||||
- API responses set their own headers (`worker/http.ts`: `no-store`,
|
||||
`nosniff`, `default-src 'none'`); assets get theirs from `public/_headers`.
|
||||
- The Worker has its own `tsconfig.worker.json`; its runtime and binding types
|
||||
come from `npm run cf:types` (`wrangler types` → gitignored
|
||||
`worker-configuration.d.ts`).
|
||||
- `compatibility_date` is pinned in `wrangler.jsonc`; move it deliberately and
|
||||
test with `npm run preview:cf`.
|
||||
|
||||
## Workers Builds (automatic deploys)
|
||||
|
||||
Configured in the Cloudflare dashboard (the `jsonprism` Worker →
|
||||
**Settings → Build**), not in the repo:
|
||||
|
||||
| Setting | Value |
|
||||
| --- | --- |
|
||||
| Repository | `poli0981/jsonPrism` |
|
||||
| Production branch | `main` |
|
||||
| Build command | `npm run build` (may also be empty) |
|
||||
| Deploy command | `npx wrangler deploy` |
|
||||
| Non-production branch deploy command | `npx wrangler preview` |
|
||||
| Root directory | repository root |
|
||||
| Node.js | 26, from `.nvmrc` or the `NODE_VERSION` build variable |
|
||||
|
||||
- `wrangler.jsonc` → `build.command` runs `npm run build` before every
|
||||
`wrangler deploy`, `preview` and `dev`, so a deploy works even with no build
|
||||
command in the dashboard (setting one only builds twice).
|
||||
- Workers Builds installs dependencies with `npm clean-install` using its own
|
||||
npm (10.9.2 at the time of writing). The lockfile must stay installable with
|
||||
that npm: a peer-dependency conflict fails the build at the install step
|
||||
(this kept `main` undeployable before 2.0.0).
|
||||
|
||||
### Previews (pull requests and other branches)
|
||||
|
||||
Non-production branches run `npx wrangler preview`, which publishes a
|
||||
[Worker Preview](https://developers.cloudflare.com/workers/previews/) named
|
||||
after the branch (`<branch>-jsonprism.<subdomain>.workers.dev` when workers.dev
|
||||
is enabled) and reports it on the pull request.
|
||||
|
||||
- Previews inherit no production vars or bindings. `wrangler.jsonc` → `previews`
|
||||
declares them again: a separate rate-limit counter (`namespace_id` 4202) and
|
||||
an empty `ALLOWED_HOSTNAMES`. Any binding added at the top level needs a
|
||||
preview-safe twin there, or `wrangler preview` fails with "missing a
|
||||
`previews` block".
|
||||
- Previews get no `TURNSTILE_SECRET` (set one with
|
||||
`npx wrangler preview base-config secret put` only if you need the check on
|
||||
previews), and the production sitekey doesn't run on preview hostnames, so
|
||||
the human check reports "unavailable" and testers continue past it. Web
|
||||
Analytics never loads there.
|
||||
|
||||
- Every push to `main` builds and deploys. No GitHub Action deploys the web
|
||||
app, and GitHub holds no Cloudflare credentials.
|
||||
- The build stamps the short commit (`WORKERS_CI_COMMIT_SHA`) into
|
||||
`<meta name="jsonprism-commit">` and the header's version chip; the smoke
|
||||
workflow uses it to recognise the new deploy.
|
||||
- A failed build leaves the previous version live. Build logs exist only in the
|
||||
dashboard (the Worker's build history).
|
||||
- Changes to `wrangler.jsonc` (route, vars, bindings) apply on the next deploy.
|
||||
CI's `npm run cf:check` (`wrangler deploy --dry-run`) catches config and
|
||||
bundling errors before merge.
|
||||
|
||||
## Custom domain
|
||||
|
||||
- `routes: [{ "pattern": "jsonprism.poli0981.dev", "custom_domain": true }]`:
|
||||
Cloudflare manages the DNS record and certificate for the hostname. The
|
||||
`poli0981.dev` zone is on the same account.
|
||||
- `workers_dev: false` — there is no `*.workers.dev` URL.
|
||||
- Changing the hostname touches more than the route. Search the repo for
|
||||
`jsonprism.poli0981.dev` (`wrangler.jsonc` route and `ALLOWED_HOSTNAMES`,
|
||||
`src/lib/analytics.ts`, `src/lib/links.ts`, `index.html`, `public/`,
|
||||
`.github/pages-redirect/`, the workflows, the legal docs), then update the
|
||||
Turnstile widget's hostnames and the Web Analytics site in the dashboard.
|
||||
|
||||
## Secrets and variables
|
||||
|
||||
| Name | Kind | Where |
|
||||
| --- | --- | --- |
|
||||
| `TURNSTILE_SECRET` | Secret | Worker → **Settings → Variables and Secrets**, or `npx wrangler secret put TURNSTILE_SECRET`. Never in the repo. |
|
||||
| `ALLOWED_HOSTNAMES` | Variable | `wrangler.jsonc` → `vars`: comma-separated hostnames a Turnstile token may be issued on. |
|
||||
| `VERIFY_LIMITER` | Binding | `wrangler.jsonc` → `ratelimits` — see [Rate limiting](#rate-limiting). |
|
||||
|
||||
- Plain variables added in the dashboard are replaced by `wrangler.jsonc` `vars`
|
||||
on every deploy (`keep_vars` is off); secrets are kept. The sitekey needs no
|
||||
Worker variable — it is compiled into the frontend.
|
||||
- Without `TURNSTILE_SECRET`, `/api/turnstile/verify` answers 503 and Workers
|
||||
Logs record `outcome: "misconfigured"`; a wrong secret also gives 503
|
||||
(`detail: "misconfigured-secret"`). Users can still continue past the check,
|
||||
so nothing looks broken — watch the logs after changing it.
|
||||
- Locally, `.dev.vars` (copied from `.dev.vars.example`) holds Cloudflare's
|
||||
always-pass test secret. With it the Worker also accepts loopback and plain
|
||||
`http` origins, because `wrangler dev` rewrites the request URL and `Origin`
|
||||
to the route host. That secret proves nothing, so nothing is lost.
|
||||
|
||||
## Turnstile
|
||||
|
||||
- **Widget**: Cloudflare dashboard → **Turnstile** → the JSONPrism widget. The
|
||||
sitekey `0x4AAAAAAFgqIzSPBs9hZJnX` is public by design and lives in
|
||||
`src/lib/turnstile.ts`; its secret is `TURNSTILE_SECRET`.
|
||||
- **Hostname management**: the widget's hostname list must contain
|
||||
`jsonprism.poli0981.dev` — keep it in step with `ALLOWED_HOSTNAMES`. Localhost
|
||||
doesn't need to be listed: on `localhost` / `127.0.0.1` the app uses
|
||||
Cloudflare's test sitekey instead.
|
||||
- **What the Worker checks**: an HTTPS `Origin` from an allowed hostname,
|
||||
`Content-Type: application/json`, a body of at most 4 KB, the rate limit,
|
||||
then Cloudflare siteverify (8 s timeout, one retry with the same idempotency
|
||||
key; the visitor IP is not sent). Tokens are rejected when their hostname is
|
||||
not allowed, their action is not `gate`, or they are older than 300 s.
|
||||
- **Responses**: 200 verified (with `verifiedUntil`, 7 days ahead) · 400 bad
|
||||
JSON or token · 403 foreign origin or rejected token · 405 not POST · 413
|
||||
body too large · 415 not JSON · 429 rate limited · 503 secret missing or
|
||||
Cloudflare unreachable.
|
||||
- **Client behaviour**: a pass is remembered for 7 days (`jsonprism.humanCheck`
|
||||
in localStorage). 400/403 keep the Consent Gate closed; anything else
|
||||
(offline, blocked script, 429, 5xx, timeout) lets the user continue after a
|
||||
warning, because conversion never needs the network.
|
||||
- **Rotating the secret**: rotate it on the widget, then update
|
||||
`TURNSTILE_SECRET` on the Worker straight away.
|
||||
|
||||
## Web Analytics
|
||||
|
||||
- Cloudflare dashboard → **Web Analytics** → site `jsonprism.poli0981.dev`.
|
||||
Token `f1f718464e5a417997c84170ddbec2b6` (public, in `src/lib/analytics.ts`).
|
||||
- **Manual beacon**: the app adds `beacon.min.js` itself, and only when all of
|
||||
these hold — production hostname, Consent Gate accepted, "Anonymous usage
|
||||
analytics" on in the Appearance menu (on by default, off by default when the
|
||||
browser sends Global Privacy Control). Never in desktop or Android builds,
|
||||
local previews or dev.
|
||||
- **Keep automatic injection OFF** in the site's Web Analytics settings.
|
||||
Automatic setup adds the beacon to every page before consent and ignores the
|
||||
user's setting.
|
||||
- The CSP already allows `static.cloudflareinsights.com` (script) and
|
||||
`cloudflareinsights.com` (reports).
|
||||
|
||||
## Zone settings to keep off
|
||||
|
||||
These zone features rewrite HTML or inject scripts the app doesn't expect; with
|
||||
the strict CSP they break pages or fill the console with violations. Keep them
|
||||
off for `poli0981.dev` (or at least for this hostname):
|
||||
|
||||
| Setting | Why |
|
||||
| --- | --- |
|
||||
| Rocket Loader | Rewrites the app's `<script>` tags and runs them through its own loader. |
|
||||
| Email Address Obfuscation | Rewrites email addresses and injects a decoder script. |
|
||||
| Web Analytics automatic injection | Loads the beacon without consent; the app loads it itself. |
|
||||
|
||||
HTML is also served with `Cache-Control: no-cache, no-transform`
|
||||
(`public/_headers`) so Cloudflare shouldn't rewrite it, but don't rely on that
|
||||
alone. Recheck these settings after any zone-wide change.
|
||||
|
||||
## Static headers and redirects
|
||||
|
||||
Vite copies `public/` into `dist/`; Workers Static Assets applies `_headers` and
|
||||
`_redirects` to asset responses.
|
||||
|
||||
`public/_headers`:
|
||||
|
||||
| Header | Value |
|
||||
| --- | --- |
|
||||
| `Content-Security-Policy` | `default-src 'self'`; scripts from self, `static.cloudflareinsights.com` and `challenges.cloudflare.com`; `connect-src` self + `cloudflareinsights.com`; `frame-src` Turnstile; `worker-src 'self'`; `object-src 'none'`, `base-uri 'self'`, `form-action 'self'`, `frame-ancestors 'none'`, `upgrade-insecure-requests`. `style-src` keeps `'unsafe-inline'` (CodeMirror, Radix and Sonner inject styles at runtime). |
|
||||
| `Strict-Transport-Security` | `max-age=31536000`, deliberately without `includeSubDomains` |
|
||||
| `X-Content-Type-Options`, `X-Frame-Options` | `nosniff`, `DENY` |
|
||||
| `Referrer-Policy` | `strict-origin-when-cross-origin` |
|
||||
| `Permissions-Policy` | camera, microphone, geolocation, motion sensors, payment, USB and Topics all disabled |
|
||||
| `Cross-Origin-Opener-Policy` | `same-origin` |
|
||||
| `Cache-Control` | HTML `no-cache, no-transform`; `/assets/*` `public, max-age=31536000, immutable` (hashed file names) |
|
||||
|
||||
- A new third-party script, frame or connection needs a CSP change here; check
|
||||
the console in `npm run preview:cf` afterwards. The desktop CSP is separate
|
||||
(`tauri.conf.json`) and stays free of third-party hosts.
|
||||
- `public/_redirects`: `/jsonPrism` and `/jsonPrism/*` → 301 to the same path
|
||||
without the old GitHub Pages prefix.
|
||||
- Also in `public/`: `robots.txt`, `sitemap.xml` (update `lastmod` when pages
|
||||
change), `.well-known/security.txt` (**expires 2027-10-01 — renew it before
|
||||
then**), `og-image.png`, and `theme-init.js` (applies the theme before first
|
||||
paint without an inline script).
|
||||
|
||||
## Rate limiting
|
||||
|
||||
- Binding `VERIFY_LIMITER` (`ratelimits` in `wrangler.jsonc`, `namespace_id`
|
||||
`4201`): 30 requests per 60 s per client, keyed on `CF-Connecting-IP`. The IP
|
||||
is only the key; it is never logged.
|
||||
- Over the limit → 429 `rate_limited` with `Retry-After: 60`. The app treats
|
||||
that as "check unavailable" and lets the user continue.
|
||||
- To change it, edit `simple.limit` / `simple.period` and deploy. Keep
|
||||
`namespace_id` unique within the Cloudflare account.
|
||||
|
||||
## Workers Logs
|
||||
|
||||
- `observability.enabled: true`, `head_sampling_rate: 1` (every request). Read
|
||||
them in the dashboard (the Worker's logs / observability view) or live with
|
||||
`npx wrangler tail`.
|
||||
- The verify endpoint writes one structured line per request:
|
||||
`{"event":"turnstile.verify","outcome":…,"status":…,"colo":…,"ms":…}`, plus
|
||||
`codes` for rejections and `detail` when Cloudflare was unavailable.
|
||||
Outcomes: `verified`, `rejected`, `bad-origin`, `bad-method`,
|
||||
`bad-content-type`, `too-large`, `rate-limited`, `bad-json`, `bad-token`,
|
||||
`misconfigured`, `unavailable`.
|
||||
- Never log IPs, tokens or user content (`logEvent()` in `worker/http.ts`).
|
||||
Source maps are not uploaded (`upload_source_maps: false`).
|
||||
|
||||
## Local preview
|
||||
|
||||
```bash
|
||||
cp .dev.vars.example .dev.vars # once
|
||||
npm run preview:cf # wrangler dev (builds first) → http://localhost:8787
|
||||
```
|
||||
|
||||
- Serves `dist/` with `_headers`, `_redirects` and the SPA fallback, plus the
|
||||
Worker — the closest thing to production. Turnstile uses the test sitekey and
|
||||
passes on its own; Web Analytics never loads (wrong hostname).
|
||||
- `npm run cf:check` is CI's deploy dry run; `npm run cf:types` regenerates
|
||||
the Worker types after binding changes.
|
||||
|
||||
## Production smoke
|
||||
|
||||
`.github/workflows/production-smoke.yml` runs on every push to `main` and on
|
||||
demand:
|
||||
|
||||
1. Waits up to 15 minutes for https://jsonprism.poli0981.dev/ to serve
|
||||
`<meta name="jsonprism-commit">` with the pushed commit (skipped on manual
|
||||
runs).
|
||||
2. Checks the CSP, HSTS, `nosniff` and `X-Frame-Options` headers; `/about` → 200
|
||||
(SPA fallback); `/jsonPrism/about` → 301 to `/about`; `/api/health`; the
|
||||
`security.txt` contact; and that `/api/turnstile/verify` answers 403 to a
|
||||
foreign `Origin`.
|
||||
|
||||
Failures reach Discord through `notify-ci-failure.yml`. When the wait step times
|
||||
out, check the build in the Cloudflare dashboard first. Run the workflow by hand
|
||||
after a rollback or a dashboard change.
|
||||
|
||||
## Rollback
|
||||
|
||||
- **Dashboard**: the `jsonprism` Worker → **Deployments** → the last good
|
||||
version → **Rollback**.
|
||||
- **CLI**: `npx wrangler deployments list`, then
|
||||
`npx wrangler rollback [version-id] -m "reason"` (without an ID it goes back
|
||||
to the previous version). Needs `npx wrangler login` with access to the
|
||||
account.
|
||||
- A rollback doesn't touch `main`: revert the bad commit too, or the next push
|
||||
deploys it again. Then run **Production smoke** by hand.
|
||||
|
||||
## GitHub Pages redirect
|
||||
|
||||
- https://poli0981.github.io/jsonPrism/ serves only
|
||||
`.github/pages-redirect/index.html` and `404.html` (identical): a script that
|
||||
drops the `/jsonPrism` prefix and keeps the rest of the path, the query and
|
||||
the hash; a 3-second meta refresh to the home page when JavaScript is off;
|
||||
`noindex`.
|
||||
- Deploy it by hand — Actions → **Pages redirect** → Run workflow — and only
|
||||
after changing `.github/pages-redirect/`. Repository Settings → Pages →
|
||||
Source must stay **GitHub Actions**.
|
||||
- Keep it online: old links in YouTube descriptions, Discord and READMEs point
|
||||
there.
|
||||
|
||||
## SonarQube Cloud
|
||||
|
||||
- Organization `poli0981`, project key `poli0981_jsonPrism`, settings in
|
||||
`sonar-project.properties`.
|
||||
- CI-based analysis: job `sonar` in `ci.yml` runs after `web` with the
|
||||
`SONAR_TOKEN` repository secret and the coverage artifact
|
||||
(`coverage/lcov.info`).
|
||||
- **Automatic Analysis must stay OFF** (SonarQube Cloud → project →
|
||||
Administration → Analysis Method); with it on, the CI scan fails.
|
||||
- Without `SONAR_TOKEN` (Dependabot and fork PRs) the job skips instead of
|
||||
failing. The quality gate is reported, not enforced
|
||||
(`sonar.qualitygate.wait=false`).
|
||||
- CodeQL runs through GitHub's default setup (no workflow file).
|
||||
|
||||
## Releases (desktop + Android)
|
||||
|
||||
The web app ships continuously from `main`; tags are for the desktop and
|
||||
Android builds.
|
||||
|
||||
1. **Bump the version** on `main`:
|
||||
- `npm version X.Y.Z --no-git-tag-version` — updates `package.json` and
|
||||
`package-lock.json`; `tauri.conf.json` reads its version from
|
||||
`package.json`.
|
||||
- `version` in `src-tauri/Cargo.toml`, then refresh `Cargo.lock` (e.g.
|
||||
`cargo check` in `src-tauri/`) — CI runs clippy with `--locked`.
|
||||
- `bundle.android.versionCode` in `src-tauri/tauri.conf.json`:
|
||||
`MAJOR*10000 + MINOR*100 + PATCH` (2.0.0 → 20000).
|
||||
- `CHANGELOG.md`.
|
||||
2. **Tag** the merged commit (signed, like earlier tags) and push the tag:
|
||||
|
||||
```bash
|
||||
git tag -s vX.Y.Z -m "JSONPrism vX.Y.Z"
|
||||
git push origin vX.Y.Z
|
||||
```
|
||||
|
||||
3. **`release.yml`** checks tag = `package.json` = `Cargo.toml`, runs the
|
||||
tests, creates one draft release, builds Windows (`.msi`, NSIS `.exe`),
|
||||
macOS universal (`.dmg`, `.app.tar.gz`), Linux (`.deb`, `.rpm`, `.AppImage`)
|
||||
and the signed Android APK (`JSONPrism_<version>_android-universal.apk`),
|
||||
then adds `SHA256SUMS.txt` and build-provenance attestations. Details in
|
||||
[TAURI-NOTES.md](TAURI-NOTES.md#release-workflow).
|
||||
4. **Review the draft** (every asset present, notes taken from the changelog),
|
||||
then **Publish**. Publishing triggers `announce-release.yml` (Discord) and
|
||||
`announce-discussion.yml` (Discussions → Announcements).
|
||||
5. **Rebuild a tag**: Actions → **Release Tauri bundles** → Run workflow with
|
||||
the tag. It reuses the draft and refuses once the release is published.
|
||||
|
||||
The bundles are not code-signed yet, so Windows SmartScreen and macOS
|
||||
Gatekeeper warn on first launch.
|
||||
|
||||
### Repository secrets
|
||||
|
||||
| Secret | Used by |
|
||||
| --- | --- |
|
||||
| `SONAR_TOKEN` | `ci.yml` (job `sonar`) |
|
||||
| `ANDROID_KEYSTORE_BASE64`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_PASSWORD`, `ANDROID_KEY_ALIAS` | `release.yml` (job `android`) — see [TAURI-NOTES.md](TAURI-NOTES.md#ci-signing-secrets) |
|
||||
| `DISCORD_RELEASES_WEBHOOK`, `DISCORD_REPO_WEBHOOK`, `DISCORD_PING_ROLE_ID` | `announce-release.yml` |
|
||||
| `DISCORD_CI_WEBHOOK` | `notify-ci-failure.yml` (CI and Production smoke failures) |
|
||||
| `DISCORD_RELEASE_PIPELINE_WEBHOOK` | `notify-release-pipeline.yml` |
|
||||
|
||||
The Discord workflows call reusable workflows from `poli0981/.github`, pinned
|
||||
to a commit, and receive only these secrets (no `secrets: inherit`).
|
||||
+17
-6
@@ -95,7 +95,7 @@ You now have flat objects like:
|
||||
2. Drop or paste `strings.en.flat.json` into the input panel
|
||||
3. The format picker highlights **RESX** (a flat object is its native shape)
|
||||
4. Click **RESX**
|
||||
5. (Optional) Open the settings panel — enable **Sort entries alphabetically** if you want stable diffs
|
||||
5. (Optional) Open the settings panel — enable **Sort entries alphabetically** if you want stable diffs (ordinal order, so the result is the same on every machine)
|
||||
6. Click **Download** → you get `output.resx`
|
||||
7. Rename to match your .NET project convention, e.g. `Strings.resx` or `Resources.resx`
|
||||
|
||||
@@ -154,16 +154,27 @@ Change the comment key in the settings panel if your convention is different (e.
|
||||
## Round-trip safety notes
|
||||
|
||||
- **Special characters**: `&`, `<`, `>` are XML-escaped automatically in values; `"` is also escaped in `name=` attributes. You don't need to pre-escape.
|
||||
- **Whitespace**: `<data>` elements get `xml:space="preserve"`, so leading/trailing spaces in values survive.
|
||||
- **Line endings**: a carriage return is written as `
`, so CRLF text survives a round trip (XML parsers would otherwise turn CRLF into LF). In `name=` attributes, tabs and line breaks are encoded as well.
|
||||
- **Control characters**: characters XML 1.0 cannot carry at all (C0 controls other than tab, LF and CR, plus U+FFFE / U+FFFF) are replaced with U+FFFD.
|
||||
- **Whitespace**: `<data>` elements get `xml:space="preserve"`, so leading/trailing spaces in values survive — in both directions.
|
||||
- **Empty values**: `null` and `undefined` in JSON become empty `<value></value>` elements.
|
||||
- **Numbers and booleans**: coerced to their string representation (`true`, `false`, `42`). If you want explicit nullability, wrap in a string in your source JSON.
|
||||
- **Schema header**: JSONPrism emits the standard RESX 2.0 schema. Visual Studio expects this — leave the **Include xsd:schema header** option on unless you're diffing manually.
|
||||
- **Schema header**: JSONPrism emits the standard RESX 2.0 schema. Visual Studio expects this — leave the **Include xsd:schema header** option on unless you're diffing manually. Turning it off drops only the `xsd:schema` block: the four `<resheader>` entries (`resmimetype`, `version`, `reader`, `writer`) are always written, because `ResXResourceReader` needs them.
|
||||
|
||||
---
|
||||
|
||||
## Reverse direction (RESX → JSON)
|
||||
|
||||
JSONPrism doesn't do this — it's a one-way "JSON → many formats" tool. If you need RESX → JSON for round-tripping, the simplest path is a small .NET console app using `ResXResourceReader`:
|
||||
JSONPrism converts RESX back to JSON (since v1.1.0). Switch the direction toggle to **→ JSON**, pick **RESX**, then paste or open a `.resx` — or drop several `.resx` files into the batch panel to get a `.zip` of `.json` files.
|
||||
|
||||
- Each `<data name="…">` becomes a key, and its `<value>` the string value.
|
||||
- An entry with a `<comment>` becomes `{ "value": "…", "_comment": "…" }`, using the comment key from the settings panel — the same shape the forward direction accepts.
|
||||
- Values always stay strings: `"007"`, `"1.10"` and padded text come back exactly as written. (Before 2.0.0, `"007"` came back as the number `7`.)
|
||||
- `
` is decoded back to a carriage return, so CRLF text round-trips.
|
||||
- The input must be well-formed XML with a `<root>` element; otherwise you get an error with its line and column. Files that declare a `<!DOCTYPE>` are rejected: RESX never uses one, and refusing it rules out entity-expansion ("billion laughs") documents.
|
||||
- `<resheader>`, `<metadata>` and `<assembly>` elements and the `type` / `mimetype` attributes are ignored, so typed (non-string) resources come back as their raw `<value>` text.
|
||||
|
||||
If you need typed resources resolved, or want to script the conversion outside JSONPrism, a small .NET console app using `ResXResourceReader` does it:
|
||||
|
||||
```csharp
|
||||
using System.Resources;
|
||||
@@ -209,11 +220,11 @@ jobs:
|
||||
node scripts/flatten.mjs "$f" "$f.flat"
|
||||
done
|
||||
# Then either:
|
||||
# a) use a CLI build of JSONPrism (Phase 4 idea), or
|
||||
# a) use a CLI build of JSONPrism (a "Beyond" idea in docs/ROADMAP.md), or
|
||||
# b) commit the .flat.json and have a separate workflow open JSONPrism manually
|
||||
```
|
||||
|
||||
A CLI version of JSONPrism is on the "Beyond Phase 3" wishlist in `docs/ROADMAP.md`. Until then, batch through the web/desktop UI manually when locales change.
|
||||
A CLI version of JSONPrism is on the "Beyond" wishlist in `docs/ROADMAP.md`. Until then, batch through the web/desktop UI manually when locales change.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+90
-11
@@ -4,6 +4,8 @@ This document is the **single source of truth** for what's done, what's next, an
|
||||
|
||||
Update it as work lands — keep the project status honest.
|
||||
|
||||
**Current release: v2.0.0 (2026-10-22).** The web app runs at https://jsonprism.poli0981.dev (Cloudflare Workers); desktop and Android builds are on [GitHub Releases](https://github.com/poli0981/jsonPrism/releases).
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 — Scaffold ✅
|
||||
@@ -42,7 +44,7 @@ Goal: make the four working converters production-quality and the UX delightful
|
||||
- [x] Folding for nested structures
|
||||
- [x] Theme: custom Prism Spectrum tokens applied to lezer highlight tags
|
||||
- [x] Parse-error linting (visible gutter markers)
|
||||
- [ ] Output panel uses CodeMirror in read-only mode with format-specific syntax — *deferred to Phase 2 (needs per-format language packages: yaml, xml, sql)*
|
||||
- [x] Output panel uses CodeMirror in read-only mode with format-specific syntax — *deferred at the time; landed in 2.0.0 (Phase 8)*
|
||||
|
||||
#### 1.2 Settings panel
|
||||
|
||||
@@ -78,11 +80,11 @@ Goal: make the four working converters production-quality and the UX delightful
|
||||
|
||||
#### 1.7 Polish
|
||||
|
||||
- [x] Keyboard shortcuts: ⌘/Ctrl+K (clear), ⌘/Ctrl+S (download)
|
||||
- [x] Keyboard shortcuts: ⌘/Ctrl+K (clear), ⌘/Ctrl+S (download) — *⌘/Ctrl+K removed in 2.0.0: it clashed with the browser's search shortcut*
|
||||
- [x] Status bar showing: input bytes, output bytes, parse time, shortcut hints
|
||||
- [x] Shape detection hint (scalar / object / array / flat-object / array-of-objects)
|
||||
- [x] Disabled-format chips show "P2"/"P3" badge with tooltip
|
||||
- [ ] Cmd/Ctrl+, to open settings — *deferred; Sheet trigger handles its own keyboard nav via Radix*
|
||||
- [x] Cmd/Ctrl+, to open settings — *deferred at the time; added in a later 1.x release*
|
||||
|
||||
### Deliverable
|
||||
|
||||
@@ -252,7 +254,7 @@ Codebase hygiene plus a small UX addition — no converter behavior changed.
|
||||
Compliance + reliability + first-paint performance. No converter behavior changed.
|
||||
|
||||
- [x] Custom error pages: reusable `ErrorState`, 404 catch-all, generic `/error/:code` (403/419/5xx variants), offline banner, and a chunk-load error boundary folded into the existing crash boundary's look.
|
||||
- [x] GitHub Pages SPA deep-link fix (`public/404.html` + `index.html` decoder for the `/jsonPrism/` base).
|
||||
- [x] GitHub Pages SPA deep-link fix (`public/404.html` + `index.html` decoder for the `/jsonPrism/` base). *Removed in 2.0.0: the web app moved to Cloudflare Workers, which has an SPA fallback.*
|
||||
- [x] First-launch legal consent gate (web only) — accept License/Terms/Privacy/Disclaimer, persisted to `localStorage` with a version for re-prompting; skipped on desktop.
|
||||
- [x] Windows installer license-acceptance page via Tauri `bundle.licenseFile` (`src-tauri/license.rtf`), covering both NSIS `.exe` and WiX `.msi`.
|
||||
- [x] Lazy-load routes + the CodeMirror editor; refined `manualChunks` (react/router/i18n/cm-core/cm-langs/per-parser/ui); removed the `bson` initial-graph leak via `lib/bytes.ts`. +16 tests (209 total).
|
||||
@@ -261,7 +263,7 @@ Compliance + reliability + first-paint performance. No converter behavior change
|
||||
|
||||
## Phase 7 — Android (sideload APK) 🔜
|
||||
|
||||
**Status**: in progress
|
||||
**Status**: in progress — the APK has shipped with every release since v1.7.0 (2026-06-16); only the real-device checks below remain.
|
||||
|
||||
Goal: ship JSONPrism as an Android app users sideload from a `.apk`. Same React UI, no behavior change to the converters. **Minimum Android 12 (API 31)** — older devices are blocked by the OS.
|
||||
|
||||
@@ -271,14 +273,14 @@ Goal: ship JSONPrism as an Android app users sideload from a `.apk`. Same React
|
||||
- [x] `tauri android init` → Android Gradle project at `src-tauri/gen/android/`, **committed** (source only; build outputs + secrets gitignored via nested + root `.gitignore`)
|
||||
- [x] Verified `minSdk = 31` propagated to `app/build.gradle.kts`; Rust compiles for all 4 ABIs (validated against NDK r27/r30)
|
||||
- [x] Release signing wired in `app/build.gradle.kts` from a gitignored `keystore.properties` (graceful unsigned fallback when absent)
|
||||
- [x] Self-hosted fonts via `@fontsource` (Geist / Instrument Serif / JetBrains Mono) — removed Google Fonts `<link>`, tightened CSP, app renders correctly **offline**
|
||||
- [x] Self-hosted fonts via `@fontsource` (Geist / Instrument Serif / JetBrains Mono) — removed Google Fonts `<link>`, tightened CSP, app renders correctly **offline** (*Instrument Serif dropped in 2.0.0: it has no Vietnamese glyphs*)
|
||||
- [x] Local scripts: `tauri:android:init` / `tauri:android:dev` / `tauri:android:build` (universal APK; chains `tauri:icon`)
|
||||
- [x] CI: `android` job in `release.yml` builds + signs (keystore from secrets) + uploads the universal APK to the same draft release
|
||||
- [x] Docs: README / README.vi "Android" sections + maintainer notes in `docs/TAURI-NOTES.md`
|
||||
- [x] Emulator-validated: signed APK installs on Android 12+, **blocked on API < 31** (`INSTALL_FAILED_OLDER_SDK`), launches, renders (CodeMirror + self-hosted fonts), runs converters, fully offline
|
||||
- [x] Native file open works — `plugin-dialog` fires the SAF picker, `plugin-fs` reads the `content://` URI; `basenameFromPath()` recovers a clean filename (unit-tested)
|
||||
- [x] Found: layout needs WebView **Chromium ≥ 111** (Tailwind v4); fine on updated Android 12+ devices, broken on the API 31 emulator's stock Chromium 91 — see `docs/TAURI-NOTES.md`
|
||||
- [ ] Add CI signing secrets (`ANDROID_KEYSTORE_BASE64`, `ANDROID_KEYSTORE_PASSWORD`, …) — maintainer action
|
||||
- [x] Add CI signing secrets (`ANDROID_KEYSTORE_BASE64`, `ANDROID_KEYSTORE_PASSWORD`, …) — maintainer action; the signed APK is attached to v1.7.0–v1.7.2
|
||||
- [ ] Remaining manual checks: save `.zip` via SAF, all 12 converters end-to-end, theme + 4 locales, upgrade-in-place on a real device
|
||||
|
||||
### Deliverable
|
||||
@@ -287,16 +289,93 @@ A signed universal `.apk` attached to each GitHub release, installable on Androi
|
||||
|
||||
---
|
||||
|
||||
## Phase 8 — 2.0.0: Cloudflare, hardening & technical UI ✅
|
||||
|
||||
**Status**: complete (shipped in v2.0.0, 2026-10-22)
|
||||
|
||||
A platform release: a new home for the web app, a human check and analytics confined to the web build, a toolchain jump, an audit of every converter, a UI refresh and a hardened pipeline. Same 12 formats, same layout.
|
||||
|
||||
### Tasks
|
||||
|
||||
#### 8.1 Cloudflare Workers + custom domain
|
||||
|
||||
- [x] Web app served by the Cloudflare Worker `jsonprism` (Workers Static Assets, SPA fallback) at **https://jsonprism.poli0981.dev**; config in `wrangler.jsonc`, operations in [`docs/DEPLOYMENT.md`](DEPLOYMENT.md)
|
||||
- [x] Cloudflare Workers Builds deploys every push to `main`; the GitHub Pages deploy workflow and `public/404.html` are gone
|
||||
- [x] `/api/*` Worker in `worker/`: `POST /api/turnstile/verify` (same-origin only, 4 KB body cap, 30 requests / 60 s rate limit) and `GET /api/health`; structured Workers Logs without IPs, tokens or user content
|
||||
- [x] Static headers in `public/_headers` (CSP, HSTS, COOP, Permissions-Policy, immutable `/assets/*`), `/jsonPrism/*` → 301 in `public/_redirects`, `robots.txt`, `sitemap.xml`, `.well-known/security.txt`, Open Graph image
|
||||
- [x] GitHub Pages keeps only a path-preserving redirect to the new domain (`pages-redirect.yml`, run by hand)
|
||||
- [x] `production-smoke.yml` waits for each pushed commit to go live, then checks headers, routes, redirects and the API
|
||||
|
||||
#### 8.2 Turnstile & Web Analytics (web only)
|
||||
|
||||
- [x] Cloudflare Turnstile inside the Consent Gate, verified server-side by the Worker; a pass is remembered for 7 days; if Cloudflare is unreachable the user may continue after a warning
|
||||
- [x] Cloudflare Web Analytics (cookieless page views): production hostname only, after consent, toggle under Appearance, off by default when the browser sends Global Privacy Control
|
||||
- [x] Neither service exists in desktop or Android builds
|
||||
- [x] `CONSENT_VERSION` 2 asks every user again; the gate shows on web, Android, macOS and Linux (Windows relies on the installer license page)
|
||||
|
||||
#### 8.3 Toolchain: TypeScript 7 / Node 26
|
||||
|
||||
- [x] Node.js 26 (`.nvmrc`, `engines`), npm 11; CI installs with `npm ci --ignore-scripts`
|
||||
- [x] TypeScript 7 native compiler for `tsc`, plus a TypeScript 6 API alias for typescript-eslint; ES2025 target with an ES2023 `lib` to keep the Android WebView (Chromium 111) and macOS 12 floors
|
||||
- [x] Majors: React 19.3, React Router 8.5 (`react-router` only), Vite 8.3, Tailwind CSS 4.3, i18next 26, ESLint 10, Vitest 5 (`app` + `worker` projects), Knip 6, Tauri 2.12
|
||||
- [x] Removed: `react-router-dom`, Instrument Serif, the Tauri os plugin
|
||||
|
||||
#### 8.4 Audit fixes
|
||||
|
||||
- [x] CSV: columns from every row (not just the first), optional `escapeFormulae` guard, reverse only converts canonical numbers
|
||||
- [x] SQL: MySQL backslash escaping, MSSQL `N'…'` + NVARCHAR and 1000-row batches, CREATE TABLE types inferred across all rows, dotted table names quoted per part
|
||||
- [x] RESX: reverse keeps strings such as `"007"`, rejects DOCTYPE, validates XML; resheaders always written; CR encoded
|
||||
- [x] XML: invalid element names sanitised, nested arrays wrapped, control characters replaced, output validated
|
||||
- [x] BSON > 16 MiB → clear error; YAML `quoteStyle` works again + alias/merge-key limits; TOML reports nulls with their path, keeps big integers, stable key order
|
||||
- [x] Batch: real binary in the ZIP for BSON/CBOR/MessagePack, processing twice keeps results, abort returns items to the queue
|
||||
- [x] Accurate JSON error line/column on every engine; precision warning for integers beyond 2^53
|
||||
- [x] Desktop/Android: trimmed capabilities and fs scope, stricter CSP, `allowBackup="false"`, downloads through the native save dialog
|
||||
- [x] Performance: inputs > 256 KB and all batches convert in a Web Worker; read-only, virtualised output editor; streaming ZIP
|
||||
- [x] Accessibility (live regions, editor names, ≥ 24 px targets, `<html lang>`), i18n (ja + zh-CN completed, parity test in CI), local-only logger + "Copy diagnostics" on About
|
||||
|
||||
#### 8.5 Technical UI refresh
|
||||
|
||||
- [x] Blueprint grid, mono uppercase labels, corner ticks, per-theme prism colours (light-theme contrast ≥ 4.5:1)
|
||||
- [x] Header: animated wordmark, `v2.0.0 · <commit>` chip, EN/VI/JA/ZH switcher, Appearance menu (theme, hide scrollbars, analytics)
|
||||
- [x] Terminal-style status bar, thin custom scrollbars, animations only under `motion-safe`, no theme flash, per-route document titles
|
||||
|
||||
#### 8.6 CI hardening
|
||||
|
||||
- [x] Actions pinned to full commit SHAs, `persist-credentials: false`, least-privilege job permissions
|
||||
- [x] CI: format, lint, knip, TypeScript 7 typecheck, tests + coverage, build, Worker deploy dry run; SonarQube Cloud (CI-based analysis); Rust fmt + clippy
|
||||
- [x] Release: tag = `package.json` = `Cargo.toml` version check, one draft release, tauri-action v1, macOS universal build, `JSONPrism_<version>_android-universal.apk`, `SHA256SUMS.txt` + build-provenance attestations
|
||||
- [x] Discord notifiers called with explicit webhook secrets; Dependabot grouped by package family with a cooldown
|
||||
|
||||
### Deliverable
|
||||
|
||||
JSONPrism 2.0.0 on its own domain, with the human check and analytics confined to the web build. **864 tests in 92 files**, 97% line coverage (converters incl. regression + contract tests, every UI component, hooks, stores, the Web Worker client, i18n parity across 4 locales, Worker).
|
||||
|
||||
---
|
||||
|
||||
## Beyond — Ideas (no commitment)
|
||||
|
||||
- **JSON → Excel (.xlsx)** via SheetJS — possible if Markdown/CSV doesn't cover the use case
|
||||
- **Reverse direction** (other format → JSON): different mental model; might warrant a sibling app
|
||||
- **Schema inference**: emit JSON Schema, TypeScript types, or Go structs from sample JSON
|
||||
### Deferred from 2.0.0
|
||||
|
||||
- **Lazy-load non-English locales** — about 20 KB gzip off the first load
|
||||
- **PWA / offline install** for the web app
|
||||
- **Code signing** — Windows Authenticode and macOS notarization — plus a signed updater
|
||||
- **SBOM** for release builds
|
||||
- **OpenSSF Scorecard**
|
||||
- **End-to-end tests** — Playwright (web), tauri-driver (desktop)
|
||||
- **JSON tools** — JSON Schema, JSONPath and diff features
|
||||
- **More formats** — INI, `.env`, Java `.properties`, Excel `.xlsx`
|
||||
- **Streaming NDJSON** for very large files
|
||||
- **Community translation workflow** (ja and zh-CN are AI-translated today)
|
||||
- **Drop the TypeScript 6 alias** once TypeScript 7 ships an API that typescript-eslint supports
|
||||
|
||||
### Other ideas
|
||||
|
||||
- **Type generation**: TypeScript types or Go structs from sample JSON
|
||||
- **CLI version**: same converter modules, exposed as a Node CLI for CI pipelines
|
||||
- **VS Code extension**: surface the converters in the editor command palette
|
||||
- **Sharing**: hash-based shareable URLs (`#data=...`) for sample inputs (privacy: opt-in only)
|
||||
|
||||
These are deliberately deferred — Phase 1–5 first.
|
||||
Nothing here is scheduled. An item moves into a numbered phase when work on it starts.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+161
-32
@@ -1,22 +1,36 @@
|
||||
# Tauri runtime notes
|
||||
|
||||
Operational notes for the desktop builds. Aimed at maintainers, not end users.
|
||||
Operational notes for the desktop and Android builds. Aimed at maintainers, not end users.
|
||||
|
||||
## Versions
|
||||
|
||||
Tauri 2.12: `tauri` 2.12.5, `tauri-plugin-dialog` 2.8, `tauri-plugin-fs` 2.7,
|
||||
`tauri-plugin-opener` 2.7 and, on desktop only, `tauri-plugin-single-instance`
|
||||
2.5 (`src-tauri/Cargo.toml` / `Cargo.lock`), with `@tauri-apps/cli` 2.12 and the
|
||||
matching `@tauri-apps/*` npm packages. Dependabot groups each side (npm `tauri`,
|
||||
cargo `tauri`) so the plugin versions move together.
|
||||
|
||||
There is **no os plugin and no shell plugin**. The os plugin was removed in
|
||||
2.0.0; the About page's "Copy diagnostics" gets OS and architecture from the
|
||||
custom `host_info` command in `src-tauri/src/lib.rs`.
|
||||
|
||||
## Process lifecycle
|
||||
|
||||
`src-tauri/src/lib.rs` wires two cleanup hooks that should keep the host
|
||||
process from outliving the main webview:
|
||||
`src-tauri/src/lib.rs` wires the hooks that keep the host process from
|
||||
outliving the main webview:
|
||||
|
||||
- **Single instance (desktop only)** — `tauri-plugin-single-instance` is
|
||||
registered first; a second launch focuses the existing window instead of
|
||||
starting another process.
|
||||
- `on_window_event` — when the main window receives `CloseRequested`, the
|
||||
app handle's `exit(0)` is called explicitly. This guards against Windows
|
||||
builds occasionally leaving `JSONPrism.exe` alive when the webview was
|
||||
the last live reference.
|
||||
- `RunEvent::ExitRequested` — calls `app_handle.cleanup_before_exit()` so
|
||||
any spawned shell children (none today, but the hook is in place) are
|
||||
signaled before the process exits.
|
||||
plugin and window resources are released before the process exits.
|
||||
|
||||
If you ever add long-running spawned commands (e.g. via a shell/command
|
||||
plugin), remember to track their handles and kill them in the same hook.
|
||||
The app spawns no child processes. If you ever add one, track its handle and
|
||||
kill it in the same hook.
|
||||
|
||||
## WebView2 GDI leak (Windows, upstream)
|
||||
|
||||
@@ -40,28 +54,116 @@ runtime team. Until then:
|
||||
|
||||
## Permissions / capabilities
|
||||
|
||||
See `src-tauri/capabilities/default.json`. Scope is intentionally narrow:
|
||||
`src-tauri/capabilities/default.json` applies to the `main` window. Scope is
|
||||
intentionally narrow (trimmed in 2.0.0):
|
||||
|
||||
- Filesystem reads/writes only inside `$HOME`, `$DOCUMENT`, `$DOWNLOAD`,
|
||||
`$DESKTOP`.
|
||||
- Dialog plugin for open/save.
|
||||
- Opener plugin (`opener:default`) for handing external URLs to the system
|
||||
browser — `shell:open` has no native Android URL handler, so the opener
|
||||
plugin's `openUrl` is used instead.
|
||||
| Permission | Why |
|
||||
| --- | --- |
|
||||
| `core:default` | Tauri's core set (app, event, path, window, webview, …), including the `tauri://drag-drop` events. |
|
||||
| `opener:default` | Opens `https://` and `mailto:` links in the system browser / mail app via `openUrl`. Works on Android, where the shell plugin's `open()` has no URL handler. |
|
||||
| `dialog:allow-open`, `dialog:allow-save` | Native open / save dialogs only — no message, ask or confirm dialogs. |
|
||||
| `fs:default` | The fs plugin's baseline: the app's own data directories; denies the webview data folder. |
|
||||
| `fs:allow-read-text-file` | Read files the user picked or dropped. |
|
||||
| `fs:allow-write-file` | Write the file the user chose in the save dialog (single output or batch `.zip`). |
|
||||
| `fs:allow-stat` | Read a file's mtime so batch de-duplication stays stable. |
|
||||
| `fs:scope` | Static scope: `$DOCUMENT/**`, `$DOWNLOAD/**`, `$DESKTOP/**` (no longer all of `$HOME`). |
|
||||
|
||||
- **Runtime scope.** Files the user picks in a dialog or drops onto the window
|
||||
are added to the fs scope at runtime by the plugins. That is how a file
|
||||
outside the three folders still opens, and how the save dialog can write
|
||||
where the user chose. Nothing else is reachable.
|
||||
- **No dotfiles.** `plugins.fs.requireLiteralLeadingDot: true` in
|
||||
`tauri.conf.json`: scope globs never match dot-files or dot-directories such
|
||||
as `~/.ssh`.
|
||||
- **Removed in 2.0.0:** the os plugin (`os:default`, `@tauri-apps/plugin-os`,
|
||||
`tauri-plugin-os`), `core:window:allow-set-title`, `dialog:default` and
|
||||
`dialog:allow-message`, `fs:allow-write-text-file`, and the `$HOME/**` scope.
|
||||
|
||||
Widening the scope requires both a capability edit and a CSP review in
|
||||
`tauri.conf.json`.
|
||||
|
||||
## Content Security Policy
|
||||
|
||||
`app.security.csp` in `tauri.conf.json`:
|
||||
|
||||
```
|
||||
default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
|
||||
```
|
||||
|
||||
- 2.0.0 added `object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'`.
|
||||
- No third-party origins. Cloudflare Turnstile and Web Analytics are web-only
|
||||
and compiled out of Tauri builds (`__IS_TAURI_BUILD__`), so this CSP never
|
||||
needs their hosts. The web CSP lives in `public/_headers` — see
|
||||
[DEPLOYMENT.md](DEPLOYMENT.md).
|
||||
- The theme is applied before first paint by `public/theme-init.js`, an
|
||||
external blocking script rather than an inline one, so neither CSP needs
|
||||
`'unsafe-inline'` for scripts (the reason is spelled out in `index.html`).
|
||||
|
||||
## Consent gate
|
||||
|
||||
The first-launch Consent Gate (License, Terms, Privacy Policy, Disclaimer)
|
||||
shows on Android, macOS and Linux, as on the web. Windows skips it: the
|
||||
installer's license page (`bundle.licenseFile` → `src-tauri/license.rtf`, in
|
||||
both the NSIS `.exe` and the WiX `.msi`) already requires acceptance.
|
||||
`CONSENT_VERSION` is 2 since 2.0.0, so existing users accept again. The
|
||||
Turnstile check inside the gate exists only on the web.
|
||||
|
||||
## Version numbers
|
||||
|
||||
- `tauri.conf.json` has `"version": "../package.json"`: the bundle version
|
||||
comes from `package.json`.
|
||||
- `src-tauri/Cargo.toml` keeps its own `version` (the `host_info` command
|
||||
reports it). Keep it equal to `package.json`; `release.yml` refuses a tag
|
||||
when they differ. CI runs clippy with `--locked`, so commit the refreshed
|
||||
`Cargo.lock` too.
|
||||
- Android `versionCode` is still set by hand — see [versionCode](#versioncode).
|
||||
|
||||
## Bundle targets
|
||||
|
||||
- Windows: MSI (via WiX) + NSIS `.exe`. Tested on Windows 10 22H2 and
|
||||
Windows 11.
|
||||
- macOS: DMG + `.app`, min version 12.0 (Monterey).
|
||||
- Linux: AppImage + Debian package.
|
||||
- macOS: universal (Apple Silicon + Intel) DMG + `.app` (published as
|
||||
`.app.tar.gz`), min version 12.0 (Monterey).
|
||||
- Linux: AppImage, `.deb` and `.rpm`, built on Ubuntu 22.04 to keep the glibc
|
||||
floor low.
|
||||
- Android: one universal APK — see [Android](#android-sideload-apk).
|
||||
|
||||
The release matrix in `.github/workflows/release.yml` builds all four
|
||||
combinations (Linux, macOS Intel, macOS Apple Silicon, Windows) on a `v*`
|
||||
tag push.
|
||||
Bundles are not code-signed yet (`certificateThumbprint` and
|
||||
`signingIdentity` are `null`), so expect Windows SmartScreen and macOS
|
||||
Gatekeeper warnings on first launch. Signing is on the roadmap.
|
||||
|
||||
## Release workflow
|
||||
|
||||
`.github/workflows/release.yml` runs on a `v*` tag push, or by hand
|
||||
(`workflow_dispatch`) with an existing tag to rebuild it:
|
||||
|
||||
1. **verify** — the tag must look like `vX.Y.Z` and match the `package.json`
|
||||
and `Cargo.toml` versions; then `npm test`.
|
||||
2. **create-release** — creates **one** draft release, or reuses the existing
|
||||
draft; it refuses when the release is already published. (Parallel
|
||||
"find or create" calls used to race and split assets across drafts.)
|
||||
3. **desktop** — matrix: Windows (`windows-latest`), macOS universal
|
||||
(`macos-14`, `--target universal-apple-darwin`), Linux (`ubuntu-22.04`).
|
||||
Each builds with `tauri-apps/tauri-action` v1 and uploads into the draft.
|
||||
4. **android** — Java 17 (Temurin), SDK platform 36 + NDK `27.2.12479018`,
|
||||
Rust Android targets; signs with the release keystore from secrets and
|
||||
uploads `JSONPrism_<version>_android-universal.apk` (1.7.x used
|
||||
`JSONPrism-v<version>-android-universal.apk`).
|
||||
5. **checksums** — downloads every asset, uploads `SHA256SUMS.txt` and creates
|
||||
GitHub build-provenance attestations for each file.
|
||||
|
||||
The maintainer reviews and publishes the draft; publishing triggers the
|
||||
Discord and GitHub Discussions announcements. Anyone can check a download:
|
||||
|
||||
```bash
|
||||
sha256sum -c SHA256SUMS.txt --ignore-missing
|
||||
gh attestation verify <file> --repo poli0981/jsonPrism
|
||||
```
|
||||
|
||||
Every action is pinned to a full commit SHA, checkouts use
|
||||
`persist-credentials: false`, each job declares only the permissions it
|
||||
needs, and installs run `npm ci --ignore-scripts`. The step-by-step release
|
||||
checklist is in [DEPLOYMENT.md](DEPLOYMENT.md#releases-desktop--android).
|
||||
|
||||
## Android (sideload APK)
|
||||
|
||||
@@ -74,8 +176,11 @@ OS installer refuses older devices. The build target is a **universal APK**
|
||||
|
||||
Environment variables Tauri's CLI reads:
|
||||
|
||||
- `JAVA_HOME` → Android Studio's JBR, e.g. `C:\Jetbrains\Android Studio\jbr`
|
||||
- `ANDROID_HOME` → `C:\Users\<you>\AppData\Local\Android\Sdk`
|
||||
- `JAVA_HOME` → a JDK 17 or newer, e.g. Android Studio's JBR at
|
||||
`C:\Jetbrains\Android Studio\jbr` (CI uses Temurin 17)
|
||||
- `ANDROID_HOME` → `C:\Users\<you>\AppData\Local\Android\Sdk`, with SDK
|
||||
Platform 36 (`compileSdk` / `targetSdk` 36), Build-Tools, Platform-Tools and
|
||||
Command-line Tools installed
|
||||
- `NDK_HOME` → `…\Android\Sdk\ndk\<version>`
|
||||
|
||||
Rust targets: `rustup target add aarch64-linux-android armv7-linux-androideabi
|
||||
@@ -92,11 +197,17 @@ i686-linux-android x86_64-linux-android`. Verify with `npm run tauri info`.
|
||||
**committed** — source only. Its nested `.gitignore` files exclude build
|
||||
outputs (`build/`, `.gradle/`, `.cxx/`, `*.so`, `local.properties`,
|
||||
`keystore.properties`). Committing it keeps the signing edits in
|
||||
`app/build.gradle.kts` and `minSdkVersion` stable, and makes CI reproducible.
|
||||
`app/build.gradle.kts`, `minSdkVersion` and the manifest stable, and makes CI
|
||||
reproducible.
|
||||
|
||||
`app/src/main/AndroidManifest.xml` sets `android:allowBackup="false"` (since
|
||||
2.0.0), so the app's data — WebView storage such as consent, theme and saved
|
||||
options — is left out of Android's cloud backup.
|
||||
|
||||
You normally do **not** run `tauri android init` again. Only re-run it after a
|
||||
major `@tauri-apps/cli` bump, and re-apply the signing block + verify
|
||||
`minSdk = 31` in `app/build.gradle.kts` afterward (the init overwrites it).
|
||||
major `@tauri-apps/cli` bump, and afterwards re-apply the signing block, verify
|
||||
`minSdk = 31` in `app/build.gradle.kts` and check that `allowBackup="false"` is
|
||||
still in the manifest (the init overwrites them).
|
||||
|
||||
Launcher icons (`res/mipmap-*/ic_launcher*.png`) are generated by
|
||||
`npm run tauri:icon` and gitignored, like the desktop icons — both the local
|
||||
@@ -111,8 +222,10 @@ Launcher icons (`res/mipmap-*/ic_launcher*.png`) are generated by
|
||||
versionCode = MAJOR*10000 + MINOR*100 + PATCH
|
||||
```
|
||||
|
||||
e.g. `1.6.1 → 10601`, `1.7.0 → 10700`. Bump it together with `version` in
|
||||
`package.json` / `Cargo.toml` / `tauri.conf.json` at release time.
|
||||
e.g. `1.7.2 → 10702`, `2.0.0 → 20000`. Set it by hand at release time, together
|
||||
with `version` in `package.json` and `Cargo.toml` (`tauri.conf.json` reads its
|
||||
version from `package.json`). `release.yml` checks the version strings, not
|
||||
`versionCode`.
|
||||
|
||||
### Signing
|
||||
|
||||
@@ -162,8 +275,9 @@ Produce the base64 (PowerShell):
|
||||
|
||||
CI decodes it to a temp path, writes `keystore.properties`, builds with
|
||||
`tauri android build --apk`, and uploads the universal APK to the same draft
|
||||
release as the desktop bundles. If `ANDROID_KEYSTORE_BASE64` is unset the job
|
||||
fails fast rather than shipping an unsigned APK.
|
||||
release as the desktop bundles, named `JSONPrism_<version>_android-universal.apk`.
|
||||
If `ANDROID_KEYSTORE_BASE64` is unset the job fails fast rather than shipping an
|
||||
unsigned APK.
|
||||
|
||||
### Output
|
||||
|
||||
@@ -171,10 +285,12 @@ fails fast rather than shipping an unsigned APK.
|
||||
|
||||
### Offline fonts
|
||||
|
||||
Fonts (Geist / Instrument Serif / JetBrains Mono) are self-hosted via
|
||||
`@fontsource` (imported in `src/main.tsx`), not loaded from Google Fonts, so the
|
||||
app renders correctly offline. The CSP in `tauri.conf.json` no longer allows the
|
||||
Google Fonts hosts — keep it that way unless fonts move back to a CDN.
|
||||
Fonts (Geist and JetBrains Mono, variable builds) are self-hosted via
|
||||
`@fontsource-variable/*` (imported in `src/main.tsx`), not loaded from Google
|
||||
Fonts, so the app renders correctly offline. Instrument Serif was dropped in
|
||||
2.0.0 because it has no Vietnamese glyphs; headings use Geist. The CSP in
|
||||
`tauri.conf.json` does not allow the Google Fonts hosts — keep it that way
|
||||
unless fonts move back to a CDN.
|
||||
|
||||
### WebView version requirement (important)
|
||||
|
||||
@@ -195,6 +311,11 @@ This is inherent to the Tailwind v4 stack (the web app has the same requirement)
|
||||
it is not Android-specific code. No action needed unless you must support devices
|
||||
with a very outdated WebView.
|
||||
|
||||
The JavaScript side keeps the same floor: since 2.0.0 the app compiles with an
|
||||
ES2025 target but an **ES2023 `lib`**, so ES2025 runtime APIs (Iterator helpers,
|
||||
Set methods, `Promise.try`, `RegExp.escape`) are compile errors. They are missing
|
||||
on Chromium 111 and on macOS 12's WebKit.
|
||||
|
||||
### Native file I/O on Android
|
||||
|
||||
`plugin-dialog` `open()` returns a percent-encoded `content://` URI on Android
|
||||
@@ -214,3 +335,11 @@ Two URI flavours show up:
|
||||
`InputPanel`) so a file the user explicitly picked is never wrongly rejected.
|
||||
The real display name would need a content-resolver `DISPLAY_NAME` query via a
|
||||
custom Rust command — not worth it; the file content loads correctly either way.
|
||||
|
||||
Saving goes through the native save dialog on desktop and Android
|
||||
(`nativeSaveBlob()` → `plugin-fs` `writeFile`), for single outputs (Download,
|
||||
Ctrl/⌘+S) and the batch `.zip` alike: Android WebViews ignore `<a download>`
|
||||
blob links. Since 2.0.0 the open dialogs filter by conversion direction: `.json`
|
||||
when converting from JSON, and the source format's extensions, aliases included
|
||||
(`.yml`, `.ndjson`), when converting back to JSON — which only JSONL, CSV, TSV,
|
||||
YAML, TOML and RESX support. Both offer `.txt` as a fallback.
|
||||
+104
-11
@@ -2,24 +2,111 @@
|
||||
|
||||
This is the toolchain the maintainer keeps installed for JSONPrism +
|
||||
sibling projects. It is **not** a strict requirement for contributing —
|
||||
most contributors only need the **Web app** column.
|
||||
most contributors only need the **web app** section.
|
||||
|
||||
## Required for the web app
|
||||
|
||||
| Tool | Minimum | Latest exercised | Notes |
|
||||
|---|---|---|---|
|
||||
| **Node.js** | 22.11.0 LTS | 25.8.1 | Set in [package.json](../package.json) `engines.node`. |
|
||||
| **npm** | bundled with Node | — | `npm ci` is what CI runs. |
|
||||
| **Node.js** | 26.0.0 | 26.12.1 | `.nvmrc` is `26`; [package.json](../package.json) `engines.node` is `>=26.0.0`. CI reads `.nvmrc`. |
|
||||
| **npm** | 11 (bundled with Node 26) | 11.20.0 | `npm ci` is what CI runs (with `--ignore-scripts`). |
|
||||
| **Git** | recent (≥ 2.40) | — | Commit signing (`commit.gpgsign=true`) recommended. |
|
||||
|
||||
**Install scripts.** npm 11 may block the install scripts of dependencies.
|
||||
Nothing in JSONPrism needs them — esbuild, workerd and the Tauri CLI resolve
|
||||
their platform binaries at runtime — so leave them blocked. CI installs with
|
||||
`npm ci --ignore-scripts`.
|
||||
|
||||
## TypeScript 7 (with a TypeScript 6 alias)
|
||||
|
||||
Two TypeScript packages are installed side by side:
|
||||
|
||||
| `package.json` name | Resolves to | Provides |
|
||||
|---|---|---|
|
||||
| `@typescript/native` | `typescript@^7` | The `tsc` binary: TypeScript 7, the native compiler used by `npm run typecheck` and `npm run build`. |
|
||||
| `typescript` | `@typescript/typescript6@^6` | The TypeScript 6 **API** (binary `tsc6`) that typescript-eslint 8.72 needs — its peer range is `<6.1`. |
|
||||
|
||||
- **`npm run typecheck` is the source of truth** (`tsc -b` plus the Worker
|
||||
project). CI fails if `tsc` is not TypeScript 7.
|
||||
- **WebStorm**: Settings → Languages & Frameworks → TypeScript → TypeScript:
|
||||
select `<project>/node_modules/typescript` (the TS 6 API) for the language
|
||||
service, or the TypeScript 7 native preview as described in JetBrains' docs.
|
||||
The IDE's TS 6 service can disagree with TS 7 on edge cases; trust
|
||||
`npm run typecheck`.
|
||||
- Don't "fix" the alias. It goes once TypeScript 7.1 ships an API that
|
||||
typescript-eslint supports; until then Dependabot ignores `typescript` ≥ 6.1.
|
||||
- TS 7 rules: no `baseUrl` (use `paths`), `types` defaults to `[]` (every
|
||||
tsconfig lists its own), enums and parameter properties are not erasable
|
||||
(`erasableSyntaxOnly`).
|
||||
- The target is ES2025 but the app's `lib` is ES2023: don't use ES2025 runtime
|
||||
APIs (Iterator helpers, Set methods, `Promise.try`, `RegExp.escape`). The
|
||||
Android WebView (Chromium 111) and macOS 12 WebKit floors lack them.
|
||||
- tsconfigs: `tsconfig.app.json` (browser code), `tsconfig.test.json` (tests),
|
||||
`tsconfig.node.json` (config files), `tsconfig.worker.json` (Cloudflare Worker).
|
||||
|
||||
## Cloudflare Worker (local)
|
||||
|
||||
`wrangler` is a devDependency; there is nothing to install globally.
|
||||
|
||||
```bash
|
||||
cp .dev.vars.example .dev.vars # once — Cloudflare's always-pass Turnstile test secret
|
||||
npm run preview:cf # wrangler dev on http://localhost:8787 (builds first)
|
||||
```
|
||||
|
||||
- `.dev.vars` holds the Worker secret `TURNSTILE_SECRET` for local runs. It is
|
||||
gitignored; never put the production secret in it.
|
||||
- `npm run preview:cf` serves `dist/` the way production does (`_headers`,
|
||||
`_redirects`, SPA fallback) together with the `/api/*` Worker. On localhost
|
||||
the app uses Cloudflare's test sitekey, so the Consent Gate's Turnstile check
|
||||
passes on its own.
|
||||
- `npm run cf:types` — regenerates `worker-configuration.d.ts` (gitignored)
|
||||
after you change bindings in `wrangler.jsonc`; `npm run typecheck` runs it too.
|
||||
- `npm run cf:check` — `wrangler deploy --dry-run`, as CI does.
|
||||
- `npm run dev` (Vite) has no Worker and no Turnstile; set
|
||||
`VITE_TURNSTILE_DEV=1` to show the widget anyway.
|
||||
|
||||
Production deploys are covered in [docs/DEPLOYMENT.md](DEPLOYMENT.md).
|
||||
|
||||
## Required for the Tauri desktop build
|
||||
|
||||
In addition to the web app deps:
|
||||
|
||||
| Tool | Minimum | Notes |
|
||||
| Tool | Minimum | Latest exercised | Notes |
|
||||
|---|---|---|---|
|
||||
| **Rust** | 1.90 | 1.98.0 | Install via `rustup`; stable channel (CI uses stable). `Cargo.toml` declares `rust-version = "1.90"`, the floor of tauri 2.12 and tauri-plugin-fs 2.7. |
|
||||
| **Platform build deps** | OS-specific | — | Windows: Visual Studio Build Tools (C++ workload) + WebView2. macOS: Xcode Command Line Tools. Linux: `libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libssl-dev libgtk-3-dev` (what CI installs). |
|
||||
|
||||
Run `npm run tauri:icon` once (the generated icons are gitignored), then
|
||||
`npm run tauri:dev` or `npm run tauri:build`. CI also runs
|
||||
`cargo fmt --check` and `cargo clippy --all-targets --locked -- -D warnings`
|
||||
in `src-tauri/`; run them before pushing Rust changes.
|
||||
|
||||
## Required for the Android build
|
||||
|
||||
In addition to the desktop toolchain:
|
||||
|
||||
| Tool | Version | Notes |
|
||||
|---|---|---|
|
||||
| **Rust** | 1.77 (per `Cargo.toml`) | Install via `rustup`; stable channel. |
|
||||
| **Platform build deps** | OS-specific | See `README.md` § Desktop app for the full list. |
|
||||
| **JDK** | 17+ | Android Studio's bundled JBR works; CI uses Temurin 17. `JAVA_HOME` must point at it. |
|
||||
| **Android SDK** | Platform 36 | `compileSdk` / `targetSdk` 36, `minSdk` 31. Also Build-Tools, Platform-Tools, Command-line Tools. `ANDROID_HOME` points at the SDK. |
|
||||
| **Android NDK** | 27.2.12479018 | The version CI pins. `NDK_HOME` → `$ANDROID_HOME/ndk/27.2.12479018`. |
|
||||
| **Rust targets** | — | `rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android` |
|
||||
|
||||
Then `npm run tauri:android:dev` or `npm run tauri:android:build`. NDK
|
||||
selection, signing and the CI secrets are in
|
||||
[docs/TAURI-NOTES.md](TAURI-NOTES.md#android-sideload-apk).
|
||||
|
||||
## Quality tools
|
||||
|
||||
- `npm run lint` — ESLint 10 flat config with typescript-eslint 8.72 and
|
||||
eslint-plugin-react-hooks 7 (React Compiler rules).
|
||||
- `npm run knip` — Knip 6: unused files, exports and dependencies
|
||||
(`knip.json`). CI runs it.
|
||||
- `npm run format` / `npm run format:check` — Prettier 3.9 with Tailwind class
|
||||
sorting.
|
||||
- `npm test` — Vitest 5 with two projects: `app` (jsdom) and `worker` (node).
|
||||
- `npm run test:coverage` — the same run with V8 coverage; reports land in
|
||||
`coverage/` (text, HTML and `lcov.info`, which CI passes to SonarQube Cloud).
|
||||
|
||||
## Other tooling on the maintainer's machine
|
||||
|
||||
@@ -33,6 +120,7 @@ the broader dev environment knows what's around:
|
||||
## IDEs
|
||||
|
||||
- **JetBrains** WebStorm (2026.x) — primary IDE; runs Prettier + ESLint on save.
|
||||
Point its TypeScript service at `node_modules/typescript` (see above).
|
||||
- **Visual Studio Code** — secondary; useful for the Tauri/Rust side via `rust-analyzer`.
|
||||
|
||||
## Recommended workflow
|
||||
@@ -40,23 +128,28 @@ the broader dev environment knows what's around:
|
||||
```bash
|
||||
# One-time
|
||||
git clone https://github.com/poli0981/jsonPrism.git
|
||||
cd jsonprism
|
||||
npm install
|
||||
cd jsonPrism
|
||||
npm ci
|
||||
cp .dev.vars.example .dev.vars
|
||||
|
||||
# Daily
|
||||
npm run dev # web dev server, http://localhost:5173
|
||||
npm run preview:cf # production-like preview with the Worker, http://localhost:8787
|
||||
|
||||
# Before pushing
|
||||
# Before pushing (CI runs the same checks, with format:check instead of format)
|
||||
npm run format
|
||||
npm run typecheck
|
||||
npm run lint
|
||||
npm test
|
||||
npm run knip
|
||||
npm run typecheck
|
||||
npm run test:coverage
|
||||
npm run build
|
||||
npm run cf:check
|
||||
```
|
||||
|
||||
## Related docs
|
||||
|
||||
- [docs/pc_spec.md](pc_spec.md) — hardware reference.
|
||||
- [docs/TAURI-NOTES.md](TAURI-NOTES.md) — Tauri-specific notes.
|
||||
- [docs/DEPLOYMENT.md](DEPLOYMENT.md) — Cloudflare hosting and releases.
|
||||
- [README.md](../README.md) — project overview + quick start.
|
||||
- [Tiếng Việt](i18n/vi/dev_env.md)
|
||||
@@ -0,0 +1,202 @@
|
||||
> **Lưu ý:** Đây là bản dịch tiếng Việt chỉ mang tính tham khảo. Nếu có
|
||||
> bất kỳ khác biệt nào giữa bản dịch này và
|
||||
> [bản gốc tiếng Anh](../../../PRIVACY.md), bản tiếng Anh được ưu tiên
|
||||
> áp dụng.
|
||||
|
||||
# Chính sách quyền riêng tư
|
||||
|
||||
**Phiên bản**: 2.0 · **Ngày hiệu lực**: 2026-10-22 · Thay thế chính sách ngày 2026-05-13.
|
||||
|
||||
## Tóm tắt
|
||||
|
||||
- **Dữ liệu của bạn ở lại trên thiết bị của bạn.** JSON, tệp và kết quả
|
||||
đầu ra đều được chuyển đổi trong trình duyệt của bạn hoặc trong ứng dụng
|
||||
desktop/Android. Chúng không bao giờ được tải lên, và JSONPrism không có
|
||||
hệ thống tài khoản, không có đồng bộ đám mây và không có cơ chế báo cáo
|
||||
lỗi (error reporting).
|
||||
- **Trang web** (<https://jsonprism.poli0981.dev>) được lưu trữ trên
|
||||
Cloudflare. Trang web chạy một bước xác minh nhanh rằng bạn là con người
|
||||
(human check) bằng Cloudflare Turnstile khi bạn mở trang lần đầu (và lặp
|
||||
lại sau mỗi 7 ngày), đồng thời đếm lượt xem trang bằng Cloudflare Web
|
||||
Analytics, một dịch vụ không sử dụng cookie. Bạn có thể tắt tính năng
|
||||
thống kê trong mục **Giao diện** (Appearance); tính năng này ban đầu ở
|
||||
trạng thái tắt nếu trình duyệt của bạn gửi tín hiệu
|
||||
[Global Privacy Control](https://globalprivacycontrol.org/).
|
||||
- **Các ứng dụng desktop và Android** không tự thực hiện bất kỳ yêu cầu
|
||||
mạng nào và không sử dụng bất kỳ dịch vụ Cloudflare nào nói trên.
|
||||
|
||||
## Bên chịu trách nhiệm
|
||||
|
||||
JSONPrism là một dự án mã nguồn mở do một cá nhân duy trì, poli0981
|
||||
(Kokone), người đồng thời là bên kiểm soát dữ liệu (controller) đối với
|
||||
các hoạt động xử lý được mô tả tại đây. Câu hỏi và yêu cầu về quyền riêng
|
||||
tư: **privacy@poli0981.dev**.
|
||||
|
||||
## Những gì diễn ra trên từng nền tảng
|
||||
|
||||
| Nền tảng | Lưu trữ (hosting) / môi trường chạy | Những gì rời khỏi thiết bị của bạn |
|
||||
|---|---|---|
|
||||
| Trang web | Cloudflare Workers (tệp tĩnh cùng một API nhỏ cho bước xác minh con người) | Dữ liệu yêu cầu HTTP tiêu chuẩn cần thiết để cung cấp trang web; bước xác minh Turnstile; số liệu lượt xem trang ẩn danh nếu tính năng thống kê đang bật. Không bao giờ bao gồm dữ liệu bạn chuyển đổi. |
|
||||
| Ứng dụng Windows, macOS, Linux | Tauri 2, chạy cục bộ | Không có gì được gửi đi từ mã của ứng dụng. Các liên kết bạn nhấp vào sẽ mở trong trình duyệt của bạn. |
|
||||
| Ứng dụng Android | Tauri 2 trong WebView của hệ thống | Không có gì được gửi đi từ mã của ứng dụng. Các liên kết bạn chạm vào sẽ mở trong trình duyệt của bạn. |
|
||||
|
||||
### Dịch vụ lưu trữ (trang web)
|
||||
|
||||
Cloudflare, Inc. phục vụ trang web và xử lý dữ liệu mà mọi yêu cầu web
|
||||
đều mang theo (địa chỉ IP, user agent, URL được yêu cầu, thời gian, thông
|
||||
tin TLS) để cung cấp các trang và bảo vệ dịch vụ trước hành vi lạm dụng.
|
||||
Phần mã phía máy chủ của riêng JSONPrism chỉ xử lý API xác minh con người
|
||||
(`/api/turnstile/verify`) và một điểm kiểm tra tình trạng hoạt động
|
||||
(health check). Với API đó, phần mã này ghi lại các sự kiện có cấu trúc —
|
||||
kết quả, trạng thái HTTP, mã trung tâm dữ liệu của Cloudflare, thời lượng
|
||||
và mã lỗi Turnstile — vào Cloudflare Workers Logs, được lưu giữ trong 7
|
||||
ngày. Các sự kiện này không bao giờ chứa địa chỉ IP, token Turnstile hay
|
||||
bất cứ nội dung nào bạn chuyển đổi. API này được Cloudflare giới hạn tần
|
||||
suất truy cập (rate limit) theo từng máy khách; JSONPrism không lưu trữ
|
||||
khoá máy khách (client key).
|
||||
|
||||
### Xác minh con người (trang web)
|
||||
|
||||
[Cloudflare Turnstile](https://www.cloudflare.com/products/turnstile/)
|
||||
phân biệt con người với bot mà không cần giải câu đố. Khi bước xác minh
|
||||
chạy, trình duyệt của bạn tải script của Cloudflare từ
|
||||
`challenges.cloudflare.com`; script này thu thập các tín hiệu như địa chỉ
|
||||
IP, dấu vân tay TLS (TLS fingerprint), user agent của bạn và khoá trang
|
||||
(site key), như được mô tả trong
|
||||
[Phụ lục quyền riêng tư của Turnstile](https://www.cloudflare.com/turnstile-privacy-policy/)
|
||||
(Turnstile Privacy Addendum) của Cloudflare. Sau đó, máy chủ của JSONPrism
|
||||
gửi token dùng một lần thu được — chứ không phải địa chỉ IP của bạn — tới
|
||||
API xác minh của Cloudflare. Nếu vượt qua bước xác minh, trình duyệt của
|
||||
bạn sẽ lưu thời điểm hết hạn (`jsonprism.humanCheck`) và không bị yêu cầu
|
||||
xác minh lại trong 7 ngày.
|
||||
|
||||
### Web Analytics (trang web, tuỳ chọn)
|
||||
|
||||
[Cloudflare Web Analytics](https://www.cloudflare.com/web-analytics/)
|
||||
đếm lượt xem trang và đo hiệu năng tải trang (đường dẫn trang, referrer,
|
||||
loại trình duyệt và thiết bị, các chỉ số thời gian). Dịch vụ này không đặt
|
||||
cookie, không sử dụng bộ nhớ cục bộ (local storage) và, theo Cloudflare,
|
||||
không thu thập hay sử dụng dữ liệu cá nhân của khách truy cập. JSONPrism
|
||||
chỉ tải dịch vụ này trên trang web chính thức (production), chỉ sau khi
|
||||
bạn đã chấp nhận các điều khoản, và chỉ khi tuỳ chọn
|
||||
**Giao diện → Thống kê truy cập ẩn danh** (Appearance → Anonymous usage
|
||||
analytics) đang bật. Tuỳ chọn này ban đầu ở trạng thái tắt khi trình duyệt
|
||||
của bạn gửi tín hiệu Global Privacy Control, và việc tắt tuỳ chọn có hiệu
|
||||
lực từ lần truy cập tiếp theo của bạn.
|
||||
|
||||
### Ứng dụng desktop và Android
|
||||
|
||||
- Không thu thập dữ liệu từ xa (telemetry), không thống kê, không
|
||||
Turnstile, không kiểm tra bản cập nhật.
|
||||
- Tệp chỉ đến được ứng dụng khi bạn chọn chúng trong hộp thoại của hệ thống
|
||||
hoặc thả chúng vào cửa sổ ứng dụng. Ứng dụng có thể đọc các tệp bạn chọn
|
||||
và chỉ ghi vào nơi bạn chọn để lưu; quyền truy cập tệp được cấp sẵn
|
||||
(static file access) của ứng dụng chỉ giới hạn trong các thư mục
|
||||
Documents, Downloads và Desktop của bạn và không bao giờ bao gồm các tệp
|
||||
ẩn như `~/.ssh`
|
||||
(xem [`src-tauri/capabilities/default.json`](../../../src-tauri/capabilities/default.json)).
|
||||
- Ứng dụng Android khai báo quyền `INTERNET` vì môi trường chạy WebView của
|
||||
Tauri yêu cầu quyền này; mã của JSONPrism không thực hiện yêu cầu mạng
|
||||
nào. Tính năng sao lưu Android đối với dữ liệu của ứng dụng đã bị tắt.
|
||||
|
||||
## Những gì được lưu trên thiết bị của bạn
|
||||
|
||||
Ứng dụng lưu các mục sau trong `localStorage` của trình duyệt (hoặc của
|
||||
WebView trong ứng dụng). Chúng không bao giờ rời khỏi thiết bị của bạn.
|
||||
|
||||
| Khoá | Nội dung |
|
||||
|---|---|
|
||||
| `jsonprism.consent` | Việc bạn đã chấp nhận Giấy phép, Điều khoản, Chính sách quyền riêng tư và Tuyên bố miễn trừ trách nhiệm: cờ đánh dấu, phiên bản chính sách, thời điểm |
|
||||
| `jsonprism.humanCheck` | Chỉ trên trang web: thời điểm hết hạn của lần xác minh con người đã vượt qua |
|
||||
| `jsonprism.prefs` | Tuỳ chọn trong mục Giao diện: ẩn thanh cuộn, bật/tắt thống kê ẩn danh |
|
||||
| `jsonprism.theme` | `light`, `dark` hoặc `system` |
|
||||
| `jsonprism.lang` | Ngôn ngữ giao diện (`en`, `vi`, `ja`, `zh-CN`) |
|
||||
| `jsonprism.selected_format` | Định dạng đích mà bạn chọn gần nhất |
|
||||
| `jsonprism.direction` | Chiều chuyển đổi |
|
||||
| `jsonprism.options.<format>` | Các tuỳ chọn của bạn cho từng định dạng |
|
||||
|
||||
`sessionStorage` tạm thời lưu `jsonprism.preloadReload` (thời điểm ứng dụng
|
||||
tự tải lại gần nhất sau khi có bản phát hành mới). Việc xoá dữ liệu của
|
||||
trang web, hoặc gỡ cài đặt ứng dụng, sẽ xoá toàn bộ các dữ liệu này.
|
||||
|
||||
Ứng dụng cũng giữ 200 dòng nhật ký (log) gần nhất trong bộ nhớ, phục vụ
|
||||
cho **Giới thiệu → Sao chép thông tin chẩn đoán** (About → Copy
|
||||
diagnostics). Các dòng này không bao giờ được gửi đi bất cứ đâu; nút này
|
||||
sao chép chúng vào bộ nhớ tạm (clipboard) của bạn, cùng với phiên bản,
|
||||
commit và nền tảng, để bạn có thể tự quyết định có dán chúng vào báo cáo
|
||||
lỗi hay không.
|
||||
|
||||
## Những điều JSONPrism không bao giờ làm
|
||||
|
||||
- Tải lên, lưu trữ hoặc xem xét nội dung bạn chuyển đổi.
|
||||
- Sử dụng cookie, quảng cáo hoặc theo dõi xuyên trang (cross-site
|
||||
tracking).
|
||||
- Bán hoặc chia sẻ thông tin cá nhân.
|
||||
- Tải phông chữ hoặc script từ bên thứ ba ngoài hai dịch vụ Cloudflare nêu
|
||||
trên (phông chữ được đóng gói sẵn cùng ứng dụng).
|
||||
- Báo cáo lỗi tới một dịch vụ từ xa.
|
||||
|
||||
## Cơ sở pháp lý (EU/EEA, Vương quốc Anh)
|
||||
|
||||
- Lưu trữ (hosting), bảo mật, phòng chống lạm dụng và bước xác minh con
|
||||
người: lợi ích hợp pháp trong việc vận hành một trang web công khai một
|
||||
cách an toàn (GDPR Art. 6(1)(f)).
|
||||
- Thống kê lượt xem trang ẩn danh: lợi ích hợp pháp trong việc hiểu, ở
|
||||
dạng tổng hợp, cách trang web được sử dụng, với cơ chế từ chối (opt-out)
|
||||
dễ dàng và tôn trọng tín hiệu Global Privacy Control (Art. 6(1)(f)).
|
||||
- Các tuỳ chọn được lưu trên thiết bị của bạn: thực sự cần thiết (strictly
|
||||
necessary) để cung cấp các tính năng bạn sử dụng.
|
||||
|
||||
Bạn có thể phản đối việc xử lý dựa trên lợi ích hợp pháp vào bất kỳ lúc
|
||||
nào bằng cách gửi email tới privacy@poli0981.dev; đối với tính năng thống
|
||||
kê, chỉ cần tắt nó trong mục Giao diện là đủ.
|
||||
|
||||
## Chuyển giao dữ liệu quốc tế
|
||||
|
||||
Cloudflare hoạt động trên toàn cầu, vì vậy dữ liệu yêu cầu có thể được xử
|
||||
lý bên ngoài quốc gia của bạn, kể cả tại Hoa Kỳ. Cloudflare được chứng
|
||||
nhận theo Khung quyền riêng tư dữ liệu EU-Hoa Kỳ (EU-U.S. Data Privacy
|
||||
Framework, cùng các phần mở rộng dành cho Vương quốc Anh và Thuỵ Sĩ), và
|
||||
phụ lục xử lý dữ liệu (data processing addendum) của Cloudflare có bao gồm
|
||||
các Điều khoản hợp đồng tiêu chuẩn (SCC) của EU. Xem
|
||||
[chính sách quyền riêng tư của Cloudflare](https://www.cloudflare.com/privacypolicy/).
|
||||
|
||||
## Thời hạn lưu giữ
|
||||
|
||||
- Dữ liệu trên thiết bị của bạn: cho đến khi bạn xoá; kết quả xác minh con
|
||||
người hết hạn sau 7 ngày, và bạn sẽ được yêu cầu chấp nhận lại mỗi khi
|
||||
phiên bản của chính sách này thay đổi.
|
||||
- Workers Logs của API xác minh con người: 7 ngày.
|
||||
- Dữ liệu xử lý yêu cầu và dữ liệu thống kê do Cloudflare nắm giữ: theo
|
||||
lịch lưu giữ riêng của Cloudflare; Web Analytics chỉ hiển thị số liệu
|
||||
tổng hợp.
|
||||
|
||||
## Quyền của bạn
|
||||
|
||||
Tuỳ thuộc vào nơi bạn sinh sống (ví dụ theo GDPR, UK GDPR hoặc CCPA/CPRA
|
||||
của California), bạn có thể có quyền truy cập, chỉnh sửa hoặc xoá dữ liệu
|
||||
cá nhân về bạn, quyền hạn chế hoặc phản đối việc xử lý dữ liệu đó, quyền
|
||||
di chuyển dữ liệu (data portability) và quyền khiếu nại với cơ quan bảo vệ
|
||||
dữ liệu có thẩm quyền. Bản thân JSONPrism không nắm giữ dữ liệu cá nhân nào
|
||||
về bạn ngoài những gì Cloudflare xử lý thay mặt cho JSONPrism, vì vậy cách
|
||||
tốt nhất để đáp ứng phần lớn các yêu cầu là xoá dữ liệu của trang web; với
|
||||
bất kỳ yêu cầu nào khác, hãy gửi email tới privacy@poli0981.dev và bạn sẽ
|
||||
nhận được phản hồi trong vòng 30 ngày. JSONPrism không bán hoặc chia sẻ
|
||||
thông tin cá nhân và tôn trọng tín hiệu Global Privacy Control.
|
||||
|
||||
## Trẻ em
|
||||
|
||||
JSONPrism là một công cụ dành cho lập trình viên và không hướng tới trẻ em
|
||||
dưới 13 tuổi (hoặc dưới độ tuổi đồng ý kỹ thuật số tại nơi bạn sinh sống).
|
||||
|
||||
## Thay đổi đối với chính sách này
|
||||
|
||||
Các thay đổi được liệt kê trong [CHANGELOG.md](../../../CHANGELOG.md). Khi
|
||||
chính sách này có thay đổi đáng kể, số phiên bản của chính sách sẽ tăng lên
|
||||
và ứng dụng sẽ yêu cầu bạn chấp nhận lại trước khi bạn tiếp tục.
|
||||
|
||||
## Liên hệ
|
||||
|
||||
- Quyền riêng tư: privacy@poli0981.dev
|
||||
- Lỗ hổng bảo mật: xem [SECURITY.md](../../../SECURITY.md)
|
||||
- Mọi vấn đề khác: [GitHub Issues](https://github.com/poli0981/jsonPrism/issues)
|
||||
@@ -0,0 +1,169 @@
|
||||
> **Lưu ý:** Đây là bản dịch tiếng Việt chỉ mang tính tham khảo. Nếu có
|
||||
> bất kỳ khác biệt nào giữa bản dịch này và
|
||||
> [bản gốc tiếng Anh](../../../TERMS.md), bản tiếng Anh được ưu tiên
|
||||
> áp dụng.
|
||||
|
||||
# Điều khoản dịch vụ / EULA
|
||||
|
||||
**Phiên bản**: 2.0 · **Ngày hiệu lực**: 2026-10-22 · Thay thế các điều khoản ngày 2026-05-13.
|
||||
|
||||
JSONPrism là một dự án mã nguồn mở do một người thực hiện với sự hỗ trợ
|
||||
của AI, được poli0981 (Kokone, [@poli0981](https://github.com/poli0981))
|
||||
phát hành theo [Apache License 2.0](../../../LICENSE). Các điều khoản này
|
||||
áp dụng cho trang web, các ứng dụng desktop và Android, kho mã nguồn và
|
||||
các tài nguyên liên quan (gọi chung là "JSONPrism").
|
||||
|
||||
Bằng việc sử dụng JSONPrism dưới bất kỳ hình thức nào, bạn đồng ý với các
|
||||
điều khoản này. Nếu bạn không đồng ý, hãy ngừng sử dụng JSONPrism.
|
||||
|
||||
---
|
||||
|
||||
## 1. Chấp nhận điều khoản
|
||||
|
||||
Việc sử dụng ứng dụng web tại <https://jsonprism.poli0981.dev>, cài đặt
|
||||
hoặc chạy ứng dụng desktop hoặc Android, clone hoặc tải xuống kho mã nguồn,
|
||||
hoặc tương tác với dự án theo bất kỳ cách nào khác đồng nghĩa với việc bạn
|
||||
chấp nhận các điều khoản này. Các ứng dụng sẽ yêu cầu bạn xác nhận điều
|
||||
này trong lần khởi chạy đầu tiên (trình cài đặt Windows thực hiện việc này
|
||||
ở trang giấy phép của nó) và yêu cầu lại mỗi khi các điều khoản này hoặc
|
||||
[Chính sách quyền riêng tư](PRIVACY.md) có thay đổi đáng kể.
|
||||
|
||||
Bạn phải từ đủ 13 tuổi trở lên, hoặc đã đạt độ tuổi đồng ý kỹ thuật số
|
||||
(age of digital consent) tại nơi bạn sinh sống, để sử dụng JSONPrism.
|
||||
|
||||
## 2. Điều khoản dịch vụ của GitHub
|
||||
|
||||
Kho mã nguồn, issue, discussion, bản phát hành (release) và pull request
|
||||
được lưu trữ trên GitHub. Việc sử dụng chúng đồng nghĩa với việc tuân thủ:
|
||||
|
||||
- [Điều khoản dịch vụ của GitHub](https://docs.github.com/en/site-policy/github-terms/github-terms-of-service) (GitHub Terms of Service)
|
||||
- [Chính sách sử dụng được chấp nhận của GitHub](https://docs.github.com/en/site-policy/acceptable-use-policies/github-acceptable-use-policies) (GitHub Acceptable Use Policies)
|
||||
- [Tuyên bố quyền riêng tư của GitHub](https://docs.github.com/en/site-policy/privacy-policies/github-general-privacy-statement) (GitHub Privacy Statement)
|
||||
|
||||
Hành vi vi phạm các quy định của GitHub cũng là vi phạm các điều khoản này.
|
||||
|
||||
## 3. Giấy phép
|
||||
|
||||
Mã nguồn của JSONPrism được cấp phép theo
|
||||
[Apache License, Version 2.0](../../../LICENSE). Bạn có thể sử dụng, nghiên
|
||||
cứu, sửa đổi và phân phối lại mã nguồn theo giấy phép đó; đặc biệt, bạn
|
||||
phải giữ lại các thông báo bản quyền và văn bản giấy phép trong các bản
|
||||
phân phối của mình. Không nội dung nào trong các điều khoản này hạn chế
|
||||
các quyền mà Apache License trao cho bạn.
|
||||
|
||||
Dự án sử dụng các thư viện, phông chữ và dịch vụ của bên thứ ba, vốn có
|
||||
giấy phép và điều khoản riêng, được liệt kê trong
|
||||
[THIRD-PARTY.md](../../../THIRD-PARTY.md). Khi phân phối lại JSONPrism hoặc
|
||||
một tác phẩm phái sinh, bạn có trách nhiệm tuân thủ các điều khoản của mọi
|
||||
thành phần thượng nguồn (upstream).
|
||||
|
||||
## 4. Dịch vụ của bên thứ ba (chỉ áp dụng cho trang web)
|
||||
|
||||
Trang web được lưu trữ trên Cloudflare và sử dụng Cloudflare Turnstile cho
|
||||
bước xác minh con người cùng Cloudflare Web Analytics để đếm lượt xem trang
|
||||
ẩn danh, như được mô tả trong [Chính sách quyền riêng tư](PRIVACY.md).
|
||||
Cloudflare cung cấp các dịch vụ này theo điều khoản và
|
||||
[chính sách quyền riêng tư](https://www.cloudflare.com/privacypolicy/) của
|
||||
riêng Cloudflare. Các ứng dụng desktop và Android không sử dụng các dịch vụ
|
||||
này.
|
||||
|
||||
## 5. Không bảo đảm và giới hạn trách nhiệm pháp lý
|
||||
|
||||
JSONPrism được cung cấp **"AS IS"** (nguyên trạng), không kèm theo bất kỳ
|
||||
bảo đảm nào, dù được nêu rõ hay ngụ ý, bao gồm các bảo đảm về khả năng
|
||||
thương mại, sự phù hợp cho một mục đích cụ thể và việc không xâm phạm
|
||||
quyền. Trong phạm vi tối đa mà pháp luật cho phép, người duy trì dự án
|
||||
(maintainer) không chịu trách nhiệm đối với bất kỳ khiếu nại, thiệt hại
|
||||
hoặc trách nhiệm pháp lý nào khác phát sinh từ việc bạn sử dụng JSONPrism,
|
||||
bao gồm cả việc mất dữ liệu hoặc chuyển đổi không chính xác. Hãy kiểm tra
|
||||
kết quả chuyển đổi trước khi bạn dựa vào nó.
|
||||
|
||||
Nội dung này nhắc lại tuyên bố miễn trừ trách nhiệm trong Apache License;
|
||||
xem [DISCLAIMER.md](../../../DISCLAIMER.md) để đọc phần trình bày của chính
|
||||
dự án về ý nghĩa thực tế của "một người cùng sự hỗ trợ của AI".
|
||||
|
||||
## 6. Dữ liệu của bạn
|
||||
|
||||
Bạn sở hữu mọi thứ bạn dán, thả, nhập hoặc tạo ra trong JSONPrism.
|
||||
|
||||
- Người duy trì không nhận, lưu trữ, truyền tải hay phân tích dữ liệu đầu
|
||||
vào hoặc kết quả đầu ra của bạn. Việc chuyển đổi chạy trên thiết bị của
|
||||
bạn ở mọi phiên bản.
|
||||
- Những gì các ứng dụng lưu trên thiết bị của bạn, cũng như những gì dịch
|
||||
vụ lưu trữ và các dịch vụ của trang web xử lý, được mô tả trong
|
||||
[PRIVACY.md](PRIVACY.md).
|
||||
- Bạn chịu trách nhiệm bảo đảm rằng mình có quyền sử dụng dữ liệu mà bạn
|
||||
đưa vào.
|
||||
|
||||
## 7. Sử dụng được chấp nhận
|
||||
|
||||
Bạn không được:
|
||||
|
||||
- Sử dụng JSONPrism, kho mã nguồn hoặc các tài nguyên của nó để tạo điều
|
||||
kiện cho hoạt động bất hợp pháp tại nơi bạn ở hoặc tại nơi dữ liệu có
|
||||
nguồn gốc.
|
||||
- Xử lý **dữ liệu cá nhân chịu sự quản lý theo luật định** (regulated
|
||||
personal data, chẳng hạn dữ liệu sức khoẻ, thẻ thanh toán, sinh trắc học
|
||||
và các loại tương tự) trên trang web được lưu trữ trực tuyến. Nếu môi
|
||||
trường của bạn đòi hỏi xử lý loại dữ liệu đó, hãy sử dụng ứng dụng
|
||||
desktop hoặc tự build JSONPrism từ mã nguồn và chạy nó trong môi trường
|
||||
do chính bạn kiểm soát.
|
||||
- Tấn công, gây quá tải, dò tìm lỗ hổng mà không tuân theo
|
||||
[SECURITY.md](../../../SECURITY.md), hoặc làm gián đoạn trang web hay API
|
||||
của trang web, hoặc tìm cách vượt qua hay tự động hoá bước xác minh con
|
||||
người của trang web.
|
||||
- Gửi pull request hoặc nội dung khác có che giấu mã độc, payload đã bị
|
||||
làm rối (obfuscated) hoặc các hình thức tấn công chuỗi cung ứng. Xem
|
||||
[CONTRIBUTING.md](../../../CONTRIBUTING.md) để biết các đóng góp như vậy
|
||||
được xử lý ra sao; người vi phạm nhiều lần sẽ bị chặn khỏi kho mã nguồn.
|
||||
- Giới thiệu JSONPrism như một sản phẩm chính thức, được chứng nhận hoặc
|
||||
được bảo đảm. Đây là một dự án indie do một người thực hiện (xem
|
||||
[MAINTAINERS.md](../../../MAINTAINERS.md)).
|
||||
|
||||
## 8. Nhãn hiệu
|
||||
|
||||
"JSONPrism" và logo lăng kính là dấu hiệu nhận diện dự án này. Bạn có thể
|
||||
nhắc đến dự án, nhưng không được sử dụng tên hoặc logo theo cách ngụ ý
|
||||
rằng người duy trì đã tạo ra hoặc bảo chứng cho sản phẩm hay bản build đã
|
||||
sửa đổi của bạn khi chưa có sự cho phép trước bằng văn bản.
|
||||
|
||||
## 9. Khiếu nại về bản quyền
|
||||
|
||||
Trang web không lưu trữ nội dung của người dùng. Nếu bạn cho rằng nội dung
|
||||
trong kho mã nguồn hoặc trong các ứng dụng xâm phạm bản quyền (quyền tác
|
||||
giả) của bạn, hãy gửi email tới **copyright@poli0981.dev**, nêu rõ nội dung
|
||||
liên quan, tác phẩm mà bạn cho rằng bị xâm phạm và thông tin liên hệ của
|
||||
bạn. Nội dung trên GitHub (issue, discussion, pull request) cũng chịu sự
|
||||
điều chỉnh của
|
||||
[quy trình DMCA của GitHub](https://docs.github.com/en/site-policy/content-removal-policies/dmca-takedown-policy).
|
||||
|
||||
## 10. Thay đổi
|
||||
|
||||
Người duy trì có thể cập nhật các điều khoản này. Các thay đổi được liệt kê
|
||||
trong [CHANGELOG.md](../../../CHANGELOG.md) dưới mục của bản phát hành đưa
|
||||
ra các thay đổi đó, và những thay đổi đáng kể sẽ làm tăng số phiên bản ở
|
||||
trên và được hiển thị trong các ứng dụng để bạn chấp nhận. Việc tiếp tục sử
|
||||
dụng JSONPrism sau khi có thay đổi đồng nghĩa với việc bạn chấp nhận các
|
||||
điều khoản đã được cập nhật.
|
||||
|
||||
## 11. Chấm dứt
|
||||
|
||||
Người duy trì có thể, vào bất kỳ lúc nào, hạn chế quyền truy cập vào trang
|
||||
web hoặc kho mã nguồn, hoặc chặn đóng góp từ bất kỳ ai có hành vi vi phạm
|
||||
các điều khoản này hoặc [Bộ quy tắc ứng xử](../../../CODE_OF_CONDUCT.md).
|
||||
Điều này không thu hồi Apache License đã được cấp cho các bản phân phối
|
||||
hiện có.
|
||||
|
||||
## 12. Tính độc lập của các điều khoản
|
||||
|
||||
Nếu bất kỳ quy định nào trong các điều khoản này bị xác định là không thể
|
||||
thi hành, các quy định còn lại vẫn giữ nguyên hiệu lực. Việc không thi hành
|
||||
một quy định không có nghĩa là từ bỏ quy định đó.
|
||||
|
||||
## 13. Liên hệ
|
||||
|
||||
- Pháp lý và giấy phép: legal@poli0981.dev
|
||||
- Bản quyền: copyright@poli0981.dev
|
||||
- Quyền riêng tư: privacy@poli0981.dev ([PRIVACY.md](PRIVACY.md))
|
||||
- Bảo mật: [SECURITY.md](../../../SECURITY.md)
|
||||
- Dự án và người duy trì: [MAINTAINERS.md](../../../MAINTAINERS.md)
|
||||
+113
-17
@@ -1,25 +1,115 @@
|
||||
# Môi trường phát triển
|
||||
|
||||
Đây là toolchain mà maintainer giữ cài đặt cho JSONPrism + các project
|
||||
anh em. **Không** phải yêu cầu bắt buộc để đóng góp — phần lớn
|
||||
contributor chỉ cần cột **App web**.
|
||||
Đây là toolchain mà maintainer luôn cài sẵn cho JSONPrism và các project
|
||||
anh em. Đây **không** phải yêu cầu bắt buộc để đóng góp — phần lớn
|
||||
contributor chỉ cần mục **app web**.
|
||||
|
||||
## Bắt buộc cho app web
|
||||
|
||||
| Tool | Tối thiểu | Đã test | Ghi chú |
|
||||
| Công cụ | Tối thiểu | Bản mới nhất đã dùng | Ghi chú |
|
||||
|---|---|---|---|
|
||||
| **Node.js** | 22.11.0 LTS | 25.8.1 | Set trong [package.json](../../../package.json) `engines.node`. |
|
||||
| **npm** | đi kèm Node | — | `npm ci` là cái CI chạy. |
|
||||
| **Git** | gần (≥ 2.40) | — | Khuyến nghị commit signing (`commit.gpgsign=true`). |
|
||||
| **Node.js** | 26.0.0 | 26.12.1 | `.nvmrc` là `26`; `engines.node` trong [package.json](../../../package.json) là `>=26.0.0`. CI đọc `.nvmrc`. |
|
||||
| **npm** | 11 (đi kèm Node 26) | 11.20.0 | CI chạy `npm ci` (kèm `--ignore-scripts`). |
|
||||
| **Git** | bản gần đây (≥ 2.40) | — | Khuyến nghị bật ký commit (`commit.gpgsign=true`). |
|
||||
|
||||
**Install script.** npm 11 có thể chặn install script của các dependency.
|
||||
JSONPrism không cần script nào trong số đó — esbuild, workerd và Tauri CLI tự
|
||||
tìm binary cho nền tảng lúc chạy — nên cứ để chúng bị chặn. CI cài bằng
|
||||
`npm ci --ignore-scripts`.
|
||||
|
||||
## TypeScript 7 (kèm alias TypeScript 6)
|
||||
|
||||
Hai package TypeScript được cài song song:
|
||||
|
||||
| Tên trong `package.json` | Thực chất là | Cung cấp |
|
||||
|---|---|---|
|
||||
| `@typescript/native` | `typescript@^7` | Binary `tsc`: TypeScript 7, trình biên dịch native mà `npm run typecheck` và `npm run build` dùng. |
|
||||
| `typescript` | `@typescript/typescript6@^6` | **API** TypeScript 6 (binary `tsc6`) mà typescript-eslint 8.72 cần — peer range của nó là `<6.1`. |
|
||||
|
||||
- **`npm run typecheck` là thước đo cuối cùng** (`tsc -b` cộng project
|
||||
Worker). CI báo lỗi nếu `tsc` không phải TypeScript 7.
|
||||
- **WebStorm**: Settings → Languages & Frameworks → TypeScript → TypeScript:
|
||||
chọn `<project>/node_modules/typescript` (API TS 6) cho language service,
|
||||
hoặc bản preview native của TypeScript 7 theo tài liệu của JetBrains.
|
||||
Language service TS 6 trong IDE có thể lệch với TS 7 ở vài trường hợp hiếm;
|
||||
khi đó hãy tin `npm run typecheck`.
|
||||
- Đừng "sửa" alias này. Nó sẽ được gỡ khi TypeScript 7.1 có API mà
|
||||
typescript-eslint hỗ trợ; tới lúc đó Dependabot bỏ qua `typescript` ≥ 6.1.
|
||||
- Quy tắc của TS 7: không còn `baseUrl` (dùng `paths`), `types` mặc định là
|
||||
`[]` (mỗi tsconfig tự khai báo), enum và parameter property không "erasable"
|
||||
(`erasableSyntaxOnly`).
|
||||
- Target là ES2025 nhưng `lib` của app là ES2023: đừng dùng API runtime của
|
||||
ES2025 (Iterator helpers, các method mới của Set, `Promise.try`,
|
||||
`RegExp.escape`). WebView Android (Chromium 111) và WebKit của macOS 12 —
|
||||
mức tối thiểu đang hỗ trợ — chưa có các API này.
|
||||
- Các tsconfig: `tsconfig.app.json` (code chạy trên trình duyệt),
|
||||
`tsconfig.test.json` (test), `tsconfig.node.json` (file cấu hình),
|
||||
`tsconfig.worker.json` (Cloudflare Worker).
|
||||
|
||||
## Cloudflare Worker (chạy local)
|
||||
|
||||
`wrangler` nằm trong devDependencies; không cần cài global gì cả.
|
||||
|
||||
```bash
|
||||
cp .dev.vars.example .dev.vars # một lần — secret test luôn pass của Turnstile
|
||||
npm run preview:cf # wrangler dev tại http://localhost:8787 (tự build trước)
|
||||
```
|
||||
|
||||
- `.dev.vars` chứa secret `TURNSTILE_SECRET` của Worker khi chạy local. File
|
||||
này đã được gitignore; tuyệt đối không đưa secret production vào đây.
|
||||
- `npm run preview:cf` phục vụ `dist/` giống hệt production (`_headers`,
|
||||
`_redirects`, SPA fallback) cùng với Worker `/api/*`. Trên localhost app
|
||||
dùng sitekey test của Cloudflare, nên bước kiểm tra Turnstile trong Consent
|
||||
Gate tự pass.
|
||||
- `npm run cf:types` — tạo lại `worker-configuration.d.ts` (đã gitignore) sau
|
||||
khi đổi binding trong `wrangler.jsonc`; `npm run typecheck` cũng chạy lệnh này.
|
||||
- `npm run cf:check` — `wrangler deploy --dry-run`, giống CI.
|
||||
- `npm run dev` (Vite) không có Worker và không có Turnstile; đặt
|
||||
`VITE_TURNSTILE_DEV=1` nếu vẫn muốn hiện widget.
|
||||
|
||||
Phần deploy production nằm trong [docs/DEPLOYMENT.md](../../DEPLOYMENT.md).
|
||||
|
||||
## Bắt buộc cho bản desktop Tauri
|
||||
|
||||
Ngoài deps của app web:
|
||||
|
||||
| Tool | Tối thiểu | Ghi chú |
|
||||
| Công cụ | Tối thiểu | Bản mới nhất đã dùng | Ghi chú |
|
||||
|---|---|---|---|
|
||||
| **Rust** | 1.90 | 1.98.0 | Cài qua `rustup`; channel stable (CI dùng stable). `Cargo.toml` khai báo `rust-version = "1.90"`, đúng mức tối thiểu của tauri 2.12 và tauri-plugin-fs 2.7. |
|
||||
| **Build deps theo nền tảng** | tuỳ OS | — | Windows: Visual Studio Build Tools (workload C++) + WebView2. macOS: Xcode Command Line Tools. Linux: `libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libssl-dev libgtk-3-dev` (đúng các gói CI cài). |
|
||||
|
||||
Chạy `npm run tauri:icon` một lần (icon sinh ra đã được gitignore), sau đó
|
||||
`npm run tauri:dev` hoặc `npm run tauri:build`. CI còn chạy
|
||||
`cargo fmt --check` và `cargo clippy --all-targets --locked -- -D warnings`
|
||||
trong `src-tauri/`; hãy chạy hai lệnh này trước khi push thay đổi phía Rust.
|
||||
|
||||
## Bắt buộc cho bản Android
|
||||
|
||||
Ngoài toolchain desktop:
|
||||
|
||||
| Công cụ | Phiên bản | Ghi chú |
|
||||
|---|---|---|
|
||||
| **Rust** | 1.77 (theo `Cargo.toml`) | Cài qua `rustup`; channel stable. |
|
||||
| **Build deps theo platform** | tuỳ OS | Xem `README.md` § Desktop app để biết list đầy đủ. |
|
||||
| **JDK** | 17+ | Dùng JBR đi kèm Android Studio là được; CI dùng Temurin 17. `JAVA_HOME` phải trỏ tới JDK này. |
|
||||
| **Android SDK** | Platform 36 | `compileSdk` / `targetSdk` 36, `minSdk` 31. Cài thêm Build-Tools, Platform-Tools, Command-line Tools. `ANDROID_HOME` trỏ tới SDK. |
|
||||
| **Android NDK** | 27.2.12479018 | Phiên bản CI cố định. `NDK_HOME` → `$ANDROID_HOME/ndk/27.2.12479018`. |
|
||||
| **Rust targets** | — | `rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android` |
|
||||
|
||||
Sau đó chạy `npm run tauri:android:dev` hoặc `npm run tauri:android:build`.
|
||||
Cách chọn NDK, ký APK và các secret của CI nằm trong
|
||||
[docs/TAURI-NOTES.md](../../TAURI-NOTES.md#android-sideload-apk).
|
||||
|
||||
## Công cụ kiểm tra chất lượng
|
||||
|
||||
- `npm run lint` — ESLint 10 (flat config) với typescript-eslint 8.72 và
|
||||
eslint-plugin-react-hooks 7 (các rule cho React Compiler).
|
||||
- `npm run knip` — Knip 6: tìm file, export và dependency không dùng đến
|
||||
(`knip.json`). CI có chạy bước này.
|
||||
- `npm run format` / `npm run format:check` — Prettier 3.9, kèm sắp xếp class
|
||||
Tailwind.
|
||||
- `npm test` — Vitest 5 với hai project: `app` (jsdom) và `worker` (node).
|
||||
- `npm run test:coverage` — chạy như `npm test` nhưng đo coverage bằng V8; báo
|
||||
cáo nằm trong `coverage/` (text, HTML và `lcov.info` — file CI gửi lên
|
||||
SonarQube Cloud).
|
||||
|
||||
## Tool khác có trên máy maintainer
|
||||
|
||||
@@ -28,11 +118,12 @@ trường tương đương:
|
||||
|
||||
- **Python**: 3.12.x, 3.14.x (cho các project script khác).
|
||||
- **.NET**: 8.x, 9.x, 10.x, 11.x (preview) — cho project anh em AutoClickForge / PhantomMAC.
|
||||
- **GPG**: bật commit signing (`commit.gpgsign=true`).
|
||||
- **GPG**: bật ký commit (`commit.gpgsign=true`).
|
||||
|
||||
## IDE
|
||||
|
||||
- **JetBrains** WebStorm (2026.x) — IDE chính; chạy Prettier + ESLint khi save.
|
||||
- **JetBrains** WebStorm (2026.x) — IDE chính; chạy Prettier + ESLint khi lưu.
|
||||
Trỏ TypeScript service vào `node_modules/typescript` (xem ở trên).
|
||||
- **Visual Studio Code** — phụ; tiện cho phần Tauri/Rust qua `rust-analyzer`.
|
||||
|
||||
## Workflow khuyến nghị
|
||||
@@ -40,23 +131,28 @@ trường tương đương:
|
||||
```bash
|
||||
# Một lần
|
||||
git clone https://github.com/poli0981/jsonPrism.git
|
||||
cd jsonprism
|
||||
npm install
|
||||
cd jsonPrism
|
||||
npm ci
|
||||
cp .dev.vars.example .dev.vars
|
||||
|
||||
# Hằng ngày
|
||||
npm run dev # dev server web, http://localhost:5173
|
||||
npm run preview:cf # bản xem trước giống production, có Worker, http://localhost:8787
|
||||
|
||||
# Trước khi push
|
||||
# Trước khi push (CI chạy đúng các bước này, dùng format:check thay cho format)
|
||||
npm run format
|
||||
npm run typecheck
|
||||
npm run lint
|
||||
npm test
|
||||
npm run knip
|
||||
npm run typecheck
|
||||
npm run test:coverage
|
||||
npm run build
|
||||
npm run cf:check
|
||||
```
|
||||
|
||||
## Tài liệu liên quan
|
||||
|
||||
- [docs/pc_spec.md (VI)](pc_spec.md) — phần cứng.
|
||||
- [docs/TAURI-NOTES.md](../../TAURI-NOTES.md) — ghi chú Tauri.
|
||||
- [docs/DEPLOYMENT.md](../../DEPLOYMENT.md) — hosting trên Cloudflare và phát hành.
|
||||
- [README.vi.md](../../../README.vi.md) — giới thiệu project + quick start.
|
||||
- [English](../../dev_env.md)
|
||||
@@ -10,8 +10,8 @@ vi hỗ trợ chung của Tauri).
|
||||
|
||||
| Thành phần | Chi tiết |
|
||||
|---|---|
|
||||
| **OS** | Windows 11 Pro 25H2 Insider Preview (Dev Channel) |
|
||||
| **Build** | 26300.8376 |
|
||||
| **OS** | Windows 11 Pro Insider Preview (Dev Channel) |
|
||||
| **Build** | 29648.1000 |
|
||||
| **CPU** | Intel Core i7-14700KF |
|
||||
| **GPU** | NVIDIA GeForce RTX 5080 (16 GB VRAM) |
|
||||
| **RAM** | 32 GB DDR5 |
|
||||
@@ -20,7 +20,8 @@ vi hỗ trợ chung của Tauri).
|
||||
|
||||
## Thiết bị di động / kiểm tra web
|
||||
|
||||
Dùng để kiểm tra bản web (chủ yếu là deploy lên GitHub Pages) trên thiết bị cảm ứng:
|
||||
Dùng để kiểm tra bản web (chủ yếu là trang production
|
||||
https://jsonprism.poli0981.dev) trên thiết bị cảm ứng:
|
||||
|
||||
- iPhone 14 Pro — iOS 26.x — Chrome, Brave
|
||||
- iPhone 13 Pro Max — iOS 26.x — Chrome, Brave
|
||||
|
||||
+4
-4
@@ -10,8 +10,8 @@ within Tauri's general support matrix).
|
||||
|
||||
| Component | Detail |
|
||||
|---|---|
|
||||
| **OS** | Windows 11 Pro 25H2 Insider Preview (Dev Channel) |
|
||||
| **Build** | 26300.8376 |
|
||||
| **OS** | Windows 11 Pro Insider Preview (Dev Channel) |
|
||||
| **Build** | 29648.1000 |
|
||||
| **CPU** | Intel Core i7-14700KF |
|
||||
| **GPU** | NVIDIA GeForce RTX 5080 (16 GB VRAM) |
|
||||
| **RAM** | 32 GB DDR5 |
|
||||
@@ -20,8 +20,8 @@ within Tauri's general support matrix).
|
||||
|
||||
## Mobile / web-test devices
|
||||
|
||||
Used to verify the web build (mainly the GitHub Pages deploy) on touch
|
||||
form factors:
|
||||
Used to verify the web build (mainly the production site,
|
||||
https://jsonprism.poli0981.dev) on touch form factors:
|
||||
|
||||
- iPhone 14 Pro — iOS 26.x — Chrome, Brave
|
||||
- iPhone 13 Pro Max — iOS 26.x — Chrome, Brave
|
||||
|
||||
@@ -10,6 +10,22 @@ Status legend:
|
||||
|
||||
Recommended minimum viewport: **360 × 640**. Phones in landscape orientation are best-effort — see [recommendation](#recommendation).
|
||||
|
||||
## v2.0.0 check (2026-10-22)
|
||||
|
||||
Chromium device emulation against the production build served by `wrangler dev` (`npm run preview:cf`), in the light and the dark theme at each size.
|
||||
|
||||
| Viewport | Form factor | Themes | Status | Notes |
|
||||
| ---------- | ----------- | ----------- | ------ | ------------------------------------- |
|
||||
| 360 × 740 | Phone | Light, dark | ✅ | No horizontal overflow; header fits |
|
||||
| 768 × 1024 | Tablet | Light, dark | ✅ | Split input/output layout from 768 px |
|
||||
| 1280 × 800 | Desktop | Light, dark | ✅ | Split input/output layout |
|
||||
|
||||
Also checked in this round:
|
||||
|
||||
- Consent Gate with the Turnstile flow on Cloudflare's test keys (always-pass sitekey and secret).
|
||||
- Appearance menu: theme switching and "Hide scrollbars".
|
||||
- Browser console free of Content-Security-Policy violations.
|
||||
|
||||
## Test results (last verified 2026-05-14)
|
||||
|
||||
### Phones (portrait)
|
||||
@@ -47,8 +63,10 @@ Recommended minimum viewport: **360 × 640**. Phones in landscape orientation ar
|
||||
|
||||
## How to retest
|
||||
|
||||
1. Open Chrome DevTools → "Toggle device toolbar" (Ctrl+Shift+M).
|
||||
2. Pick a device from the dropdown or set a custom viewport.
|
||||
3. Verify on the Home page: Header navigation visible, Input/Output Tabs accessible, FormatPicker trigger fits, no horizontal scroll on `<body>`.
|
||||
1. Serve the production build with `npm run preview:cf` (http://localhost:8787; needs `.dev.vars`, see [dev_env.md](dev_env.md)). Unlike `npm run dev`, it applies the CSP from `public/_headers` and runs the Worker that verifies Turnstile.
|
||||
2. Open Chrome DevTools → "Toggle device toolbar" (Ctrl+Shift+M).
|
||||
3. Pick a device from the dropdown or set a custom viewport.
|
||||
4. Verify on the Home page: Header navigation visible, Input/Output Tabs accessible, FormatPicker trigger fits, no horizontal scroll on `<body>`.
|
||||
5. Repeat in light and dark (Appearance menu), pass the Consent Gate (the Turnstile test key passes on its own), and check the console for CSP violations.
|
||||
|
||||
Test results contributed by the maintainer. PRs welcome to expand the matrix.
|
||||
+36
-14
@@ -1,28 +1,30 @@
|
||||
import js from '@eslint/js';
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
import globals from 'globals';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import reactRefresh from 'eslint-plugin-react-refresh';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist', 'node_modules', 'src/components/ui/**', 'src-tauri/**'] },
|
||||
export default defineConfig([
|
||||
globalIgnores([
|
||||
'.claude/**',
|
||||
'.idea/**',
|
||||
'dist',
|
||||
'coverage',
|
||||
'.wrangler',
|
||||
'node_modules',
|
||||
'src/components/ui/**',
|
||||
'src-tauri/**',
|
||||
'worker-configuration.d.ts',
|
||||
]),
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [js.configs.recommended, tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2022,
|
||||
ecmaVersion: 'latest',
|
||||
globals: globals.browser,
|
||||
},
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
'react-refresh': reactRefresh,
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'warn',
|
||||
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
|
||||
@@ -33,4 +35,24 @@ export default tseslint.config(
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
{
|
||||
files: ['src/**/*.{ts,tsx}'],
|
||||
extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite],
|
||||
rules: {
|
||||
// All diagnostics go through src/lib/logger.ts.
|
||||
'no-console': 'warn',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['src/lib/logger.ts'],
|
||||
rules: { 'no-console': 'off' },
|
||||
},
|
||||
{
|
||||
files: ['worker/**/*.ts'],
|
||||
languageOptions: { globals: globals.serviceworker },
|
||||
},
|
||||
{
|
||||
files: ['vite.config.ts', 'vitest.config.ts', 'eslint.config.js'],
|
||||
languageOptions: { globals: globals.node },
|
||||
},
|
||||
]);
|
||||
+37
-32
@@ -1,50 +1,55 @@
|
||||
<!doctype html>
|
||||
<html lang="en" class="dark">
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<meta name="color-scheme" content="dark light" />
|
||||
<meta name="theme-color" content="#0a0b14" />
|
||||
<meta name="theme-color" content="#0b0c14" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
|
||||
<!--
|
||||
Restores a deep-link path that public/404.html encoded into the query
|
||||
string on GitHub Pages (see that file). Must run before the SPA router
|
||||
reads the URL. No-op everywhere else (including Tauri) since `?/` is only
|
||||
ever present right after the 404 redirect.
|
||||
Applies the saved theme + display preferences before first paint (no
|
||||
flash of the wrong theme). External and blocking on purpose: an inline
|
||||
script would need 'unsafe-inline' in the web CSP, and Tauri hashes inline
|
||||
scripts into its CSP, which would disable 'unsafe-inline' for styles.
|
||||
-->
|
||||
<script type="text/javascript">
|
||||
(function (l) {
|
||||
if (l.search[1] === '/') {
|
||||
var decoded = l.search
|
||||
.slice(1)
|
||||
.split('&')
|
||||
.map(function (s) {
|
||||
return s.replace(/~and~/g, '&');
|
||||
})
|
||||
.join('?');
|
||||
window.history.replaceState(null, null, l.pathname.slice(0, -1) + decoded + l.hash);
|
||||
}
|
||||
})(window.location);
|
||||
</script>
|
||||
<script src="/theme-init.js"></script>
|
||||
|
||||
<meta name="description" content="JSONPrism — disperse JSON into many formats. Convert to JSONL, CSV, YAML, XML, TOML, RESX, Markdown, SQL. Fully client-side, batch up to 500 files." />
|
||||
<meta name="keywords" content="JSON, converter, JSONL, YAML, CSV, XML, TOML, RESX, Markdown, SQL, batch, offline" />
|
||||
<title>JSONPrism · Disperse JSON into 12 formats</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="JSONPrism converts JSON to JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR and MessagePack, and six of them back to JSON. Conversion runs on your device; batch up to 500 files."
|
||||
/>
|
||||
<meta
|
||||
name="keywords"
|
||||
content="JSON converter, JSONL, NDJSON, CSV, YAML, XML, TOML, RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack, batch, offline"
|
||||
/>
|
||||
<!-- Updated per route by Layout (useCanonicalUrl). -->
|
||||
<link rel="canonical" href="https://jsonprism.poli0981.dev/" />
|
||||
|
||||
<!-- Open Graph -->
|
||||
<meta property="og:title" content="JSONPrism — Disperse JSON into many formats" />
|
||||
<meta property="og:description" content="A refracting tool for developers. One JSON input, eight target formats, fully in-browser." />
|
||||
<!-- Open Graph / link previews (Discord, X, Bluesky) -->
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:site_name" content="JSONPrism" />
|
||||
<meta property="og:title" content="JSONPrism — Disperse JSON into 12 formats" />
|
||||
<meta
|
||||
property="og:description"
|
||||
content="A refracting tool for developers: one JSON input, twelve target formats, six of them reversible. Runs on your device."
|
||||
/>
|
||||
<meta property="og:url" content="https://jsonprism.poli0981.dev/" />
|
||||
<meta property="og:image" content="https://jsonprism.poli0981.dev/og-image.png" />
|
||||
<meta property="og:image:width" content="1200" />
|
||||
<meta property="og:image:height" content="630" />
|
||||
<meta property="og:image:alt" content="JSONPrism — a prism splitting JSON into many formats" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
|
||||
<!--
|
||||
Fonts: Instrument Serif (display) + Geist (body) + JetBrains Mono (code).
|
||||
Self-hosted via @fontsource and imported in src/main.tsx so the app works
|
||||
fully offline (desktop + Android sideload) with no third-party requests.
|
||||
Fonts: Geist (UI + headings) and JetBrains Mono (code), self-hosted via
|
||||
@fontsource and imported in src/main.tsx so the app works fully offline
|
||||
(desktop + Android) with no third-party font requests.
|
||||
-->
|
||||
|
||||
<title>JSONPrism · Disperse JSON</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>JSONPrism needs JavaScript to convert files in your browser.</noscript>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
{
|
||||
"project": ["src/**/*.{ts,tsx}"],
|
||||
"$schema": "https://unpkg.com/knip@6/schema.json",
|
||||
"entry": ["src/lib/convert-worker.ts"],
|
||||
"project": ["src/**/*.{ts,tsx,css}", "worker/**/*.ts"],
|
||||
"ignore": ["src/components/ui/**"],
|
||||
"ignoreDependencies": [
|
||||
"@radix-ui/react-slot",
|
||||
"tailwindcss",
|
||||
"tw-animate-css",
|
||||
"@tauri-apps/plugin-opener",
|
||||
"@tauri-apps/plugin-os",
|
||||
"@testing-library/user-event"
|
||||
],
|
||||
"ignoreDependencies": ["@radix-ui/react-slot", "@testing-library/user-event"],
|
||||
"rules": {
|
||||
"types": "off"
|
||||
}
|
||||
|
||||
Generated
+4214
-1674
File diff suppressed because it is too large.
Load diff
+81
-74
@@ -1,18 +1,21 @@
|
||||
{
|
||||
"name": "jsonprism",
|
||||
"private": true,
|
||||
"version": "1.7.2",
|
||||
"version": "2.0.0",
|
||||
"type": "module",
|
||||
"description": "Disperse JSON into many formats — JSONL, CSV, YAML, XML, TOML, RESX, Markdown, SQL — fully client-side.",
|
||||
"author": "poli0981 <https://github.com/poli0981>",
|
||||
"description": "Disperse JSON into 12 formats (six convert back) — JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR, MessagePack. Conversion runs locally in your browser or desktop app.",
|
||||
"author": "poli0981 <code@poli0981.dev> (https://github.com/poli0981)",
|
||||
"license": "Apache-2.0",
|
||||
"homepage": "https://poli0981.github.io/jsonPrism/",
|
||||
"homepage": "https://jsonprism.poli0981.dev",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/poli0981/jsonPrism.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/poli0981/jsonPrism/issues"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.11.0"
|
||||
"node": ">=26.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -21,13 +24,16 @@
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"knip": "knip",
|
||||
"format": "prettier --write \"src/**/*.{ts,tsx,css,md,json}\"",
|
||||
"format:check": "prettier --check \"src/**/*.{ts,tsx,css,md,json}\"",
|
||||
"typecheck": "tsc -b --noEmit",
|
||||
"format": "prettier --write \"src/**/*.{ts,tsx,css,md,json}\" \"worker/**/*.ts\"",
|
||||
"format:check": "prettier --check \"src/**/*.{ts,tsx,css,md,json}\" \"worker/**/*.ts\"",
|
||||
"typecheck": "tsc -b && npm run typecheck:worker",
|
||||
"typecheck:worker": "wrangler types && tsc -p tsconfig.worker.json",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"cf:types": "wrangler types",
|
||||
"cf:check": "wrangler deploy --dry-run --outdir .wrangler/dry-run",
|
||||
"preview:cf": "wrangler dev",
|
||||
"tauri": "tauri",
|
||||
"tauri:dev": "tauri dev",
|
||||
"tauri:build": "tauri build",
|
||||
@@ -37,79 +43,80 @@
|
||||
"tauri:android:build": "npm run tauri:icon && tauri android build --apk"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/lang-json": "^6.0.0",
|
||||
"@codemirror/lang-markdown": "^6.5.0",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/lang-markdown": "^6.5.2",
|
||||
"@codemirror/lang-sql": "^6.10.0",
|
||||
"@codemirror/lang-xml": "^6.1.0",
|
||||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/language": "^6.10.0",
|
||||
"@codemirror/legacy-modes": "^6.5.3",
|
||||
"@codemirror/language": "^6.13.1",
|
||||
"@codemirror/legacy-modes": "^6.5.5",
|
||||
"@codemirror/lint": "^6.9.7",
|
||||
"@codemirror/state": "^6.4.0",
|
||||
"@codemirror/view": "^6.43.1",
|
||||
"@fontsource-variable/geist": "^5.2.9",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.2.8",
|
||||
"@fontsource/instrument-serif": "^5.2.8",
|
||||
"@lezer/highlight": "^1.2.0",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/view": "^6.43.15",
|
||||
"@fontsource-variable/geist": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@lezer/highlight": "^1.2.5",
|
||||
"@marsidev/react-turnstile": "^1.6.3",
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
"@radix-ui/react-dialog": "^1.1.16",
|
||||
"@radix-ui/react-slot": "^1.1.0",
|
||||
"@radix-ui/react-switch": "^1.3.0",
|
||||
"@radix-ui/react-tabs": "^1.1.14",
|
||||
"@tauri-apps/api": "^2.0.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.0.0",
|
||||
"@tauri-apps/plugin-fs": "^2.0.0",
|
||||
"@tauri-apps/plugin-opener": "^2.0.0",
|
||||
"@tauri-apps/plugin-os": "^2.0.0",
|
||||
"@uiw/react-codemirror": "^4.25.10",
|
||||
"bson": "^7.2.0",
|
||||
"cbor-x": "^1.6.4",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.0",
|
||||
"fast-xml-parser": "^5.8.0",
|
||||
"@radix-ui/react-dialog": "^1.3.1",
|
||||
"@radix-ui/react-slot": "^1.5.0",
|
||||
"@radix-ui/react-switch": "^1.4.1",
|
||||
"@radix-ui/react-tabs": "^1.2.1",
|
||||
"@tauri-apps/api": "^2.12.4",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.3",
|
||||
"@tauri-apps/plugin-fs": "^2.7.1",
|
||||
"@tauri-apps/plugin-opener": "^2.7.2",
|
||||
"@uiw/react-codemirror": "^4.25.12",
|
||||
"bson": "^7.3.3",
|
||||
"cbor-x": "^1.6.8",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"fast-xml-parser": "^5.11.2",
|
||||
"fflate": "^0.8.3",
|
||||
"i18next": "^23.0.0",
|
||||
"i18next-browser-languagedetector": "^8.0.0",
|
||||
"js-yaml": "^4.2.0",
|
||||
"lucide-react": "^0.460.0",
|
||||
"papaparse": "^5.4.0",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-dropzone": "^14.3.0",
|
||||
"react-i18next": "^15.0.0",
|
||||
"react-router-dom": "^7.17.0",
|
||||
"smol-toml": "^1.3.0",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^2.5.0",
|
||||
"zustand": "^5.0.14"
|
||||
"i18next": "^26.5.5",
|
||||
"i18next-browser-languagedetector": "^8.2.1",
|
||||
"js-yaml": "^5.5.0",
|
||||
"lucide-react": "^1.61.0",
|
||||
"papaparse": "^5.7.0",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-dropzone": "^20.1.4",
|
||||
"react-i18next": "^17.1.1",
|
||||
"react-router": "^8.5.0",
|
||||
"smol-toml": "^1.9.1",
|
||||
"sonner": "^2.0.8",
|
||||
"tailwind-merge": "^3.7.0",
|
||||
"zustand": "^5.0.16"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@tailwindcss/vite": "^4.3.1",
|
||||
"@tauri-apps/cli": "^2.11.2",
|
||||
"@testing-library/jest-dom": "^6.6.0",
|
||||
"@testing-library/react": "^16.1.0",
|
||||
"@testing-library/user-event": "^14.5.0",
|
||||
"@types/js-yaml": "^4.0.0",
|
||||
"@types/node": "^25.9.3",
|
||||
"@types/papaparse": "^5.3.0",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"@vitest/coverage-v8": "^4.1.8",
|
||||
"eslint": "^10.5.0",
|
||||
"eslint-plugin-react-hooks": "^5.0.0",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.6.0",
|
||||
"jsdom": "^29.0.0",
|
||||
"knip": "^6.16.1",
|
||||
"prettier": "^3.8.4",
|
||||
"prettier-plugin-tailwindcss": "^0.8.0",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"tw-animate-css": "^1.2.0",
|
||||
"typescript": "^5.7.0",
|
||||
"typescript-eslint": "^8.61.0",
|
||||
"vite": "^8.0.16",
|
||||
"vitest": "^4.1.6"
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tauri-apps/cli": "^2.12.4",
|
||||
"@testing-library/dom": "^10.4.2",
|
||||
"@testing-library/jest-dom": "^7.0.1",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.8",
|
||||
"@types/node": "^26.6.5",
|
||||
"@types/papaparse": "^5.5.2",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@typescript/native": "npm:typescript@^7.0.2",
|
||||
"@vitejs/plugin-react": "^6.1.2",
|
||||
"@vitest/coverage-v8": "^5.0.5",
|
||||
"eslint": "^10.13.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.7",
|
||||
"globals": "^17.13.0",
|
||||
"jsdom": "^30.1.3",
|
||||
"knip": "^6.42.1",
|
||||
"prettier": "^3.9.10",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "npm:@typescript/typescript6@^6.0.2",
|
||||
"typescript-eslint": "^8.72.0",
|
||||
"vite": "^8.3.5",
|
||||
"vitest": "^5.0.5",
|
||||
"wrangler": "^4.151.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Security contact for JSONPrism (RFC 9116). Policy: SECURITY.md.
|
||||
Contact: https://github.com/poli0981/jsonPrism/security/advisories/new
|
||||
Contact: mailto:security@poli0981.dev
|
||||
Expires: 2027-10-01T00:00:00.000Z
|
||||
Preferred-Languages: en, vi
|
||||
Canonical: https://jsonprism.poli0981.dev/.well-known/security.txt
|
||||
Policy: https://github.com/poli0981/jsonPrism/blob/main/SECURITY.md
|
||||
@@ -1,41 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>JSONPrism</title>
|
||||
<!--
|
||||
GitHub Pages serves this file for any unknown path. Because JSONPrism is a
|
||||
BrowserRouter SPA, a deep-link refresh (e.g. /jsonPrism/about) would 404
|
||||
here. This script encodes the requested path into a query string and
|
||||
redirects to the app's index, where a small decoder in index.html restores
|
||||
the real route. Technique: https://github.com/rafgraph/spa-github-pages
|
||||
|
||||
pathSegmentsToKeep = 1 preserves the project-page base segment (/jsonPrism/).
|
||||
-->
|
||||
<script type="text/javascript">
|
||||
var pathSegmentsToKeep = 1;
|
||||
var l = window.location;
|
||||
l.replace(
|
||||
l.protocol +
|
||||
'//' +
|
||||
l.hostname +
|
||||
(l.port ? ':' + l.port : '') +
|
||||
l.pathname
|
||||
.split('/')
|
||||
.slice(0, 1 + pathSegmentsToKeep)
|
||||
.join('/') +
|
||||
'/?/' +
|
||||
l.pathname
|
||||
.slice(1)
|
||||
.split('/')
|
||||
.slice(pathSegmentsToKeep)
|
||||
.join('/')
|
||||
.replace(/&/g, '~and~') +
|
||||
(l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
|
||||
l.hash,
|
||||
);
|
||||
</script>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
@@ -0,0 +1,26 @@
|
||||
# Response headers for static assets (Cloudflare Workers Static Assets).
|
||||
# API responses from worker/ set their own headers.
|
||||
#
|
||||
# CSP notes:
|
||||
# - script-src: the Cloudflare Web Analytics beacon and the Turnstile widget.
|
||||
# - style-src 'unsafe-inline': CodeMirror, Radix and Sonner inject styles at runtime.
|
||||
# - connect-src: the analytics beacon reports to cloudflareinsights.com (or /cdn-cgi/rum).
|
||||
# - frame-src: the Turnstile challenge iframe.
|
||||
# - worker-src 'self': the conversion Web Worker.
|
||||
/*
|
||||
Content-Security-Policy: default-src 'self'; script-src 'self' https://static.cloudflareinsights.com https://challenges.cloudflare.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' https://cloudflareinsights.com; frame-src https://challenges.cloudflare.com; worker-src 'self'; manifest-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests
|
||||
Strict-Transport-Security: max-age=31536000
|
||||
X-Content-Type-Options: nosniff
|
||||
X-Frame-Options: DENY
|
||||
Referrer-Policy: strict-origin-when-cross-origin
|
||||
Permissions-Policy: accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=(), browsing-topics=()
|
||||
Cross-Origin-Opener-Policy: same-origin
|
||||
# HTML must revalidate so a deploy is picked up; no-transform keeps zone
|
||||
# features (Rocket Loader, Email Obfuscation) from rewriting pages and
|
||||
# breaking the CSP.
|
||||
Cache-Control: no-cache, no-transform
|
||||
|
||||
# Vite's hashed bundles never change content under the same name.
|
||||
/assets/*
|
||||
! Cache-Control
|
||||
Cache-Control: public, max-age=31536000, immutable
|
||||
@@ -0,0 +1,4 @@
|
||||
# Old GitHub Pages paths (https://poli0981.github.io/jsonPrism/…) carried a
|
||||
# /jsonPrism prefix; keep links that were rewritten to the new host working.
|
||||
/jsonPrism / 301
|
||||
/jsonPrism/* /:splat 301
|
||||
+10
-2
@@ -1,8 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none">
|
||||
<style>
|
||||
.ink { stroke: #f5f5f5; }
|
||||
.body { fill: #0b0c14; }
|
||||
@media (prefers-color-scheme: light) {
|
||||
.ink { stroke: #14151f; }
|
||||
.body { fill: #fbfbfe; }
|
||||
}
|
||||
</style>
|
||||
<!-- Incoming white ray -->
|
||||
<line x1="2" y1="32" x2="22" y2="32" stroke="#f5f5f5" stroke-width="3" stroke-linecap="round" />
|
||||
<line class="ink" x1="2" y1="32" x2="22" y2="32" stroke-width="3" stroke-linecap="round" />
|
||||
<!-- Prism triangle -->
|
||||
<path d="M22 12 L46 32 L22 52 Z" fill="#0a0b14" stroke="#f5f5f5" stroke-width="2.5" stroke-linejoin="round" />
|
||||
<path class="ink body" d="M22 12 L46 32 L22 52 Z" stroke-width="2.5" stroke-linejoin="round" />
|
||||
<!-- Dispersed rays -->
|
||||
<line x1="46" y1="32" x2="62" y2="20" stroke="#a78bfa" stroke-width="2.5" stroke-linecap="round" />
|
||||
<line x1="46" y1="32" x2="62" y2="28" stroke="#22d3ee" stroke-width="2.5" stroke-linecap="round" />
|
||||
|
||||
|
Before Width: | Height: | Size: 782 B After Width: | Height: | Size: 954 B |
Binary file not shown.
|
After Width: | Height: | Size: 157 KiB |
@@ -0,0 +1,4 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
|
||||
Sitemap: https://jsonprism.poli0981.dev/sitemap.xml
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url>
|
||||
<loc>https://jsonprism.poli0981.dev/</loc>
|
||||
<lastmod>2026-10-22</lastmod>
|
||||
<changefreq>monthly</changefreq>
|
||||
<priority>1.0</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://jsonprism.poli0981.dev/about</loc>
|
||||
<lastmod>2026-10-22</lastmod>
|
||||
<changefreq>monthly</changefreq>
|
||||
<priority>0.5</priority>
|
||||
</url>
|
||||
</urlset>
|
||||
@@ -0,0 +1,29 @@
|
||||
// Applies the saved theme and display preferences before the first paint so
|
||||
// the page never flashes the wrong theme. Loaded as a blocking external script
|
||||
// (not inline) so the Content-Security-Policy can stay free of 'unsafe-inline'.
|
||||
// Mirrors src/lib/theme.tsx and src/stores/preferencesStore.ts — keep the
|
||||
// storage keys and colors in sync with those files.
|
||||
(function () {
|
||||
var root = document.documentElement;
|
||||
var theme = 'system';
|
||||
var hideScrollbars = false;
|
||||
try {
|
||||
var stored = window.localStorage.getItem('jsonprism.theme');
|
||||
if (stored === 'light' || stored === 'dark' || stored === 'system') theme = stored;
|
||||
var prefs = JSON.parse(window.localStorage.getItem('jsonprism.prefs') || 'null');
|
||||
hideScrollbars = !!(prefs && prefs.hideScrollbars === true);
|
||||
} catch (e) {
|
||||
// Blocked storage: fall back to the system theme.
|
||||
}
|
||||
// Same default as systemTheme() in src/lib/theme-dom.ts: dark when the
|
||||
// browser cannot report a preference.
|
||||
var dark =
|
||||
theme === 'dark' ||
|
||||
(theme === 'system' &&
|
||||
(!window.matchMedia || window.matchMedia('(prefers-color-scheme: dark)').matches));
|
||||
root.classList.toggle('dark', dark);
|
||||
root.style.colorScheme = dark ? 'dark' : 'light';
|
||||
if (hideScrollbars) root.setAttribute('data-scrollbars', 'hidden');
|
||||
var meta = document.querySelector('meta[name="theme-color"]');
|
||||
if (meta) meta.setAttribute('content', dark ? '#0b0c14' : '#fbfbfe');
|
||||
})();
|
||||
@@ -0,0 +1,22 @@
|
||||
# SonarQube Cloud, CI-based analysis (.github/workflows/ci.yml, job "sonar").
|
||||
# Automatic Analysis must stay off in the project settings, or the CI scan fails.
|
||||
sonar.organization=poli0981
|
||||
sonar.projectKey=poli0981_jsonPrism
|
||||
sonar.projectName=JSONPrism
|
||||
sonar.sourceEncoding=UTF-8
|
||||
|
||||
# The Android project under src-tauri/gen is Tauri scaffolding; only the files
|
||||
# we maintain (manifest, Kotlin entry point) are analysed, not its Gradle setup.
|
||||
sonar.sources=src,worker,src-tauri/src,src-tauri/gen/android/app/src/main,.github/workflows,vite.config.ts,vitest.config.ts
|
||||
sonar.tests=src,worker
|
||||
sonar.test.inclusions=**/__tests__/**,**/*.test.ts,**/*.test.tsx,src/test/**
|
||||
sonar.exclusions=**/__tests__/**,**/*.test.ts,**/*.test.tsx,src/test/**,src/components/ui/**,**/*.d.ts,src-tauri/gen/android/app/src/main/res/**
|
||||
|
||||
# Coverage comes from Vitest (npm run test:coverage). Rust, Android and
|
||||
# workflow files have no JS coverage to report.
|
||||
sonar.javascript.lcov.reportPaths=coverage/lcov.info
|
||||
sonar.coverage.exclusions=src/main.tsx,src/i18n/locales/**,src-tauri/**,.github/**,vite.config.ts,vitest.config.ts
|
||||
sonar.cpd.exclusions=src/i18n/locales/**
|
||||
|
||||
# Report the Quality Gate without blocking CI until coverage settles.
|
||||
sonar.qualitygate.wait=false
|
||||
Generated
+687
-1020
File diff suppressed because it is too large.
Load diff
@@ -1,12 +1,13 @@
|
||||
[package]
|
||||
name = "jsonprism"
|
||||
version = "1.7.2"
|
||||
version = "2.0.0"
|
||||
description = "Disperse JSON into many formats."
|
||||
authors = ["poli0981 <https://github.com/poli0981>"]
|
||||
authors = ["poli0981 <code@poli0981.dev>"]
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/poli0981/jsonPrism"
|
||||
homepage = "https://jsonprism.poli0981.dev"
|
||||
edition = "2021"
|
||||
rust-version = "1.77"
|
||||
rust-version = "1.90"
|
||||
|
||||
# Disable the default `main.rs` binary lookup; we want a library + bin.
|
||||
[lib]
|
||||
@@ -21,7 +22,6 @@ tauri = { version = "2", features = [] }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-fs = "2"
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-os = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
|
||||
|
||||
@@ -1,29 +1,20 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Default permissions for the JSONPrism main window.",
|
||||
"description": "JSONPrism main window: native open/save dialogs, reading files the user picks or drops, writing where they choose to save, and opening links in the system browser. Picked and dropped paths are added to the fs scope at runtime; the static scope only covers common folders.",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-unlisten",
|
||||
"core:webview:default",
|
||||
"core:window:default",
|
||||
"core:window:allow-set-title",
|
||||
"opener:default",
|
||||
"os:default",
|
||||
"dialog:default",
|
||||
"dialog:allow-open",
|
||||
"dialog:allow-save",
|
||||
"dialog:allow-message",
|
||||
"fs:default",
|
||||
"fs:allow-read-text-file",
|
||||
"fs:allow-write-text-file",
|
||||
"fs:allow-write-file",
|
||||
"fs:allow-stat",
|
||||
{
|
||||
"identifier": "fs:scope",
|
||||
"allow": ["$HOME/**", "$DOCUMENT/**", "$DOWNLOAD/**", "$DESKTOP/**"]
|
||||
"allow": ["$DOCUMENT/**", "$DOWNLOAD/**", "$DESKTOP/**"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
<uses-feature android:name="android.software.leanback" android:required="false" />
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.jsonprism"
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
{\rtf1\ansi\ansicpg1252\deff0
|
||||
{\fonttbl{\f0\fswiss Segoe UI;}}
|
||||
\f0\fs20
|
||||
\b JSONPrism \endash End User License Agreement\b0\par
|
||||
\b JSONPrism 2.0 \endash End User License Agreement\b0\par
|
||||
\par
|
||||
By installing and using JSONPrism, you agree to the terms below.\par
|
||||
\par
|
||||
JSONPrism is free, open-source software licensed under the Apache License 2.0:\par
|
||||
https://github.com/poli0981/jsonPrism/blob/main/LICENSE\par
|
||||
https://github.com/poli0981/jsonPrism/blob/v2.0.0/LICENSE\par
|
||||
\par
|
||||
Your use is also governed by the following documents:\par
|
||||
\bullet\tab Terms of Use (EULA): https://github.com/poli0981/jsonPrism/blob/main/TERMS.md\par
|
||||
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/main/PRIVACY.md\par
|
||||
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/main/DISCLAIMER.md\par
|
||||
Your use is also governed by the following documents (version 2.0, effective 2026-10-22):\par
|
||||
\bullet\tab Terms of Service (EULA): https://github.com/poli0981/jsonPrism/blob/v2.0.0/TERMS.md\par
|
||||
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/v2.0.0/PRIVACY.md\par
|
||||
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/v2.0.0/DISCLAIMER.md\par
|
||||
\par
|
||||
JSONPrism is provided \ldblquote as is\rdblquote , without warranty of any kind. It runs fully on your device and sends no data to any server.\par
|
||||
JSONPrism is provided \ldblquote as is\rdblquote , without warranty of any kind. The desktop app converts everything on your device and makes no network requests of its own.\par
|
||||
\par
|
||||
Questions: legal@poli0981.dev\par
|
||||
\par
|
||||
If you do not agree to these terms, do not install or use this software.\par
|
||||
}
|
||||
@@ -45,7 +45,6 @@ pub fn run() {
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.plugin(tauri_plugin_os::init())
|
||||
.invoke_handler(tauri::generate_handler![host_info])
|
||||
.on_window_event(|window, event| {
|
||||
// Ensure the main window doesn't hold up the runtime on close.
|
||||
@@ -53,7 +52,7 @@ pub fn run() {
|
||||
// process alive when the webview is the last live handle.
|
||||
if let WindowEvent::CloseRequested { .. } = event {
|
||||
if window.label() == "main" {
|
||||
let _ = window.app_handle().exit(0);
|
||||
window.app_handle().exit(0);
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -76,9 +75,8 @@ pub fn run() {
|
||||
|
||||
app.run(|app_handle, event| {
|
||||
if let RunEvent::ExitRequested { .. } = event {
|
||||
// Let Tauri's default exit path proceed — plugins clean up on drop.
|
||||
// Explicitly request cleanup so any spawned shell children are
|
||||
// sent SIGTERM/TerminateProcess before the process exits.
|
||||
// Let Tauri's default exit path proceed, but release plugin and
|
||||
// window resources first so nothing outlives the process.
|
||||
app_handle.cleanup_before_exit();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "JSONPrism",
|
||||
"version": "1.7.2",
|
||||
"version": "../package.json",
|
||||
"identifier": "com.poli0981.jsonprism",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
@@ -26,7 +26,7 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; connect-src 'self' ipc: http://ipc.localhost"
|
||||
"csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
@@ -42,10 +42,10 @@
|
||||
],
|
||||
"category": "DeveloperTool",
|
||||
"shortDescription": "Disperse JSON into many formats",
|
||||
"longDescription": "JSONPrism is a refracting tool for developers. It takes a single JSON input and disperses it into many target formats — JSONL, CSV/TSV, YAML, XML, TOML, Markdown, SQL INSERT — fully on your machine.",
|
||||
"longDescription": "JSONPrism is a refracting tool for developers. It takes a single JSON input and disperses it into twelve formats — JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR and MessagePack — and parses six of them back, entirely on your machine.",
|
||||
"copyright": "Copyright (c) 2026 poli0981",
|
||||
"publisher": "poli0981",
|
||||
"homepage": "https://github.com/poli0981/jsonPrism",
|
||||
"homepage": "https://jsonprism.poli0981.dev",
|
||||
"windows": {
|
||||
"wix": {
|
||||
"language": "en-US"
|
||||
@@ -78,12 +78,12 @@
|
||||
},
|
||||
"android": {
|
||||
"minSdkVersion": 31,
|
||||
"versionCode": 10702
|
||||
"versionCode": 20000
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
"fs": {
|
||||
"requireLiteralLeadingDot": false
|
||||
"requireLiteralLeadingDot": true
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
-6
@@ -1,11 +1,14 @@
|
||||
import { lazy } from 'react';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
import { lazy, useEffect } from 'react';
|
||||
import { Route, Routes } from 'react-router';
|
||||
import { ThemeProvider } from '@/lib/theme';
|
||||
import { ErrorBoundary } from '@/components/common/ErrorBoundary';
|
||||
import { ConsentGate } from '@/components/common/ConsentGate';
|
||||
import { Layout } from '@/components/layout/Layout';
|
||||
import { Toaster } from '@/components/ui/sonner';
|
||||
import { useExternalLinkInterceptor } from '@/hooks/useExternalLinkInterceptor';
|
||||
import { loadWebAnalytics } from '@/lib/analytics';
|
||||
import { useConsentStore } from '@/stores/consentStore';
|
||||
import { usePreferencesStore } from '@/stores/preferencesStore';
|
||||
|
||||
// Routes are code-split so the entry chunk stays small and the consent gate +
|
||||
// app shell paint before any page's heavy graph (editor, parsers) loads.
|
||||
@@ -14,12 +17,24 @@ const About = lazy(() => import('@/pages/About').then((m) => ({ default: m.About
|
||||
const NotFound = lazy(() => import('@/pages/errors/NotFound'));
|
||||
const ErrorRoute = lazy(() => import('@/pages/errors/ErrorRoute'));
|
||||
|
||||
/** Cloudflare Web Analytics: production web only, after consent, if the user didn't opt out. */
|
||||
function useWebAnalytics() {
|
||||
const consented = useConsentStore((s) => s.accepted);
|
||||
const enabled = usePreferencesStore((s) => s.analytics);
|
||||
useEffect(() => {
|
||||
loadWebAnalytics({ consented, enabled });
|
||||
}, [consented, enabled]);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
useExternalLinkInterceptor();
|
||||
useWebAnalytics();
|
||||
|
||||
return (
|
||||
<ThemeProvider defaultTheme="system">
|
||||
<ErrorBoundary>
|
||||
// The crash boundary is outermost so even a theme/storage failure renders
|
||||
// the fallback instead of a blank page.
|
||||
<ErrorBoundary>
|
||||
<ThemeProvider defaultTheme="system">
|
||||
<ConsentGate>
|
||||
<Routes>
|
||||
<Route element={<Layout />}>
|
||||
@@ -31,7 +46,7 @@ export function App() {
|
||||
</Routes>
|
||||
<Toaster />
|
||||
</ConsentGate>
|
||||
</ErrorBoundary>
|
||||
</ThemeProvider>
|
||||
</ThemeProvider>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import '@/i18n';
|
||||
import { App } from '../App';
|
||||
import { loadWebAnalytics } from '@/lib/analytics';
|
||||
import { useConsentStore } from '@/stores/consentStore';
|
||||
import { usePreferencesStore } from '@/stores/preferencesStore';
|
||||
|
||||
const home = vi.hoisted(() => ({ crash: false }));
|
||||
|
||||
vi.mock('@/lib/analytics', () => ({ loadWebAnalytics: vi.fn(() => false) }));
|
||||
|
||||
// The real workspace pulls in the editor and every parser; the routing and
|
||||
// app-shell wiring are what's under test here.
|
||||
vi.mock('@/pages/Home', () => ({
|
||||
Home: () => {
|
||||
if (home.crash) throw new Error('Workspace exploded');
|
||||
return <h1>Converter workspace</h1>;
|
||||
},
|
||||
}));
|
||||
|
||||
function renderApp(path = '/') {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<App />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
home.crash = false;
|
||||
useConsentStore.setState({ accepted: true, humanVerified: true });
|
||||
usePreferencesStore.setState({ hideScrollbars: false, analytics: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
document.documentElement.classList.remove('dark');
|
||||
});
|
||||
|
||||
describe('App', () => {
|
||||
it.each([
|
||||
['/', 'Converter workspace'],
|
||||
['/about', 'About JSONPrism'],
|
||||
['/error/403', 'Forbidden'],
|
||||
['/no/such/page', 'Page not found'],
|
||||
])('renders %s inside the app shell', async (path, heading) => {
|
||||
renderApp(path);
|
||||
expect(await screen.findByRole('heading', { level: 1, name: heading })).toBeInTheDocument();
|
||||
expect(screen.getByRole('banner')).toBeInTheDocument();
|
||||
expect(screen.getByRole('contentinfo')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('mounts the translated toast region', async () => {
|
||||
renderApp('/');
|
||||
await screen.findByRole('heading', { name: 'Converter workspace' });
|
||||
expect(screen.getByRole('region', { name: /^Notifications/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('puts the consent gate in front of the app on first launch', async () => {
|
||||
useConsentStore.setState({ accepted: false });
|
||||
renderApp('/');
|
||||
expect(await screen.findByRole('dialog', { name: 'Before you start' })).toBeInTheDocument();
|
||||
// The shell renders behind the modal but is hidden from assistive tech.
|
||||
expect(screen.queryByRole('banner')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('loads analytics only after consent and re-checks when the opt-out changes', async () => {
|
||||
useConsentStore.setState({ accepted: false });
|
||||
renderApp('/');
|
||||
await screen.findByRole('dialog');
|
||||
expect(loadWebAnalytics).toHaveBeenLastCalledWith({ consented: false, enabled: true });
|
||||
|
||||
act(() => useConsentStore.getState().accept());
|
||||
expect(loadWebAnalytics).toHaveBeenLastCalledWith({ consented: true, enabled: true });
|
||||
|
||||
act(() => usePreferencesStore.getState().setAnalytics(false));
|
||||
expect(loadWebAnalytics).toHaveBeenLastCalledWith({ consented: true, enabled: false });
|
||||
});
|
||||
|
||||
it('falls back to the crash screen when a page fails for reasons other than loading', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
home.crash = true;
|
||||
renderApp('/');
|
||||
expect(
|
||||
await screen.findByRole('heading', { name: 'Something refracted unexpectedly.' }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('Workspace exploded')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Reload' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react';
|
||||
import { ChunkErrorFallback } from '@/components/common/ChunkErrorFallback';
|
||||
import { isChunkLoadError } from '@/lib/chunk-error';
|
||||
import { createLogger } from '@/lib/logger';
|
||||
|
||||
const log = createLogger('chunk');
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
@@ -25,7 +28,7 @@ export class ChunkErrorBoundary extends Component<Props, State> {
|
||||
|
||||
override componentDidCatch(error: Error, info: ErrorInfo): void {
|
||||
if (isChunkLoadError(error)) {
|
||||
console.error('JSONPrism chunk-load error:', error, info);
|
||||
log.error('Chunk failed to load:', error, info.componentStack ?? '');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,83 +8,127 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { HumanCheck } from '@/components/common/HumanCheck';
|
||||
import { legalDocUrl } from '@/lib/links';
|
||||
import { isTurnstileEnabled } from '@/lib/turnstile';
|
||||
import { useConsentStore } from '@/stores/consentStore';
|
||||
|
||||
const REPO_URL = 'https://github.com/poli0981/jsonPrism';
|
||||
|
||||
const LEGAL_LINKS = [
|
||||
{ key: 'license', href: `${REPO_URL}/blob/main/LICENSE` },
|
||||
{ key: 'terms', href: `${REPO_URL}/blob/main/TERMS.md` },
|
||||
{ key: 'privacy', href: `${REPO_URL}/blob/main/PRIVACY.md` },
|
||||
{ key: 'disclaimer', href: `${REPO_URL}/blob/main/DISCLAIMER.md` },
|
||||
const LEGAL_DOCS = [
|
||||
{ key: 'license', file: 'LICENSE' },
|
||||
{ key: 'terms', file: 'TERMS.md' },
|
||||
{ key: 'privacy', file: 'PRIVACY.md' },
|
||||
{ key: 'disclaimer', file: 'DISCLAIMER.md' },
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* First-launch legal gate (web + Android). Blocks the app behind a
|
||||
* non-dismissible modal until the user accepts. On desktop the store seeds
|
||||
* `accepted = true` (the installer's license page already gated acceptance), so
|
||||
* this renders its children straight through; the Android sideload APK has no
|
||||
* such installer step, so it shows the gate like the web build.
|
||||
* First-launch legal gate. Blocks the app behind a non-dismissible modal until
|
||||
* the user accepts; on the web build it also runs the Cloudflare Turnstile
|
||||
* human check (re-run alone every 7 days for returning visitors).
|
||||
*
|
||||
* The app renders behind the modal (inert) so the page has real content for
|
||||
* search engines and context for the user. Windows desktop builds skip the
|
||||
* gate — their installer's license page already required acceptance.
|
||||
*/
|
||||
export function ConsentGate({ children }: { children: ReactNode }) {
|
||||
const accepted = useConsentStore((s) => s.accepted);
|
||||
const accept = useConsentStore((s) => s.accept);
|
||||
const { t } = useTranslation();
|
||||
const [checked, setChecked] = useState(false);
|
||||
|
||||
if (accepted) return <>{children}</>;
|
||||
const humanVerified = useConsentStore((s) => s.humanVerified);
|
||||
const gated = !accepted || !humanVerified;
|
||||
|
||||
// One stable wrapper, so passing the gate doesn't remount the whole app.
|
||||
return (
|
||||
<div className="bg-background h-dvh w-full">
|
||||
<Dialog open>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
onEscapeKeyDown={(e) => e.preventDefault()}
|
||||
onPointerDownOutside={(e) => e.preventDefault()}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
className="max-w-md"
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('consent.title')}</DialogTitle>
|
||||
<DialogDescription>{t('consent.intro')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ul className="flex flex-wrap gap-x-4 gap-y-1 text-sm">
|
||||
{LEGAL_LINKS.map((l) => (
|
||||
<li key={l.key}>
|
||||
<a
|
||||
href={l.href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary inline-flex items-center gap-1 underline-offset-4 hover:underline"
|
||||
>
|
||||
{t(`consent.links.${l.key}`)}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<label className="flex cursor-pointer items-start gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={(e) => setChecked(e.target.checked)}
|
||||
className="accent-primary mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<span>{t('consent.agree')}</span>
|
||||
</label>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
disabled={!checked}
|
||||
onClick={accept}
|
||||
className="bg-primary text-primary-foreground rounded-md px-4 py-2 text-sm font-medium transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
<>
|
||||
<div inert={gated} aria-hidden={gated || undefined} className={gated ? 'h-dvh' : 'contents'}>
|
||||
{children}
|
||||
</div>
|
||||
{gated && (
|
||||
<Dialog open>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
onEscapeKeyDown={(e) => e.preventDefault()}
|
||||
onPointerDownOutside={(e) => e.preventDefault()}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
className="max-w-md"
|
||||
>
|
||||
{t('consent.continue')}
|
||||
</button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
{/* Tauri builds never run the human check, so the bundler drops it there. */}
|
||||
{accepted && !__IS_TAURI_BUILD__ ? (
|
||||
<RecheckForm />
|
||||
) : (
|
||||
<ConsentForm humanVerified={humanVerified} />
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ConsentForm({ humanVerified }: { humanVerified: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const accept = useConsentStore((s) => s.accept);
|
||||
const [checked, setChecked] = useState(false);
|
||||
// Decided once, so a passed check stays visible (and announced) instead of vanishing.
|
||||
const [needsCheck] = useState(() => isTurnstileEnabled() && !humanVerified);
|
||||
const web = !__IS_TAURI_BUILD__;
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('consent.title')}</DialogTitle>
|
||||
<DialogDescription>{t('consent.intro')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{web && <p className="text-muted-foreground text-sm">{t('consent.web_services')}</p>}
|
||||
|
||||
<ul className="flex flex-wrap gap-x-4 gap-y-1 text-sm">
|
||||
{LEGAL_DOCS.map((doc) => (
|
||||
<li key={doc.key}>
|
||||
<a
|
||||
href={legalDocUrl(doc.file)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary inline-flex min-h-8 items-center gap-1 underline-offset-4 hover:underline"
|
||||
>
|
||||
{t(`consent.links.${doc.key}`)}
|
||||
<ExternalLink className="h-3 w-3" aria-hidden />
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<label className="flex cursor-pointer items-start gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={(e) => setChecked(e.target.checked)}
|
||||
className="accent-primary mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<span>{t('consent.agree')}</span>
|
||||
</label>
|
||||
|
||||
{!__IS_TAURI_BUILD__ && needsCheck && <HumanCheck />}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
disabled={!checked || !humanVerified}
|
||||
onClick={accept}
|
||||
className="bg-primary text-primary-foreground min-h-10 rounded-md px-4 text-sm font-medium transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{t('consent.continue')}
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Returning visitor whose 7-day human check expired: just the check. */
|
||||
function RecheckForm() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('human_check.title')}</DialogTitle>
|
||||
<DialogDescription>{t('human_check.recheck_intro')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<HumanCheck />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react';
|
||||
import { ErrorState, errorActionPrimary } from '@/components/common/ErrorState';
|
||||
import { createLogger } from '@/lib/logger';
|
||||
|
||||
const log = createLogger('error-boundary');
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
@@ -19,7 +22,7 @@ export class ErrorBoundary extends Component<Props, State> {
|
||||
}
|
||||
|
||||
override componentDidCatch(error: Error, info: ErrorInfo): void {
|
||||
console.error('JSONPrism error boundary caught:', error, info);
|
||||
log.error(error, info.componentStack ?? '');
|
||||
}
|
||||
|
||||
override render(): ReactNode {
|
||||
|
||||
@@ -29,12 +29,16 @@ export function ErrorState({ code, title, message, icon, actions, className }: E
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="border-border bg-card flex w-full max-w-md flex-col items-center gap-4 rounded-lg border p-8 text-center">
|
||||
{/* Hoisted into <head> by React 19, so error routes aren't titled like the app. */}
|
||||
<title>{`${title} · JSONPrism`}</title>
|
||||
<div className="border-border bg-card corner-ticks flex w-full max-w-md flex-col items-center gap-4 rounded-lg border p-8 text-center">
|
||||
{code !== undefined && (
|
||||
<span className="font-display text-spectrum text-6xl leading-none italic">{code}</span>
|
||||
<span className="text-spectrum font-mono text-6xl leading-none font-semibold">
|
||||
{code}
|
||||
</span>
|
||||
)}
|
||||
{icon}
|
||||
<h1 className="font-display text-2xl">{title}</h1>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
|
||||
{message && <p className="text-muted-foreground text-sm">{message}</p>}
|
||||
{actions && (
|
||||
<div className="mt-2 flex flex-wrap items-center justify-center gap-2">{actions}</div>
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Turnstile, type TurnstileInstance } from '@marsidev/react-turnstile';
|
||||
import { LoaderCircle, ShieldCheck, TriangleAlert } from 'lucide-react';
|
||||
import { createLogger } from '@/lib/logger';
|
||||
import { useTheme } from '@/lib/theme';
|
||||
import {
|
||||
TURNSTILE_ACTION,
|
||||
turnstileLanguage,
|
||||
turnstileSiteKey,
|
||||
verifyToken,
|
||||
} from '@/lib/turnstile';
|
||||
import { useConsentStore } from '@/stores/consentStore';
|
||||
|
||||
const log = createLogger('turnstile');
|
||||
|
||||
type CheckState = 'loading' | 'verifying' | 'verified' | 'rejected' | 'unavailable';
|
||||
|
||||
/** If the widget neither solves nor errors in this time, offer the fallback. */
|
||||
const WIDGET_TIMEOUT_MS = 20_000;
|
||||
|
||||
/**
|
||||
* Cloudflare Turnstile check for the web build, verified server-side by the
|
||||
* Worker (`/api/turnstile/verify`). A rejected token keeps the gate closed; an
|
||||
* unreachable Cloudflare (offline, blocked script, 5xx) lets the user continue
|
||||
* after a warning, because conversion itself never needs the network.
|
||||
*/
|
||||
export function HumanCheck() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const markHumanVerified = useConsentStore((s) => s.markHumanVerified);
|
||||
const allowUnverified = useConsentStore((s) => s.allowUnverified);
|
||||
const widgetRef = useRef<TurnstileInstance | undefined>(undefined);
|
||||
const [state, setState] = useState<CheckState>('loading');
|
||||
|
||||
useEffect(() => {
|
||||
if (state !== 'loading') return;
|
||||
const timer = setTimeout(() => setState('unavailable'), WIDGET_TIMEOUT_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [state]);
|
||||
|
||||
const onSuccess = useCallback(
|
||||
(token: string) => {
|
||||
setState('verifying');
|
||||
void verifyToken(token).then((result) => {
|
||||
if (result.status === 'verified') {
|
||||
setState('verified');
|
||||
markHumanVerified(result.verifiedUntil);
|
||||
} else if (result.status === 'rejected') {
|
||||
log.warn('Turnstile token rejected:', result.codes.join(', ') || 'no codes');
|
||||
setState('rejected');
|
||||
widgetRef.current?.reset();
|
||||
} else {
|
||||
log.warn('Turnstile verification unavailable:', result.reason);
|
||||
setState('unavailable');
|
||||
}
|
||||
});
|
||||
},
|
||||
[markHumanVerified],
|
||||
);
|
||||
|
||||
const onWidgetError = useCallback((code?: string) => {
|
||||
log.warn('Turnstile widget error:', code ?? 'unknown');
|
||||
setState('unavailable');
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="border-border bg-muted/40 flex flex-col gap-2 rounded-md border p-3">
|
||||
<div className="flex items-center gap-2 text-sm" role="status" aria-live="polite">
|
||||
{state === 'verified' ? (
|
||||
<ShieldCheck className="text-success motion-safe:animate-pop h-4 w-4" aria-hidden />
|
||||
) : state === 'unavailable' || state === 'rejected' ? (
|
||||
<TriangleAlert className="text-warning h-4 w-4" aria-hidden />
|
||||
) : (
|
||||
<LoaderCircle className="text-primary h-4 w-4 motion-safe:animate-spin" aria-hidden />
|
||||
)}
|
||||
<span>{t(`human_check.${state}`)}</span>
|
||||
</div>
|
||||
{state !== 'verified' && state !== 'unavailable' && (
|
||||
<Turnstile
|
||||
ref={widgetRef}
|
||||
siteKey={turnstileSiteKey()}
|
||||
options={{
|
||||
action: TURNSTILE_ACTION,
|
||||
theme: resolvedTheme,
|
||||
language: turnstileLanguage(i18n.resolvedLanguage),
|
||||
size: 'flexible',
|
||||
refreshExpired: 'auto',
|
||||
}}
|
||||
scriptOptions={{ onError: () => onWidgetError('script-load-failed') }}
|
||||
onSuccess={onSuccess}
|
||||
onError={onWidgetError}
|
||||
onExpire={() => widgetRef.current?.reset()}
|
||||
onUnsupported={() => onWidgetError('unsupported-browser')}
|
||||
/>
|
||||
)}
|
||||
{state === 'unavailable' && (
|
||||
<div className="flex flex-col gap-2 text-xs">
|
||||
<p className="text-muted-foreground">{t('human_check.unavailable_hint')}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={allowUnverified}
|
||||
className="border-border hover:bg-muted min-h-8 self-start rounded-md border px-3 font-medium"
|
||||
>
|
||||
{t('human_check.continue_anyway')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,33 +2,57 @@ import { useTranslation } from 'react-i18next';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const LANGUAGES = [
|
||||
{ code: 'en', label: 'EN' },
|
||||
{ code: 'vi', label: 'VI' },
|
||||
{ code: 'ja', label: 'JA' },
|
||||
{ code: 'zh-CN', label: 'ZH' },
|
||||
{ code: 'en', label: 'EN', name: 'English' },
|
||||
{ code: 'vi', label: 'VI', name: 'Tiếng Việt' },
|
||||
{ code: 'ja', label: 'JA', name: '日本語' },
|
||||
{ code: 'zh-CN', label: 'ZH', name: '简体中文' },
|
||||
] as const;
|
||||
|
||||
/** Button group on ≥ sm screens; a compact native select on phones (fits 360px headers). */
|
||||
export function LanguageSwitcher() {
|
||||
const { i18n } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const current = i18n.resolvedLanguage ?? 'en';
|
||||
const change = (code: string) => void i18n.changeLanguage(code);
|
||||
|
||||
return (
|
||||
<div className="border-border/60 flex items-center gap-0.5 rounded-md border p-0.5">
|
||||
{LANGUAGES.map((lang) => (
|
||||
<button
|
||||
key={lang.code}
|
||||
type="button"
|
||||
onClick={() => void i18n.changeLanguage(lang.code)}
|
||||
className={cn(
|
||||
'rounded px-2 py-0.5 text-xs font-medium transition',
|
||||
current === lang.code
|
||||
? 'bg-muted text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{lang.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<>
|
||||
<div
|
||||
className="border-border/70 hidden items-center gap-0.5 rounded-md border p-0.5 sm:flex"
|
||||
role="group"
|
||||
aria-label={t('language.label')}
|
||||
>
|
||||
{LANGUAGES.map((lang) => (
|
||||
<button
|
||||
key={lang.code}
|
||||
type="button"
|
||||
lang={lang.code}
|
||||
aria-pressed={current === lang.code}
|
||||
aria-label={lang.name}
|
||||
title={lang.name}
|
||||
onClick={() => change(lang.code)}
|
||||
className={cn(
|
||||
'focus-visible:ring-ring min-h-7 min-w-8 rounded px-1.5 font-mono text-xs font-medium transition outline-none focus-visible:ring-2',
|
||||
current === lang.code
|
||||
? 'bg-muted text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{lang.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<select
|
||||
value={current}
|
||||
onChange={(e) => change(e.target.value)}
|
||||
aria-label={t('language.label')}
|
||||
className="border-border/70 text-foreground h-9 rounded-md border bg-transparent px-1.5 font-mono text-xs sm:hidden"
|
||||
>
|
||||
{LANGUAGES.map((lang) => (
|
||||
<option key={lang.code} value={lang.code} lang={lang.code}>
|
||||
{lang.label} · {lang.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -4,19 +4,24 @@ import { useOnlineStatus } from '@/hooks/useOnlineStatus';
|
||||
|
||||
/**
|
||||
* Non-blocking strip shown when the browser goes offline. Deliberately not a
|
||||
* route — going offline must never interrupt a conversion in progress.
|
||||
* route — going offline must never interrupt a conversion in progress. Not
|
||||
* shown in the desktop/Android apps, where offline is the normal state.
|
||||
*/
|
||||
export function OfflineBanner() {
|
||||
if (__IS_TAURI_BUILD__) return null;
|
||||
return <WebOfflineBanner />;
|
||||
}
|
||||
|
||||
function WebOfflineBanner() {
|
||||
const { t } = useTranslation();
|
||||
const online = useOnlineStatus();
|
||||
if (online) return null;
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className="border-border/60 bg-card flex items-center justify-center gap-2 border-b px-4 py-1.5 text-xs"
|
||||
style={{ color: 'var(--color-prism-amber)' }}
|
||||
className="border-border/70 bg-card text-warning flex items-center justify-center gap-2 border-b px-4 py-1.5 text-xs"
|
||||
>
|
||||
<WifiOff className="h-3.5 w-3.5" />
|
||||
<WifiOff className="h-3.5 w-3.5" aria-hidden />
|
||||
<span>{t('error_page.offline.message')}</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -52,3 +52,11 @@ export function YoutubeIcon({ className }: IconProps) {
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function GithubIcon({ className }: IconProps) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" fill="currentColor" className={className} aria-hidden>
|
||||
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,28 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ToolbarButtonProps {
|
||||
onClick: () => void;
|
||||
label: string;
|
||||
icon: React.ReactNode;
|
||||
disabled?: boolean;
|
||||
/** Shown instead of `label` (visually) without changing the accessible name. */
|
||||
visibleLabel?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ToolbarButton({ onClick, label, icon, disabled }: ToolbarButtonProps) {
|
||||
/**
|
||||
* Compact icon + label button for panel headers. The `group` class lets icons
|
||||
* animate on hover (`motion-safe:group-hover:…`); the label hides on narrow
|
||||
* screens but stays the accessible name.
|
||||
*/
|
||||
export function ToolbarButton({
|
||||
onClick,
|
||||
label,
|
||||
icon,
|
||||
disabled,
|
||||
visibleLabel,
|
||||
className,
|
||||
}: ToolbarButtonProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
@@ -13,10 +30,13 @@ export function ToolbarButton({ onClick, label, icon, disabled }: ToolbarButtonP
|
||||
disabled={disabled}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
className={cn(
|
||||
'group text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:ring-ring inline-flex min-h-8 items-center gap-1.5 rounded-md px-2 text-xs transition outline-none focus-visible:ring-2 disabled:cursor-not-allowed disabled:opacity-40',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
<span className="hidden sm:inline">{label}</span>
|
||||
<span className="hidden sm:inline">{visibleLabel ?? label}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import '@/i18n';
|
||||
import { ChunkErrorBoundary } from '../ChunkErrorBoundary';
|
||||
import { ChunkErrorFallback } from '../ChunkErrorFallback';
|
||||
import { ErrorBoundary } from '../ErrorBoundary';
|
||||
import { clearLogs, recentLogs } from '@/lib/logger';
|
||||
|
||||
const CHUNK_ERROR = 'Failed to fetch dynamically imported module: /assets/About-1a2b3c.js';
|
||||
|
||||
function Bomb({ message }: { message: string }): never {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
function stubReload() {
|
||||
const reload = vi.fn();
|
||||
vi.stubGlobal('location', { ...window.location, reload });
|
||||
return reload;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
// React and the logger both report caught render errors to the console.
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
clearLogs();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('ChunkErrorBoundary', () => {
|
||||
it('renders its children when the chunk loads', () => {
|
||||
render(
|
||||
<ChunkErrorBoundary>
|
||||
<p>page</p>
|
||||
</ChunkErrorBoundary>,
|
||||
);
|
||||
expect(screen.getByText('page')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the reload panel for a failed chunk and logs it', async () => {
|
||||
const user = userEvent.setup();
|
||||
const reload = stubReload();
|
||||
render(
|
||||
<ChunkErrorBoundary>
|
||||
<Bomb message={CHUNK_ERROR} />
|
||||
</ChunkErrorBoundary>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByRole('heading', { name: "Couldn't load part of the app" }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText(/usually a new version was just deployed/)).toBeInTheDocument();
|
||||
const entry = recentLogs().find((e) => e.scope === 'chunk');
|
||||
expect(entry?.message).toContain('Chunk failed to load:');
|
||||
expect(entry?.message).toContain('/assets/About-1a2b3c.js');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reload' }));
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('renders a custom fallback for chunk errors', () => {
|
||||
render(
|
||||
<ChunkErrorBoundary fallback={<textarea aria-label="Plain editor" />}>
|
||||
<Bomb message="Loading chunk 42 failed." />
|
||||
</ChunkErrorBoundary>,
|
||||
);
|
||||
expect(screen.getByRole('textbox', { name: 'Plain editor' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Reload' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('passes any other error to the outer crash boundary', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ChunkErrorBoundary>
|
||||
<Bomb message="Cannot read properties of undefined" />
|
||||
</ChunkErrorBoundary>
|
||||
</ErrorBoundary>,
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('heading', { name: 'Something refracted unexpectedly.' }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('Cannot read properties of undefined')).toBeInTheDocument();
|
||||
expect(recentLogs().some((e) => e.scope === 'chunk')).toBe(false);
|
||||
});
|
||||
|
||||
it('still logs a chunk failure when React supplies no component stack', () => {
|
||||
new ChunkErrorBoundary({ children: null }).componentDidCatch(new Error(CHUNK_ERROR), {});
|
||||
expect(recentLogs(1)[0]).toMatchObject({ scope: 'chunk', level: 'error' });
|
||||
});
|
||||
|
||||
it('leaves logging of other errors to the crash boundary', () => {
|
||||
const boundary = new ChunkErrorBoundary({ children: null });
|
||||
boundary.componentDidCatch(new Error('Cannot read properties of undefined'), {
|
||||
componentStack: '\n at Page',
|
||||
});
|
||||
expect(recentLogs()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ChunkErrorFallback', () => {
|
||||
it('explains the failure and offers a reload', async () => {
|
||||
const user = userEvent.setup();
|
||||
const reload = stubReload();
|
||||
render(<ChunkErrorFallback />);
|
||||
expect(document.title).toBe("Couldn't load part of the app · JSONPrism");
|
||||
await user.click(screen.getByRole('button', { name: 'Reload' }));
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,229 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { useEffect, useImperativeHandle, type Ref } from 'react';
|
||||
import '@/i18n';
|
||||
import { ConsentGate } from '../ConsentGate';
|
||||
import { CONSENT_VERSION } from '@/lib/consent-storage';
|
||||
import { ThemeProvider } from '@/lib/theme';
|
||||
import { verifyToken } from '@/lib/turnstile';
|
||||
import type * as TurnstileModule from '@/lib/turnstile';
|
||||
import { useConsentStore } from '@/stores/consentStore';
|
||||
|
||||
const gate = vi.hoisted(() => ({ turnstile: false, reset: vi.fn() }));
|
||||
|
||||
vi.mock('@/lib/turnstile', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof TurnstileModule>()),
|
||||
isTurnstileEnabled: () => gate.turnstile,
|
||||
verifyToken: vi.fn(),
|
||||
}));
|
||||
|
||||
interface FakeTurnstileProps {
|
||||
ref?: Ref<{ reset(): void } | undefined>;
|
||||
onSuccess?: (token: string) => void;
|
||||
onError?: (code?: string) => void;
|
||||
}
|
||||
|
||||
// Stand-in for Cloudflare's widget: buttons fire the callbacks the real one would.
|
||||
vi.mock('@marsidev/react-turnstile', () => ({
|
||||
Turnstile({ ref, onSuccess, onError }: FakeTurnstileProps) {
|
||||
useImperativeHandle(ref, () => ({ reset: gate.reset }));
|
||||
return (
|
||||
<div data-testid="turnstile">
|
||||
<button type="button" onClick={() => onSuccess?.('widget-token')}>
|
||||
solve
|
||||
</button>
|
||||
<button type="button" onClick={() => onError?.('network')}>
|
||||
widget error
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
const appMounted = vi.fn();
|
||||
|
||||
function FakeApp() {
|
||||
useEffect(() => {
|
||||
appMounted();
|
||||
}, []);
|
||||
return (
|
||||
<div data-testid="app">
|
||||
<h1>Converter</h1>
|
||||
<button type="button">Convert now</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderGate() {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<ThemeProvider>
|
||||
<ConsentGate>
|
||||
<FakeApp />
|
||||
</ConsentGate>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
return user;
|
||||
}
|
||||
|
||||
const appWrapper = () => screen.getByTestId('app').parentElement;
|
||||
const agreeBox = () => screen.getByRole('checkbox', { name: /I have read and agree/ });
|
||||
const continueButton = () => screen.getByRole('button', { name: 'Continue' });
|
||||
|
||||
beforeEach(() => {
|
||||
gate.turnstile = false;
|
||||
useConsentStore.setState({ accepted: false, humanVerified: true });
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('ConsentGate', () => {
|
||||
it('shows the terms over the app, which renders behind it but stays unreachable', () => {
|
||||
renderGate();
|
||||
const dialog = screen.getByRole('dialog', { name: 'Before you start' });
|
||||
expect(dialog).toHaveAccessibleDescription(/converts everything on your device/);
|
||||
expect(within(dialog).getByText(/Cloudflare hosts the app/)).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText('Converter')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Convert now' })).not.toBeInTheDocument();
|
||||
expect(appWrapper()).toHaveAttribute('inert');
|
||||
expect(appWrapper()).toHaveAttribute('aria-hidden', 'true');
|
||||
});
|
||||
|
||||
it('links each legal document as of this build', () => {
|
||||
renderGate();
|
||||
const dialog = screen.getByRole('dialog');
|
||||
const docs = {
|
||||
License: 'LICENSE',
|
||||
'Terms (EULA)': 'TERMS.md',
|
||||
'Privacy Policy': 'PRIVACY.md',
|
||||
Disclaimer: 'DISCLAIMER.md',
|
||||
};
|
||||
for (const [name, file] of Object.entries(docs)) {
|
||||
const link = within(dialog).getByRole('link', { name });
|
||||
// Test builds have no commit hash, so links fall back to `main`.
|
||||
expect(link).toHaveAttribute(
|
||||
'href',
|
||||
`https://github.com/poli0981/jsonPrism/blob/main/${file}`,
|
||||
);
|
||||
expect(link).toHaveAttribute('target', '_blank');
|
||||
expect(link).toHaveAttribute('rel', 'noopener noreferrer');
|
||||
}
|
||||
});
|
||||
|
||||
it('enables Continue only while the terms are accepted, then opens the app in place', async () => {
|
||||
const user = renderGate();
|
||||
expect(continueButton()).toBeDisabled();
|
||||
|
||||
await user.click(agreeBox());
|
||||
expect(continueButton()).toBeEnabled();
|
||||
await user.click(agreeBox());
|
||||
expect(continueButton()).toBeDisabled();
|
||||
|
||||
await user.click(agreeBox());
|
||||
await user.click(continueButton());
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
expect(useConsentStore.getState().accepted).toBe(true);
|
||||
expect(JSON.parse(window.localStorage.getItem('jsonprism.consent') as string)).toMatchObject({
|
||||
accepted: true,
|
||||
version: CONSENT_VERSION,
|
||||
});
|
||||
expect(screen.getByRole('button', { name: 'Convert now' })).toBeInTheDocument();
|
||||
expect(appWrapper()).not.toHaveAttribute('inert');
|
||||
expect(appWrapper()).not.toHaveAttribute('aria-hidden');
|
||||
expect(appWrapper()).toHaveClass('contents');
|
||||
// One stable wrapper: passing the gate must not remount the app.
|
||||
expect(appMounted).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('cannot be dismissed with Escape or a click outside', async () => {
|
||||
renderGate();
|
||||
// Radix arms its outside-pointer listener on the next tick.
|
||||
await act(() => new Promise((resolve) => setTimeout(resolve, 0)));
|
||||
|
||||
fireEvent.keyDown(document.body, { key: 'Escape' });
|
||||
// A modal Radix dialog dismisses on the click that completes an outside press.
|
||||
fireEvent.pointerDown(document.body);
|
||||
fireEvent.click(document.body);
|
||||
fireEvent.focusIn(document.body);
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Before you start' })).toBeInTheDocument();
|
||||
expect(useConsentStore.getState().accepted).toBe(false);
|
||||
});
|
||||
|
||||
it('requires a passed human check before Continue when Turnstile is on', async () => {
|
||||
gate.turnstile = true;
|
||||
useConsentStore.setState({ accepted: false, humanVerified: false });
|
||||
vi.mocked(verifyToken).mockResolvedValue({
|
||||
status: 'verified',
|
||||
verifiedUntil: Date.now() + 60_000,
|
||||
});
|
||||
const user = renderGate();
|
||||
|
||||
await user.click(agreeBox());
|
||||
expect(continueButton()).toBeDisabled();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'solve' }));
|
||||
// The passed check stays visible (and announced) instead of vanishing.
|
||||
expect(await screen.findByText('Verified — thanks!')).toBeInTheDocument();
|
||||
expect(continueButton()).toBeEnabled();
|
||||
|
||||
await user.click(continueButton());
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
expect(useConsentStore.getState()).toMatchObject({ accepted: true, humanVerified: true });
|
||||
});
|
||||
|
||||
it('lets the user continue without the check when it cannot run', async () => {
|
||||
gate.turnstile = true;
|
||||
useConsentStore.setState({ accepted: false, humanVerified: false });
|
||||
const user = renderGate();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'widget error' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Continue without the check' }));
|
||||
await user.click(agreeBox());
|
||||
await user.click(continueButton());
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
expect(window.localStorage.getItem('jsonprism.humanCheck')).toBeNull();
|
||||
});
|
||||
|
||||
it('skips the human check when a recent one is remembered', () => {
|
||||
gate.turnstile = true;
|
||||
renderGate();
|
||||
expect(screen.getByRole('dialog', { name: 'Before you start' })).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('turnstile')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('only re-runs the human check for returning visitors', async () => {
|
||||
gate.turnstile = true;
|
||||
useConsentStore.setState({ accepted: true, humanVerified: false });
|
||||
vi.mocked(verifyToken).mockResolvedValue({
|
||||
status: 'verified',
|
||||
verifiedUntil: Date.now() + 60_000,
|
||||
});
|
||||
const user = renderGate();
|
||||
|
||||
const dialog = screen.getByRole('dialog', { name: 'Quick check' });
|
||||
expect(dialog).toHaveAccessibleDescription(/about once a week/);
|
||||
expect(within(dialog).queryByRole('checkbox')).not.toBeInTheDocument();
|
||||
expect(within(dialog).queryByRole('button', { name: 'Continue' })).not.toBeInTheDocument();
|
||||
|
||||
await user.click(within(dialog).getByRole('button', { name: 'solve' }));
|
||||
expect(await screen.findByRole('button', { name: 'Convert now' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('stays out of the way once consent and the check are in place', () => {
|
||||
useConsentStore.setState({ accepted: true, humanVerified: true });
|
||||
renderGate();
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Convert now' })).toBeInTheDocument();
|
||||
expect(appWrapper()).not.toHaveAttribute('inert');
|
||||
expect(appWrapper()).toHaveClass('contents');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { ErrorBoundary } from '../ErrorBoundary';
|
||||
import { clearLogs, recentLogs } from '@/lib/logger';
|
||||
|
||||
function Bomb({ error }: { error: unknown }): never {
|
||||
throw error;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
// React and the logger both report caught render errors to the console.
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
clearLogs();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('ErrorBoundary', () => {
|
||||
it('renders its children when nothing throws', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<p>all good</p>
|
||||
</ErrorBoundary>,
|
||||
);
|
||||
expect(screen.getByText('all good')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('replaces a crashed tree with the crash screen and logs the error', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<Bomb error={new Error('kaboom')} />
|
||||
</ErrorBoundary>,
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('heading', { name: 'Something refracted unexpectedly.' }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('kaboom')).toBeInTheDocument();
|
||||
expect(document.title).toBe('Something refracted unexpectedly. · JSONPrism');
|
||||
|
||||
const entry = recentLogs().find((e) => e.scope === 'error-boundary');
|
||||
expect(entry).toMatchObject({ level: 'error' });
|
||||
expect(entry?.message).toContain('kaboom');
|
||||
});
|
||||
|
||||
it('shows a generic message when something other than an Error is thrown', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<Bomb error="not an Error" />
|
||||
</ErrorBoundary>,
|
||||
);
|
||||
expect(screen.getByText('Unknown error.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders a custom fallback instead of the crash screen', () => {
|
||||
render(
|
||||
<ErrorBoundary fallback={<p>custom fallback</p>}>
|
||||
<Bomb error={new Error('kaboom')} />
|
||||
</ErrorBoundary>,
|
||||
);
|
||||
expect(screen.getByText('custom fallback')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Reload' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('reloads the page from the crash screen', async () => {
|
||||
const user = userEvent.setup();
|
||||
const reload = vi.fn();
|
||||
vi.stubGlobal('location', { ...window.location, reload });
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<Bomb error={new Error('kaboom')} />
|
||||
</ErrorBoundary>,
|
||||
);
|
||||
await user.click(screen.getByRole('button', { name: 'Reload' }));
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('still logs when React supplies no component stack', () => {
|
||||
new ErrorBoundary({ children: null }).componentDidCatch(new Error('bare'), {});
|
||||
expect(recentLogs(1)[0]).toMatchObject({ scope: 'error-boundary', level: 'error' });
|
||||
expect(recentLogs(1)[0]?.message).toContain('bare');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { useImperativeHandle, type Ref } from 'react';
|
||||
import '@/i18n';
|
||||
import { HumanCheck } from '../HumanCheck';
|
||||
import { clearLogs, recentLogs } from '@/lib/logger';
|
||||
import { ThemeProvider } from '@/lib/theme';
|
||||
import { TEST_SITE_KEY, verifyToken, type VerifyResult } from '@/lib/turnstile';
|
||||
import type * as TurnstileModule from '@/lib/turnstile';
|
||||
import { useConsentStore } from '@/stores/consentStore';
|
||||
|
||||
const widget = vi.hoisted(() => ({ reset: vi.fn() }));
|
||||
|
||||
vi.mock('@/lib/turnstile', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof TurnstileModule>()),
|
||||
verifyToken: vi.fn(),
|
||||
}));
|
||||
|
||||
interface FakeTurnstileProps {
|
||||
ref?: Ref<{ reset(): void } | undefined>;
|
||||
siteKey: string;
|
||||
options?: { action?: string; theme?: string; language?: string };
|
||||
scriptOptions?: { onError?: () => void };
|
||||
onSuccess?: (token: string) => void;
|
||||
onError?: (code?: string) => void;
|
||||
onExpire?: () => void;
|
||||
onUnsupported?: () => void;
|
||||
}
|
||||
|
||||
// Stand-in for Cloudflare's widget: each button fires a callback the real one would.
|
||||
vi.mock('@marsidev/react-turnstile', () => ({
|
||||
Turnstile({
|
||||
ref,
|
||||
siteKey,
|
||||
options,
|
||||
scriptOptions,
|
||||
onSuccess,
|
||||
onError,
|
||||
onExpire,
|
||||
onUnsupported,
|
||||
}: FakeTurnstileProps) {
|
||||
useImperativeHandle(ref, () => widget);
|
||||
return (
|
||||
<div
|
||||
data-testid="turnstile"
|
||||
data-sitekey={siteKey}
|
||||
data-action={options?.action}
|
||||
data-theme={options?.theme}
|
||||
data-language={options?.language}
|
||||
>
|
||||
<button type="button" onClick={() => onSuccess?.('widget-token')}>
|
||||
solve
|
||||
</button>
|
||||
<button type="button" onClick={() => onError?.('110200')}>
|
||||
widget error
|
||||
</button>
|
||||
<button type="button" onClick={() => onError?.()}>
|
||||
widget error without code
|
||||
</button>
|
||||
<button type="button" onClick={() => onUnsupported?.()}>
|
||||
unsupported browser
|
||||
</button>
|
||||
<button type="button" onClick={() => scriptOptions?.onError?.()}>
|
||||
script blocked
|
||||
</button>
|
||||
<button type="button" onClick={() => onExpire?.()}>
|
||||
expire
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
const LOADING = "Checking that you're human…";
|
||||
const UNAVAILABLE = 'The human check is unavailable right now.';
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve: (value: T) => void = () => {};
|
||||
const promise = new Promise<T>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function renderCheck() {
|
||||
return render(
|
||||
<ThemeProvider defaultTheme="light">
|
||||
<HumanCheck />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
const status = () => screen.getByRole('status');
|
||||
const lastLog = () => recentLogs(1)[0]?.message;
|
||||
|
||||
beforeEach(() => {
|
||||
useConsentStore.setState({ accepted: false, humanVerified: false });
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
clearLogs();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('HumanCheck', () => {
|
||||
it('renders the widget for the gate action in the current theme and language', () => {
|
||||
renderCheck();
|
||||
expect(status()).toHaveTextContent(LOADING);
|
||||
const turnstile = screen.getByTestId('turnstile');
|
||||
// jsdom runs on localhost, where Cloudflare's always-pass test key is used.
|
||||
expect(turnstile).toHaveAttribute('data-sitekey', TEST_SITE_KEY);
|
||||
expect(turnstile).toHaveAttribute('data-action', 'gate');
|
||||
expect(turnstile).toHaveAttribute('data-theme', 'light');
|
||||
expect(turnstile).toHaveAttribute('data-language', 'en');
|
||||
});
|
||||
|
||||
it('verifies a solved challenge server-side, then opens and remembers the gate', async () => {
|
||||
const user = userEvent.setup();
|
||||
const pending = deferred<VerifyResult>();
|
||||
vi.mocked(verifyToken).mockReturnValue(pending.promise);
|
||||
renderCheck();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'solve' }));
|
||||
expect(verifyToken).toHaveBeenCalledWith('widget-token');
|
||||
expect(status()).toHaveTextContent('Verifying…');
|
||||
expect(useConsentStore.getState().humanVerified).toBe(false);
|
||||
|
||||
const verifiedUntil = Date.now() + 60_000;
|
||||
await act(async () => {
|
||||
pending.resolve({ status: 'verified', verifiedUntil });
|
||||
await pending.promise;
|
||||
});
|
||||
expect(status()).toHaveTextContent('Verified — thanks!');
|
||||
expect(screen.queryByTestId('turnstile')).not.toBeInTheDocument();
|
||||
expect(useConsentStore.getState().humanVerified).toBe(true);
|
||||
expect(JSON.parse(window.localStorage.getItem('jsonprism.humanCheck') as string)).toEqual({
|
||||
verifiedUntil,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
['invalid-input-response', 'timeout-or-duplicate'],
|
||||
'invalid-input-response, timeout-or-duplicate',
|
||||
],
|
||||
[[], 'no codes'],
|
||||
])(
|
||||
'keeps the gate closed and resets the widget on a rejected token (%j)',
|
||||
async (codes, logged) => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(verifyToken).mockResolvedValue({ status: 'rejected', codes });
|
||||
renderCheck();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'solve' }));
|
||||
expect(
|
||||
await screen.findByText('Verification failed. Please try the check again.'),
|
||||
).toBeInTheDocument();
|
||||
expect(widget.reset).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByTestId('turnstile')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /without the check/ })).not.toBeInTheDocument();
|
||||
expect(useConsentStore.getState().humanVerified).toBe(false);
|
||||
expect(lastLog()).toBe(`Turnstile token rejected: ${logged}`);
|
||||
},
|
||||
);
|
||||
|
||||
it('offers to continue without the check when verification is unreachable', async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(verifyToken).mockResolvedValue({ status: 'unavailable', reason: 'http-503' });
|
||||
renderCheck();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'solve' }));
|
||||
expect(await screen.findByText(UNAVAILABLE)).toBeInTheDocument();
|
||||
expect(screen.getByText(/JSONPrism converts on your device/)).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('turnstile')).not.toBeInTheDocument();
|
||||
expect(lastLog()).toBe('Turnstile verification unavailable: http-503');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Continue without the check' }));
|
||||
expect(useConsentStore.getState().humanVerified).toBe(true);
|
||||
// Not persisted: the next visit tries the check again.
|
||||
expect(window.localStorage.getItem('jsonprism.humanCheck')).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['widget error', '110200'],
|
||||
['widget error without code', 'unknown'],
|
||||
['unsupported browser', 'unsupported-browser'],
|
||||
['script blocked', 'script-load-failed'],
|
||||
])('treats "%s" as the check being unavailable', async (button, code) => {
|
||||
const user = userEvent.setup();
|
||||
renderCheck();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: button }));
|
||||
expect(status()).toHaveTextContent(UNAVAILABLE);
|
||||
expect(screen.getByRole('button', { name: 'Continue without the check' })).toBeInTheDocument();
|
||||
expect(lastLog()).toBe(`Turnstile widget error: ${code}`);
|
||||
expect(verifyToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resets an expired token instead of failing the check', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderCheck();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'expire' }));
|
||||
expect(widget.reset).toHaveBeenCalledTimes(1);
|
||||
expect(status()).toHaveTextContent(LOADING);
|
||||
});
|
||||
|
||||
describe('widget timeout', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('offers the fallback after 20 s without any widget response', () => {
|
||||
renderCheck();
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(19_999);
|
||||
});
|
||||
expect(status()).toHaveTextContent(LOADING);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(1);
|
||||
});
|
||||
expect(status()).toHaveTextContent(UNAVAILABLE);
|
||||
expect(screen.queryByTestId('turnstile')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not time out while a token is being verified', () => {
|
||||
vi.mocked(verifyToken).mockReturnValue(new Promise<VerifyResult>(() => {}));
|
||||
renderCheck();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'solve' }));
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(30_000);
|
||||
});
|
||||
expect(status()).toHaveTextContent('Verifying…');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { act, render, screen, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { createInstance } from 'i18next';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import i18n from 'i18next';
|
||||
import '@/i18n';
|
||||
import { LanguageSwitcher } from '../LanguageSwitcher';
|
||||
|
||||
afterEach(async () => {
|
||||
await act(() => i18n.changeLanguage('en'));
|
||||
});
|
||||
|
||||
describe('LanguageSwitcher', () => {
|
||||
it('offers every UI language and marks the current one', () => {
|
||||
render(<LanguageSwitcher />);
|
||||
const group = screen.getByRole('group', { name: 'Language' });
|
||||
const buttons = within(group).getAllByRole('button');
|
||||
expect(buttons.map((b) => b.textContent)).toEqual(['EN', 'VI', 'JA', 'ZH']);
|
||||
expect(within(group).getByRole('button', { name: 'English' })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'true',
|
||||
);
|
||||
expect(within(group).getByRole('button', { name: '日本語' })).toHaveAttribute('lang', 'ja');
|
||||
expect(screen.getByRole('combobox', { name: 'Language' })).toHaveValue('en');
|
||||
});
|
||||
|
||||
it('switches the UI language and <html lang> from the button group', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LanguageSwitcher />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Tiếng Việt' }));
|
||||
expect(i18n.resolvedLanguage).toBe('vi');
|
||||
expect(document.documentElement.lang).toBe('vi');
|
||||
expect(screen.getByRole('button', { name: 'Tiếng Việt' })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'true',
|
||||
);
|
||||
expect(screen.getByRole('button', { name: 'English' })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'false',
|
||||
);
|
||||
expect(window.localStorage.getItem('jsonprism.lang')).toBe('vi');
|
||||
});
|
||||
|
||||
it('switches the UI language from the compact select on phones', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LanguageSwitcher />);
|
||||
|
||||
await user.selectOptions(screen.getByRole('combobox'), 'zh-CN');
|
||||
expect(i18n.resolvedLanguage).toBe('zh-CN');
|
||||
expect(document.documentElement.lang).toBe('zh-CN');
|
||||
expect(screen.getByRole('combobox')).toHaveValue('zh-CN');
|
||||
expect(screen.getByRole('button', { name: '简体中文' })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
|
||||
it('treats the UI as English until a language has resolved', async () => {
|
||||
const unresolved = createInstance();
|
||||
await unresolved.init({ resources: {} });
|
||||
expect(unresolved.resolvedLanguage).toBeUndefined();
|
||||
|
||||
render(
|
||||
<I18nextProvider i18n={unresolved}>
|
||||
<LanguageSwitcher />
|
||||
</I18nextProvider>,
|
||||
);
|
||||
expect(screen.getByRole('combobox')).toHaveValue('en');
|
||||
expect(screen.getByRole('button', { name: 'English' })).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import '@/i18n';
|
||||
import { OfflineBanner } from '../OfflineBanner';
|
||||
|
||||
function setNavigatorOnline(value: boolean) {
|
||||
Object.defineProperty(navigator, 'onLine', { configurable: true, value });
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setNavigatorOnline(true);
|
||||
});
|
||||
|
||||
describe('OfflineBanner', () => {
|
||||
it('renders nothing while online', () => {
|
||||
setNavigatorOnline(true);
|
||||
const { container } = render(<OfflineBanner />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('announces offline mode without blocking, and clears on reconnect', () => {
|
||||
setNavigatorOnline(false);
|
||||
render(<OfflineBanner />);
|
||||
expect(screen.getByRole('status')).toHaveTextContent(
|
||||
"You're offline — JSONPrism keeps working; conversion never needs the network.",
|
||||
);
|
||||
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event('online'));
|
||||
});
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument();
|
||||
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
});
|
||||
expect(screen.getByRole('status')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import '@/i18n';
|
||||
import { RouteFallback } from '../RouteFallback';
|
||||
|
||||
describe('RouteFallback', () => {
|
||||
it('shows a translated loading indicator while a route chunk streams in', () => {
|
||||
const { container } = render(<RouteFallback />);
|
||||
expect(screen.getByText('Loading…')).toBeInTheDocument();
|
||||
expect(container.querySelector('svg')).toHaveClass('animate-spin');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { useLayoutEffect, useRef } from 'react';
|
||||
import '@/i18n';
|
||||
import { ScrollToTop } from '../ScrollToTop';
|
||||
|
||||
/** jsdom ships without matchMedia; only the reduced-motion query matters here. */
|
||||
function stubReducedMotion(reduce: boolean) {
|
||||
const matchMedia = vi.fn((query: string) => ({
|
||||
matches: reduce && query === '(prefers-reduced-motion: reduce)',
|
||||
media: query,
|
||||
}));
|
||||
vi.stubGlobal('matchMedia', matchMedia);
|
||||
return matchMedia;
|
||||
}
|
||||
|
||||
function ScrollArea({
|
||||
threshold,
|
||||
initialScroll = 0,
|
||||
}: {
|
||||
threshold?: number;
|
||||
initialScroll?: number;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
// Runs before ScrollToTop's passive effect reads the initial position.
|
||||
useLayoutEffect(() => {
|
||||
if (ref.current) ref.current.scrollTop = initialScroll;
|
||||
}, [initialScroll]);
|
||||
return (
|
||||
<div>
|
||||
<div ref={ref} data-testid="scroller" />
|
||||
<ScrollToTop scrollRef={ref} {...(threshold !== undefined ? { threshold } : {})} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function scrollTo(el: HTMLElement, top: number) {
|
||||
el.scrollTop = top;
|
||||
fireEvent.scroll(el);
|
||||
}
|
||||
|
||||
// aria-hidden elements have no accessible name, so find the hidden button by its tooltip.
|
||||
const hiddenButton = () => screen.getByTitle('Back to top');
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('ScrollToTop', () => {
|
||||
it('stays hidden and out of the tab order near the top', () => {
|
||||
render(<ScrollArea />);
|
||||
expect(screen.queryByRole('button', { name: 'Back to top' })).not.toBeInTheDocument();
|
||||
expect(hiddenButton()).toHaveAttribute('aria-hidden', 'true');
|
||||
expect(hiddenButton()).toHaveAttribute('tabindex', '-1');
|
||||
expect(hiddenButton()).toHaveAttribute('aria-label', 'Back to top');
|
||||
});
|
||||
|
||||
it('appears after scrolling past the default threshold and hides again near the top', () => {
|
||||
render(<ScrollArea />);
|
||||
const scroller = screen.getByTestId('scroller');
|
||||
|
||||
scrollTo(scroller, 320);
|
||||
expect(screen.queryByRole('button', { name: 'Back to top' })).not.toBeInTheDocument();
|
||||
|
||||
scrollTo(scroller, 321);
|
||||
const button = screen.getByRole('button', { name: 'Back to top' });
|
||||
expect(button).toHaveAttribute('tabindex', '0');
|
||||
expect(button).toHaveAttribute('aria-hidden', 'false');
|
||||
|
||||
scrollTo(scroller, 10);
|
||||
expect(screen.queryByRole('button', { name: 'Back to top' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('honours a custom threshold', () => {
|
||||
render(<ScrollArea threshold={50} />);
|
||||
scrollTo(screen.getByTestId('scroller'), 60);
|
||||
expect(screen.getByRole('button', { name: 'Back to top' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('checks the position on mount', () => {
|
||||
render(<ScrollArea initialScroll={1000} />);
|
||||
expect(screen.getByRole('button', { name: 'Back to top' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[false, 'smooth'],
|
||||
[true, 'auto'],
|
||||
])('scrolls back to the top (reduced motion: %s → %s)', async (reduce, behavior) => {
|
||||
const user = userEvent.setup();
|
||||
stubReducedMotion(reduce);
|
||||
render(<ScrollArea initialScroll={1000} />);
|
||||
const scroller = screen.getByTestId('scroller');
|
||||
const scroll = vi.fn();
|
||||
Object.defineProperty(scroller, 'scrollTo', { configurable: true, value: scroll });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Back to top' }));
|
||||
expect(scroll).toHaveBeenCalledWith({ top: 0, behavior });
|
||||
});
|
||||
|
||||
it('does nothing without a scroll container', async () => {
|
||||
const user = userEvent.setup();
|
||||
const matchMedia = stubReducedMotion(false);
|
||||
render(<ScrollToTop scrollRef={{ current: null }} />);
|
||||
await user.click(hiddenButton());
|
||||
expect(matchMedia).not.toHaveBeenCalled();
|
||||
expect(hiddenButton()).toHaveAttribute('aria-hidden', 'true');
|
||||
});
|
||||
|
||||
it('stops listening to the container when unmounted', () => {
|
||||
const { unmount } = render(<ScrollArea />);
|
||||
const scroller = screen.getByTestId('scroller');
|
||||
const remove = vi.spyOn(scroller, 'removeEventListener');
|
||||
unmount();
|
||||
expect(remove).toHaveBeenCalledWith('scroll', expect.any(Function));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { render } from '@testing-library/react';
|
||||
import {
|
||||
BlueskyIcon,
|
||||
DiscordIcon,
|
||||
GithubIcon,
|
||||
MastodonIcon,
|
||||
TelegramIcon,
|
||||
XIcon,
|
||||
YoutubeIcon,
|
||||
} from '../SocialIcons';
|
||||
|
||||
const ICONS = {
|
||||
BlueskyIcon,
|
||||
DiscordIcon,
|
||||
GithubIcon,
|
||||
MastodonIcon,
|
||||
TelegramIcon,
|
||||
XIcon,
|
||||
YoutubeIcon,
|
||||
};
|
||||
|
||||
describe('SocialIcons', () => {
|
||||
it.each(Object.entries(ICONS))(
|
||||
'%s is a decorative glyph that inherits size and color',
|
||||
(_name, Icon) => {
|
||||
const { container } = render(<Icon className="h-4 w-4" />);
|
||||
const svg = container.querySelector('svg');
|
||||
expect(svg).toHaveAttribute('aria-hidden', 'true');
|
||||
expect(svg).toHaveAttribute('viewBox', '0 0 24 24');
|
||||
expect(svg).toHaveAttribute('fill', 'currentColor');
|
||||
expect(svg).toHaveClass('h-4', 'w-4');
|
||||
expect(svg?.querySelector('path')?.getAttribute('d')).toMatch(/^M/);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { ToolbarButton } from '../ToolbarButton';
|
||||
|
||||
const icon = <svg data-testid="icon" aria-hidden />;
|
||||
|
||||
describe('ToolbarButton', () => {
|
||||
it('keeps the label as accessible name and tooltip when a shorter visible label is shown', () => {
|
||||
render(
|
||||
<ToolbarButton onClick={() => {}} label="Download output" visibleLabel="Save" icon={icon} />,
|
||||
);
|
||||
const button = screen.getByRole('button', { name: 'Download output' });
|
||||
expect(button).toHaveAttribute('title', 'Download output');
|
||||
expect(button).toHaveAttribute('type', 'button');
|
||||
expect(button).toHaveTextContent('Save');
|
||||
expect(screen.getByTestId('icon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the label itself when no visible label is given', () => {
|
||||
render(<ToolbarButton onClick={() => {}} label="Copy" icon={icon} />);
|
||||
expect(screen.getByRole('button', { name: 'Copy' })).toHaveTextContent('Copy');
|
||||
});
|
||||
|
||||
it('calls onClick unless disabled', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClick = vi.fn();
|
||||
const { rerender } = render(<ToolbarButton onClick={onClick} label="Clear" icon={icon} />);
|
||||
await user.click(screen.getByRole('button', { name: 'Clear' }));
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
|
||||
rerender(<ToolbarButton onClick={onClick} label="Clear" icon={icon} disabled />);
|
||||
expect(screen.getByRole('button', { name: 'Clear' })).toBeDisabled();
|
||||
await user.click(screen.getByRole('button', { name: 'Clear' }));
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('merges extra classes with its own', () => {
|
||||
render(<ToolbarButton onClick={() => {}} label="Options" icon={icon} className="ml-auto" />);
|
||||
expect(screen.getByRole('button', { name: 'Options' })).toHaveClass('ml-auto', 'inline-flex');
|
||||
});
|
||||
});
|
||||
@@ -1,114 +1,108 @@
|
||||
import { memo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Loader2, Trash2 } from 'lucide-react';
|
||||
import { LoaderCircle, Trash2 } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { formatBytes } from '@/lib/format-bytes';
|
||||
import type { BatchItem } from '@/stores/batchStore';
|
||||
import { useBatchStore, type BatchItemStatus } from '@/stores/batchStore';
|
||||
|
||||
interface BatchItemRowProps {
|
||||
item: BatchItem;
|
||||
id: string;
|
||||
outputExt: string;
|
||||
onRemove: () => void;
|
||||
onRemove: (id: string) => void;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
export function BatchItemRow({ item, outputExt, onRemove, disabled }: BatchItemRowProps) {
|
||||
/** One queue row. Subscribes to its own item so updates re-render only this row. */
|
||||
export const BatchItemRow = memo(function BatchItemRow({
|
||||
id,
|
||||
outputExt,
|
||||
onRemove,
|
||||
disabled,
|
||||
}: BatchItemRowProps) {
|
||||
const { t } = useTranslation();
|
||||
const Icon = statusIcon(item.status);
|
||||
const tone = statusTone(item.status);
|
||||
const item = useBatchStore((s) => s.items[id]);
|
||||
if (!item) return null;
|
||||
|
||||
const error = item.errorCode ? t(`batch.error.${item.errorCode}`) : item.error;
|
||||
|
||||
return (
|
||||
<li className="flex items-start gap-2 py-2.5">
|
||||
<Icon className={cn('mt-0.5 h-4 w-4 shrink-0', tone)} />
|
||||
<StatusIcon status={item.status} />
|
||||
<span className="sr-only">{t(`batch.stat.${item.status}`)}</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-foreground truncate font-mono text-xs">{item.filename}</span>
|
||||
<span className="text-muted-foreground/60 font-mono text-[10px]">→ .{outputExt}</span>
|
||||
<span className="text-muted-foreground font-mono text-[10px]">→ .{outputExt}</span>
|
||||
</div>
|
||||
<div className="text-muted-foreground mt-0.5 flex items-center gap-2 font-mono text-[10px]">
|
||||
<span>{formatBytes(item.size)}</span>
|
||||
{item.outputSize !== undefined && (
|
||||
<>
|
||||
<span>·</span>
|
||||
<span>
|
||||
{t('batch.row.out')}: {formatBytes(item.outputSize)}
|
||||
</span>
|
||||
<span aria-hidden>·</span>
|
||||
<span>{t('batch.row.out_value', { size: formatBytes(item.outputSize) })}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{item.error && (
|
||||
<p className="text-destructive mt-1 font-mono text-[10px] break-words">{item.error}</p>
|
||||
{error && (
|
||||
<p className="text-destructive mt-1 font-mono text-[10px] break-words">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRemove}
|
||||
onClick={() => onRemove(id)}
|
||||
disabled={disabled}
|
||||
aria-label={t('batch.row.remove')}
|
||||
className="text-muted-foreground hover:bg-muted hover:text-foreground rounded p-1 transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
aria-label={t('batch.row.remove', { name: item.filename })}
|
||||
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex h-7 w-7 shrink-0 items-center justify-center rounded transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
<Trash2 className="h-3.5 w-3.5" aria-hidden />
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
function statusIcon(status: BatchItem['status']) {
|
||||
function StatusIcon({ status }: { status: BatchItemStatus }) {
|
||||
const base = 'mt-0.5 h-4 w-4 shrink-0';
|
||||
switch (status) {
|
||||
case 'queued':
|
||||
return CircleIcon;
|
||||
case 'processing':
|
||||
return ProcessingIcon;
|
||||
return (
|
||||
<LoaderCircle
|
||||
className={cn(base, 'text-foreground motion-safe:animate-spin')}
|
||||
aria-hidden
|
||||
/>
|
||||
);
|
||||
case 'done':
|
||||
return CheckIcon;
|
||||
return (
|
||||
<svg viewBox="0 0 16 16" fill="none" className={cn(base, 'text-success')} aria-hidden>
|
||||
<path
|
||||
d="M3 8.5L6.5 12L13 5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
case 'error':
|
||||
return ErrorIcon;
|
||||
return (
|
||||
<svg viewBox="0 0 16 16" fill="none" className={cn(base, 'text-destructive')} aria-hidden>
|
||||
<path
|
||||
d="M4 4L12 12M12 4L4 12"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
case 'queued':
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
className={cn(base, 'text-muted-foreground')}
|
||||
aria-hidden
|
||||
>
|
||||
<circle cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="1.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function statusTone(status: BatchItem['status']): string {
|
||||
switch (status) {
|
||||
case 'done':
|
||||
return 'text-primary';
|
||||
case 'error':
|
||||
return 'text-destructive';
|
||||
case 'processing':
|
||||
return 'text-foreground';
|
||||
case 'queued':
|
||||
default:
|
||||
return 'text-muted-foreground/60';
|
||||
}
|
||||
}
|
||||
|
||||
function CircleIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
|
||||
<circle cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="1.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function ProcessingIcon({ className }: { className?: string }) {
|
||||
return <Loader2 className={cn(className, 'animate-spin')} />;
|
||||
}
|
||||
|
||||
function CheckIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
|
||||
<path
|
||||
d="M3 8.5L6.5 12L13 5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function ErrorIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
|
||||
<path d="M4 4L12 12M12 4L4 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useDropzone } from 'react-dropzone';
|
||||
import { Download, FileStack, FolderOpen, Play, StopCircle, Trash2 } from 'lucide-react';
|
||||
import { useDropzone, type FileRejection } from 'react-dropzone';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { CircleStop, Download, FileStack, FolderOpen, Play, Trash2 } from 'lucide-react';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
@@ -11,14 +12,15 @@ import {
|
||||
SheetTrigger,
|
||||
} from '@/components/ui/sheet';
|
||||
import { toast } from '@/components/ui/sonner';
|
||||
import { extensionsFor } from '@/converters/registry';
|
||||
import type { Direction, FormatId } from '@/converters/types';
|
||||
import { useBatchActions } from '@/hooks/useBatchActions';
|
||||
import { useFileAccept } from '@/hooks/useFileAccept';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { filterByExtension } from '@/lib/file-filter';
|
||||
import { isTauri, nativeOpenFiles, fileFromNativePath } from '@/lib/tauri';
|
||||
import { fileFromNativePath, isTauri, nativeOpenFiles } from '@/lib/tauri';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useBatchStore, BATCH_MAX_FILES } from '@/stores/batchStore';
|
||||
import type { FormatId } from '@/converters/types';
|
||||
import type { Direction } from './DirectionToggle';
|
||||
import { BatchItemRow } from './BatchItemRow';
|
||||
import { BatchSummaryChips } from './BatchSummaryChips';
|
||||
|
||||
@@ -32,20 +34,30 @@ interface BatchPanelProps {
|
||||
|
||||
export function BatchPanel({ format, direction, options, open, onOpenChange }: BatchPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const items = useBatchStore((s) => s.items);
|
||||
// Counts and order only — each row subscribes to its own item, so a status
|
||||
// change re-renders one row instead of the whole 500-row list.
|
||||
const itemOrder = useBatchStore((s) => s.itemOrder);
|
||||
const counts = useBatchStore(
|
||||
useShallow((s) => {
|
||||
let done = 0;
|
||||
let failed = 0;
|
||||
let queued = 0;
|
||||
for (const id of s.itemOrder) {
|
||||
const status = s.items[id]?.status;
|
||||
if (status === 'done') done += 1;
|
||||
else if (status === 'error') failed += 1;
|
||||
else if (status === 'queued') queued += 1;
|
||||
}
|
||||
return { done, failed, queued };
|
||||
}),
|
||||
);
|
||||
const processing = useBatchStore((s) => s.processing);
|
||||
const addFiles = useBatchStore((s) => s.addFiles);
|
||||
const removeItem = useBatchStore((s) => s.removeItem);
|
||||
const clear = useBatchStore((s) => s.clear);
|
||||
const resetStatuses = useBatchStore((s) => s.resetStatuses);
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const totalCount = itemOrder.length;
|
||||
const doneCount = itemOrder.filter((id) => items[id]?.status === 'done').length;
|
||||
const errorCount = itemOrder.filter((id) => items[id]?.status === 'error').length;
|
||||
const queuedCount = itemOrder.filter((id) => items[id]?.status === 'queued').length;
|
||||
|
||||
const { converter, isReverse, accept, fileInputAccept, allowedExtensions } = useFileAccept(
|
||||
format,
|
||||
@@ -77,14 +89,13 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
|
||||
|
||||
const onDrop = useCallback(
|
||||
(accepted: File[]) => {
|
||||
if (accepted.length === 0) return;
|
||||
handleAddFiles(accepted);
|
||||
if (accepted.length > 0) handleAddFiles(accepted);
|
||||
},
|
||||
[handleAddFiles],
|
||||
);
|
||||
|
||||
const onDropRejected = useCallback(
|
||||
(rejections: { file: File }[]) => {
|
||||
(rejections: FileRejection[]) => {
|
||||
// react-dropzone rejects via MIME mismatch; surface as wrong-format toast
|
||||
// so the user sees something, not a silent drop.
|
||||
if (rejections.length > 0) {
|
||||
@@ -103,23 +114,40 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
|
||||
noKeyboard: true,
|
||||
});
|
||||
|
||||
const formatLabel = t(converter.meta.labelKey);
|
||||
|
||||
const handleOpenFiles = async () => {
|
||||
if (isTauri()) {
|
||||
const paths = await nativeOpenFiles({ multiple: true });
|
||||
if (!isTauri()) {
|
||||
fileInputRef.current?.click();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const paths = await nativeOpenFiles({
|
||||
multiple: true,
|
||||
filters: isReverse
|
||||
? [
|
||||
{ name: formatLabel, extensions: extensionsFor(format) },
|
||||
{ name: t('file_dialog.text'), extensions: ['txt'] },
|
||||
]
|
||||
: [
|
||||
{ name: t('file_dialog.json'), extensions: ['json'] },
|
||||
{ name: t('file_dialog.text'), extensions: ['txt'] },
|
||||
],
|
||||
});
|
||||
if (!paths || paths.length === 0) return;
|
||||
const files = await Promise.all(paths.map(fileFromNativePath));
|
||||
// The native dialog already filtered; Android content URIs may carry no
|
||||
// extension, so don't re-reject them here.
|
||||
handleAddFiles(files, true);
|
||||
return;
|
||||
} catch (err) {
|
||||
toast.error(t('toast.file_failed', { message: errorMessage(err) }));
|
||||
}
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const onFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files ?? []);
|
||||
if (files.length > 0) handleAddFiles(files);
|
||||
e.target.value = '';
|
||||
if (files.length > 0) handleAddFiles(files);
|
||||
};
|
||||
|
||||
// Cancel processing if the user clears the queue while it's running.
|
||||
@@ -129,11 +157,12 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
|
||||
}
|
||||
}, [totalCount, processing]);
|
||||
|
||||
const formatLabel = t(converter.meta.labelKey);
|
||||
// Direction-aware labels for the SheetDescription and dropzone text.
|
||||
// In reverse mode the user supplies `<format>` files and gets JSON back.
|
||||
const removeRow = useCallback((id: string) => removeItem(id), [removeItem]);
|
||||
// Direction-aware labels: in reverse mode the user supplies `<format>` files
|
||||
// and gets JSON back.
|
||||
const fromLabel = isReverse ? formatLabel : 'JSON';
|
||||
const toLabel = isReverse ? 'JSON' : formatLabel;
|
||||
const outputExt = isReverse ? 'json' : converter.meta.extension;
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
@@ -141,11 +170,11 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'text-muted-foreground hover:bg-muted hover:text-foreground border-border/60 inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition',
|
||||
'group text-muted-foreground hover:bg-muted hover:text-foreground border-border bg-card/60 inline-flex min-h-8 items-center gap-1.5 rounded-md border px-2.5 text-xs transition',
|
||||
totalCount > 0 && 'border-primary/40 text-foreground',
|
||||
)}
|
||||
>
|
||||
<FileStack className="h-3.5 w-3.5" />
|
||||
<FileStack className="motion-safe:group-hover:animate-bob h-3.5 w-3.5" aria-hidden />
|
||||
<span>{t('batch.trigger')}</span>
|
||||
{totalCount > 0 && (
|
||||
<span className="bg-primary/15 text-primary rounded px-1 py-px font-mono text-[10px] leading-none">
|
||||
@@ -155,12 +184,15 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
|
||||
</button>
|
||||
</SheetTrigger>
|
||||
|
||||
<SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-lg">
|
||||
<SheetContent
|
||||
closeLabel={t('common.close')}
|
||||
className="flex w-full flex-col gap-0 p-0 sm:max-w-lg"
|
||||
>
|
||||
<SheetHeader>
|
||||
<SheetTitle>
|
||||
<span className="text-spectrum italic">{t('batch.title')}</span>{' '}
|
||||
<span className="text-muted-foreground font-sans text-base font-normal not-italic">
|
||||
· {totalCount} / {BATCH_MAX_FILES}
|
||||
<span className="text-spectrum">{t('batch.title')}</span>{' '}
|
||||
<span className="text-muted-foreground font-mono text-sm font-normal">
|
||||
{totalCount} / {BATCH_MAX_FILES}
|
||||
</span>
|
||||
</SheetTitle>
|
||||
<SheetDescription>
|
||||
@@ -178,16 +210,21 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={onFileInputChange}
|
||||
tabIndex={-1}
|
||||
aria-hidden
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center gap-1.5 rounded-lg border-2 border-dashed py-6 transition',
|
||||
'corner-ticks flex flex-col items-center justify-center gap-1.5 rounded-lg border border-dashed py-6 transition',
|
||||
isDragActive
|
||||
? 'border-primary/60 bg-primary/5 text-foreground'
|
||||
: 'border-border bg-card/30 text-muted-foreground',
|
||||
: 'border-border bg-card/40 text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
<FolderOpen className="h-5 w-5" />
|
||||
<FolderOpen
|
||||
className={cn('h-5 w-5', isDragActive && 'motion-safe:animate-bob')}
|
||||
aria-hidden
|
||||
/>
|
||||
<p className="text-xs">
|
||||
{isDragActive
|
||||
? t('batch.drop_active')
|
||||
@@ -195,57 +232,56 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleOpenFiles}
|
||||
className="text-primary text-xs hover:underline"
|
||||
onClick={() => void handleOpenFiles()}
|
||||
className="text-primary min-h-8 px-2 text-xs hover:underline"
|
||||
>
|
||||
{t('batch.browse')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Summary chips */}
|
||||
{totalCount > 0 && (
|
||||
<BatchSummaryChips
|
||||
queuedCount={queuedCount}
|
||||
doneCount={doneCount}
|
||||
errorCount={errorCount}
|
||||
queuedCount={counts.queued}
|
||||
doneCount={counts.done}
|
||||
errorCount={counts.failed}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Queue list */}
|
||||
<div className="flex-1 overflow-y-auto px-6 pb-3">
|
||||
<div
|
||||
className="flex-1 [scrollbar-gutter:stable] overflow-y-auto px-6 pb-3"
|
||||
tabIndex={0} // NOSONAR(S6845): scrollable region; keyboard users need focus to scroll it
|
||||
aria-label={t('batch.queue_label')}
|
||||
>
|
||||
{totalCount === 0 ? (
|
||||
<p className="text-muted-foreground py-12 text-center text-sm italic">
|
||||
<p className="text-muted-foreground py-12 text-center text-sm">
|
||||
{t('batch.empty_format', { format: fromLabel })}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="divide-border/40 flex flex-col divide-y">
|
||||
{itemOrder.map((id) => {
|
||||
const item = items[id];
|
||||
if (!item) return null;
|
||||
return (
|
||||
<BatchItemRow
|
||||
key={id}
|
||||
item={item}
|
||||
outputExt={isReverse ? 'json' : converter.meta.extension}
|
||||
onRemove={() => removeItem(id)}
|
||||
disabled={processing}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<ul className="divide-border/50 flex flex-col divide-y">
|
||||
{itemOrder.map((id) => (
|
||||
<BatchItemRow
|
||||
key={id}
|
||||
id={id}
|
||||
outputExt={outputExt}
|
||||
onRemove={removeRow}
|
||||
disabled={processing}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer controls */}
|
||||
<div className="border-border/60 flex items-center justify-between gap-2 border-t px-6 py-3">
|
||||
<div className="border-border/70 flex items-center justify-between gap-2 border-t px-6 py-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => clear()}
|
||||
disabled={totalCount === 0 || processing}
|
||||
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex min-h-8 items-center gap-1.5 rounded-md px-2.5 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
<Trash2 className="h-3.5 w-3.5" aria-hidden />
|
||||
{t('batch.clear')}
|
||||
</button>
|
||||
|
||||
@@ -254,22 +290,19 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
|
||||
<button
|
||||
type="button"
|
||||
onClick={cancel}
|
||||
className="bg-destructive/10 text-destructive hover:bg-destructive/20 inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition"
|
||||
className="bg-destructive/10 text-destructive hover:bg-destructive/20 inline-flex min-h-8 items-center gap-1.5 rounded-md px-3 text-xs font-medium transition"
|
||||
>
|
||||
<StopCircle className="h-3.5 w-3.5" />
|
||||
<CircleStop className="h-3.5 w-3.5" aria-hidden />
|
||||
{t('batch.cancel')}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
resetStatuses();
|
||||
void start();
|
||||
}}
|
||||
onClick={() => void start()}
|
||||
disabled={totalCount === 0}
|
||||
className="bg-primary/15 text-primary hover:bg-primary/25 inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
className="group bg-primary/15 text-primary hover:bg-primary/25 inline-flex min-h-8 items-center gap-1.5 rounded-md px-3 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
<Play className="h-3.5 w-3.5" />
|
||||
<Play className="motion-safe:group-hover:animate-nudge h-3.5 w-3.5" aria-hidden />
|
||||
{t('batch.process')}
|
||||
</button>
|
||||
)}
|
||||
@@ -277,10 +310,10 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void downloadZip()}
|
||||
disabled={doneCount === 0 || processing}
|
||||
className="bg-foreground/90 text-background hover:bg-foreground inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
disabled={counts.done === 0 || processing}
|
||||
className="group bg-foreground/90 text-background hover:bg-foreground inline-flex min-h-8 items-center gap-1.5 rounded-md px-3 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
<Download className="h-3.5 w-3.5" />
|
||||
<Download className="motion-safe:group-hover:animate-bob h-3.5 w-3.5" aria-hidden />
|
||||
{t('batch.download_zip')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -10,7 +10,11 @@ interface BatchSummaryChipsProps {
|
||||
export function BatchSummaryChips({ queuedCount, doneCount, errorCount }: BatchSummaryChipsProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="text-muted-foreground flex flex-wrap items-center gap-2 px-6 pb-3 font-mono text-[11px]">
|
||||
<div
|
||||
className="text-muted-foreground flex flex-wrap items-center gap-2 px-6 pb-3 font-mono text-[11px]"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
<Chip label={t('batch.stat.queued')} value={queuedCount} />
|
||||
<Chip label={t('batch.stat.done')} value={doneCount} tone="ok" />
|
||||
{errorCount > 0 && <Chip label={t('batch.stat.failed')} value={errorCount} tone="err" />}
|
||||
@@ -23,13 +27,13 @@ function Chip({ label, value, tone }: { label: string; value: number; tone?: 'ok
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded px-1.5 py-0.5',
|
||||
tone === 'ok' && 'bg-primary/10 text-primary',
|
||||
tone === 'ok' && 'bg-success/10 text-success',
|
||||
tone === 'err' && 'bg-destructive/10 text-destructive',
|
||||
!tone && 'bg-muted/40',
|
||||
!tone && 'bg-muted',
|
||||
)}
|
||||
>
|
||||
<span className="opacity-70">{label}:</span>
|
||||
<span>{value}</span>
|
||||
<span>{label}</span>
|
||||
<span className="text-foreground">{value}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +1,21 @@
|
||||
import { useMemo } from 'react';
|
||||
import CodeMirror, { type ReactCodeMirrorRef, EditorView } from '@uiw/react-codemirror';
|
||||
import { json, jsonParseLinter } from '@codemirror/lang-json';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import CodeMirror, { EditorState, EditorView, type BasicSetupOptions } from '@uiw/react-codemirror';
|
||||
import { json } from '@codemirror/lang-json';
|
||||
import { yaml } from '@codemirror/lang-yaml';
|
||||
import { xml } from '@codemirror/lang-xml';
|
||||
import { markdown } from '@codemirror/lang-markdown';
|
||||
import { sql } from '@codemirror/lang-sql';
|
||||
import { HighlightStyle, StreamLanguage, syntaxHighlighting } from '@codemirror/language';
|
||||
import { toml } from '@codemirror/legacy-modes/mode/toml';
|
||||
import { lintGutter, linter } from '@codemirror/lint';
|
||||
import { lintGutter, linter, type Diagnostic } from '@codemirror/lint';
|
||||
import { tags as t } from '@lezer/highlight';
|
||||
import { parseJsonInput } from '@/lib/detect';
|
||||
import { useTheme } from '@/lib/theme';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type EditorLanguage = 'json' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
|
||||
export type EditorLanguage =
|
||||
'json' | 'jsonl' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
|
||||
|
||||
export interface CodeEditorProps {
|
||||
value: string;
|
||||
@@ -21,7 +24,8 @@ export interface CodeEditorProps {
|
||||
language?: EditorLanguage;
|
||||
className?: string;
|
||||
placeholder?: string;
|
||||
editorRef?: React.RefObject<ReactCodeMirrorRef | null>;
|
||||
/** Accessible name for the editable region (screen readers). */
|
||||
ariaLabel?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -38,6 +42,116 @@ const prismHighlightStyle = HighlightStyle.define([
|
||||
{ tag: t.comment, color: 'var(--muted-foreground)', fontStyle: 'italic' },
|
||||
]);
|
||||
|
||||
// Stable references: a new basicSetup object or extensions array on every
|
||||
// render makes @uiw/react-codemirror reconfigure the whole editor per keystroke.
|
||||
const EDITABLE_SETUP: BasicSetupOptions = {
|
||||
lineNumbers: true,
|
||||
highlightActiveLine: true,
|
||||
highlightActiveLineGutter: true,
|
||||
foldGutter: true,
|
||||
autocompletion: false,
|
||||
searchKeymap: true,
|
||||
};
|
||||
const READ_ONLY_SETUP: BasicSetupOptions = {
|
||||
...EDITABLE_SETUP,
|
||||
highlightActiveLine: false,
|
||||
highlightActiveLineGutter: false,
|
||||
};
|
||||
|
||||
/** Wrapping a multi-megabyte single line (minified JSON, base64) is very slow. */
|
||||
const WRAP_LIMIT_CHARS = 1_000_000;
|
||||
|
||||
// File drops belong to the panel's dropzone (load into the editor or route to
|
||||
// the batch queue). Without this, CodeMirror inserts the files' text itself.
|
||||
const yieldFileDrops = EditorView.domEventHandlers({
|
||||
drop: (event) => (event.dataTransfer?.files.length ?? 0) > 0,
|
||||
});
|
||||
|
||||
/** Linting re-parses the whole document; beyond this the conversion reports errors alone. */
|
||||
const LINT_LIMIT_CHARS = 2_000_000;
|
||||
const MAX_JSONL_DIAGNOSTICS = 100;
|
||||
|
||||
/**
|
||||
* Lints `text` (starting at document offset `start`) with the converter's own
|
||||
* parser, so the editor and the conversion agree — a leading byte-order mark
|
||||
* is fine, and error positions match on every engine. Blank text is a
|
||||
* prompt, not an error.
|
||||
*/
|
||||
function parseDiagnostic(view: EditorView, text: string, start: number): Diagnostic | null {
|
||||
const result = parseJsonInput(text);
|
||||
if (result.ok || result.error === 'empty') return null;
|
||||
const { doc } = view.state;
|
||||
let from = start;
|
||||
if (result.line !== undefined && result.column !== undefined) {
|
||||
const line = doc.line(Math.min(doc.lineAt(start).number + result.line - 1, doc.lines));
|
||||
from = Math.min(line.from + result.column - 1, line.to);
|
||||
}
|
||||
return { from, to: from, severity: 'error', message: result.error };
|
||||
}
|
||||
|
||||
const jsonLint = linter((view) => {
|
||||
if (view.state.doc.length > LINT_LIMIT_CHARS) return [];
|
||||
const diagnostic = parseDiagnostic(view, view.state.doc.toString(), 0);
|
||||
return diagnostic ? [diagnostic] : [];
|
||||
});
|
||||
|
||||
// JSONL: every non-blank line is its own JSON document.
|
||||
const jsonlLint = linter((view) => {
|
||||
const { doc } = view.state;
|
||||
if (doc.length > LINT_LIMIT_CHARS) return [];
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
for (let n = 1; n <= doc.lines && diagnostics.length < MAX_JSONL_DIAGNOSTICS; n++) {
|
||||
const line = doc.line(n);
|
||||
const diagnostic = parseDiagnostic(view, line.text, line.from);
|
||||
if (diagnostic) diagnostics.push(diagnostic);
|
||||
}
|
||||
return diagnostics;
|
||||
});
|
||||
|
||||
function languageExtensions(language: EditorLanguage, readOnly: boolean) {
|
||||
switch (language) {
|
||||
case 'json':
|
||||
return readOnly ? [json()] : [json(), lintGutter(), jsonLint];
|
||||
case 'jsonl':
|
||||
return readOnly ? [json()] : [json(), lintGutter(), jsonlLint];
|
||||
case 'yaml':
|
||||
return [yaml()];
|
||||
case 'xml':
|
||||
return [xml()];
|
||||
case 'markdown':
|
||||
return [markdown()];
|
||||
case 'sql':
|
||||
return [sql()];
|
||||
case 'toml':
|
||||
return [StreamLanguage.define(toml)];
|
||||
case 'plain':
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// English phrases used by CodeMirror's search panel, folding and lint UI.
|
||||
const PHRASE_KEYS: Record<string, string> = {
|
||||
Find: 'find',
|
||||
Replace: 'replace',
|
||||
next: 'next',
|
||||
previous: 'previous',
|
||||
all: 'all',
|
||||
'match case': 'match_case',
|
||||
regexp: 'regexp',
|
||||
'by word': 'by_word',
|
||||
replace: 'replace_one',
|
||||
'replace all': 'replace_all',
|
||||
close: 'close',
|
||||
'Go to line': 'go_to_line',
|
||||
go: 'go',
|
||||
'Fold line': 'fold_line',
|
||||
'Unfold line': 'unfold_line',
|
||||
'folded code': 'folded_code',
|
||||
unfold: 'unfold',
|
||||
Diagnostics: 'diagnostics',
|
||||
'No diagnostics': 'no_diagnostics',
|
||||
};
|
||||
|
||||
export function CodeEditor({
|
||||
value,
|
||||
onChange,
|
||||
@@ -45,36 +159,25 @@ export function CodeEditor({
|
||||
language = 'json',
|
||||
className,
|
||||
placeholder,
|
||||
editorRef,
|
||||
ariaLabel,
|
||||
}: CodeEditorProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { t: translate, i18n } = useTranslation();
|
||||
const wrap = value.length < WRAP_LIMIT_CHARS;
|
||||
|
||||
const phrases = useMemo(() => {
|
||||
const entries = Object.entries(PHRASE_KEYS).map(([phrase, key]) => [
|
||||
phrase,
|
||||
translate(`editor.phrases.${key}`, { defaultValue: phrase }),
|
||||
]);
|
||||
return EditorState.phrases.of(Object.fromEntries(entries));
|
||||
// i18n.language drives re-translation; translate is stable per language.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language]);
|
||||
|
||||
const extensions = useMemo(() => {
|
||||
const exts = [];
|
||||
if (language === 'json') {
|
||||
exts.push(json());
|
||||
if (!readOnly) {
|
||||
exts.push(lintGutter(), linter(jsonParseLinter()));
|
||||
}
|
||||
} else if (language === 'yaml') {
|
||||
exts.push(yaml());
|
||||
} else if (language === 'xml') {
|
||||
exts.push(xml());
|
||||
} else if (language === 'markdown') {
|
||||
exts.push(markdown());
|
||||
} else if (language === 'sql') {
|
||||
exts.push(sql());
|
||||
} else if (language === 'toml') {
|
||||
exts.push(StreamLanguage.define(toml));
|
||||
}
|
||||
exts.push(syntaxHighlighting(prismHighlightStyle));
|
||||
exts.push(EditorView.lineWrapping);
|
||||
return exts;
|
||||
}, [language, readOnly]);
|
||||
|
||||
const themeExt = useMemo(() => {
|
||||
const isDark = resolvedTheme === 'dark';
|
||||
return EditorView.theme(
|
||||
const theme = EditorView.theme(
|
||||
{
|
||||
'&': {
|
||||
backgroundColor: 'transparent',
|
||||
@@ -82,41 +185,30 @@ export function CodeEditor({
|
||||
height: '100%',
|
||||
fontSize: '13px',
|
||||
},
|
||||
// Scrollbar styling comes from globals.css so the "hide scrollbars"
|
||||
// preference applies here too.
|
||||
'.cm-scroller': {
|
||||
fontFamily: 'var(--font-mono)',
|
||||
lineHeight: '1.6',
|
||||
overflow: 'auto',
|
||||
// Show a thin native scrollbar — `scrollbarWidth: 'none'` made wheel
|
||||
// scroll require a click-to-focus first on some browsers.
|
||||
scrollbarWidth: 'thin',
|
||||
},
|
||||
'.cm-scroller::-webkit-scrollbar': {
|
||||
width: '8px',
|
||||
height: '8px',
|
||||
},
|
||||
'.cm-scroller::-webkit-scrollbar-thumb': {
|
||||
backgroundColor: 'color-mix(in oklch, var(--muted-foreground) 30%, transparent)',
|
||||
borderRadius: '4px',
|
||||
},
|
||||
'.cm-content': {
|
||||
padding: '16px 0',
|
||||
padding: '12px 0',
|
||||
caretColor: 'var(--color-prism-violet)',
|
||||
},
|
||||
'.cm-gutters': {
|
||||
backgroundColor: 'transparent',
|
||||
border: 'none',
|
||||
color: 'var(--muted-foreground)',
|
||||
opacity: '0.5',
|
||||
},
|
||||
'.cm-activeLine': {
|
||||
backgroundColor: isDark
|
||||
? 'color-mix(in oklch, var(--color-prism-violet) 6%, transparent)'
|
||||
: 'color-mix(in oklch, var(--color-prism-violet) 4%, transparent)',
|
||||
? 'color-mix(in oklch, var(--color-prism-violet) 7%, transparent)'
|
||||
: 'color-mix(in oklch, var(--color-prism-violet) 5%, transparent)',
|
||||
},
|
||||
'.cm-activeLineGutter': {
|
||||
backgroundColor: 'transparent',
|
||||
color: 'var(--foreground)',
|
||||
opacity: '0.9',
|
||||
},
|
||||
'&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection': {
|
||||
backgroundColor:
|
||||
@@ -128,31 +220,37 @@ export function CodeEditor({
|
||||
},
|
||||
'.cm-placeholder': {
|
||||
color: 'var(--muted-foreground)',
|
||||
opacity: '0.5',
|
||||
},
|
||||
'&.cm-focused': {
|
||||
outline: 'none',
|
||||
},
|
||||
},
|
||||
{ dark: isDark },
|
||||
);
|
||||
}, [resolvedTheme]);
|
||||
return [
|
||||
...languageExtensions(language, readOnly),
|
||||
syntaxHighlighting(prismHighlightStyle),
|
||||
...(wrap ? [EditorView.lineWrapping] : []),
|
||||
yieldFileDrops,
|
||||
phrases,
|
||||
EditorView.contentAttributes.of({
|
||||
...(ariaLabel ? { 'aria-label': ariaLabel } : {}),
|
||||
...(readOnly ? { 'aria-readonly': 'true' } : {}),
|
||||
}),
|
||||
theme,
|
||||
];
|
||||
}, [ariaLabel, language, phrases, readOnly, resolvedTheme, wrap]);
|
||||
|
||||
return (
|
||||
<div className={cn('h-full overflow-hidden', className)}>
|
||||
<CodeMirror
|
||||
ref={editorRef}
|
||||
value={value}
|
||||
readOnly={readOnly}
|
||||
editable={!readOnly}
|
||||
{...(onChange !== undefined ? { onChange } : {})}
|
||||
{...(placeholder !== undefined ? { placeholder } : {})}
|
||||
extensions={[...extensions, themeExt]}
|
||||
basicSetup={{
|
||||
lineNumbers: true,
|
||||
highlightActiveLine: !readOnly,
|
||||
highlightActiveLineGutter: !readOnly,
|
||||
foldGutter: true,
|
||||
autocompletion: false,
|
||||
searchKeymap: true,
|
||||
}}
|
||||
extensions={extensions}
|
||||
basicSetup={readOnly ? READ_ONLY_SETUP : EDITABLE_SETUP}
|
||||
height="100%"
|
||||
theme="none"
|
||||
/>
|
||||
|
||||
@@ -19,6 +19,7 @@ function EditorFallback({
|
||||
placeholder,
|
||||
readOnly = false,
|
||||
className,
|
||||
ariaLabel,
|
||||
}: CodeEditorProps) {
|
||||
return (
|
||||
<div className={cn('h-full overflow-hidden', className)}>
|
||||
@@ -27,8 +28,9 @@ function EditorFallback({
|
||||
readOnly={readOnly}
|
||||
spellCheck={false}
|
||||
placeholder={placeholder}
|
||||
aria-label={ariaLabel}
|
||||
onChange={onChange ? (e) => onChange(e.target.value) : undefined}
|
||||
className="text-foreground placeholder:text-muted-foreground/50 h-full w-full resize-none bg-transparent px-4 py-4 font-mono text-[13px] leading-[1.6] outline-none"
|
||||
className="text-foreground placeholder:text-muted-foreground h-full w-full resize-none bg-transparent px-4 py-3 font-mono text-[13px] leading-[1.6] outline-none"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -2,22 +2,28 @@ import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toast } from '@/components/ui/sonner';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { extensionsFor, getConverter } from '@/converters/registry';
|
||||
import type { Direction, FormatId } from '@/converters/types';
|
||||
import { useBatchFileRouter } from '@/hooks/useBatchFileRouter';
|
||||
import { useConversionResult } from '@/hooks/useConversionResult';
|
||||
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts';
|
||||
import { useMediaQuery } from '@/hooks/useMediaQuery';
|
||||
import { useOutputBadge } from '@/hooks/useOutputBadge';
|
||||
import { getConverter } from '@/converters/registry';
|
||||
import type { FormatId } from '@/converters/types';
|
||||
import { utf8ByteLength } from '@/lib/bytes';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { extOf, getAllowedExtensions } from '@/lib/file-filter';
|
||||
import { useWorkspaceStore } from '@/stores/workspaceStore';
|
||||
import { DirectionToggle, type Direction } from './DirectionToggle';
|
||||
import { DirectionToggle } from './DirectionToggle';
|
||||
import { FormatPicker } from './FormatPicker';
|
||||
import { InputPanel } from './InputPanel';
|
||||
import { OutputPanel } from './OutputPanel';
|
||||
import { SettingsPanel } from './SettingsPanel';
|
||||
import { ShapeHint } from './ShapeHint';
|
||||
import { StatusBar } from './StatusBar';
|
||||
import { StatusBar, type ConversionState } from './StatusBar';
|
||||
import { BatchPanel } from './BatchPanel';
|
||||
|
||||
const REVERSIBLE_FALLBACKS: FormatId[] = ['jsonl', 'csv', 'yaml', 'toml', 'resx'];
|
||||
|
||||
export function ConverterWorkspace() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -29,32 +35,47 @@ export function ConverterWorkspace() {
|
||||
const setFormat = useWorkspaceStore((s) => s.setFormat);
|
||||
const direction = useWorkspaceStore((s) => s.direction);
|
||||
const setDirection = useWorkspaceStore((s) => s.setDirection);
|
||||
const optionsByFormat = useWorkspaceStore((s) => s.optionsByFormat);
|
||||
const storedOptions = useWorkspaceStore((s) => s.optionsByFormat[s.format]);
|
||||
const setOptionsForFormat = useWorkspaceStore((s) => s.setOptionsForFormat);
|
||||
const resetOptionsForFormat = useWorkspaceStore((s) => s.resetOptionsForFormat);
|
||||
|
||||
const actionsRef = useRef<{ copy: () => void; download: () => void } | null>(null);
|
||||
const [batchOpen, setBatchOpen] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
// Mobile tab state — desktop ignores this and renders both panels side-by-side.
|
||||
// Mobile tab state — desktop renders both panels side-by-side.
|
||||
const [activeTab, setActiveTab] = useState<'input' | 'output'>('input');
|
||||
// One layout at a time: mounting both (CSS-hidden) doubled every editor
|
||||
// update. Defaults to desktop where matchMedia is unavailable.
|
||||
const isDesktop = useMediaQuery('(min-width: 768px)', true);
|
||||
|
||||
const openBatch = useCallback(() => setBatchOpen(true), []);
|
||||
const handleMultiFileDrop = useBatchFileRouter(format, direction, openBatch);
|
||||
|
||||
const switchFormat = useCallback(
|
||||
(next: FormatId) => {
|
||||
setFormat(next);
|
||||
const loadSingleFile = useCallback(
|
||||
(file: File) => {
|
||||
const allowed = getAllowedExtensions(direction, extensionsFor(format));
|
||||
const ext = extOf(file.name);
|
||||
if (ext && !allowed.includes(ext)) {
|
||||
toast.warning(t('batch.toast.wrong_format', { count: 1 }));
|
||||
return;
|
||||
}
|
||||
file.text().then(
|
||||
(text) => {
|
||||
setInput(text);
|
||||
toast.success(t('toast.file_loaded', { name: file.name }));
|
||||
},
|
||||
(err: unknown) => toast.error(t('toast.file_failed', { message: errorMessage(err) })),
|
||||
);
|
||||
},
|
||||
[setFormat],
|
||||
[direction, format, setInput, t],
|
||||
);
|
||||
const handleMultiFileDrop = useBatchFileRouter(format, direction, loadSingleFile, openBatch);
|
||||
|
||||
const switchDirection = useCallback(
|
||||
(next: Direction) => {
|
||||
setDirection(next);
|
||||
// If the current format doesn't support the new direction, switch to one that does.
|
||||
if (next === 'reverse' && typeof getConverter(format).reverse !== 'function') {
|
||||
const fallback = (['jsonl', 'csv', 'yaml', 'toml', 'resx'] as FormatId[]).find(
|
||||
const fallback = REVERSIBLE_FALLBACKS.find(
|
||||
(id) => typeof getConverter(id).reverse === 'function',
|
||||
);
|
||||
if (fallback) setFormat(fallback);
|
||||
@@ -63,12 +84,13 @@ export function ConverterWorkspace() {
|
||||
[format, setDirection, setFormat],
|
||||
);
|
||||
|
||||
const currentOptions = optionsByFormat[format] ?? getConverter(format).defaultOptions;
|
||||
const currentOptions = useMemo(
|
||||
() => storedOptions ?? { ...getConverter(format).defaultOptions },
|
||||
[format, storedOptions],
|
||||
);
|
||||
|
||||
const setCurrentOptions = useCallback(
|
||||
(next: Record<string, unknown>) => {
|
||||
setOptionsForFormat(format, next);
|
||||
},
|
||||
(next: Record<string, unknown>) => setOptionsForFormat(format, next),
|
||||
[format, setOptionsForFormat],
|
||||
);
|
||||
|
||||
@@ -77,38 +99,65 @@ export function ConverterWorkspace() {
|
||||
toast.success(t('toast.options_reset'));
|
||||
}, [format, resetOptionsForFormat, t]);
|
||||
|
||||
const { output, inputError, outputError, shape, parseMs } = useConversionResult(
|
||||
input,
|
||||
format,
|
||||
direction,
|
||||
currentOptions,
|
||||
);
|
||||
const result = useConversionResult(input, format, direction, currentOptions);
|
||||
|
||||
useKeyboardShortcuts([
|
||||
{ key: 'k', mod: true, handler: () => setInput('') },
|
||||
{ key: 's', mod: true, handler: () => actionsRef.current?.download() },
|
||||
{ key: ',', mod: true, handler: () => setSettingsOpen((v) => !v) },
|
||||
{ code: 'KeyS', mod: true, handler: () => actionsRef.current?.download() },
|
||||
{ code: 'Comma', mod: true, handler: () => setSettingsOpen((v) => !v) },
|
||||
]);
|
||||
|
||||
const hasUnreadOutput = useOutputBadge(output, activeTab);
|
||||
const hasUnreadOutput = useOutputBadge(result.output, activeTab);
|
||||
const inputBytes = useMemo(() => utf8ByteLength(input), [input]);
|
||||
const registerActions = useCallback((a: { copy: () => void; download: () => void }) => {
|
||||
actionsRef.current = a;
|
||||
}, []);
|
||||
|
||||
const inputBytes = useMemo(() => new TextEncoder().encode(input).length, [input]);
|
||||
const outputBytes = useMemo(() => new TextEncoder().encode(output).length, [output]);
|
||||
const state: ConversionState = result.pending
|
||||
? 'working'
|
||||
: result.inputError || result.outputError
|
||||
? 'error'
|
||||
: result.output
|
||||
? 'ok'
|
||||
: 'idle';
|
||||
|
||||
const inputPanel = (
|
||||
<InputPanel
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
error={result.inputError}
|
||||
errorLine={result.inputErrorLine}
|
||||
errorColumn={result.inputErrorColumn}
|
||||
format={format}
|
||||
direction={direction}
|
||||
onMultiFileDrop={handleMultiFileDrop}
|
||||
/>
|
||||
);
|
||||
const outputPanel = (
|
||||
<OutputPanel
|
||||
format={format}
|
||||
content={result.output}
|
||||
error={result.outputError}
|
||||
pending={result.pending}
|
||||
options={currentOptions}
|
||||
direction={direction}
|
||||
registerActions={registerActions}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col gap-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="flex h-full flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<DirectionToggle value={direction} onChange={switchDirection} />
|
||||
<FormatPicker
|
||||
value={format}
|
||||
onChange={switchFormat}
|
||||
shape={shape}
|
||||
onChange={setFormat}
|
||||
shape={result.shape}
|
||||
direction={direction}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<ShapeHint shape={shape} />
|
||||
<div className="flex items-center gap-2">
|
||||
<ShapeHint shape={result.shape} />
|
||||
<BatchPanel
|
||||
format={format}
|
||||
direction={direction}
|
||||
@@ -127,79 +176,55 @@ export function ConverterWorkspace() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-border bg-card/40 flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border">
|
||||
{/* Mobile: Tabs UI — each tab gets the full workspace height so panels
|
||||
never overlap on short viewports. */}
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={(v) => setActiveTab(v as 'input' | 'output')}
|
||||
className="flex min-h-0 flex-1 flex-col md:hidden"
|
||||
>
|
||||
<TabsList className="border-border/60 w-full justify-start gap-0 rounded-none border-b px-2">
|
||||
<TabsTrigger value="input">{t('home.tab_input')}</TabsTrigger>
|
||||
<TabsTrigger value="output" className="relative">
|
||||
{t('home.tab_output')}
|
||||
{hasUnreadOutput && (
|
||||
<span
|
||||
aria-hidden
|
||||
className="bg-primary absolute top-1 right-1 h-1.5 w-1.5 rounded-full"
|
||||
/>
|
||||
)}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="input" className="min-h-0 flex-1">
|
||||
<InputPanel
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
error={inputError}
|
||||
format={format}
|
||||
direction={direction}
|
||||
onMultiFileDrop={handleMultiFileDrop}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="output" className="min-h-0 flex-1">
|
||||
<OutputPanel
|
||||
format={format}
|
||||
content={output}
|
||||
error={outputError}
|
||||
options={currentOptions}
|
||||
direction={direction}
|
||||
registerActions={(a) => {
|
||||
actionsRef.current = a;
|
||||
}}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{/* Desktop: side-by-side grid (≥ md). Rendered in parallel with the
|
||||
Tabs above so neither remounts on viewport resize and CodeMirror
|
||||
state survives the swap. */}
|
||||
<div className="hidden min-h-0 flex-1 md:grid md:grid-cols-2">
|
||||
<div className="border-border/60 min-h-0 border-r">
|
||||
<InputPanel
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
error={inputError}
|
||||
format={format}
|
||||
direction={direction}
|
||||
onMultiFileDrop={handleMultiFileDrop}
|
||||
/>
|
||||
<div className="border-border bg-card/60 corner-ticks flex min-h-0 flex-1 flex-col rounded-lg border backdrop-blur-[2px]">
|
||||
{isDesktop ? (
|
||||
<div className="grid min-h-0 flex-1 grid-cols-2">
|
||||
<div className="border-border/70 min-h-0 border-r">{inputPanel}</div>
|
||||
<div className="min-h-0">{outputPanel}</div>
|
||||
</div>
|
||||
<div className="min-h-0">
|
||||
<OutputPanel
|
||||
format={format}
|
||||
content={output}
|
||||
error={outputError}
|
||||
options={currentOptions}
|
||||
direction={direction}
|
||||
registerActions={(a) => {
|
||||
actionsRef.current = a;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={(v) => setActiveTab(v as 'input' | 'output')}
|
||||
className="flex min-h-0 flex-1 flex-col"
|
||||
>
|
||||
<TabsList className="border-border/70 w-full justify-start gap-0 rounded-none border-b px-2">
|
||||
<TabsTrigger value="input">{t('home.tab_input')}</TabsTrigger>
|
||||
<TabsTrigger value="output" className="relative">
|
||||
{t('home.tab_output')}
|
||||
{hasUnreadOutput && (
|
||||
<span
|
||||
aria-hidden
|
||||
className="bg-primary absolute top-1 right-1 h-1.5 w-1.5 rounded-full"
|
||||
/>
|
||||
)}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
{/* forceMount keeps both editors alive (undo history, scroll) across tab switches. */}
|
||||
<TabsContent
|
||||
value="input"
|
||||
forceMount
|
||||
className="min-h-0 flex-1 data-[state=inactive]:hidden"
|
||||
>
|
||||
{inputPanel}
|
||||
</TabsContent>
|
||||
<TabsContent
|
||||
value="output"
|
||||
forceMount
|
||||
className="min-h-0 flex-1 data-[state=inactive]:hidden"
|
||||
>
|
||||
{outputPanel}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)}
|
||||
|
||||
<StatusBar inputBytes={inputBytes} outputBytes={outputBytes} parseMs={parseMs} />
|
||||
<StatusBar
|
||||
state={state}
|
||||
inputBytes={inputBytes}
|
||||
outputBytes={result.outputBytes}
|
||||
ms={result.ms}
|
||||
precisionLoss={result.precisionLoss}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,50 +1,50 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ArrowLeft, ArrowRight } from 'lucide-react';
|
||||
import type { Direction } from '@/converters/types';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type Direction = 'forward' | 'reverse';
|
||||
|
||||
interface DirectionToggleProps {
|
||||
value: Direction;
|
||||
onChange: (next: Direction) => void;
|
||||
}
|
||||
|
||||
const OPTIONS: Array<{ value: Direction; Icon: typeof ArrowRight }> = [
|
||||
{ value: 'forward', Icon: ArrowRight },
|
||||
{ value: 'reverse', Icon: ArrowLeft },
|
||||
];
|
||||
|
||||
export function DirectionToggle({ value, onChange }: DirectionToggleProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
className="border-border/60 inline-flex items-center gap-0.5 rounded-md border p-0.5"
|
||||
className="border-border bg-card/60 inline-flex items-center gap-0.5 rounded-md border p-0.5"
|
||||
role="group"
|
||||
aria-label={t('direction.title')}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange('forward')}
|
||||
title={t('direction.hint')}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-medium transition',
|
||||
value === 'forward'
|
||||
? 'bg-muted text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<ArrowRight className="h-3 w-3" />
|
||||
<span>{t('direction.forward')}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange('reverse')}
|
||||
title={t('direction.hint')}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-medium transition',
|
||||
value === 'reverse'
|
||||
? 'bg-muted text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<ArrowLeft className="h-3 w-3" />
|
||||
<span>{t('direction.reverse')}</span>
|
||||
</button>
|
||||
{OPTIONS.map(({ value: option, Icon }) => {
|
||||
const active = value === option;
|
||||
return (
|
||||
<button
|
||||
key={option}
|
||||
type="button"
|
||||
aria-pressed={active}
|
||||
onClick={() => onChange(option)}
|
||||
title={t('direction.hint')}
|
||||
className={cn(
|
||||
'focus-visible:ring-ring inline-flex min-h-7 items-center gap-1.5 rounded px-2.5 text-xs font-medium transition outline-none focus-visible:ring-2',
|
||||
active ? 'bg-muted text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{/* Re-keyed on change so the "refract" spin replays each time. */}
|
||||
<Icon
|
||||
key={active ? `${option}-on` : option}
|
||||
className={cn('h-3.5 w-3.5', active && 'text-primary motion-safe:animate-refract')}
|
||||
aria-hidden
|
||||
/>
|
||||
<span>{t(`direction.${option}`)}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,11 +3,10 @@ import { useTranslation } from 'react-i18next';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';
|
||||
import { ALL_FORMATS, getConverter } from '@/converters/registry';
|
||||
import type { FormatId } from '@/converters/types';
|
||||
import type { Direction, FormatId } from '@/converters/types';
|
||||
import type { JsonShape } from '@/lib/detect';
|
||||
import { isFormatSuggested } from '@/lib/suggestions';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { Direction } from './DirectionToggle';
|
||||
|
||||
interface FormatPickerProps {
|
||||
value: FormatId;
|
||||
@@ -36,21 +35,26 @@ export function FormatPicker({ value, onChange, shape, direction = 'forward' }:
|
||||
<SheetTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="border-border bg-card/40 text-muted-foreground hover:border-primary/40 hover:text-foreground inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs font-medium transition md:hidden"
|
||||
aria-label={t('home.format_picker_label')}
|
||||
className="border-border bg-card/60 text-muted-foreground hover:border-primary/40 hover:text-foreground inline-flex min-h-8 items-center gap-1.5 rounded-md border px-2.5 text-xs font-medium transition md:hidden"
|
||||
>
|
||||
<span className="tracking-wider uppercase opacity-70">
|
||||
{t('home.format_picker_label')}
|
||||
</span>
|
||||
<span className="label-mono">{t('home.format_picker_label')}</span>
|
||||
<span className="text-foreground font-mono">{t(current.meta.labelKey)}</span>
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
<ChevronDown className="h-3.5 w-3.5" aria-hidden />
|
||||
</button>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="bottom" className="max-h-[80vh] w-full overflow-y-auto">
|
||||
<SheetContent
|
||||
closeLabel={t('common.close')}
|
||||
side="bottom"
|
||||
className="max-h-[80vh] w-full overflow-y-auto"
|
||||
>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('home.format_picker_label')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="grid grid-cols-2 gap-1.5 p-4 pt-2 sm:grid-cols-3">
|
||||
<div
|
||||
className="grid grid-cols-2 gap-1.5 p-4 pt-2 sm:grid-cols-3"
|
||||
role="group"
|
||||
aria-label={t('home.format_picker_label')}
|
||||
>
|
||||
{ALL_FORMATS.map((id) => (
|
||||
<FormatChip
|
||||
key={id}
|
||||
@@ -67,7 +71,11 @@ export function FormatPicker({ value, onChange, shape, direction = 'forward' }:
|
||||
</Sheet>
|
||||
|
||||
{/* Desktop: 12 chips inline. */}
|
||||
<div className="hidden flex-wrap gap-1.5 md:flex">
|
||||
<div
|
||||
className="hidden flex-wrap gap-1 md:flex"
|
||||
role="group"
|
||||
aria-label={t('home.format_picker_label')}
|
||||
>
|
||||
{ALL_FORMATS.map((id) => (
|
||||
<FormatChip
|
||||
key={id}
|
||||
@@ -93,6 +101,12 @@ interface FormatChipProps {
|
||||
expanded?: boolean;
|
||||
}
|
||||
|
||||
function chipStatus(noReverse: boolean, suggested: boolean, dimmed: boolean) {
|
||||
if (noReverse) return 'no_reverse';
|
||||
if (suggested) return 'suggested';
|
||||
return dimmed ? 'not_suggested' : 'ready';
|
||||
}
|
||||
|
||||
function FormatChip({ id, value, onChange, shape, direction, expanded }: FormatChipProps) {
|
||||
const { t } = useTranslation();
|
||||
const c = getConverter(id);
|
||||
@@ -100,41 +114,37 @@ function FormatChip({ id, value, onChange, shape, direction, expanded }: FormatC
|
||||
const suggested = direction === 'forward' && shape ? isFormatSuggested(id, shape) : false;
|
||||
const noReverse = direction === 'reverse' && typeof c.reverse !== 'function';
|
||||
const enabled = c.meta.ready && !noReverse;
|
||||
const dimmed = direction === 'forward' && shape && !suggested && c.meta.ready;
|
||||
const dimmed = direction === 'forward' && !!shape && !suggested && c.meta.ready;
|
||||
const status = chipStatus(noReverse, suggested, dimmed);
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={active}
|
||||
onClick={() => onChange(id)}
|
||||
disabled={!enabled}
|
||||
className={cn(
|
||||
'group relative inline-flex items-center gap-1.5 rounded-md border font-medium transition',
|
||||
expanded
|
||||
? 'justify-between px-3 py-2 text-sm'
|
||||
: 'px-2 py-0.5 text-[11px] sm:px-2.5 sm:py-1 sm:text-xs',
|
||||
'group focus-visible:ring-ring relative inline-flex items-center gap-1.5 overflow-hidden rounded-md border font-mono font-medium transition outline-none focus-visible:ring-2',
|
||||
expanded ? 'min-h-10 justify-between px-3 text-sm' : 'min-h-7 px-2 text-xs',
|
||||
active
|
||||
? 'border-primary/60 bg-primary/10 text-foreground'
|
||||
: 'border-border bg-card/40 text-muted-foreground hover:text-foreground hover:border-border',
|
||||
: 'border-border bg-card/60 text-muted-foreground hover:text-foreground hover:border-foreground/30',
|
||||
!enabled && 'cursor-not-allowed opacity-50',
|
||||
dimmed && !active && 'opacity-50',
|
||||
// Dashed rather than faded, so the label keeps its contrast.
|
||||
dimmed && !active && 'border-dashed',
|
||||
suggested && !active && 'ring-primary/30 ring-offset-background ring-1 ring-offset-1',
|
||||
)}
|
||||
title={
|
||||
!c.meta.ready
|
||||
? t('format_status.planned', { phase: c.meta.phase })
|
||||
: noReverse
|
||||
? t('format_status.no_reverse')
|
||||
: suggested
|
||||
? t('format_status.suggested')
|
||||
: t('format_status.ready')
|
||||
}
|
||||
title={t(`format_status.${status}`)}
|
||||
>
|
||||
<span className="font-mono">{t(c.meta.labelKey)}</span>
|
||||
{!c.meta.ready && (
|
||||
<span className="border-border text-muted-foreground rounded border px-1 text-[10px] tracking-wide">
|
||||
P{c.meta.phase}
|
||||
</span>
|
||||
)}
|
||||
<span>{t(c.meta.labelKey)}</span>
|
||||
{/* Spectrum underline marks the active format. */}
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
'bg-spectrum absolute inset-x-1 bottom-0 h-px origin-left transition-transform duration-300',
|
||||
active ? 'scale-x-100' : 'scale-x-0 group-hover:scale-x-50',
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +1,30 @@
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useDropzone } from 'react-dropzone';
|
||||
import { useDropzone, type FileRejection } from 'react-dropzone';
|
||||
import { Eraser, FileText, FolderOpen } from 'lucide-react';
|
||||
import { ToolbarButton } from '@/components/common/ToolbarButton';
|
||||
import { toast } from '@/components/ui/sonner';
|
||||
import { extensionsFor } from '@/converters/registry';
|
||||
import type { Direction, FormatId } from '@/converters/types';
|
||||
import { useFileAccept } from '@/hooks/useFileAccept';
|
||||
import { editorLanguageFor } from '@/lib/editor-language';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { extOf } from '@/lib/file-filter';
|
||||
import { readFileText } from '@/lib/read-file';
|
||||
import { SAMPLE_JSON } from '@/lib/sample';
|
||||
import { isTauri, nativeOpenFiles, fileFromNativePath } from '@/lib/tauri';
|
||||
import type { FormatId } from '@/converters/types';
|
||||
import { fileFromNativePath, isTauri, nativeOpenFiles, type DialogFilter } from '@/lib/tauri';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { CodeEditorLazy } from './CodeEditorLazy';
|
||||
import type { Direction } from './DirectionToggle';
|
||||
|
||||
interface InputPanelProps {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
error?: string | null;
|
||||
errorLine?: number | null;
|
||||
errorColumn?: number | null;
|
||||
/** Drives accept list, file picker filter, and editor label. */
|
||||
format: FormatId;
|
||||
/** Forward = JSON-only; reverse = the format's native extension. */
|
||||
/** Forward = JSON-only; reverse = the format's native extensions. */
|
||||
direction: Direction;
|
||||
/** Called when 2+ files are dropped — workspace routes them into batch. */
|
||||
onMultiFileDrop?: (files: File[]) => void;
|
||||
@@ -30,6 +34,8 @@ export function InputPanel({
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
errorLine,
|
||||
errorColumn,
|
||||
format,
|
||||
direction,
|
||||
onMultiFileDrop,
|
||||
@@ -42,18 +48,33 @@ export function InputPanel({
|
||||
format,
|
||||
direction,
|
||||
);
|
||||
|
||||
const formatLabel = t(converter.meta.labelKey);
|
||||
const inputLabel = isReverse
|
||||
? t('home.input_label_format', { format: t(converter.meta.labelKey) })
|
||||
? t('home.input_label_format', { format: formatLabel })
|
||||
: t('home.input_label');
|
||||
|
||||
const editorLanguage = editorLanguageFor(format, direction);
|
||||
|
||||
const hasAllowedExt = useCallback(
|
||||
(name: string) => allowedExtensions.includes(extOf(name)),
|
||||
[allowedExtensions],
|
||||
);
|
||||
|
||||
const loadFile = useCallback(
|
||||
(file: File) => {
|
||||
if (!hasAllowedExt(file.name)) {
|
||||
toast.warning(t('batch.toast.wrong_format', { count: 1 }));
|
||||
return;
|
||||
}
|
||||
readFileText(file).then(
|
||||
(text) => {
|
||||
onChange(text);
|
||||
toast.success(t('toast.file_loaded', { name: file.name }));
|
||||
},
|
||||
(err: unknown) => toast.error(t('toast.file_failed', { message: errorMessage(err) })),
|
||||
);
|
||||
},
|
||||
[hasAllowedExt, onChange, t],
|
||||
);
|
||||
|
||||
const onDrop = useCallback(
|
||||
(acceptedFiles: File[]) => {
|
||||
setDragActive(false);
|
||||
@@ -62,26 +83,14 @@ export function InputPanel({
|
||||
onMultiFileDrop(acceptedFiles);
|
||||
return;
|
||||
}
|
||||
const file = acceptedFiles[0]!;
|
||||
if (!hasAllowedExt(file.name)) {
|
||||
toast.warning(t('batch.toast.wrong_format', { count: 1 }));
|
||||
return;
|
||||
}
|
||||
void readFileText(file).then(
|
||||
(text) => {
|
||||
onChange(text);
|
||||
toast.success(t('toast.file_loaded', { name: file.name }));
|
||||
},
|
||||
(err: Error) => {
|
||||
toast.error(t('toast.file_failed', { message: err.message }));
|
||||
},
|
||||
);
|
||||
loadFile(acceptedFiles[0]!);
|
||||
},
|
||||
[hasAllowedExt, onChange, onMultiFileDrop, t],
|
||||
[loadFile, onMultiFileDrop],
|
||||
);
|
||||
|
||||
const onDropRejected = useCallback(
|
||||
(rejections: { file: File }[]) => {
|
||||
(rejections: FileRejection[]) => {
|
||||
setDragActive(false);
|
||||
if (rejections.length > 0) {
|
||||
toast.warning(t('batch.toast.wrong_format', { count: rejections.length }));
|
||||
}
|
||||
@@ -100,59 +109,58 @@ export function InputPanel({
|
||||
noKeyboard: true,
|
||||
});
|
||||
|
||||
const dialogFilters = (): DialogFilter[] =>
|
||||
isReverse
|
||||
? [
|
||||
{ name: formatLabel, extensions: extensionsFor(format) },
|
||||
{ name: t('file_dialog.text'), extensions: ['txt'] },
|
||||
]
|
||||
: [
|
||||
{ name: t('file_dialog.json'), extensions: ['json'] },
|
||||
{ name: t('file_dialog.text'), extensions: ['txt'] },
|
||||
];
|
||||
|
||||
const handleOpenFile = async () => {
|
||||
if (isTauri()) {
|
||||
const paths = await nativeOpenFiles({ multiple: false });
|
||||
if (!paths || paths.length === 0) return;
|
||||
try {
|
||||
const file = await fileFromNativePath(paths[0]!);
|
||||
// The native dialog already filtered; reject only when the name carries
|
||||
// a recognizable, disallowed extension. Android content URIs often have
|
||||
// no extension at all (opaque document ids) — don't reject those.
|
||||
const pickedExt = extOf(file.name);
|
||||
if (pickedExt && !allowedExtensions.includes(pickedExt)) {
|
||||
toast.warning(t('batch.toast.wrong_format', { count: 1 }));
|
||||
return;
|
||||
}
|
||||
const text = await file.text();
|
||||
onChange(text);
|
||||
// Android content URIs sometimes yield an opaque document id with no
|
||||
// real filename (e.g. `msf:1000000123`). When there's no usable
|
||||
// extension to show a clean name, fall back to a count-based message.
|
||||
toast.success(
|
||||
pickedExt
|
||||
? t('toast.file_loaded', { name: file.name })
|
||||
: t('toast.files_loaded', { count: 1 }),
|
||||
);
|
||||
} catch (err) {
|
||||
toast.error(t('toast.file_failed', { message: (err as Error).message }));
|
||||
}
|
||||
if (!isTauri()) {
|
||||
fileInputRef.current?.click();
|
||||
return;
|
||||
}
|
||||
fileInputRef.current?.click();
|
||||
try {
|
||||
const paths = await nativeOpenFiles({ multiple: false, filters: dialogFilters() });
|
||||
if (!paths || paths.length === 0) return;
|
||||
const file = await fileFromNativePath(paths[0]!);
|
||||
// The native dialog already filtered; reject only when the name carries
|
||||
// a recognizable, disallowed extension. Android content URIs often have
|
||||
// no extension at all (opaque document ids) — don't reject those.
|
||||
const pickedExt = extOf(file.name);
|
||||
if (pickedExt && !allowedExtensions.includes(pickedExt)) {
|
||||
toast.warning(t('batch.toast.wrong_format', { count: 1 }));
|
||||
return;
|
||||
}
|
||||
onChange(await file.text());
|
||||
// Android content URIs sometimes yield an opaque document id with no
|
||||
// real filename (e.g. `msf:1000000123`); fall back to a count message.
|
||||
toast.success(
|
||||
pickedExt
|
||||
? t('toast.file_loaded', { name: file.name })
|
||||
: t('toast.files_loaded', { count: 1 }),
|
||||
);
|
||||
} catch (err) {
|
||||
toast.error(t('toast.file_failed', { message: errorMessage(err) }));
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
if (!hasAllowedExt(file.name)) {
|
||||
toast.warning(t('batch.toast.wrong_format', { count: 1 }));
|
||||
e.target.value = '';
|
||||
return;
|
||||
}
|
||||
void readFileText(file).then(
|
||||
(text) => {
|
||||
onChange(text);
|
||||
toast.success(t('toast.file_loaded', { name: file.name }));
|
||||
},
|
||||
(err: Error) => {
|
||||
toast.error(t('toast.file_failed', { message: err.message }));
|
||||
},
|
||||
);
|
||||
e.target.value = '';
|
||||
if (file) loadFile(file);
|
||||
};
|
||||
|
||||
const showOverlay = isDragActive || dragActive;
|
||||
const position =
|
||||
errorLine != null
|
||||
? t('home.error_position', { line: errorLine, column: errorColumn ?? 1 })
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="relative flex h-full flex-col" {...getRootProps()}>
|
||||
@@ -163,46 +171,60 @@ export function InputPanel({
|
||||
accept={fileInputAccept}
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
tabIndex={-1}
|
||||
aria-hidden
|
||||
/>
|
||||
|
||||
<div className="border-border/60 flex items-center justify-between border-b px-3 py-2">
|
||||
<div className="border-border/70 flex items-center justify-between gap-2 border-b px-3 py-1">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="text-muted-foreground text-xs font-medium tracking-wider uppercase">
|
||||
{inputLabel}
|
||||
</span>
|
||||
{error && (
|
||||
<span className="text-destructive max-w-md truncate text-xs" title={error}>
|
||||
· {error}
|
||||
</span>
|
||||
)}
|
||||
<span className="label-mono truncate">{inputLabel}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="flex items-center gap-0.5">
|
||||
<ToolbarButton
|
||||
onClick={handleOpenFile}
|
||||
onClick={() => void handleOpenFile()}
|
||||
label={t('home.open_file')}
|
||||
icon={<FolderOpen className="h-3.5 w-3.5" />}
|
||||
icon={<FolderOpen className="motion-safe:group-hover:animate-bob h-3.5 w-3.5" />}
|
||||
/>
|
||||
{!isReverse && (
|
||||
<ToolbarButton
|
||||
onClick={() => onChange(SAMPLE_JSON)}
|
||||
label={t('home.load_sample')}
|
||||
icon={<FileText className="h-3.5 w-3.5" />}
|
||||
icon={
|
||||
<FileText className="h-3.5 w-3.5 transition-transform motion-safe:group-hover:-rotate-6" />
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<ToolbarButton
|
||||
onClick={() => onChange('')}
|
||||
label={t('home.clear')}
|
||||
icon={<Eraser className="h-3.5 w-3.5" />}
|
||||
icon={<Eraser className="motion-safe:group-hover:animate-nudge h-3.5 w-3.5" />}
|
||||
disabled={!value}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className={cn(
|
||||
'border-destructive/30 bg-destructive/5 text-destructive border-b px-3 py-1 font-mono text-xs',
|
||||
!error && 'sr-only',
|
||||
)}
|
||||
>
|
||||
{error ? (
|
||||
<>
|
||||
{position && <span className="mr-2 font-semibold">{position}</span>}
|
||||
<span className="break-words">{error}</span>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<CodeEditorLazy
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
language={editorLanguage}
|
||||
language={editorLanguageFor(format, direction)}
|
||||
ariaLabel={inputLabel}
|
||||
placeholder={
|
||||
isReverse
|
||||
? t('home.input_placeholder_format', {
|
||||
@@ -213,11 +235,9 @@ export function InputPanel({
|
||||
/>
|
||||
{showOverlay && (
|
||||
<div className="bg-background/80 pointer-events-none absolute inset-0 z-10 flex items-center justify-center backdrop-blur-sm">
|
||||
<div className="border-primary/60 bg-card flex flex-col items-center gap-2 rounded-lg border-2 border-dashed px-8 py-6">
|
||||
<FolderOpen className="text-primary h-8 w-8" />
|
||||
<p className="font-display text-spectrum text-lg italic">
|
||||
{t('home.drop_zone_active')}
|
||||
</p>
|
||||
<div className="border-primary/60 bg-card corner-ticks flex flex-col items-center gap-2 rounded-lg border border-dashed px-8 py-6">
|
||||
<FolderOpen className="text-primary motion-safe:animate-bob h-8 w-8" />
|
||||
<p className="label-mono text-foreground">{t('home.drop_zone_active')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check, Copy, Download } from 'lucide-react';
|
||||
import { Check, Copy, Download, LoaderCircle } from 'lucide-react';
|
||||
import { toast } from '@/components/ui/sonner';
|
||||
import { ToolbarButton } from '@/components/common/ToolbarButton';
|
||||
import type { FormatId } from '@/converters/types';
|
||||
import { getConverter } from '@/converters/registry';
|
||||
import { decodeBytes } from '@/lib/bytes';
|
||||
import type { Direction } from './DirectionToggle';
|
||||
import type { Direction, FormatId } from '@/converters/types';
|
||||
import { decodeBytes, type Encoding } from '@/lib/bytes';
|
||||
import { downloadBlob } from '@/lib/download';
|
||||
import { outputLanguageFor } from '@/lib/editor-language';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { isTauri, nativeSaveBlob } from '@/lib/tauri';
|
||||
import { CodeEditorLazy } from './CodeEditorLazy';
|
||||
|
||||
interface OutputPanelProps {
|
||||
format: FormatId;
|
||||
content: string;
|
||||
error?: string | null;
|
||||
/** A newer result is being computed (large input in the worker). */
|
||||
pending?: boolean;
|
||||
/** Current converter options — needed to decode binary output for download. */
|
||||
options?: Record<string, unknown>;
|
||||
/** Forward = JSON→format; reverse = format→JSON. Drives download extension. */
|
||||
@@ -20,96 +26,139 @@ interface OutputPanelProps {
|
||||
registerActions?: (actions: { copy: () => void; download: () => void }) => void;
|
||||
}
|
||||
|
||||
const COPIED_FEEDBACK_MS = 1500;
|
||||
|
||||
export function OutputPanel({
|
||||
format,
|
||||
content,
|
||||
error,
|
||||
pending = false,
|
||||
options,
|
||||
direction = 'forward',
|
||||
registerActions,
|
||||
}: OutputPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const converter = getConverter(format);
|
||||
const isReverse = direction === 'reverse';
|
||||
const outputExt = isReverse ? 'json' : converter.meta.extension;
|
||||
const outputMime = isReverse ? 'application/json' : converter.meta.mimeType;
|
||||
const formatLabel = isReverse ? 'JSON' : t(converter.meta.labelKey);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (copiedTimer.current) clearTimeout(copiedTimer.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleCopy = useCallback(async () => {
|
||||
if (!content) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
setCopied(true);
|
||||
toast.success(t('toast.copied', { format: t(converter.meta.labelKey) }));
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
toast.success(t('toast.copied', { format: formatLabel }));
|
||||
if (copiedTimer.current) clearTimeout(copiedTimer.current);
|
||||
copiedTimer.current = setTimeout(() => setCopied(false), COPIED_FEEDBACK_MS);
|
||||
} catch {
|
||||
toast.error(t('toast.copy_failed'));
|
||||
}
|
||||
}, [content, converter, t]);
|
||||
}, [content, formatLabel, t]);
|
||||
|
||||
const handleDownload = useCallback(() => {
|
||||
if (!content) return;
|
||||
const handleDownload = useCallback(async () => {
|
||||
if (!content || error) return;
|
||||
const filename = `output.${outputExt}`;
|
||||
let blob: Blob;
|
||||
if (!isReverse && converter.meta.binary) {
|
||||
// Decode encoded text back to raw bytes so the downloaded file is a
|
||||
// real binary BSON / CBOR / MessagePack payload.
|
||||
const encoding = (options?.['encoding'] ?? 'base64') as 'base64' | 'hex';
|
||||
const bytes = decodeBytes(content, encoding);
|
||||
// .slice() copies into a fresh ArrayBuffer (not SharedArrayBuffer),
|
||||
// which is what Blob's typed constructor accepts.
|
||||
blob = new Blob([bytes.slice()], { type: outputMime });
|
||||
} else {
|
||||
blob = new Blob([content], { type: outputMime });
|
||||
try {
|
||||
const blob =
|
||||
!isReverse && converter.meta.binary
|
||||
? // Decode the displayed text back to raw bytes so the file is real
|
||||
// BSON / CBOR / MessagePack. .slice() yields a plain ArrayBuffer view.
|
||||
new Blob(
|
||||
[
|
||||
decodeBytes(
|
||||
content,
|
||||
(options?.['encoding'] as Encoding | undefined) ?? 'base64',
|
||||
).slice(),
|
||||
],
|
||||
{ type: outputMime },
|
||||
)
|
||||
: new Blob([content], { type: outputMime });
|
||||
if (isTauri()) {
|
||||
// Android WebViews ignore <a download>; desktop webviews are inconsistent.
|
||||
const saved = await nativeSaveBlob(blob, filename, {
|
||||
name: formatLabel,
|
||||
extensions: [outputExt],
|
||||
});
|
||||
if (saved) toast.success(t('toast.downloaded', { filename }));
|
||||
return;
|
||||
}
|
||||
downloadBlob(blob, filename);
|
||||
toast.success(t('toast.downloaded', { filename }));
|
||||
} catch (err) {
|
||||
toast.error(t('toast.download_failed', { message: errorMessage(err) }));
|
||||
}
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
toast.success(t('toast.downloaded', { filename }));
|
||||
}, [content, converter, isReverse, outputExt, outputMime, options, t]);
|
||||
}, [content, converter, error, formatLabel, isReverse, options, outputExt, outputMime, t]);
|
||||
|
||||
useEffect(() => {
|
||||
registerActions?.({ copy: handleCopy, download: handleDownload });
|
||||
registerActions?.({ copy: () => void handleCopy(), download: () => void handleDownload() });
|
||||
}, [registerActions, handleCopy, handleDownload]);
|
||||
|
||||
const disabled = !content || !!error;
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="border-border/60 flex items-center justify-between border-b px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-muted-foreground text-xs font-medium tracking-wider uppercase">
|
||||
{t('home.output_label')}
|
||||
</span>
|
||||
<span className="text-muted-foreground/60 font-mono text-xs">· .{outputExt}</span>
|
||||
<div className="border-border/70 flex items-center justify-between gap-2 border-b px-3 py-1">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="label-mono">{t('home.output_label')}</span>
|
||||
<span className="label-mono text-foreground/70">.{outputExt}</span>
|
||||
{pending && (
|
||||
<LoaderCircle
|
||||
className="text-primary h-3.5 w-3.5 motion-safe:animate-spin"
|
||||
aria-label={t('common.loading')}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="flex items-center gap-0.5">
|
||||
<ToolbarButton
|
||||
onClick={handleCopy}
|
||||
label={copied ? '✓' : t('home.copy')}
|
||||
icon={copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
onClick={() => void handleCopy()}
|
||||
label={t('home.copy')}
|
||||
visibleLabel={copied ? t('home.copied') : t('home.copy')}
|
||||
icon={
|
||||
copied ? (
|
||||
<Check className="text-success motion-safe:animate-pop h-3.5 w-3.5" />
|
||||
) : (
|
||||
<Copy className="h-3.5 w-3.5 transition-transform motion-safe:group-hover:-translate-y-px" />
|
||||
)
|
||||
}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<ToolbarButton
|
||||
onClick={handleDownload}
|
||||
onClick={() => void handleDownload()}
|
||||
label={t('home.download')}
|
||||
icon={<Download className="h-3.5 w-3.5" />}
|
||||
icon={<Download className="motion-safe:group-hover:animate-bob h-3.5 w-3.5" />}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="scrollbar-hide relative flex-1 overflow-auto">
|
||||
<div className="relative min-h-0 flex-1">
|
||||
{error ? (
|
||||
<div className="text-destructive p-4 font-mono text-sm whitespace-pre-wrap">{error}</div>
|
||||
<div
|
||||
role="alert"
|
||||
tabIndex={0} // NOSONAR(S6845): scrollable region; keyboard users need focus to scroll it
|
||||
className="text-destructive h-full overflow-auto p-4 font-mono text-sm whitespace-pre-wrap"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
) : content ? (
|
||||
<pre className="p-4 font-mono text-sm leading-relaxed break-words whitespace-pre-wrap">
|
||||
{content}
|
||||
</pre>
|
||||
<CodeEditorLazy
|
||||
value={content}
|
||||
readOnly
|
||||
language={outputLanguageFor(format, direction)}
|
||||
ariaLabel={t('home.output_aria', { format: formatLabel })}
|
||||
/>
|
||||
) : (
|
||||
<div className="text-muted-foreground/60 p-4 text-sm italic">
|
||||
<div className="text-muted-foreground p-4 text-sm">
|
||||
{isReverse
|
||||
? t('home.output_empty_format', {
|
||||
ext: converter.meta.extension.toUpperCase(),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { RotateCcw, Settings2 } from 'lucide-react';
|
||||
import {
|
||||
@@ -47,18 +48,23 @@ export function SettingsPanel({
|
||||
<SheetTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground hover:bg-muted hover:text-foreground border-border/60 inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition"
|
||||
aria-label={t('home.options')}
|
||||
className="group text-muted-foreground hover:bg-muted hover:text-foreground border-border bg-card/60 inline-flex min-h-8 items-center gap-1.5 rounded-md border px-2.5 text-xs transition"
|
||||
>
|
||||
<Settings2 className="h-3.5 w-3.5" />
|
||||
<Settings2
|
||||
className="h-3.5 w-3.5 transition-transform duration-500 motion-safe:group-hover:rotate-90"
|
||||
aria-hidden
|
||||
/>
|
||||
<span>{t('home.options')}</span>
|
||||
</button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-md">
|
||||
<SheetContent
|
||||
closeLabel={t('common.close')}
|
||||
className="flex w-full flex-col gap-0 p-0 sm:max-w-md"
|
||||
>
|
||||
<SheetHeader>
|
||||
<SheetTitle>
|
||||
<span className="text-spectrum italic">{formatLabel}</span>{' '}
|
||||
<span className="text-muted-foreground font-sans text-base font-normal not-italic">
|
||||
<span className="text-spectrum">{formatLabel}</span>{' '}
|
||||
<span className="text-muted-foreground text-base font-normal">
|
||||
· {t('settings.title')}
|
||||
</span>
|
||||
</SheetTitle>
|
||||
@@ -67,12 +73,12 @@ export function SettingsPanel({
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-6 pb-6">
|
||||
<div className="flex-1 [scrollbar-gutter:stable] overflow-y-auto px-6 pb-6">
|
||||
{hasFields ? (
|
||||
<div className="flex flex-col gap-5">
|
||||
{schema.map((field) => (
|
||||
<FieldRenderer
|
||||
key={field.key}
|
||||
key={`${format}:${field.key}`}
|
||||
field={field}
|
||||
value={options[field.key]}
|
||||
onChange={(v) => setField(field.key, v)}
|
||||
@@ -80,20 +86,23 @@ export function SettingsPanel({
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground py-12 text-center text-sm italic">
|
||||
<p className="text-muted-foreground py-12 text-center text-sm">
|
||||
{t('settings.no_options_long')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{hasFields && (
|
||||
<div className="border-border/60 flex items-center justify-end gap-2 border-t px-6 py-3">
|
||||
<div className="border-border/70 flex items-center justify-end gap-2 border-t px-6 py-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onReset}
|
||||
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs transition"
|
||||
className="group text-muted-foreground hover:bg-muted hover:text-foreground inline-flex min-h-8 items-center gap-1.5 rounded-md px-3 text-xs transition"
|
||||
>
|
||||
<RotateCcw className="h-3.5 w-3.5" />
|
||||
<RotateCcw
|
||||
className="h-3.5 w-3.5 transition-transform duration-500 motion-safe:group-hover:-rotate-180"
|
||||
aria-hidden
|
||||
/>
|
||||
{t('settings.reset')}
|
||||
</button>
|
||||
</div>
|
||||
@@ -111,23 +120,18 @@ interface FieldRendererProps {
|
||||
|
||||
function FieldRenderer({ field, value, onChange }: FieldRendererProps) {
|
||||
const { t } = useTranslation();
|
||||
const id = `field-${field.key}`;
|
||||
const descriptionId = field.descriptionKey ? `${id}-desc` : undefined;
|
||||
const description = field.descriptionKey && (
|
||||
<p id={descriptionId} className="text-muted-foreground text-xs">
|
||||
{t(field.descriptionKey)}
|
||||
</p>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className="text-sm font-medium" htmlFor={`field-${field.key}`}>
|
||||
{t(field.labelKey)}
|
||||
</label>
|
||||
{field.type === 'boolean' && (
|
||||
<Switch
|
||||
id={`field-${field.key}`}
|
||||
checked={Boolean(value)}
|
||||
onCheckedChange={(v) => onChange(v)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{field.type === 'enum' && (
|
||||
if (field.type === 'enum') {
|
||||
return (
|
||||
<fieldset className="flex flex-col gap-1.5" aria-describedby={descriptionId}>
|
||||
<legend className="mb-1.5 text-sm font-medium">{t(field.labelKey)}</legend>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{field.choices.map((choice) => {
|
||||
const active = String(value) === choice.value;
|
||||
@@ -135,12 +139,13 @@ function FieldRenderer({ field, value, onChange }: FieldRendererProps) {
|
||||
<button
|
||||
key={choice.value}
|
||||
type="button"
|
||||
aria-pressed={active}
|
||||
onClick={() => onChange(choice.value)}
|
||||
className={cn(
|
||||
'rounded-md border px-2.5 py-1 text-xs font-medium transition',
|
||||
'min-h-8 rounded-md border px-2.5 text-xs font-medium transition',
|
||||
active
|
||||
? 'border-primary/60 bg-primary/10 text-foreground'
|
||||
: 'border-border bg-card/40 text-muted-foreground hover:text-foreground',
|
||||
: 'border-border bg-card/60 text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{t(choice.labelKey)}
|
||||
@@ -148,37 +153,97 @@ function FieldRenderer({ field, value, onChange }: FieldRendererProps) {
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{description}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className="text-sm font-medium" htmlFor={id}>
|
||||
{t(field.labelKey)}
|
||||
</label>
|
||||
{field.type === 'boolean' && (
|
||||
<Switch
|
||||
id={id}
|
||||
checked={Boolean(value)}
|
||||
onCheckedChange={(v) => onChange(v)}
|
||||
aria-describedby={descriptionId}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{field.type === 'integer' && (
|
||||
<input
|
||||
id={`field-${field.key}`}
|
||||
type="number"
|
||||
value={Number(value)}
|
||||
<IntegerInput
|
||||
id={id}
|
||||
value={typeof value === 'number' ? value : (field.min ?? 0)}
|
||||
min={field.min}
|
||||
max={field.max}
|
||||
onChange={(e) => {
|
||||
const n = Number(e.target.value);
|
||||
if (Number.isFinite(n)) onChange(n);
|
||||
}}
|
||||
className="border-border bg-background focus:ring-ring rounded-md border px-3 py-1.5 font-mono text-sm focus:ring-2 focus:outline-none"
|
||||
describedBy={descriptionId}
|
||||
onCommit={onChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
{field.type === 'string' && (
|
||||
<input
|
||||
id={`field-${field.key}`}
|
||||
id={id}
|
||||
type="text"
|
||||
value={String(value ?? '')}
|
||||
placeholder={field.placeholder}
|
||||
aria-describedby={descriptionId}
|
||||
maxLength={200}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="border-border bg-background focus:ring-ring rounded-md border px-3 py-1.5 font-mono text-sm focus:ring-2 focus:outline-none"
|
||||
/>
|
||||
)}
|
||||
|
||||
{field.descriptionKey && (
|
||||
<p className="text-muted-foreground text-xs">{t(field.descriptionKey)}</p>
|
||||
)}
|
||||
{description}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface IntegerInputProps {
|
||||
id: string;
|
||||
value: number;
|
||||
min: number | undefined;
|
||||
max: number | undefined;
|
||||
describedBy: string | undefined;
|
||||
onCommit: (v: number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the raw text while typing (so "", "-" or "1" on the way to "10" are
|
||||
* allowed) and commits a clamped integer when the text parses or on blur.
|
||||
*/
|
||||
function IntegerInput({ id, value, min, max, describedBy, onCommit }: IntegerInputProps) {
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
const clamp = (n: number) => Math.min(max ?? Infinity, Math.max(min ?? -Infinity, Math.trunc(n)));
|
||||
|
||||
return (
|
||||
<input
|
||||
id={id}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
value={draft ?? String(value)}
|
||||
min={min}
|
||||
max={max}
|
||||
step={1}
|
||||
aria-describedby={describedBy}
|
||||
onChange={(e) => {
|
||||
const text = e.target.value;
|
||||
setDraft(text);
|
||||
const n = Number(text);
|
||||
if (text.trim() !== '' && Number.isFinite(n) && clamp(n) === n) onCommit(n);
|
||||
}}
|
||||
onBlur={() => {
|
||||
if (draft !== null) {
|
||||
const n = Number(draft);
|
||||
if (draft.trim() !== '' && Number.isFinite(n)) onCommit(clamp(n));
|
||||
setDraft(null);
|
||||
}
|
||||
}}
|
||||
className="border-border bg-background focus:ring-ring rounded-md border px-3 py-1.5 font-mono text-sm focus:ring-2 focus:outline-none"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -11,10 +11,9 @@ export function ShapeHint({ shape }: ShapeHintProps) {
|
||||
if (!shape || shape === 'unknown') return null;
|
||||
|
||||
return (
|
||||
<div className="text-muted-foreground inline-flex items-center gap-1.5 font-mono text-xs">
|
||||
<Sparkles className="text-primary h-3 w-3" />
|
||||
<span>{t('shape.detected')}:</span>
|
||||
<span className="text-foreground">{t(`shape.${shape}`)}</span>
|
||||
<div className="text-muted-foreground hidden items-center gap-1.5 font-mono text-xs lg:inline-flex">
|
||||
<Sparkles className="text-primary motion-safe:animate-pop h-3.5 w-3.5" aria-hidden />
|
||||
<span>{t('shape.detected_value', { shape: t(`shape.${shape}`) })}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +1,57 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { TriangleAlert } from 'lucide-react';
|
||||
import { modKey } from '@/hooks/useKeyboardShortcuts';
|
||||
import { formatBytes } from '@/lib/format-bytes';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type ConversionState = 'idle' | 'working' | 'ok' | 'error';
|
||||
|
||||
interface StatusBarProps {
|
||||
state: ConversionState;
|
||||
inputBytes: number;
|
||||
outputBytes: number;
|
||||
parseMs: number | null;
|
||||
ms: number | null;
|
||||
precisionLoss: boolean;
|
||||
}
|
||||
|
||||
export function StatusBar({ inputBytes, outputBytes, parseMs }: StatusBarProps) {
|
||||
const DOT_TONE: Record<ConversionState, string> = {
|
||||
idle: 'bg-muted-foreground/50',
|
||||
working: 'bg-warning motion-safe:animate-pulse-dot',
|
||||
ok: 'bg-success',
|
||||
error: 'bg-destructive',
|
||||
};
|
||||
|
||||
/** Terminal-style footer: state light, bytes in → out, timing, encoding, shortcuts. */
|
||||
export function StatusBar({ state, inputBytes, outputBytes, ms, precisionLoss }: StatusBarProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="text-muted-foreground border-border/60 flex items-center justify-between border-t px-3 py-1.5 font-mono text-[11px]">
|
||||
<div className="flex gap-3">
|
||||
<Stat label={t('status.in')} value={formatBytes(inputBytes)} />
|
||||
<Stat label={t('status.out')} value={formatBytes(outputBytes)} />
|
||||
{parseMs !== null && <Stat label={t('status.time')} value={`${parseMs.toFixed(1)}ms`} />}
|
||||
<div className="border-border/70 text-muted-foreground flex items-center justify-between gap-3 border-t px-3 py-1 font-mono text-[11px]">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-0.5" aria-live="polite">
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<span aria-hidden className={cn('h-1.5 w-1.5 rounded-full', DOT_TONE[state])} />
|
||||
<span className="text-foreground">{t(`status.state.${state}`)}</span>
|
||||
</span>
|
||||
<span>
|
||||
{t('status.in')} <span className="text-foreground">{formatBytes(inputBytes)}</span>
|
||||
</span>
|
||||
<span aria-hidden>→</span>
|
||||
<span>
|
||||
{t('status.out')} <span className="text-foreground">{formatBytes(outputBytes)}</span>
|
||||
</span>
|
||||
{ms !== null && <span>{t('status.time_value', { ms: ms.toFixed(1) })}</span>}
|
||||
{precisionLoss && (
|
||||
<span
|
||||
className="text-warning inline-flex items-center gap-1"
|
||||
title={t('status.precision_hint')}
|
||||
>
|
||||
<TriangleAlert className="h-3 w-3" aria-hidden />
|
||||
{t('status.precision')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="hidden gap-3 md:flex">
|
||||
<Shortcut keys={`${modKey()}+K`} label={t('shortcut.clear')} />
|
||||
<div className="hidden shrink-0 items-center gap-3 md:flex">
|
||||
<span>UTF-8</span>
|
||||
<Shortcut keys={`${modKey()}+S`} label={t('shortcut.download')} />
|
||||
<Shortcut keys={`${modKey()}+,`} label={t('shortcut.settings')} />
|
||||
</div>
|
||||
@@ -26,29 +59,11 @@ export function StatusBar({ inputBytes, outputBytes, parseMs }: StatusBarProps)
|
||||
);
|
||||
}
|
||||
|
||||
function Stat({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span className="opacity-60">{label}:</span>
|
||||
<span className="text-foreground/80">{value}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Shortcut({ keys, label }: { keys: string; label: string }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<kbd className="border-border bg-muted/40 text-foreground/80 rounded border px-1 py-0 text-[10px] leading-none">
|
||||
{keys}
|
||||
</kbd>
|
||||
<span className="opacity-60">{label}</span>
|
||||
<kbd className="kbd">{keys}</kbd>
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return '0 B';
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import '@/i18n';
|
||||
import { useBatchStore, type BatchItem } from '@/stores/batchStore';
|
||||
import { BatchItemRow } from '../BatchItemRow';
|
||||
|
||||
function queue(name: string, bytes: number): string {
|
||||
useBatchStore.getState().addFiles([new File(['x'.repeat(bytes)], name)]);
|
||||
const { itemOrder } = useBatchStore.getState();
|
||||
return itemOrder[itemOrder.length - 1]!;
|
||||
}
|
||||
|
||||
function update(id: string, patch: Partial<BatchItem>): void {
|
||||
act(() => useBatchStore.getState().updateItem(id, patch));
|
||||
}
|
||||
|
||||
function renderRow(id: string, { disabled = false, outputExt = 'csv' } = {}) {
|
||||
const onRemove = vi.fn<(id: string) => void>();
|
||||
const view = render(
|
||||
<ul>
|
||||
<BatchItemRow id={id} outputExt={outputExt} onRemove={onRemove} disabled={disabled} />
|
||||
</ul>,
|
||||
);
|
||||
return { ...view, onRemove };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useBatchStore.getState().clear();
|
||||
});
|
||||
|
||||
describe('BatchItemRow', () => {
|
||||
it('renders nothing for an id that is not in the queue', () => {
|
||||
const { container } = renderRow('missing');
|
||||
expect(container.querySelector('li')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows a queued file with its size and target extension', () => {
|
||||
const id = queue('data.json', 2048);
|
||||
renderRow(id);
|
||||
|
||||
expect(screen.getByText('data.json')).toBeInTheDocument();
|
||||
expect(screen.getByText('→ .csv')).toBeInTheDocument();
|
||||
expect(screen.getByText('2.0 KB')).toBeInTheDocument();
|
||||
expect(screen.getByText('queued')).toHaveClass('sr-only');
|
||||
expect(screen.queryByText(/^out:/)).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Remove data.json from queue' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('shows a spinner while the file is processing', () => {
|
||||
const id = queue('data.json', 10);
|
||||
const { container } = renderRow(id);
|
||||
|
||||
update(id, { status: 'processing' });
|
||||
|
||||
expect(screen.getByText('processing')).toHaveClass('sr-only');
|
||||
expect(container.querySelector('svg.motion-safe\\:animate-spin')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('shows the output size once the file is converted', () => {
|
||||
const id = queue('data.json', 10);
|
||||
renderRow(id);
|
||||
|
||||
update(id, { status: 'done', output: 'a,b\n', outputSize: 1536 });
|
||||
|
||||
expect(screen.getByText('done')).toHaveClass('sr-only');
|
||||
expect(screen.getByText('out: 1.5 KB')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('translates known error codes', () => {
|
||||
const id = queue('empty.json', 0);
|
||||
renderRow(id);
|
||||
|
||||
update(id, { status: 'error', error: 'Empty file.', errorCode: 'empty_file' });
|
||||
|
||||
expect(screen.getByText('failed')).toHaveClass('sr-only');
|
||||
expect(screen.getByText('The file is empty.')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Empty file.')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the converter's own message for other errors", () => {
|
||||
const id = queue('broken.json', 5);
|
||||
renderRow(id);
|
||||
|
||||
update(id, { status: 'error', error: 'Unexpected end of JSON input' });
|
||||
|
||||
expect(screen.getByText('Unexpected end of JSON input')).toHaveClass('text-destructive');
|
||||
});
|
||||
|
||||
it('removes the row through onRemove', async () => {
|
||||
const id = queue('data.json', 10);
|
||||
const { onRemove } = renderRow(id);
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Remove data.json from queue' }));
|
||||
|
||||
expect(onRemove).toHaveBeenCalledWith(id);
|
||||
});
|
||||
|
||||
it('cannot be removed while the batch is processing', async () => {
|
||||
const id = queue('data.json', 10);
|
||||
const { onRemove } = renderRow(id, { disabled: true });
|
||||
|
||||
const remove = screen.getByRole('button', { name: 'Remove data.json from queue' });
|
||||
expect(remove).toBeDisabled();
|
||||
await userEvent.click(remove);
|
||||
expect(onRemove).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disappears when its item leaves the queue', () => {
|
||||
const id = queue('data.json', 10);
|
||||
const { container } = renderRow(id, { outputExt: 'json' });
|
||||
expect(screen.getByText('→ .json')).toBeInTheDocument();
|
||||
|
||||
act(() => useBatchStore.getState().removeItem(id));
|
||||
|
||||
expect(container.querySelector('li')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,465 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent, { type UserEvent } from '@testing-library/user-event';
|
||||
import { clearMocks, mockIPC } from '@tauri-apps/api/mocks';
|
||||
import '@/i18n';
|
||||
import { toast } from '@/components/ui/sonner';
|
||||
import type { Direction, FormatId } from '@/converters/types';
|
||||
import { pathHashAsMillis } from '@/lib/tauri';
|
||||
import { BATCH_MAX_FILES, useBatchStore } from '@/stores/batchStore';
|
||||
import { BatchPanel } from '../BatchPanel';
|
||||
|
||||
function jsonFile(name: string, content = '[{"id":1}]'): File {
|
||||
return new File([content], name, { type: 'application/json', lastModified: 1_700_000_000_000 });
|
||||
}
|
||||
|
||||
/** Queues files directly through the store; returns their ids. */
|
||||
function seed(...files: File[]): string[] {
|
||||
const before = useBatchStore.getState().itemOrder.length;
|
||||
act(() => {
|
||||
useBatchStore.getState().addFiles(files);
|
||||
});
|
||||
return useBatchStore.getState().itemOrder.slice(before);
|
||||
}
|
||||
|
||||
function queuedNames(): string[] {
|
||||
const { items, itemOrder } = useBatchStore.getState();
|
||||
return itemOrder.map((id) => items[id]?.filename ?? '?');
|
||||
}
|
||||
|
||||
function renderPanel({
|
||||
format = 'jsonl' as FormatId,
|
||||
direction = 'forward' as Direction,
|
||||
open = true,
|
||||
}: { format?: FormatId; direction?: Direction; open?: boolean } = {}) {
|
||||
const onOpenChange = vi.fn<(open: boolean) => void>();
|
||||
const view = render(
|
||||
<BatchPanel
|
||||
format={format}
|
||||
direction={direction}
|
||||
options={{ pretty: false }}
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
/>,
|
||||
);
|
||||
return { ...view, onOpenChange };
|
||||
}
|
||||
|
||||
/** The hidden `<input type="file">` the browse button forwards to. */
|
||||
function browseInput(): HTMLInputElement {
|
||||
const input = document.querySelector<HTMLInputElement>('input[type="file"].hidden');
|
||||
if (!input) throw new Error('browse input not rendered');
|
||||
return input;
|
||||
}
|
||||
|
||||
function dropZone(): HTMLElement {
|
||||
const zone = browseInput().parentElement;
|
||||
if (!zone) throw new Error('drop zone not rendered');
|
||||
return zone;
|
||||
}
|
||||
|
||||
/** A drag event payload as react-dropzone reads it (jsdom has no DataTransfer). */
|
||||
function withFiles(files: File[]) {
|
||||
return {
|
||||
dataTransfer: {
|
||||
files,
|
||||
items: files.map((file) => ({ kind: 'file', type: file.type, getAsFile: () => file })),
|
||||
types: ['Files'],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function chip(label: string): HTMLElement {
|
||||
return within(screen.getByRole('status')).getByText(label).parentElement!;
|
||||
}
|
||||
|
||||
const button = (name: string | RegExp) => screen.getByRole('button', { name });
|
||||
|
||||
let user: UserEvent;
|
||||
|
||||
beforeEach(() => {
|
||||
// No artificial delays between pointer steps; `accept` is only a hint, so
|
||||
// uploads reach the component's own extension filter.
|
||||
user = userEvent.setup({ delay: null, applyAccept: false });
|
||||
useBatchStore.getState().clear();
|
||||
vi.spyOn(toast, 'success').mockImplementation(() => 0);
|
||||
vi.spyOn(toast, 'warning').mockImplementation(() => 0);
|
||||
vi.spyOn(toast, 'info').mockImplementation(() => 0);
|
||||
vi.spyOn(toast, 'error').mockImplementation(() => 0);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('BatchPanel trigger', () => {
|
||||
it('shows how many files are queued and asks to open the sheet', async () => {
|
||||
seed(jsonFile('a.json'), jsonFile('b.json'), jsonFile('c.json'));
|
||||
const { onOpenChange } = renderPanel({ open: false });
|
||||
|
||||
const trigger = button(/Batch/);
|
||||
expect(trigger).toHaveTextContent('Batch3');
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
|
||||
await user.click(trigger);
|
||||
expect(onOpenChange).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('shows no count while the queue is empty', () => {
|
||||
renderPanel({ open: false });
|
||||
expect(button(/Batch/)).toHaveTextContent(/^Batch$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BatchPanel sheet', () => {
|
||||
it('renders an empty queue with every action disabled', () => {
|
||||
renderPanel();
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Batch queue 0 / 500' })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Process multiple JSON files into JSONL at once. All processing happens on your device.',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('Drop JSON files here')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('No files queued yet. Drop JSON files above to begin.'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument();
|
||||
expect(button('Clear')).toBeDisabled();
|
||||
expect(button('Process')).toBeDisabled();
|
||||
expect(button('Download .zip')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('labels everything for the reverse direction', () => {
|
||||
seed(new File(['a: 1'], 'config.yaml'));
|
||||
renderPanel({ format: 'yaml', direction: 'reverse' });
|
||||
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Process multiple YAML files into JSON at once. All processing happens on your device.',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('Drop YAML files here')).toBeInTheDocument();
|
||||
expect(screen.getByText('→ .json')).toBeInTheDocument();
|
||||
expect(browseInput()).toHaveAttribute('accept', '.yaml,.yml,.txt,application/yaml');
|
||||
});
|
||||
|
||||
it('lists queued files with live summary counts', () => {
|
||||
const [, done, failed] = seed(jsonFile('a.json'), jsonFile('b.json'), jsonFile('c.json'));
|
||||
act(() => {
|
||||
useBatchStore.getState().updateItem(done!, { status: 'done', output: '{"id":1}\n' });
|
||||
useBatchStore.getState().updateItem(failed!, { status: 'error', error: 'Bad JSON' });
|
||||
});
|
||||
renderPanel();
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Batch queue 3 / 500' })).toBeInTheDocument();
|
||||
expect(chip('queued')).toHaveTextContent('queued1');
|
||||
expect(chip('done')).toHaveTextContent('done1');
|
||||
expect(chip('failed')).toHaveTextContent('failed1');
|
||||
const list = screen.getByRole('list');
|
||||
expect(within(list).getAllByRole('listitem')).toHaveLength(3);
|
||||
expect(within(list).getAllByText('→ .jsonl')).toHaveLength(3);
|
||||
expect(button('Clear')).toBeEnabled();
|
||||
expect(button('Process')).toBeEnabled();
|
||||
expect(button('Download .zip')).toBeEnabled();
|
||||
});
|
||||
|
||||
it('closes from the sheet close button', async () => {
|
||||
const { onOpenChange } = renderPanel();
|
||||
|
||||
await user.click(button('Close'));
|
||||
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BatchPanel adding files (web)', () => {
|
||||
it('forwards the browse button to the hidden file input', async () => {
|
||||
renderPanel();
|
||||
const click = vi.spyOn(browseInput(), 'click').mockImplementation(() => {});
|
||||
|
||||
await user.click(button('or click to browse…'));
|
||||
|
||||
expect(click).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('queues picked files, skipping the wrong format, and resets the input', async () => {
|
||||
renderPanel();
|
||||
const input = browseInput();
|
||||
|
||||
await user.upload(input, [jsonFile('a.json'), new File(['x,y'], 'table.csv')]);
|
||||
|
||||
expect(queuedNames()).toEqual(['a.json']);
|
||||
expect(toast.success).toHaveBeenCalledWith('Added 1 file to the queue');
|
||||
expect(toast.warning).toHaveBeenCalledWith('Skipped 1 file (wrong format)');
|
||||
expect(input.value).toBe('');
|
||||
expect(screen.getByRole('dialog', { name: 'Batch queue 1 / 500' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('ignores an empty selection', () => {
|
||||
renderPanel();
|
||||
|
||||
fireEvent.change(browseInput(), { target: { files: [] } });
|
||||
|
||||
expect(queuedNames()).toEqual([]);
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
expect(toast.warning).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('adds nothing when every picked file has the wrong format', async () => {
|
||||
renderPanel();
|
||||
|
||||
await user.upload(browseInput(), [new File(['x,y'], 'table.csv')]);
|
||||
|
||||
expect(queuedNames()).toEqual([]);
|
||||
expect(toast.warning).toHaveBeenCalledWith('Skipped 1 file (wrong format)');
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports duplicates', async () => {
|
||||
const data = jsonFile('data.json');
|
||||
seed(data);
|
||||
renderPanel();
|
||||
|
||||
await user.upload(browseInput(), [data]);
|
||||
|
||||
expect(queuedNames()).toEqual(['data.json']);
|
||||
expect(toast.warning).toHaveBeenCalledWith('Skipped 1 duplicate file');
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports files beyond the queue limit', async () => {
|
||||
seed(...Array.from({ length: BATCH_MAX_FILES - 1 }, (_, i) => jsonFile(`f${i}.json`)));
|
||||
renderPanel();
|
||||
|
||||
await user.upload(browseInput(), [jsonFile('x.json'), jsonFile('y.json')]);
|
||||
|
||||
expect(useBatchStore.getState().itemOrder).toHaveLength(BATCH_MAX_FILES);
|
||||
expect(toast.success).toHaveBeenCalledWith('Added 1 file to the queue');
|
||||
expect(toast.warning).toHaveBeenCalledWith('Skipped 1 file (limit: 500)');
|
||||
});
|
||||
|
||||
it('highlights the drop zone while dragging and queues dropped files', async () => {
|
||||
renderPanel();
|
||||
const file = jsonFile('dropped.json');
|
||||
|
||||
fireEvent.dragEnter(dropZone(), withFiles([file]));
|
||||
expect(await screen.findByText('Release to add files')).toBeInTheDocument();
|
||||
|
||||
fireEvent.drop(dropZone(), withFiles([file]));
|
||||
|
||||
await waitFor(() => expect(queuedNames()).toEqual(['dropped.json']));
|
||||
expect(toast.success).toHaveBeenCalledWith('Added 1 file to the queue');
|
||||
expect(screen.getByText('Drop JSON files here')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('warns when the drop contains files of another type', async () => {
|
||||
renderPanel();
|
||||
|
||||
fireEvent.drop(dropZone(), withFiles([new File(['x,y'], 'table.csv', { type: 'text/csv' })]));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(toast.warning).toHaveBeenCalledWith('Skipped 1 file (wrong format)'),
|
||||
);
|
||||
expect(queuedNames()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BatchPanel queue actions', () => {
|
||||
it('processes the queue and offers the outputs as a zip', async () => {
|
||||
const createObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:batch');
|
||||
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
|
||||
const downloads: string[] = [];
|
||||
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (
|
||||
this: HTMLAnchorElement,
|
||||
) {
|
||||
downloads.push(this.download);
|
||||
});
|
||||
seed(jsonFile('one.json', '[{"a":1}]'), jsonFile('two.json', '[{"b":2},{"c":3}]'));
|
||||
renderPanel();
|
||||
|
||||
await user.click(button('Process'));
|
||||
|
||||
await waitFor(() => expect(chip('done')).toHaveTextContent('done2'));
|
||||
expect(chip('queued')).toHaveTextContent('queued0');
|
||||
expect(screen.getByText('out: 8 B')).toBeInTheDocument();
|
||||
expect(screen.getByText('out: 16 B')).toBeInTheDocument();
|
||||
await waitFor(() => expect(button('Process')).toBeEnabled());
|
||||
|
||||
await user.click(button('Download .zip'));
|
||||
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Packed 2 files into a .zip'));
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(1);
|
||||
expect(downloads).toHaveLength(1);
|
||||
expect(downloads[0]).toMatch(/^jsonprism-batch-\d{4}-\d{2}-\d{2}\.zip$/);
|
||||
});
|
||||
|
||||
it('swaps Process for Cancel while a batch runs', async () => {
|
||||
const [running] = seed(jsonFile('a.json'), jsonFile('b.json'));
|
||||
const controller = new AbortController();
|
||||
act(() => {
|
||||
useBatchStore.getState().setAbortController(controller);
|
||||
useBatchStore.getState().setProcessing(true);
|
||||
useBatchStore.getState().updateItem(running!, { status: 'processing' });
|
||||
});
|
||||
renderPanel();
|
||||
|
||||
// The row being converted is neither queued, done nor failed.
|
||||
expect(chip('queued')).toHaveTextContent('queued1');
|
||||
expect(chip('done')).toHaveTextContent('done0');
|
||||
expect(screen.queryByRole('button', { name: 'Process' })).not.toBeInTheDocument();
|
||||
expect(button('Clear')).toBeDisabled();
|
||||
expect(button('Download .zip')).toBeDisabled();
|
||||
expect(button('Remove a.json from queue')).toBeDisabled();
|
||||
|
||||
await user.click(button('Cancel'));
|
||||
|
||||
expect(controller.signal.aborted).toBe(true);
|
||||
expect(toast.info).toHaveBeenCalledWith('Batch cancelled');
|
||||
});
|
||||
|
||||
it('removes single rows and clears the queue', async () => {
|
||||
seed(jsonFile('a.json'), jsonFile('b.json'));
|
||||
renderPanel();
|
||||
|
||||
await user.click(button('Remove a.json from queue'));
|
||||
expect(queuedNames()).toEqual(['b.json']);
|
||||
expect(screen.queryByText('a.json')).not.toBeInTheDocument();
|
||||
|
||||
await user.click(button('Clear'));
|
||||
expect(queuedNames()).toEqual([]);
|
||||
expect(
|
||||
screen.getByText('No files queued yet. Drop JSON files above to begin.'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('aborts a running batch when its queue empties', () => {
|
||||
const [only] = seed(jsonFile('a.json'));
|
||||
const controller = new AbortController();
|
||||
act(() => {
|
||||
useBatchStore.getState().setAbortController(controller);
|
||||
useBatchStore.getState().setProcessing(true);
|
||||
});
|
||||
renderPanel();
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
|
||||
act(() => useBatchStore.getState().removeItem(only!));
|
||||
|
||||
expect(controller.signal.aborted).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BatchPanel native picker (Tauri)', () => {
|
||||
const ANDROID_URI = 'content://com.android.providers.media.documents/document/msf%3A1000000123';
|
||||
let ipc: [string, Record<string, unknown>][];
|
||||
let picked: string[] | null;
|
||||
let unreadable: string | null;
|
||||
|
||||
beforeEach(() => {
|
||||
ipc = [];
|
||||
picked = ['/home/me/a.json', ANDROID_URI];
|
||||
unreadable = null;
|
||||
// fileFromNativePath logs the stat() fallback at debug level.
|
||||
vi.spyOn(console, 'debug').mockImplementation(() => {});
|
||||
vi.stubGlobal('__IS_TAURI_BUILD__', true);
|
||||
mockIPC((cmd, payload) => {
|
||||
const args = (payload ?? {}) as Record<string, unknown>;
|
||||
ipc.push([cmd, args]);
|
||||
switch (cmd) {
|
||||
case 'plugin:dialog|open':
|
||||
return picked;
|
||||
case 'plugin:fs|read_text_file':
|
||||
if (args['path'] === unreadable) throw new Error('permission denied');
|
||||
return Array.from(new TextEncoder().encode('[{"id":1}]'));
|
||||
case 'plugin:fs|stat':
|
||||
// stat() on Android content URIs is unreliable.
|
||||
if (String(args['path']).startsWith('content://')) throw new Error('unsupported');
|
||||
return { mtime: 1_700_000_000_000 };
|
||||
default:
|
||||
throw new Error(`Unexpected IPC command ${cmd}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
clearMocks();
|
||||
Reflect.deleteProperty(window, '__TAURI_INTERNALS__');
|
||||
Reflect.deleteProperty(window, '__TAURI_EVENT_PLUGIN_INTERNALS__');
|
||||
});
|
||||
|
||||
const dialogOptions = () => ipc.find(([cmd]) => cmd === 'plugin:dialog|open')?.[1]['options'];
|
||||
|
||||
it('queues files chosen in the native dialog, keeping extension-less Android picks', async () => {
|
||||
renderPanel();
|
||||
const webPicker = vi.spyOn(browseInput(), 'click');
|
||||
|
||||
await user.click(button('or click to browse…'));
|
||||
|
||||
await waitFor(() => expect(queuedNames()).toEqual(['a.json', '1000000123']));
|
||||
const { items, itemOrder } = useBatchStore.getState();
|
||||
// Real mtime where stat() works, a stable path hash where it does not.
|
||||
expect(itemOrder.map((id) => items[id]!.file.lastModified)).toEqual([
|
||||
1_700_000_000_000,
|
||||
pathHashAsMillis(ANDROID_URI),
|
||||
]);
|
||||
expect(webPicker).not.toHaveBeenCalled();
|
||||
expect(dialogOptions()).toEqual({
|
||||
multiple: true,
|
||||
filters: [
|
||||
{ name: 'JSON', extensions: ['json'] },
|
||||
{ name: 'Text', extensions: ['txt'] },
|
||||
],
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith('Added 2 files to the queue');
|
||||
expect(toast.warning).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('offers the source format in reverse mode and does nothing on cancel', async () => {
|
||||
picked = null;
|
||||
renderPanel({ format: 'yaml', direction: 'reverse' });
|
||||
|
||||
await user.click(button('or click to browse…'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(dialogOptions()).toEqual({
|
||||
multiple: true,
|
||||
filters: [
|
||||
{ name: 'YAML', extensions: ['yaml', 'yml'] },
|
||||
{ name: 'Text', extensions: ['txt'] },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(ipc.map(([cmd]) => cmd)).toEqual(['plugin:dialog|open']);
|
||||
expect(queuedNames()).toEqual([]);
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does nothing when the dialog returns no paths', async () => {
|
||||
picked = [];
|
||||
renderPanel();
|
||||
|
||||
await user.click(button('or click to browse…'));
|
||||
|
||||
await waitFor(() => expect(dialogOptions()).toBeDefined());
|
||||
expect(queuedNames()).toEqual([]);
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
expect(toast.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports files the native side cannot read', async () => {
|
||||
picked = ['/home/me/a.json'];
|
||||
unreadable = '/home/me/a.json';
|
||||
renderPanel();
|
||||
|
||||
await user.click(button('or click to browse…'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(toast.error).toHaveBeenCalledWith('Failed to load file: permission denied'),
|
||||
);
|
||||
expect(queuedNames()).toEqual([]);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 242 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user