Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3d0e8b917 | ||
|
|
b148f91635 | ||
|
|
72cb9a033d | ||
|
|
6229199137 | ||
|
|
9309fae1f6 | ||
|
|
46d1e53656 | ||
|
|
db94730fa5 |
No files matched your search
@@ -28,37 +28,60 @@ jobs:
|
||||
timeout-minutes: 20
|
||||
permissions: {}
|
||||
steps:
|
||||
# A new deploy reaches Cloudflare's edge locations over a minute or so;
|
||||
# until then some requests still hit the previous version. Wait until the
|
||||
# commit has been served several times in a row.
|
||||
- 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
|
||||
streak=0
|
||||
for attempt in $(seq 1 90); 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
|
||||
streak=$((streak + 1))
|
||||
if [ "$streak" -ge 3 ]; then
|
||||
echo "Production serves $live"
|
||||
exit 0
|
||||
fi
|
||||
sleep 10
|
||||
continue
|
||||
fi
|
||||
streak=0
|
||||
echo "Attempt $attempt: live=${live:-unknown}, waiting for $want"
|
||||
sleep 15
|
||||
sleep 10
|
||||
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"
|
||||
set -uo pipefail
|
||||
checks() {
|
||||
local headers expected old code
|
||||
headers=$(curl -fsSI -A "$UA" "$SITE/") || { echo "home page unreachable"; return 1; }
|
||||
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" || { echo "missing header: $expected"; return 1; }
|
||||
done
|
||||
[ "$(curl -sS -A "$UA" -o /dev/null -w '%{http_code}' "$SITE/about")" = 200 ] || { echo "/about is not served by the SPA fallback"; return 1; }
|
||||
old=$(curl -sS -A "$UA" -o /dev/null -w '%{http_code} %{redirect_url}' "$SITE/jsonPrism/about")
|
||||
[ "$old" = "301 $SITE/about" ] || { echo "/jsonPrism/about gave '$old', expected a 301 to /about"; return 1; }
|
||||
[ "$(curl -fsS -A "$UA" "$SITE/api/health")" = '{"ok":true,"service":"jsonprism"}' ] || { echo "/api/health is not healthy"; return 1; }
|
||||
curl -fsS -A "$UA" "$SITE/.well-known/security.txt" | grep -q '^Contact: mailto:security@poli0981.dev' || { echo "security.txt is missing or stale"; return 1; }
|
||||
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 ] || { echo "/api/turnstile/verify answered $code to a foreign origin, expected 403"; return 1; }
|
||||
}
|
||||
# Retry briefly in case a request still lands on an edge location
|
||||
# that hasn't picked up the deploy yet.
|
||||
for attempt in 1 2 3 4; do
|
||||
if problem=$(checks); then
|
||||
echo "Production checks passed."
|
||||
exit 0
|
||||
fi
|
||||
echo "Attempt $attempt: $problem"
|
||||
sleep 20
|
||||
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."
|
||||
echo "::error::$problem"
|
||||
exit 1
|
||||
@@ -8,6 +8,37 @@ 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.1.0] — 2026-10-29
|
||||
|
||||
### Added
|
||||
|
||||
- **JSONC → JSON.** A new input-only format for JSON with comments, such as `tsconfig.json`, VS Code `settings.json`, `.code-workspace` and `deno.jsonc` files. Pick **JSONC** in the **→ JSON** direction, paste or drop `.jsonc` and `.json` files (batches included), and get standard JSON back: `//` and `/* */` comments and trailing commas are removed. Values are copied token by token rather than through JavaScript numbers, so integers beyond 2^53, `1.0`, `1e3`, duplicate keys and `__proto__` come out exactly as written. Output layout: 2 spaces (default), 4 spaces, tab or minified. The parser is hand-written and runs on your device; there is no new dependency.
|
||||
- **"This looks like JSONC" hint.** In the JSON → direction, when the input fails only because of comments or trailing commas, the input panel offers **Convert JSONC → JSON**, which switches the direction and format in one click.
|
||||
- The JSONC input editor highlights comments and marks errors in the gutter at the same line and column the converter reports.
|
||||
|
||||
### Changed
|
||||
|
||||
- Converting back to JSON can now report the line and column of an error. JSONC uses it, so its errors show `Ln …, Col …` like JSON input errors do.
|
||||
- The JSONC chip is disabled in the JSON → direction with an "Input only" note. Switching to JSON → while JSONC is selected moves to JSONL.
|
||||
|
||||
## [2.0.2] — 2026-10-27
|
||||
|
||||
### Added
|
||||
|
||||
- **Rate limiting for the whole website, not just the human check.** The Worker now runs first for every request except the content-hashed bundles under `/assets/` (`run_worker_first: ["/*", "!/assets/*"]`) and counts it against a per-client limit before serving it: pages and public files 120 requests a minute (`SITE_LIMITER`, about 40 page loads), every `/api/*` request 60 a minute (`API_LIMITER`), and `/api/turnstile/verify` keeps its own 30 a minute on top. Over the limit, pages get a plain-text `429 Too Many Requests` in English, Vietnamese, Japanese and Chinese, and the API gets `{"ok":false,"error":"rate_limited"}`; both carry `Retry-After: 60`. Clients are keyed on their IPv4 address or the /64 network of their IPv6 address, which is never logged. Pages are still served through the assets binding, so the security headers, the old-path redirects and the SPA fallback are unchanged. If the limiter itself fails, requests go through rather than taking the site down. Preview deployments get their own counters.
|
||||
|
||||
### Changed
|
||||
|
||||
- The Privacy Policy describes the rate limit for page requests too. Nothing new is collected, so you are not asked to accept it again.
|
||||
|
||||
## [2.0.1] — 2026-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The editor and the output panel scroll again.** The wrapper `@uiw/react-codemirror` renders around the editor had no height, so both editors grew to fit their content inside a clipped panel: long input or output could not be scrolled with the mouse, touch or keyboard. The wrapper now fills its panel. The read-only output's scroll container also takes keyboard focus, so the arrow and page keys scroll it, without making the output editable (which would open the on-screen keyboard on phones).
|
||||
- **Fewer console errors.** The content security policy now allows WebAssembly (`'wasm-unsafe-eval'`, which still forbids JavaScript `eval`) on the website and in the apps, so the bson library's small 64-bit math helper no longer logs a violation (it fell back to JavaScript before). `browsing-topics` was removed from the `Permissions-Policy` header, which Brave and Firefox reported as an unknown feature. The remaining messages come from inside Cloudflare's Turnstile frame, which has its own policy.
|
||||
- **Production smoke check.** After a deploy it now waits until the new version answers several times in a row and retries before failing, because a deploy takes a moment to reach every Cloudflare edge location.
|
||||
|
||||
## [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).
|
||||
|
||||
@@ -4,16 +4,16 @@ Guidance for Claude (and other AI assistants) working on this repository.
|
||||
|
||||
## Project context
|
||||
|
||||
**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:
|
||||
**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, plus the input-only JSONC → JSON. Conversion always runs on the user's device. It ships as:
|
||||
|
||||
- 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`;
|
||||
- a web app at <https://jsonprism.poli0981.dev>, served by the Cloudflare Worker `jsonprism` (static assets behind a tiny Worker that rate limits requests and answers `/api/*`), deployed by Cloudflare Workers Builds on every push to `main`;
|
||||
- native apps built with Tauri 2: Windows, macOS, Linux and Android (sideload APK).
|
||||
|
||||
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.
|
||||
**Current release**: 2.1.0. See [`docs/ROADMAP.md`](docs/ROADMAP.md) for what is next.
|
||||
|
||||
## Stack — exact versions matter
|
||||
|
||||
@@ -33,7 +33,7 @@ Do not propose downgrading or "modernizing" to deprecated patterns.
|
||||
|
||||
## Web platform (Cloudflare)
|
||||
|
||||
- `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`).
|
||||
- `wrangler.jsonc`: static assets from `dist/` with SPA fallback. Every request except the hashed `/assets/*` bundles runs the Worker first (`run_worker_first`): it rate limits per client (`worker/rate-limit.ts`), then passes pages to `env.ASSETS.fetch()` (which still applies `_headers`, `_redirects` and the SPA fallback) or answers `/api/*`. Bindings: `ASSETS`, `SITE_LIMITER` / `API_LIMITER` / `VERIFY_LIMITER` (rate limits; each needs a preview twin with its own `namespace_id` under `previews`), 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).
|
||||
@@ -118,7 +118,7 @@ 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`.
|
||||
2. Implement `Converter<MyFormatOptions>`, including `meta.extension` (plus `altExtensions` for aliases such as `yml`, and `binary` for byte formats). Return errors as values.
|
||||
2. Implement `Converter<MyFormatOptions>`, including `meta.extension` (plus `altExtensions` for aliases such as `yml`, `binary` for byte formats, and `inputOnly` for formats that only convert to JSON, like JSONC — their `convert()` returns an error). 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.
|
||||
|
||||
+9
-5
@@ -117,16 +117,20 @@ Cloudflare's runtime and is not bound by this rule.
|
||||
## 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
|
||||
[`wrangler.jsonc`](wrangler.jsonc). Every request except the hashed bundles
|
||||
under `/assets/` runs the Worker first: it applies a per-client rate limit,
|
||||
then serves pages from `dist/` through the `ASSETS` binding or answers
|
||||
`/api/*`. 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/index.ts` | Router: rate limit, then the `ASSETS` binding for pages or the API handlers. The entry module must only have a **default export**: workerd treats named exports as entrypoints. |
|
||||
| `worker/rate-limit.ts` | Per-client limits (`SITE_LIMITER`, `API_LIMITER`), IPv4 / IPv6-/64 keys, 429 responses |
|
||||
| `worker/env.ts` | The bindings and variables the Worker reads |
|
||||
| `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/http.ts` | JSON and plain-text responses with strict headers, structured logs |
|
||||
|
||||
Worker logs must never contain IP addresses, tokens or user content.
|
||||
|
||||
@@ -204,7 +208,7 @@ See the **"Adding a new converter — checklist"** section in [`CLAUDE.md`](CLAU
|
||||
|
||||
Briefly:
|
||||
|
||||
1. New file `src/converters/myformat.ts` implementing `Converter<TOptions>` (pure, errors as values)
|
||||
1. New file `src/converters/myformat.ts` implementing `Converter<TOptions>` (pure, errors as values; an input-only format such as JSONC sets `meta.inputOnly`)
|
||||
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)
|
||||
|
||||
+2
-1
@@ -59,7 +59,8 @@ do not depend on these services.
|
||||
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.
|
||||
to JSON at all. JSONC → JSON removes comments and trailing commas, so
|
||||
they are not kept.
|
||||
- Pin a specific JSONPrism version if you depend on its behaviour; future
|
||||
releases may change defaults.
|
||||
|
||||
|
||||
+8
-7
@@ -35,13 +35,14 @@ Privacy questions and requests: **privacy@poli0981.dev**.
|
||||
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.
|
||||
server code answers only the human-check API (`/api/turnstile/verify`) and
|
||||
a health check, and counts page and API requests against a per-client rate
|
||||
limit before serving them. It records structured events — outcome, HTTP
|
||||
status, the Cloudflare data centre code, duration, Turnstile error codes
|
||||
and refused over-limit requests — in Cloudflare Workers Logs, kept for 7
|
||||
days. These events never contain IP addresses, Turnstile tokens or anything
|
||||
you convert. The rate-limit counters are kept by Cloudflare, keyed on your
|
||||
IP address (for IPv6, its /64 network); JSONPrism does not store the key.
|
||||
|
||||
### Human check (website)
|
||||
|
||||
|
||||
@@ -20,22 +20,23 @@ JSONPrism is a refracting tool for developers. It takes a single JSON input and
|
||||
|
||||
## Target formats
|
||||
|
||||
| Format | Extension | Status | Reverse (→ JSON) |
|
||||
| ----------------- | ----------- | ------------- | ---------------- |
|
||||
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
|
||||
| CSV | `.csv` | ✅ Phase 1 | ✅ |
|
||||
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
|
||||
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
|
||||
| XML | `.xml` | ✅ Phase 2 | — |
|
||||
| TOML | `.toml` | ✅ Phase 2 | ✅ |
|
||||
| Markdown table | `.md` | ✅ Phase 2 | — |
|
||||
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
|
||||
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
|
||||
| BSON | `.bson` | ✅ Phase 4 | — |
|
||||
| CBOR | `.cbor` | ✅ Phase 4 | — |
|
||||
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
|
||||
| Format | Extension | Status | Reverse (→ JSON) |
|
||||
| ------------------ | ----------------- | --------- | ---------------- |
|
||||
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
|
||||
| JSONC (input only) | `.jsonc`, `.json` | ✅ 2.1.0 | ✅ (only) |
|
||||
| CSV | `.csv` | ✅ Phase 1 | ✅ |
|
||||
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
|
||||
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
|
||||
| XML | `.xml` | ✅ Phase 2 | — |
|
||||
| TOML | `.toml` | ✅ Phase 2 | ✅ |
|
||||
| Markdown table | `.md` | ✅ Phase 2 | — |
|
||||
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
|
||||
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
|
||||
| BSON | `.bson` | ✅ Phase 4 | — |
|
||||
| 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.
|
||||
Twelve target 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. **JSONC** (JSON with comments: `tsconfig.json`, VS Code settings) is input only: it turns `.jsonc` and `.json` files into plain JSON, dropping comments and trailing commas while keeping every value, number and key exactly as written. Paste JSONC in the JSON → direction and the app offers to switch. 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
|
||||
|
||||
@@ -70,7 +71,7 @@ Details: [`PRIVACY.md`](PRIVACY.md).
|
||||
- **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/*`)
|
||||
- **Cloudflare Workers** hosts the web app (static assets behind a small Worker that rate limits requests and serves `/api/*`)
|
||||
- **Tauri 2.12** for the desktop (Windows, macOS, Linux) and Android apps
|
||||
|
||||
## Quick start
|
||||
@@ -295,6 +296,8 @@ export const myFormatConverter: Converter<MyFormatOptions> = {
|
||||
};
|
||||
```
|
||||
|
||||
An input-only format (like JSONC) sets `meta.inputOnly: true`, implements `reverse()`, and has `convert()` return an error; the UI then disables it in the JSON → direction.
|
||||
|
||||
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.
|
||||
|
||||
+19
-16
@@ -20,22 +20,23 @@ JSONPrism là công cụ "tán sắc" cho developer. Nhận một JSON đầu v
|
||||
|
||||
## Định dạng hỗ trợ
|
||||
|
||||
| Định dạng | Phần mở rộng | Trạng thái | Đảo (→ JSON) |
|
||||
| ----------------- | ------------ | -------------- | ------------ |
|
||||
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
|
||||
| CSV | `.csv` | ✅ Phase 1 | ✅ |
|
||||
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
|
||||
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
|
||||
| XML | `.xml` | ✅ Phase 2 | — |
|
||||
| TOML | `.toml` | ✅ Phase 2 | ✅ |
|
||||
| Bảng Markdown | `.md` | ✅ Phase 2 | — |
|
||||
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
|
||||
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
|
||||
| BSON | `.bson` | ✅ Phase 4 | — |
|
||||
| CBOR | `.cbor` | ✅ Phase 4 | — |
|
||||
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
|
||||
| Định dạng | Phần mở rộng | Trạng thái | Đảo (→ JSON) |
|
||||
| ------------------- | ----------------- | ---------- | ----------------- |
|
||||
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
|
||||
| JSONC (chỉ đầu vào) | `.jsonc`, `.json` | ✅ 2.1.0 | ✅ (chỉ chiều này) |
|
||||
| CSV | `.csv` | ✅ Phase 1 | ✅ |
|
||||
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
|
||||
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
|
||||
| XML | `.xml` | ✅ Phase 2 | — |
|
||||
| TOML | `.toml` | ✅ Phase 2 | ✅ |
|
||||
| Bảng Markdown | `.md` | ✅ Phase 2 | — |
|
||||
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
|
||||
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
|
||||
| BSON | `.bson` | ✅ Phase 4 | — |
|
||||
| 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ổng cộng 12 định dạng đích. 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`. **JSONC** (JSON có comment: `tsconfig.json`, settings của VS Code) là định dạng chỉ-đầu-vào: biến file `.jsonc` và `.json` thành JSON thuần, bỏ comment và dấu phẩy thừa nhưng giữ nguyên mọi giá trị, con số và key như bạn viết. Dán JSONC ở chiều JSON → thì app sẽ gợi ý chuyển sang. 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
|
||||
|
||||
@@ -70,7 +71,7 @@ Chi tiết: [`PRIVACY.md`](PRIVACY.md).
|
||||
- **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/*`)
|
||||
- **Cloudflare Workers** host bản web (static assets phía sau một Worker nhỏ giới hạn tần suất request và phục vụ `/api/*`)
|
||||
- **Tauri 2.12** cho app desktop (Windows, macOS, Linux) và Android
|
||||
|
||||
## Bắt đầu nhanh
|
||||
@@ -295,6 +296,8 @@ export const myFormatConverter: Converter<MyFormatOptions> = {
|
||||
};
|
||||
```
|
||||
|
||||
Định dạng chỉ-đầu-vào (như JSONC) đặt `meta.inputOnly: true`, cài `reverse()`, còn `convert()` trả lỗi; UI sẽ disable nó ở chiều 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 đủ.
|
||||
|
||||
+3
-2
@@ -50,8 +50,9 @@ website's edge configuration.
|
||||
In scope:
|
||||
|
||||
- `src/` — the React app, converters and batch processor.
|
||||
- `worker/` — the Cloudflare Worker (`/api/turnstile/verify`,
|
||||
`/api/health`): origin checks, rate limiting, request validation.
|
||||
- `worker/` — the Cloudflare Worker (per-client rate limits for the whole
|
||||
site, `/api/turnstile/verify`, `/api/health`): rate limiting, origin
|
||||
checks, 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.
|
||||
|
||||
+65
-17
@@ -19,16 +19,23 @@ in [dev_env.md](dev_env.md), Tauri details in [TAURI-NOTES.md](TAURI-NOTES.md).
|
||||
|
||||
```
|
||||
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)
|
||||
├─ /assets/* → static assets from dist/ (hashed bundles, no Worker)
|
||||
└─ everything → worker/index.ts: per-client rate limit, then
|
||||
else ├─ /api/* → answered here ──► Turnstile siteverify
|
||||
└─ pages → ASSETS binding: dist/ with _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/*"]`).
|
||||
- **Worker code** runs first for every request except `/assets/*`
|
||||
(`run_worker_first: ["/*", "!/assets/*"]`). It counts the request against a
|
||||
per-client [rate limit](#rate-limiting), hands pages and public files to the
|
||||
`ASSETS` binding — which still applies `_headers`, `_redirects` and the SPA
|
||||
fallback — and answers `/api/*` itself. `/assets/*` holds the content-hashed
|
||||
bundles, most of each page load, and stays on the Worker-free path.
|
||||
Conversion never happens on the server.
|
||||
|
||||
| Route | Code | Response |
|
||||
@@ -39,8 +46,9 @@ browser ──► jsonprism.poli0981.dev (Cloudflare Worker "jsonprism")
|
||||
|
||||
- `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`.
|
||||
- Responses the Worker builds itself (API answers, 429s) set their own headers
|
||||
(`worker/http.ts`: `no-store`, `nosniff`, `default-src 'none'`); pages and
|
||||
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`).
|
||||
@@ -78,8 +86,8 @@ 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
|
||||
declares them again: separate rate-limit counters (`namespace_id` 4202, 4204,
|
||||
4206) 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
|
||||
@@ -117,7 +125,7 @@ is enabled) and reports it on the pull request.
|
||||
| --- | --- | --- |
|
||||
| `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). |
|
||||
| `SITE_LIMITER`, `API_LIMITER`, `VERIFY_LIMITER` | Bindings | `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
|
||||
@@ -196,11 +204,11 @@ Vite copies `public/` into `dist/`; Workers Static Assets applies `_headers` and
|
||||
|
||||
| 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). |
|
||||
| `Content-Security-Policy` | `default-src 'self'`; scripts from self, `static.cloudflareinsights.com` and `challenges.cloudflare.com`, plus `'wasm-unsafe-eval'` (WebAssembly only, for bson's 64-bit math helper); `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 |
|
||||
| `Permissions-Policy` | camera, microphone, geolocation, motion sensors, payment and USB disabled (`browsing-topics` was dropped in 2.0.1: Brave and Firefox log it as an unknown feature, and the site runs no ad code) |
|
||||
| `Cross-Origin-Opener-Policy` | `same-origin` |
|
||||
| `Cache-Control` | HTML `no-cache, no-transform`; `/assets/*` `public, max-age=31536000, immutable` (hashed file names) |
|
||||
|
||||
@@ -216,13 +224,50 @@ Vite copies `public/` into `dist/`; Workers Static Assets applies `_headers` and
|
||||
|
||||
## 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
|
||||
Three [Rate Limiting bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/)
|
||||
(`ratelimits` in `wrangler.jsonc`), applied in `worker/rate-limit.ts`:
|
||||
|
||||
| Binding | Counts | Limit | `namespace_id` (production / preview) |
|
||||
| --- | --- | --- | --- |
|
||||
| `SITE_LIMITER` | pages and public files: everything outside `/api/` and `/assets/` | 120 requests / 60 s | 4205 / 4206 |
|
||||
| `API_LIMITER` | every `/api/*` request | 60 requests / 60 s | 4203 / 4204 |
|
||||
| `VERIFY_LIMITER` | `/api/turnstile/verify`, on top of `API_LIMITER` | 30 requests / 60 s | 4201 / 4202 |
|
||||
|
||||
- The key is the client's IPv4 address, or the /64 network of an IPv6 address
|
||||
(one subscriber usually holds a whole /64), from `CF-Connecting-IP`. It is
|
||||
only the key; it is never logged.
|
||||
- A page load makes about three counted requests (`index.html`,
|
||||
`theme-init.js`, `favicon.svg`); the hashed bundles under `/assets/` are not
|
||||
counted. 120 per minute is about 40 page loads a minute from one address.
|
||||
- Over the limit: pages get a plain-text 429 in the four UI languages, the API
|
||||
gets a JSON 429 `{"ok":false,"error":"rate_limited"}`; both carry
|
||||
`Retry-After: 60` and `Cache-Control: no-store`. The app treats a 429 from
|
||||
the verify endpoint as "check unavailable" and lets the user continue.
|
||||
- The limits are approximate. Counts are kept per Cloudflare data centre, and
|
||||
each edge machine checks a locally cached count that syncs in the
|
||||
background. Measured on production (2026-10-27): on one keep-alive
|
||||
connection they hold almost exactly (120 pages, then 429s), but 300
|
||||
requests on fresh parallel connections in 13 s all passed, because they
|
||||
spread over many machines before the counts caught up. They throttle
|
||||
browsers, crawlers and simple scripts; a strict cap would need a Durable
|
||||
Object or a WAF rule (below).
|
||||
- If the limiter itself fails the request goes through (`ratelimit.error` in
|
||||
the logs): a broken counter must not take the site down.
|
||||
- Every request that reaches the Worker is billed as a Worker request,
|
||||
refused ones included. The limits keep floods off the API and slow scrapers;
|
||||
volumetric attacks are Cloudflare's DDoS protection's job, in front of the
|
||||
Worker. For a zone-level limit that also covers `/assets/*` and runs before
|
||||
the Worker, add a WAF rate limiting rule for the hostname in the dashboard
|
||||
(**Security → WAF → Rate limiting rules**).
|
||||
- To change a limit, edit `simple.limit` / `simple.period` (10 or 60 s) for
|
||||
production and its twin under `previews`, then deploy. Keep every
|
||||
`namespace_id` unique within the Cloudflare account.
|
||||
- To see it work locally, run `npm run preview:cf` and then
|
||||
`for i in $(seq 70); do curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8787/api/health; done | sort | uniq -c`
|
||||
— 60 × 200, then 429s for the rest of the minute. Against production, send
|
||||
the burst over one connection so it reaches one machine, e.g.
|
||||
`curl -s -w '%{http_code}\n' $(printf -- '-o /dev/null https://jsonprism.poli0981.dev/api/health %.0s' $(seq 100)) | sort | uniq -c`
|
||||
(this throttles your own address for a minute).
|
||||
|
||||
## Workers Logs
|
||||
|
||||
@@ -235,6 +280,9 @@ Vite copies `public/` into `dist/`; Workers Static Assets applies `_headers` and
|
||||
Outcomes: `verified`, `rejected`, `bad-origin`, `bad-method`,
|
||||
`bad-content-type`, `too-large`, `rate-limited`, `bad-json`, `bad-token`,
|
||||
`misconfigured`, `unavailable`.
|
||||
- Rate limiting writes `{"event":"ratelimit.exceeded","scope":"site"|"api","colo":…}`
|
||||
for each refused request, and `ratelimit.error` with a `detail` if the
|
||||
limiter binding fails.
|
||||
- Never log IPs, tokens or user content (`logEvent()` in `worker/http.ts`).
|
||||
Source maps are not uploaded (`upload_source_maps: false`).
|
||||
|
||||
|
||||
+22
-1
@@ -4,7 +4,7 @@ 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).
|
||||
**Current release: v2.1.0 (2026-10-29).** 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).
|
||||
|
||||
---
|
||||
|
||||
@@ -302,6 +302,7 @@ A platform release: a new home for the web app, a human check and analytics conf
|
||||
- [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] 2.0.2: per-client rate limits for the whole site — the Worker runs first for everything except the hashed `/assets/*` bundles; pages 120 / 60 s, API 60 / 60 s, verify 30 / 60 s; IPv6 keyed on its /64; 429 with `Retry-After`
|
||||
- [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
|
||||
@@ -352,6 +353,25 @@ JSONPrism 2.0.0 on its own domain, with the human check and analytics confined t
|
||||
|
||||
---
|
||||
|
||||
## Phase 9 — 2.1.0: JSONC → JSON ✅
|
||||
|
||||
**Status**: complete (shipped in v2.1.0, 2026-10-29)
|
||||
|
||||
The most common "this isn't valid JSON" paste — config files with comments — now converts in one step.
|
||||
|
||||
- [x] `src/converters/jsonc.ts`: hand-written, no dependency. Comments and trailing commas become spaces at the same offsets (error line/column match the input), `JSON.parse` validates, then a token-level printer lays the result out without building JS values — big integers, number spelling, duplicate and `__proto__` keys survive. Iterative, with an output-size guard for pathological nesting.
|
||||
- [x] Input-only formats: `ConverterMeta.inputOnly`; the chip is disabled in the JSON → direction, switching to JSON → falls back to JSONL, and a stored input-only format opens in → JSON.
|
||||
- [x] Reverse errors carry an optional line/column (`ConversionFailure`), shown like JSON input errors.
|
||||
- [x] JSONC input editor: legacy JSON mode for comment highlighting plus a linter that shares the converter's parser.
|
||||
- [x] JSON → input that is valid JSONC gets a one-click "Convert JSONC → JSON" hint.
|
||||
- [x] Accepts `.jsonc` and `.json` (plus `.txt`) in the single-file and batch flows; strings in all four locales.
|
||||
|
||||
### Deliverable
|
||||
|
||||
13 chips — 12 target formats plus JSONC as an input. **932 tests in 94 files.**
|
||||
|
||||
---
|
||||
|
||||
## Beyond — Ideas (no commitment)
|
||||
|
||||
### Deferred from 2.0.0
|
||||
@@ -364,6 +384,7 @@ JSONPrism 2.0.0 on its own domain, with the human check and analytics confined t
|
||||
- **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`
|
||||
- **JSONC as input for every target** — accept comments in the JSON → direction (e.g. `tsconfig.json` straight to YAML) instead of converting to JSON first; changes the strict `parseJsonInput` contract, so it needs its own design
|
||||
- **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
|
||||
|
||||
+2
-1
@@ -87,10 +87,11 @@ Widening the scope requires both a capability edit and a CSP review in
|
||||
`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'
|
||||
default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self' 'wasm-unsafe-eval'; 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'`.
|
||||
- 2.0.1 added `'wasm-unsafe-eval'` to `script-src`: bson compiles a tiny WebAssembly helper for 64-bit math (it falls back to JavaScript when blocked, but every WebView logged a CSP violation).
|
||||
- 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
|
||||
|
||||
+1
-1
@@ -56,7 +56,7 @@ npm run preview:cf # wrangler dev on http://localhost:8787 (builds
|
||||
- `.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
|
||||
`_redirects`, SPA fallback) behind the Worker (rate limits, `/api/*`). 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)
|
||||
|
||||
+3
-3
@@ -18,11 +18,11 @@
|
||||
<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."
|
||||
content="JSONPrism converts JSON to JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR and MessagePack, reads six of them back, and turns JSONC (JSON with comments) into plain 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"
|
||||
content="JSON converter, JSONC to JSON, 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/" />
|
||||
@@ -33,7 +33,7 @@
|
||||
<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."
|
||||
content="A refracting tool for developers: one JSON input, twelve target formats, six of them reversible, plus JSONC to JSON. 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" />
|
||||
|
||||
Generated
+18
-18
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "jsonprism",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "jsonprism",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
@@ -39,7 +39,7 @@
|
||||
"clsx": "^2.1.1",
|
||||
"fast-xml-parser": "^5.11.2",
|
||||
"fflate": "^0.8.3",
|
||||
"i18next": "^26.5.5",
|
||||
"i18next": "^26.5.6",
|
||||
"i18next-browser-languagedetector": "^8.2.1",
|
||||
"js-yaml": "^5.5.0",
|
||||
"lucide-react": "^1.61.0",
|
||||
@@ -47,7 +47,7 @@
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-dropzone": "^20.1.4",
|
||||
"react-i18next": "^17.1.1",
|
||||
"react-i18next": "^17.1.3",
|
||||
"react-router": "^8.5.0",
|
||||
"smol-toml": "^1.9.1",
|
||||
"sonner": "^2.0.8",
|
||||
@@ -83,7 +83,7 @@
|
||||
"typescript-eslint": "^8.72.0",
|
||||
"vite": "^8.3.5",
|
||||
"vitest": "^5.0.5",
|
||||
"wrangler": "^4.151.3"
|
||||
"wrangler": "^4.152.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=26.0.0"
|
||||
@@ -6721,9 +6721,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/i18next": {
|
||||
"version": "26.5.5",
|
||||
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.5.5.tgz",
|
||||
"integrity": "sha512-txdaNOlnZCdiTMSlEzl5hUJU8TC9R4J/RCR1G7XrDPbWT2t3mR142QPz84ZuZeXDt3yq+9zmsdPiakxYtmp3fw==",
|
||||
"version": "26.5.6",
|
||||
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.5.6.tgz",
|
||||
"integrity": "sha512-GFWrDwGmYhOQS3bKvjA2Ir2ob9ScEdyY1UbeQJ10jyVACGQ6XxmDYqC/lxEj/IPEJlPQYNRnYffDET6TM8mnFg==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
@@ -7401,9 +7401,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/miniflare": {
|
||||
"version": "5.20261019.1-beta",
|
||||
"resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261019.1-beta.tgz",
|
||||
"integrity": "sha512-1n7MN2UqZnPniyYAqNuV1YEAaja66ozKGVCc5ZTmYQhTubnoAwGLccwb+ZWYLOajuw3pOaJ70u//bZMuURlRew==",
|
||||
"version": "5.20261019.2-beta",
|
||||
"resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261019.2-beta.tgz",
|
||||
"integrity": "sha512-QNgCA/axizZ7kv7RV3nwbRoz+w4watBlwIsyXjwgYHw4eSw5BrR1F2152s3Kz+Bzy/YxjKFHrZl3LzBRbPgYoQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -7952,9 +7952,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-i18next": {
|
||||
"version": "17.1.1",
|
||||
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.1.1.tgz",
|
||||
"integrity": "sha512-Q76xpzxrZNcqhB7M31Ns7isulGOlmhURqRsJOGlYgJJCyoy1pMq6tRl8KQycGNNY1vPaxbIdrogrqY9nkb+SEA==",
|
||||
"version": "17.1.3",
|
||||
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.1.3.tgz",
|
||||
"integrity": "sha512-XfaTqU09NPuBDuADQ8TEPbE0Goc2Gh6FHu0qvdFWfOWCdGQWRxRY2Uo5tDPtGBdzu4COXp0LQCkQIYa0IhJXlA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.29.7",
|
||||
@@ -9285,9 +9285,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/wrangler": {
|
||||
"version": "4.151.3",
|
||||
"resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.151.3.tgz",
|
||||
"integrity": "sha512-mzPQLmkAhZUV7CdiAhE+hiIAJlS9xPL6vZe1B8oQFuWxFu7nmQnvHAVjcAcabwSGkXFXH9uspzXwHOFrfbQmqQ==",
|
||||
"version": "4.152.0",
|
||||
"resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.152.0.tgz",
|
||||
"integrity": "sha512-lmXTF1sCDEqBaEMpreGczvg/x3AIh1d/qxc4BN7utQ4jEDwdA4YG0L6kr3ev0TtVLHRb6QLySNAOAunwn+dHeA==",
|
||||
"dev": true,
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"dependencies": {
|
||||
@@ -9295,7 +9295,7 @@
|
||||
"@cloudflare/unenv-preset": "2.16.2",
|
||||
"blake3-wasm": "2.1.5",
|
||||
"esbuild": "0.28.2",
|
||||
"miniflare": "5.20261019.1-beta",
|
||||
"miniflare": "5.20261019.2-beta",
|
||||
"path-to-regexp": "6.3.0",
|
||||
"unenv": "2.0.0-rc.24",
|
||||
"workerd": "1.20261019.1"
|
||||
|
||||
+5
-5
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "jsonprism",
|
||||
"private": true,
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.0",
|
||||
"type": "module",
|
||||
"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.",
|
||||
"description": "Disperse JSON into 12 formats (six convert back, plus JSONC → JSON) — 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://jsonprism.poli0981.dev",
|
||||
@@ -73,7 +73,7 @@
|
||||
"clsx": "^2.1.1",
|
||||
"fast-xml-parser": "^5.11.2",
|
||||
"fflate": "^0.8.3",
|
||||
"i18next": "^26.5.5",
|
||||
"i18next": "^26.5.6",
|
||||
"i18next-browser-languagedetector": "^8.2.1",
|
||||
"js-yaml": "^5.5.0",
|
||||
"lucide-react": "^1.61.0",
|
||||
@@ -81,7 +81,7 @@
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-dropzone": "^20.1.4",
|
||||
"react-i18next": "^17.1.1",
|
||||
"react-i18next": "^17.1.3",
|
||||
"react-router": "^8.5.0",
|
||||
"smol-toml": "^1.9.1",
|
||||
"sonner": "^2.0.8",
|
||||
@@ -117,6 +117,6 @@
|
||||
"typescript-eslint": "^8.72.0",
|
||||
"vite": "^8.3.5",
|
||||
"vitest": "^5.0.5",
|
||||
"wrangler": "^4.151.3"
|
||||
"wrangler": "^4.152.0"
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -2,18 +2,20 @@
|
||||
# API responses from worker/ set their own headers.
|
||||
#
|
||||
# CSP notes:
|
||||
# - script-src: the Cloudflare Web Analytics beacon and the Turnstile widget.
|
||||
# - script-src: the Cloudflare Web Analytics beacon and the Turnstile widget;
|
||||
# 'wasm-unsafe-eval' lets bson compile its small WebAssembly helper for
|
||||
# 64-bit math (it allows WebAssembly only, not JavaScript eval).
|
||||
# - 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
|
||||
Content-Security-Policy: default-src 'self'; script-src 'self' 'wasm-unsafe-eval' 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=()
|
||||
Permissions-Policy: accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()
|
||||
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
|
||||
|
||||
Generated
+2
-2
@@ -1,6 +1,6 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "adler2"
|
||||
@@ -1876,7 +1876,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jsonprism"
|
||||
version = "2.0.0"
|
||||
version = "2.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "jsonprism"
|
||||
version = "2.0.0"
|
||||
version = "2.1.0"
|
||||
description = "Disperse JSON into many formats."
|
||||
authors = ["poli0981 <code@poli0981.dev>"]
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
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/v2.0.0/LICENSE\par
|
||||
https://github.com/poli0981/jsonPrism/blob/v2.1.0/LICENSE\par
|
||||
\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
|
||||
\bullet\tab Terms of Service (EULA): https://github.com/poli0981/jsonPrism/blob/v2.1.0/TERMS.md\par
|
||||
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/v2.1.0/PRIVACY.md\par
|
||||
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/v2.1.0/DISCLAIMER.md\par
|
||||
\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
|
||||
|
||||
@@ -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; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
|
||||
"csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self' 'wasm-unsafe-eval'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
@@ -42,7 +42,7 @@
|
||||
],
|
||||
"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 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.",
|
||||
"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 (plus JSONC into plain JSON), entirely on your machine.",
|
||||
"copyright": "Copyright (c) 2026 poli0981",
|
||||
"publisher": "poli0981",
|
||||
"homepage": "https://jsonprism.poli0981.dev",
|
||||
@@ -78,7 +78,7 @@
|
||||
},
|
||||
"android": {
|
||||
"minSdkVersion": 31,
|
||||
"versionCode": 20000
|
||||
"versionCode": 20100
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
|
||||
@@ -1,21 +1,29 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import CodeMirror, { EditorState, EditorView, type BasicSetupOptions } from '@uiw/react-codemirror';
|
||||
import CodeMirror, {
|
||||
EditorState,
|
||||
EditorView,
|
||||
ViewPlugin,
|
||||
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 { json as jsonStream } from '@codemirror/legacy-modes/mode/javascript';
|
||||
import { toml } from '@codemirror/legacy-modes/mode/toml';
|
||||
import { lintGutter, linter, type Diagnostic } from '@codemirror/lint';
|
||||
import { tags as t } from '@lezer/highlight';
|
||||
import { parseJsonInput } from '@/lib/detect';
|
||||
import { parseJsonc } from '@/converters/jsonc';
|
||||
import type { ConversionFailure } from '@/converters/types';
|
||||
import { parseJsonInput, type ParseFailure } from '@/lib/detect';
|
||||
import { useTheme } from '@/lib/theme';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type EditorLanguage =
|
||||
'json' | 'jsonl' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
|
||||
'json' | 'jsonl' | 'jsonc' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
|
||||
|
||||
export interface CodeEditorProps {
|
||||
value: string;
|
||||
@@ -71,15 +79,23 @@ const yieldFileDrops = EditorView.domEventHandlers({
|
||||
const LINT_LIMIT_CHARS = 2_000_000;
|
||||
const MAX_JSONL_DIAGNOSTICS = 100;
|
||||
|
||||
type Check = (text: string) => { ok: true } | ParseFailure | ConversionFailure;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
function parseDiagnostic(
|
||||
view: EditorView,
|
||||
text: string,
|
||||
start: number,
|
||||
check: Check = parseJsonInput,
|
||||
): Diagnostic | null {
|
||||
if (!text.trim()) return null;
|
||||
const result = check(text);
|
||||
if (result.ok) return null;
|
||||
const { doc } = view.state;
|
||||
let from = start;
|
||||
if (result.line !== undefined && result.column !== undefined) {
|
||||
@@ -95,6 +111,17 @@ const jsonLint = linter((view) => {
|
||||
return diagnostic ? [diagnostic] : [];
|
||||
});
|
||||
|
||||
// @lezer/json has no comment tokens, so JSONC uses the legacy JSON mode, which
|
||||
// highlights them. It calls true/false/null "atom"; colour them like JSON's.
|
||||
const jsoncLanguage = StreamLanguage.define({ ...jsonStream, tokenTable: { atom: t.bool } });
|
||||
|
||||
// JSONC: comments and trailing commas are fine; the rest must be JSON.
|
||||
const jsoncLint = linter((view) => {
|
||||
if (view.state.doc.length > LINT_LIMIT_CHARS) return [];
|
||||
const diagnostic = parseDiagnostic(view, view.state.doc.toString(), 0, parseJsonc);
|
||||
return diagnostic ? [diagnostic] : [];
|
||||
});
|
||||
|
||||
// JSONL: every non-blank line is its own JSON document.
|
||||
const jsonlLint = linter((view) => {
|
||||
const { doc } = view.state;
|
||||
@@ -108,12 +135,29 @@ const jsonlLint = linter((view) => {
|
||||
return diagnostics;
|
||||
});
|
||||
|
||||
/**
|
||||
* Read-only output isn't contenteditable (that would raise the on-screen
|
||||
* keyboard on phones), so CodeMirror never moves a cursor through it and
|
||||
* swallows the arrow keys. Make the scroll container itself focusable instead:
|
||||
* the browser then scrolls it with the arrow and page keys.
|
||||
*/
|
||||
function focusableScroller(label: string | undefined) {
|
||||
return ViewPlugin.define((view) => {
|
||||
view.scrollDOM.tabIndex = 0;
|
||||
view.scrollDOM.setAttribute('role', 'region');
|
||||
if (label) view.scrollDOM.setAttribute('aria-label', label);
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
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 'jsonc':
|
||||
return readOnly ? [jsoncLanguage] : [jsoncLanguage, lintGutter(), jsoncLint];
|
||||
case 'yaml':
|
||||
return [yaml()];
|
||||
case 'xml':
|
||||
@@ -237,6 +281,7 @@ export function CodeEditor({
|
||||
...(ariaLabel ? { 'aria-label': ariaLabel } : {}),
|
||||
...(readOnly ? { 'aria-readonly': 'true' } : {}),
|
||||
}),
|
||||
...(readOnly ? [focusableScroller(ariaLabel)] : []),
|
||||
theme,
|
||||
];
|
||||
}, [ariaLabel, language, phrases, readOnly, resolvedTheme, wrap]);
|
||||
@@ -244,6 +289,10 @@ export function CodeEditor({
|
||||
return (
|
||||
<div className={cn('h-full overflow-hidden', className)}>
|
||||
<CodeMirror
|
||||
// The wrapper div this component renders must fill the panel too, or
|
||||
// `height="100%"` has nothing to resolve against: the editor grows to
|
||||
// its content, gets clipped, and never scrolls.
|
||||
className="h-full"
|
||||
value={value}
|
||||
readOnly={readOnly}
|
||||
editable={!readOnly}
|
||||
|
||||
@@ -23,6 +23,8 @@ import { StatusBar, type ConversionState } from './StatusBar';
|
||||
import { BatchPanel } from './BatchPanel';
|
||||
|
||||
const REVERSIBLE_FALLBACKS: FormatId[] = ['jsonl', 'csv', 'yaml', 'toml', 'resx'];
|
||||
/** Where the JSON → direction lands when the current format is input-only. */
|
||||
const FORWARD_FALLBACK: FormatId = 'jsonl';
|
||||
|
||||
export function ConverterWorkspace() {
|
||||
const { t } = useTranslation();
|
||||
@@ -74,16 +76,24 @@ export function ConverterWorkspace() {
|
||||
(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 converter = getConverter(format);
|
||||
if (next === 'reverse' && typeof converter.reverse !== 'function') {
|
||||
const fallback = REVERSIBLE_FALLBACKS.find(
|
||||
(id) => typeof getConverter(id).reverse === 'function',
|
||||
);
|
||||
if (fallback) setFormat(fallback);
|
||||
}
|
||||
if (next === 'forward' && converter.meta.inputOnly) setFormat(FORWARD_FALLBACK);
|
||||
},
|
||||
[format, setDirection, setFormat],
|
||||
);
|
||||
|
||||
// Offered by the input panel when JSON → fails on text that is valid JSONC.
|
||||
const readAsJsonc = useCallback(() => {
|
||||
setDirection('reverse');
|
||||
setFormat('jsonc');
|
||||
}, [setDirection, setFormat]);
|
||||
|
||||
const currentOptions = useMemo(
|
||||
() => storedOptions ?? { ...getConverter(format).defaultOptions },
|
||||
[format, storedOptions],
|
||||
@@ -130,6 +140,7 @@ export function ConverterWorkspace() {
|
||||
format={format}
|
||||
direction={direction}
|
||||
onMultiFileDrop={handleMultiFileDrop}
|
||||
onReadAsJsonc={readAsJsonc}
|
||||
/>
|
||||
);
|
||||
const outputPanel = (
|
||||
|
||||
@@ -13,7 +13,10 @@ interface FormatPickerProps {
|
||||
onChange: (id: FormatId) => void;
|
||||
/** Drives the subtle highlight ring on suggested chips. */
|
||||
shape?: JsonShape | null;
|
||||
/** When reverse, formats without a reverse() implementation are disabled. */
|
||||
/**
|
||||
* When reverse, formats without a reverse() implementation are disabled;
|
||||
* when forward, input-only formats (JSONC) are.
|
||||
*/
|
||||
direction?: Direction;
|
||||
}
|
||||
|
||||
@@ -30,7 +33,7 @@ export function FormatPicker({ value, onChange, shape, direction = 'forward' }:
|
||||
return (
|
||||
<>
|
||||
{/* Mobile: compact Sheet trigger — saves ~50-80px of toolbar height when
|
||||
the 12 chip grid would otherwise wrap to 2-3 rows on narrow viewports. */}
|
||||
the chip grid would otherwise wrap to 2-3 rows on narrow viewports. */}
|
||||
<Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<button
|
||||
@@ -70,7 +73,7 @@ export function FormatPicker({ value, onChange, shape, direction = 'forward' }:
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
{/* Desktop: 12 chips inline. */}
|
||||
{/* Desktop: every chip inline. */}
|
||||
<div
|
||||
className="hidden flex-wrap gap-1 md:flex"
|
||||
role="group"
|
||||
@@ -101,8 +104,9 @@ interface FormatChipProps {
|
||||
expanded?: boolean;
|
||||
}
|
||||
|
||||
function chipStatus(noReverse: boolean, suggested: boolean, dimmed: boolean) {
|
||||
function chipStatus(noReverse: boolean, inputOnly: boolean, suggested: boolean, dimmed: boolean) {
|
||||
if (noReverse) return 'no_reverse';
|
||||
if (inputOnly) return 'input_only';
|
||||
if (suggested) return 'suggested';
|
||||
return dimmed ? 'not_suggested' : 'ready';
|
||||
}
|
||||
@@ -113,9 +117,10 @@ function FormatChip({ id, value, onChange, shape, direction, expanded }: FormatC
|
||||
const active = value === id;
|
||||
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 status = chipStatus(noReverse, suggested, dimmed);
|
||||
const inputOnly = direction === 'forward' && c.meta.inputOnly === true;
|
||||
const enabled = c.meta.ready && !noReverse && !inputOnly;
|
||||
const dimmed = direction === 'forward' && !!shape && !suggested && enabled;
|
||||
const status = chipStatus(noReverse, inputOnly, suggested, dimmed);
|
||||
|
||||
return (
|
||||
<button
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useDropzone, type FileRejection } from 'react-dropzone';
|
||||
import { Eraser, FileText, FolderOpen } from 'lucide-react';
|
||||
import { Eraser, FileText, FolderOpen, MessageSquareCode } from 'lucide-react';
|
||||
import { ToolbarButton } from '@/components/common/ToolbarButton';
|
||||
import { toast } from '@/components/ui/sonner';
|
||||
import { parseJsonc } from '@/converters/jsonc';
|
||||
import { extensionsFor } from '@/converters/registry';
|
||||
import type { Direction, FormatId } from '@/converters/types';
|
||||
import { useFileAccept } from '@/hooks/useFileAccept';
|
||||
import { WORKER_THRESHOLD_CHARS } from '@/lib/convert-client';
|
||||
import { editorLanguageFor } from '@/lib/editor-language';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { extOf } from '@/lib/file-filter';
|
||||
@@ -28,6 +30,8 @@ interface InputPanelProps {
|
||||
direction: Direction;
|
||||
/** Called when 2+ files are dropped — workspace routes them into batch. */
|
||||
onMultiFileDrop?: (files: File[]) => void;
|
||||
/** Switches to JSONC → JSON; offered when JSON → fails on valid JSONC. */
|
||||
onReadAsJsonc?: () => void;
|
||||
}
|
||||
|
||||
export function InputPanel({
|
||||
@@ -39,6 +43,7 @@ export function InputPanel({
|
||||
format,
|
||||
direction,
|
||||
onMultiFileDrop,
|
||||
onReadAsJsonc,
|
||||
}: InputPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
@@ -156,6 +161,13 @@ export function InputPanel({
|
||||
if (file) loadFile(file);
|
||||
};
|
||||
|
||||
// Comments or trailing commas make JSON → fail; if that is all that is wrong,
|
||||
// offer JSONC. Inputs this big convert in the worker, so skip the extra parse.
|
||||
const looksLikeJsonc = useMemo(
|
||||
() => !isReverse && !!error && value.length < WORKER_THRESHOLD_CHARS && parseJsonc(value).ok,
|
||||
[error, isReverse, value],
|
||||
);
|
||||
|
||||
const showOverlay = isDragActive || dragActive;
|
||||
const position =
|
||||
errorLine != null
|
||||
@@ -219,6 +231,23 @@ export function InputPanel({
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{looksLikeJsonc && onReadAsJsonc && (
|
||||
<div className="border-border/70 flex flex-wrap items-center justify-between gap-x-3 gap-y-1 border-b px-3 py-1 text-xs">
|
||||
<span className="text-muted-foreground">{t('home.jsonc_hint')}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onReadAsJsonc}
|
||||
className="group border-primary/40 text-foreground hover:bg-primary/10 focus-visible:ring-ring inline-flex min-h-6 items-center gap-1.5 rounded-md border px-2 font-mono font-medium transition outline-none focus-visible:ring-2"
|
||||
>
|
||||
<MessageSquareCode
|
||||
className="h-3.5 w-3.5 transition-transform motion-safe:group-hover:-rotate-6"
|
||||
aria-hidden
|
||||
/>
|
||||
{t('home.jsonc_switch')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<CodeEditorLazy
|
||||
value={value}
|
||||
|
||||
@@ -113,6 +113,17 @@ describe('CodeEditor — editable', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('CodeEditor — sizing', () => {
|
||||
// Regression: the wrapper @uiw/react-codemirror renders had no height, so the
|
||||
// editor grew to its content inside an overflow-hidden panel and could not scroll.
|
||||
it.each([false, true])('fills its panel so long documents scroll (readOnly=%s)', (readOnly) => {
|
||||
const { root } = renderEditor({ value: 'x\n'.repeat(500), readOnly });
|
||||
const wrapper = root.parentElement!;
|
||||
expect(wrapper).toHaveClass('cm-theme-none', 'h-full');
|
||||
expect(wrapper.parentElement).toHaveClass('h-full', 'overflow-hidden');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CodeEditor — read-only', () => {
|
||||
it('marks the content read-only and drops the editing chrome', () => {
|
||||
const { content, container } = renderEditor({
|
||||
@@ -123,6 +134,12 @@ describe('CodeEditor — read-only', () => {
|
||||
});
|
||||
expect(content).toHaveAttribute('contenteditable', 'false');
|
||||
expect(content).toHaveAttribute('aria-readonly', 'true');
|
||||
// Regression: not contenteditable, so the scroll container takes focus and
|
||||
// the browser scrolls it with the arrow and page keys.
|
||||
const scroller = container.querySelector('.cm-scroller')!;
|
||||
expect(scroller).toHaveAttribute('tabindex', '0');
|
||||
expect(scroller).toHaveAttribute('role', 'region');
|
||||
expect(scroller).toHaveAttribute('aria-label', 'YAML output (read-only)');
|
||||
expect(content).toHaveAttribute('aria-label', 'YAML output (read-only)');
|
||||
expect(container.querySelector('.cm-lineNumbers')).not.toBeNull();
|
||||
expect(container.querySelector('.cm-activeLine')).toBeNull();
|
||||
@@ -139,6 +156,7 @@ describe('CodeEditor — languages', () => {
|
||||
it.each<[EditorLanguage, string | null]>([
|
||||
['json', 'json'],
|
||||
['jsonl', 'json'],
|
||||
['jsonc', 'json'],
|
||||
['yaml', 'yaml'],
|
||||
['xml', 'xml'],
|
||||
['markdown', 'markdown'],
|
||||
@@ -201,6 +219,26 @@ describe('CodeEditor — JSON linting', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('CodeEditor — JSONC linting', () => {
|
||||
const language = editorLanguageFor('jsonc', 'reverse');
|
||||
|
||||
it('accepts comments and trailing commas', async () => {
|
||||
const { view } = renderEditor({
|
||||
value: '{\n // note\n "a": [1, 2,], /* more */\n}',
|
||||
language,
|
||||
});
|
||||
expect(await lintNow(view)).toBe(0);
|
||||
});
|
||||
|
||||
it('flags JSONC errors where the converter does', async () => {
|
||||
const { view } = renderEditor({ value: '{\n "a": 1 /* open\n}', language });
|
||||
expect(await lintNow(view)).toBe(1);
|
||||
|
||||
typeInto(view, '');
|
||||
expect(await lintNow(view)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CodeEditor — behaviour', () => {
|
||||
it('leaves file drops to the surrounding dropzone', async () => {
|
||||
const { content, view } = renderEditor({ value: 'keep' });
|
||||
|
||||
@@ -195,6 +195,39 @@ describe('ConverterWorkspace — direction', () => {
|
||||
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'forward', format: 'csv' });
|
||||
expect(inputBox()).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('converts JSONC back to JSON and places errors in the original text', () => {
|
||||
useWorkspaceStore.setState({ format: 'jsonc', direction: 'reverse' });
|
||||
render(<ConverterWorkspace />);
|
||||
|
||||
type('{\n // comment\n "a": [1, 2,],\n}', 'Input JSONC');
|
||||
expect(outputBox('JSON output (read-only)')).toHaveValue('{\n "a": [\n 1,\n 2\n ]\n}');
|
||||
|
||||
type('{\n /* comment */\n "a": 1\n "b": 2\n}', 'Input JSONC');
|
||||
expect(screen.getByRole('status')).toHaveTextContent(/^Ln 4, Col 3/);
|
||||
expect(screen.getByText('error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('leaves an input-only format when switching to JSON →', async () => {
|
||||
const user = userEvent.setup();
|
||||
useWorkspaceStore.setState({ format: 'jsonc', direction: 'reverse' });
|
||||
render(<ConverterWorkspace />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'JSON →' }));
|
||||
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'forward', format: 'jsonl' });
|
||||
expect(within(chips()).getByRole('button', { name: 'JSONC' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('offers to read JSON with comments as JSONC', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<ConverterWorkspace />);
|
||||
type('[1, /* two */ 2]');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Convert JSONC → JSON' }));
|
||||
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'reverse', format: 'jsonc' });
|
||||
expect(inputBox('Input JSONC')).toHaveValue('[1, /* two */ 2]');
|
||||
expect(outputBox('JSON output (read-only)')).toHaveValue('[\n 1,\n 2\n]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ConverterWorkspace — options', () => {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { FormatPicker } from '../FormatPicker';
|
||||
|
||||
const LABELS: Record<FormatId, string> = {
|
||||
jsonl: 'JSONL',
|
||||
jsonc: 'JSONC',
|
||||
csv: 'CSV',
|
||||
tsv: 'TSV',
|
||||
yaml: 'YAML',
|
||||
@@ -34,7 +35,7 @@ describe('FormatPicker — inline chips', () => {
|
||||
render(<FormatPicker value="yaml" onChange={() => {}} />);
|
||||
const buttons = within(inlineGroup()).getAllByRole('button');
|
||||
expect(buttons.map((b) => b.textContent)).toEqual(Object.values(LABELS));
|
||||
for (const button of buttons) {
|
||||
for (const button of buttons.filter((b) => b.textContent !== 'JSONC')) {
|
||||
expect(button).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
button.textContent === 'YAML' ? 'true' : 'false',
|
||||
@@ -44,6 +45,23 @@ describe('FormatPicker — inline chips', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('disables input-only formats going forward', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
render(<FormatPicker value="jsonl" onChange={onChange} shape="object" />);
|
||||
|
||||
expect(chip('jsonc')).toBeDisabled();
|
||||
expect(chip('jsonc')).toHaveAttribute(
|
||||
'title',
|
||||
'Input only: converts to JSON in the → JSON direction',
|
||||
);
|
||||
// Disabled, not "not suggested": no dashed border.
|
||||
expect(chip('jsonc')).not.toHaveClass('border-dashed');
|
||||
|
||||
await user.click(chip('jsonc'));
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports the picked format', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
@@ -84,8 +102,9 @@ describe('FormatPicker — inline chips', () => {
|
||||
expect(chip(format)).toBeDisabled();
|
||||
expect(chip(format)).toHaveAttribute('title', 'Reverse parse not supported for this format');
|
||||
}
|
||||
for (const format of ['jsonl', 'csv', 'tsv', 'yaml', 'toml', 'resx'] as const) {
|
||||
for (const format of ['jsonl', 'jsonc', 'csv', 'tsv', 'yaml', 'toml', 'resx'] as const) {
|
||||
expect(chip(format)).toBeEnabled();
|
||||
expect(chip(format)).toHaveAttribute('title', 'Ready');
|
||||
}
|
||||
|
||||
await user.click(chip('xml'));
|
||||
@@ -107,7 +126,7 @@ describe('FormatPicker — compact sheet (mobile)', () => {
|
||||
await user.click(screen.getByRole('button', { name: /Target format\s*JSONL/ }));
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Target format' });
|
||||
const sheetGroup = within(dialog).getByRole('group', { name: 'Target format' });
|
||||
expect(within(sheetGroup).getAllByRole('button')).toHaveLength(12);
|
||||
expect(within(sheetGroup).getAllByRole('button')).toHaveLength(13);
|
||||
expect(chip('jsonl', sheetGroup)).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(chip('yaml', sheetGroup)).toHaveAttribute('title', 'Suggested for the detected shape');
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ interface PanelProps {
|
||||
format?: FormatId;
|
||||
direction?: Direction;
|
||||
onMultiFileDrop?: (files: File[]) => void;
|
||||
onReadAsJsonc?: () => void;
|
||||
}
|
||||
|
||||
function renderPanel(props: PanelProps = {}) {
|
||||
@@ -54,6 +55,7 @@ function renderPanel(props: PanelProps = {}) {
|
||||
format={props.format ?? 'csv'}
|
||||
direction={props.direction ?? 'forward'}
|
||||
{...(props.onMultiFileDrop ? { onMultiFileDrop: props.onMultiFileDrop } : {})}
|
||||
{...(props.onReadAsJsonc ? { onReadAsJsonc: props.onReadAsJsonc } : {})}
|
||||
/>,
|
||||
);
|
||||
const root = utils.container.firstElementChild as HTMLElement;
|
||||
@@ -113,6 +115,15 @@ describe('InputPanel — layout', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('highlights and accepts JSONC going back', () => {
|
||||
const { fileInput } = renderPanel({ format: 'jsonc', direction: 'reverse' });
|
||||
expect(screen.getByRole('textbox', { name: 'Input JSONC' })).toHaveAttribute(
|
||||
'data-language',
|
||||
'jsonc',
|
||||
);
|
||||
expect(fileInput).toHaveAttribute('accept', '.jsonc,.json,.txt,application/jsonc');
|
||||
});
|
||||
|
||||
it('passes edits straight through', () => {
|
||||
const { onChange } = renderPanel();
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'Input JSON' }), {
|
||||
@@ -174,6 +185,38 @@ describe('InputPanel — error banner', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('InputPanel — JSONC hint', () => {
|
||||
const jsonc = '{\n // compiler options\n "strict": true,\n}';
|
||||
const error = "Expected property name or '}' in JSON";
|
||||
|
||||
it('offers JSONC → JSON when the JSON error is only comments or trailing commas', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onReadAsJsonc = vi.fn();
|
||||
renderPanel({ value: jsonc, error, onReadAsJsonc });
|
||||
|
||||
expect(
|
||||
screen.getByText('This looks like JSONC — JSON with comments or trailing commas.'),
|
||||
).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Convert JSONC → JSON' }));
|
||||
expect(onReadAsJsonc).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each<[string, PanelProps]>([
|
||||
['the input is valid', { value: jsonc, error: null }],
|
||||
['the text is not valid JSONC either', { value: '{"a": }', error }],
|
||||
['already converting back', { value: jsonc, error, direction: 'reverse', format: 'jsonc' }],
|
||||
['the input is too big to check here', { value: jsonc + ' '.repeat(256 * 1024), error }],
|
||||
])('stays hidden when %s', (_case, props) => {
|
||||
renderPanel({ ...props, onReadAsJsonc: vi.fn() });
|
||||
expect(screen.queryByRole('button', { name: 'Convert JSONC → JSON' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('stays hidden without a handler', () => {
|
||||
renderPanel({ value: jsonc, error });
|
||||
expect(screen.queryByRole('button', { name: 'Convert JSONC → JSON' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('InputPanel — file picker (web)', () => {
|
||||
it('opens the hidden file input', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
@@ -37,6 +37,12 @@ const ADVERSARIAL_TEXT = [
|
||||
'\u0000\u0001\u0002',
|
||||
'key = = value',
|
||||
'<root><data name="x"><value>1</value></data></root>',
|
||||
// JSONC-shaped: comments, stray commas, a string cut off mid-escape.
|
||||
'/*',
|
||||
'//',
|
||||
'[,]',
|
||||
'{"a": 1,} // ok',
|
||||
'"\\',
|
||||
];
|
||||
|
||||
describe('converter contract', () => {
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { ConversionResult } from '../types';
|
||||
import { jsoncConverter, parseJsonc } from '../jsonc';
|
||||
|
||||
type Indent = (typeof jsoncConverter.defaultOptions)['indent'];
|
||||
|
||||
function reverse(text: string, indent: Indent = '2'): ConversionResult {
|
||||
return jsoncConverter.reverse!({ text }, { indent });
|
||||
}
|
||||
|
||||
function ok(result: ConversionResult): string {
|
||||
if (!result.ok) throw new Error(`expected ok, got error: ${result.error}`);
|
||||
return result.output;
|
||||
}
|
||||
|
||||
function fail(result: ConversionResult) {
|
||||
if (result.ok) throw new Error(`expected an error, got output: ${result.output.slice(0, 200)}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
describe('jsoncConverter — comments', () => {
|
||||
it('removes line and block comments', () => {
|
||||
const text = `// leading
|
||||
{
|
||||
"a": 1, // trailing
|
||||
/* block */ "b": [true, /* inline */ null]
|
||||
}
|
||||
/* end */`;
|
||||
expect(JSON.parse(ok(reverse(text)))).toEqual({ a: 1, b: [true, null] });
|
||||
});
|
||||
|
||||
it('ends a line comment at CR or LF and keeps the rest', () => {
|
||||
expect(JSON.parse(ok(reverse('[1, // one\r\n2, // two\r3]')))).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('keeps comment-like text inside strings', () => {
|
||||
const text = '{"url": "http://example.com/*x*/", "path": "C:\\\\dir\\\\", "q": "a\\"//b"} // c';
|
||||
expect(JSON.parse(ok(reverse(text)))).toEqual({
|
||||
url: 'http://example.com/*x*/',
|
||||
path: 'C:\\dir\\',
|
||||
q: 'a"//b',
|
||||
});
|
||||
});
|
||||
|
||||
it('reports an unterminated block comment where it starts', () => {
|
||||
const result = fail(reverse('{\n "a": 1 /* open\n}'));
|
||||
expect(result.error).toMatch(/Unterminated block comment/);
|
||||
expect(result).toMatchObject({ line: 2, column: 10 });
|
||||
});
|
||||
|
||||
it('rejects input that only has comments', () => {
|
||||
expect(fail(reverse('// nothing\n/* here */')).error).toMatch(/No JSON value/);
|
||||
expect(fail(reverse('')).error).toMatch(/No JSON value/);
|
||||
});
|
||||
|
||||
it('reports an unterminated string, even with comments after it', () => {
|
||||
expect(fail(reverse('["abc\n// x\n"]'))).toMatchObject({ line: 1 });
|
||||
expect(fail(reverse('["abc // x'))).toMatchObject({ line: 1 });
|
||||
});
|
||||
|
||||
it('leaves a lone slash for JSON.parse to reject', () => {
|
||||
expect(fail(reverse('[1 / 2]')).error.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsoncConverter — trailing commas', () => {
|
||||
it('removes trailing commas in objects, arrays and nested containers', () => {
|
||||
const text = '{"a": [1, 2,], "b": {"c": 3,},}';
|
||||
expect(JSON.parse(ok(reverse(text)))).toEqual({ a: [1, 2], b: { c: 3 } });
|
||||
});
|
||||
|
||||
it('removes a trailing comma with comments and line breaks before the bracket', () => {
|
||||
const text = '[\n "x", // last item\n /* nothing more */\n]';
|
||||
expect(JSON.parse(ok(reverse(text)))).toEqual(['x']);
|
||||
});
|
||||
|
||||
it.each(['[,]', '{,}', '[1,,2]', '[1,,]', '{"a":,}'])('still rejects %s', (text) => {
|
||||
expect(fail(reverse(text)).error.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsoncConverter — errors line up with the input', () => {
|
||||
it('reports a JSON error at its line and column despite earlier comments', () => {
|
||||
const text = '/* a\n b */\n{\n "a": 1 // ok\n "b": 2\n}';
|
||||
expect(fail(reverse(text))).toMatchObject({ line: 5, column: 3 });
|
||||
});
|
||||
|
||||
it('counts columns in UTF-16 code units, like the editor', () => {
|
||||
const text = '/* 🎮 */ [1 2]';
|
||||
expect(fail(reverse(text))).toMatchObject({ line: 1, column: 13 });
|
||||
});
|
||||
|
||||
it('accepts a byte-order mark', () => {
|
||||
expect(ok(reverse('\uFEFF// bom\n[1]'))).toBe('[\n 1\n]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsoncConverter — output keeps values exactly', () => {
|
||||
it('copies number literals verbatim', () => {
|
||||
const output = ok(reverse('[12345678901234567890, 1.0, 1e3, -0, 0.1e-7]', 'minify'));
|
||||
expect(output).toBe('[12345678901234567890,1.0,1e3,-0,0.1e-7]');
|
||||
});
|
||||
|
||||
it('keeps duplicate and __proto__ keys', () => {
|
||||
const output = ok(reverse('{"a": 1, "a": 2, "__proto__": {"x": 1}}', 'minify'));
|
||||
expect(output).toBe('{"a":1,"a":2,"__proto__":{"x":1}}');
|
||||
});
|
||||
|
||||
it('collapses empty containers, comments inside included', () => {
|
||||
expect(ok(reverse('{ /* nothing */ "a": [ ], "b": { // none\n } }'))).toBe(
|
||||
'{\n "a": [],\n "b": {}\n}',
|
||||
);
|
||||
});
|
||||
|
||||
it('formats scalars at the root', () => {
|
||||
expect(ok(reverse('/* answer */ 42'))).toBe('42');
|
||||
expect(ok(reverse('"text" // c'))).toBe('"text"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsoncConverter — layout', () => {
|
||||
const text = '{"a": [1, {"b": null}], "c": "d"} // c';
|
||||
|
||||
it.each<[Indent, string]>([
|
||||
['2', '{\n "a": [\n 1,\n {\n "b": null\n }\n ],\n "c": "d"\n}'],
|
||||
[
|
||||
'4',
|
||||
'{\n "a": [\n 1,\n {\n "b": null\n }\n ],\n "c": "d"\n}',
|
||||
],
|
||||
['tab', '{\n\t"a": [\n\t\t1,\n\t\t{\n\t\t\t"b": null\n\t\t}\n\t],\n\t"c": "d"\n}'],
|
||||
['minify', '{"a":[1,{"b":null}],"c":"d"}'],
|
||||
])('indent %s', (indent, expected) => {
|
||||
expect(ok(reverse(text, indent))).toBe(expected);
|
||||
});
|
||||
|
||||
it('handles deep nesting without recursion', () => {
|
||||
const depth = 10_000;
|
||||
const text = '['.repeat(depth) + '/* deep */' + ']'.repeat(depth);
|
||||
const output = ok(reverse(text, 'minify'));
|
||||
expect(output).toBe('['.repeat(depth - 1) + '[]' + ']'.repeat(depth - 1));
|
||||
});
|
||||
|
||||
it('refuses pretty output that would be enormous', () => {
|
||||
const depth = 50_000;
|
||||
const text = '['.repeat(depth) + '1' + ']'.repeat(depth);
|
||||
expect(fail(reverse(text)).error).toMatch(/too large/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsoncConverter — contract', () => {
|
||||
it('is input-only and has no forward pass', () => {
|
||||
expect(jsoncConverter.meta.inputOnly).toBe(true);
|
||||
const result = jsoncConverter.convert({ data: { a: 1 } }, jsoncConverter.defaultOptions);
|
||||
expect(result.ok).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts .jsonc and .json files', () => {
|
||||
expect(jsoncConverter.meta.extension).toBe('jsonc');
|
||||
expect(jsoncConverter.meta.altExtensions).toEqual(['json']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseJsonc', () => {
|
||||
it('returns JSON text at the same offsets as the input', () => {
|
||||
const text = '{"a": 1, /* c */ "b": [2,],} // end';
|
||||
const result = parseJsonc(text);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.json).toHaveLength(text.length);
|
||||
expect(result.json).toBe(`{"a": 1, ${' '.repeat(7)} "b": [2 ] } ${' '.repeat(6)}`);
|
||||
expect(JSON.parse(result.json)).toEqual({ a: 1, b: [2] });
|
||||
});
|
||||
|
||||
it('returns plain JSON unchanged', () => {
|
||||
const text = '{"a": [1, 2]}';
|
||||
expect(parseJsonc(text)).toEqual({ ok: true, json: text });
|
||||
});
|
||||
});
|
||||
@@ -3,11 +3,12 @@ import { ALL_FORMATS, CONVERTERS, getConverter } from '../registry';
|
||||
import type { FormatId } from '../types';
|
||||
|
||||
describe('converter registry', () => {
|
||||
it('exposes all 12 format IDs', () => {
|
||||
expect(ALL_FORMATS).toHaveLength(12);
|
||||
it('exposes all 13 format IDs', () => {
|
||||
expect(ALL_FORMATS).toHaveLength(13);
|
||||
expect(new Set(ALL_FORMATS)).toEqual(
|
||||
new Set<FormatId>([
|
||||
'jsonl',
|
||||
'jsonc',
|
||||
'csv',
|
||||
'tsv',
|
||||
'yaml',
|
||||
@@ -42,7 +43,7 @@ describe('converter registry', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('all 12 converters are marked ready', () => {
|
||||
it('all 13 converters are marked ready', () => {
|
||||
for (const id of ALL_FORMATS) {
|
||||
expect(getConverter(id).meta.ready).toBe(true);
|
||||
}
|
||||
@@ -50,7 +51,13 @@ describe('converter registry', () => {
|
||||
|
||||
it('phase metadata covers all expected phases', () => {
|
||||
const phases = ALL_FORMATS.map((id) => getConverter(id).meta.phase);
|
||||
// P1 jsonl/csv/tsv/yaml, P2 xml/toml/markdown/sql, P3 resx, P4 bson/cbor/msgpack.
|
||||
// P1 jsonl/csv/tsv/yaml, P2 xml/toml/markdown/sql, P3 resx, P4 bson/cbor/msgpack/jsonc.
|
||||
expect(new Set(phases)).toEqual(new Set([1, 2, 3, 4]));
|
||||
});
|
||||
|
||||
it('only JSONC is input-only, and it parses back to JSON', () => {
|
||||
const inputOnly = ALL_FORMATS.filter((id) => getConverter(id).meta.inputOnly);
|
||||
expect(inputOnly).toEqual(['jsonc']);
|
||||
expect(typeof getConverter('jsonc').reverse).toBe('function');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,295 @@
|
||||
import type { ConversionFailure, Converter } from './types';
|
||||
import { errorPosition, offsetToLineColumn } from '@/lib/detect';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
|
||||
type JsoncIndent = '2' | '4' | 'tab' | 'minify';
|
||||
|
||||
interface JsoncOptions {
|
||||
/** Layout of the JSON output; `minify` puts it on one line. */
|
||||
indent: JsoncIndent;
|
||||
}
|
||||
|
||||
const INDENT_UNITS: Record<JsoncIndent, string | null> = {
|
||||
'2': ' ',
|
||||
'4': ' ',
|
||||
tab: '\t',
|
||||
minify: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* Formatted output beyond this many characters is refused: deep nesting makes
|
||||
* indentation grow quadratically, and engines cap strings near 2^29.
|
||||
*/
|
||||
const MAX_OUTPUT_CHARS = 2 ** 28;
|
||||
|
||||
const QUOTE = 0x22;
|
||||
const SLASH = 0x2f;
|
||||
const STAR = 0x2a;
|
||||
const BACKSLASH = 0x5c;
|
||||
const COMMA = 0x2c;
|
||||
const COLON = 0x3a;
|
||||
const LF = 0x0a;
|
||||
const CR = 0x0d;
|
||||
const OPEN_BRACE = 0x7b;
|
||||
const CLOSE_BRACE = 0x7d;
|
||||
const OPEN_BRACKET = 0x5b;
|
||||
const CLOSE_BRACKET = 0x5d;
|
||||
|
||||
/** Characters that end a number or `true`/`false`/`null` literal. */
|
||||
const DELIMITERS = ' \t\r\n{}[],:';
|
||||
|
||||
function isJsonWhitespace(c: number): boolean {
|
||||
return c === 0x20 || c === 0x09 || c === LF || c === CR;
|
||||
}
|
||||
|
||||
/**
|
||||
* Index just past the string literal opening at `start`. An unterminated
|
||||
* string stops at the end of its line; JSON.parse reports it later.
|
||||
*/
|
||||
function skipString(text: string, start: number): number {
|
||||
let i = start + 1;
|
||||
while (i < text.length) {
|
||||
const c = text.charCodeAt(i);
|
||||
if (c === QUOTE) return i + 1;
|
||||
if (c === LF || c === CR) return i;
|
||||
i += c === BACKSLASH ? 2 : 1;
|
||||
}
|
||||
return text.length;
|
||||
}
|
||||
|
||||
function skipWhitespace(text: string, start: number): number {
|
||||
let i = start;
|
||||
while (i < text.length && isJsonWhitespace(text.charCodeAt(i))) i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
/**
|
||||
* End of the comment starting at `start`: `start` itself when there is no
|
||||
* comment there, -1 for a block comment that never closes.
|
||||
*/
|
||||
function commentEnd(text: string, start: number): number {
|
||||
const next = text.charCodeAt(start + 1);
|
||||
if (next === SLASH) {
|
||||
let i = start + 2;
|
||||
while (i < text.length && text.charCodeAt(i) !== LF && text.charCodeAt(i) !== CR) i++;
|
||||
return i;
|
||||
}
|
||||
if (next === STAR) {
|
||||
const close = text.indexOf('*/', start + 2);
|
||||
return close < 0 ? -1 : close + 2;
|
||||
}
|
||||
return start;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces every comment with spaces, keeping line breaks, so offsets — and
|
||||
* the line/column of any later JSON error — still match the user's text.
|
||||
* Returns the offset of an unterminated block comment instead.
|
||||
*/
|
||||
function blankComments(text: string): string | number {
|
||||
const parts: string[] = [];
|
||||
let copied = 0;
|
||||
let i = 0;
|
||||
while (i < text.length) {
|
||||
const c = text.charCodeAt(i);
|
||||
if (c === QUOTE) {
|
||||
i = skipString(text, i);
|
||||
continue;
|
||||
}
|
||||
const end = c === SLASH ? commentEnd(text, i) : i;
|
||||
if (end < 0) return i;
|
||||
if (end === i) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
parts.push(text.slice(copied, i), text.slice(i, end).replace(/[^\r\n]/g, ' '));
|
||||
copied = end;
|
||||
i = end;
|
||||
}
|
||||
if (copied === 0) return text;
|
||||
parts.push(text.slice(copied));
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
/** A comma after `[`, `{`, `,` or `:` is a syntax error, never a trailing comma. */
|
||||
function followsValue(previous: number): boolean {
|
||||
return (
|
||||
previous !== OPEN_BRACKET && previous !== OPEN_BRACE && previous !== COMMA && previous !== COLON
|
||||
);
|
||||
}
|
||||
|
||||
/** Replaces each comma that directly precedes `]` or `}` with a space. */
|
||||
function blankTrailingCommas(json: string): string {
|
||||
const commas: number[] = [];
|
||||
let pending = -1;
|
||||
let previous = OPEN_BRACKET;
|
||||
let i = 0;
|
||||
while (i < json.length) {
|
||||
const c = json.charCodeAt(i);
|
||||
if (isJsonWhitespace(c)) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (pending >= 0 && (c === CLOSE_BRACKET || c === CLOSE_BRACE)) commas.push(pending);
|
||||
pending = c === COMMA && followsValue(previous) ? i : -1;
|
||||
previous = c;
|
||||
i = c === QUOTE ? skipString(json, i) : i + 1;
|
||||
}
|
||||
if (commas.length === 0) return json;
|
||||
const parts: string[] = [];
|
||||
let copied = 0;
|
||||
for (const at of commas) {
|
||||
parts.push(json.slice(copied, at), ' ');
|
||||
copied = at + 1;
|
||||
}
|
||||
parts.push(json.slice(copied));
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
function failAt(error: string, text: string, offset: number): ConversionFailure {
|
||||
return { ok: false, error, ...offsetToLineColumn(text, offset) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns JSONC into plain JSON text at the same offsets: comments and trailing
|
||||
* commas become spaces, then JSON.parse validates the rest. Shared by the
|
||||
* converter and the input editor's linter so both report the same errors.
|
||||
*/
|
||||
export function parseJsonc(text: string): { ok: true; json: string } | ConversionFailure {
|
||||
// JSON.parse rejects a byte-order mark; a space keeps the offsets.
|
||||
const source = text.charCodeAt(0) === 0xfeff ? ' ' + text.slice(1) : text;
|
||||
const uncommented = blankComments(source);
|
||||
if (typeof uncommented === 'number') {
|
||||
return failAt('Unterminated block comment: add the closing */.', source, uncommented);
|
||||
}
|
||||
const json = blankTrailingCommas(uncommented);
|
||||
if (skipWhitespace(json, 0) === json.length) {
|
||||
return { ok: false, error: 'No JSON value: the input is empty or only has comments.' };
|
||||
}
|
||||
try {
|
||||
JSON.parse(json);
|
||||
return { ok: true, json };
|
||||
} catch (err) {
|
||||
const message = errorMessage(err);
|
||||
const position = errorPosition(message, json);
|
||||
return position ? { ok: false, error: message, ...position } : { ok: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
/** End of the string, number or literal token starting at `start`. */
|
||||
function valueEnd(json: string, start: number): number {
|
||||
if (json.charCodeAt(start) === QUOTE) return skipString(json, start);
|
||||
let i = start + 1;
|
||||
while (i < json.length && !DELIMITERS.includes(json[i]!)) i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lays out valid JSON token by token. Tokens are copied verbatim — numbers
|
||||
* keep every digit, duplicate and `__proto__` keys survive — because no JS
|
||||
* value is built. Iterative, so deep nesting cannot overflow the stack.
|
||||
* Returns null when the output would be too large.
|
||||
*/
|
||||
function reprint(json: string, unit: string | null): string | null {
|
||||
const out: string[] = [];
|
||||
const colon = unit === null ? ':' : ': ';
|
||||
// Line breaks slice one shared indent string instead of repeating per line.
|
||||
let indent = '';
|
||||
const newline = (depth: number): string => {
|
||||
if (unit === null) return '';
|
||||
const width = depth * unit.length;
|
||||
if (indent.length < width) indent = unit.repeat(depth * 2);
|
||||
return '\n' + indent.slice(0, width);
|
||||
};
|
||||
let size = 0;
|
||||
let depth = 0;
|
||||
let i = skipWhitespace(json, 0);
|
||||
while (i < json.length) {
|
||||
const ch = json[i]!;
|
||||
let end = i + 1;
|
||||
let piece: string;
|
||||
switch (ch) {
|
||||
case '{':
|
||||
case '[': {
|
||||
const next = skipWhitespace(json, end);
|
||||
if (json[next] === (ch === '{' ? '}' : ']')) {
|
||||
piece = ch + json[next];
|
||||
end = next + 1;
|
||||
} else {
|
||||
depth++;
|
||||
piece = ch + newline(depth);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case '}':
|
||||
case ']':
|
||||
depth--;
|
||||
piece = newline(depth) + ch;
|
||||
break;
|
||||
case ',':
|
||||
piece = ',' + newline(depth);
|
||||
break;
|
||||
case ':':
|
||||
piece = colon;
|
||||
break;
|
||||
default:
|
||||
end = valueEnd(json, i);
|
||||
piece = json.slice(i, end);
|
||||
}
|
||||
size += piece.length;
|
||||
if (size > MAX_OUTPUT_CHARS) return null;
|
||||
out.push(piece);
|
||||
i = skipWhitespace(json, end);
|
||||
}
|
||||
return out.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* JSONC (JSON with Comments — tsconfig.json, VS Code settings) → JSON. An
|
||||
* input-only format: JSON is already valid JSONC, so there is no forward pass.
|
||||
*/
|
||||
export const jsoncConverter: Converter<JsoncOptions> = {
|
||||
meta: {
|
||||
id: 'jsonc',
|
||||
labelKey: 'formats.jsonc',
|
||||
extension: 'jsonc',
|
||||
// Most JSONC files are named .json (tsconfig.json, settings.json).
|
||||
altExtensions: ['json'],
|
||||
mimeType: 'application/jsonc',
|
||||
phase: 4,
|
||||
ready: true,
|
||||
inputOnly: true,
|
||||
},
|
||||
defaultOptions: { indent: '2' },
|
||||
optionSchema: [
|
||||
{
|
||||
type: 'enum',
|
||||
key: 'indent',
|
||||
labelKey: 'options.jsonc.indent',
|
||||
descriptionKey: 'options.jsonc.indent_desc',
|
||||
choices: [
|
||||
{ value: '2', labelKey: 'options.jsonc.indent_2' },
|
||||
{ value: '4', labelKey: 'options.jsonc.indent_4' },
|
||||
{ value: 'tab', labelKey: 'options.jsonc.indent_tab' },
|
||||
{ value: 'minify', labelKey: 'options.jsonc.indent_minify' },
|
||||
],
|
||||
},
|
||||
],
|
||||
convert() {
|
||||
return {
|
||||
ok: false,
|
||||
error: 'JSONC is an input format: switch the direction to → JSON to convert it.',
|
||||
};
|
||||
},
|
||||
reverse({ text }, { indent }) {
|
||||
const parsed = parseJsonc(text);
|
||||
if (!parsed.ok) return parsed;
|
||||
const output = reprint(parsed.json, INDENT_UNITS[indent]);
|
||||
return output === null
|
||||
? {
|
||||
ok: false,
|
||||
error: 'The formatted JSON is too large (very deep nesting). Choose "Minified".',
|
||||
}
|
||||
: { ok: true, output };
|
||||
},
|
||||
};
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ConversionInput, ConversionResult, Converter, FormatId, ReverseInput } from './types';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { jsonlConverter } from './jsonl';
|
||||
import { jsoncConverter } from './jsonc';
|
||||
import { csvConverter, tsvConverter } from './csv';
|
||||
import { yamlConverter } from './yaml';
|
||||
import { xmlConverter } from './xml';
|
||||
@@ -15,6 +16,7 @@ import { msgpackConverter } from './msgpack';
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export const CONVERTERS: Record<FormatId, Converter<any>> = {
|
||||
jsonl: jsonlConverter,
|
||||
jsonc: jsoncConverter,
|
||||
csv: csvConverter,
|
||||
tsv: tsvConverter,
|
||||
yaml: yamlConverter,
|
||||
@@ -30,6 +32,7 @@ export const CONVERTERS: Record<FormatId, Converter<any>> = {
|
||||
|
||||
export const ALL_FORMATS: FormatId[] = [
|
||||
'jsonl',
|
||||
'jsonc',
|
||||
'csv',
|
||||
'tsv',
|
||||
'yaml',
|
||||
|
||||
+15
-1
@@ -9,6 +9,7 @@
|
||||
|
||||
export type FormatId =
|
||||
| 'jsonl'
|
||||
| 'jsonc'
|
||||
| 'csv'
|
||||
| 'tsv'
|
||||
| 'yaml'
|
||||
@@ -43,6 +44,11 @@ export interface ConverterMeta {
|
||||
* for display, but downloads decode back to raw bytes via the MIME type.
|
||||
*/
|
||||
binary?: boolean;
|
||||
/**
|
||||
* Input-only formats (JSONC) only convert *to* JSON: `convert()` returns an
|
||||
* error and the UI disables them in the JSON → direction.
|
||||
*/
|
||||
inputOnly?: boolean;
|
||||
}
|
||||
|
||||
export interface ConversionInput {
|
||||
@@ -57,7 +63,15 @@ export interface ReverseInput {
|
||||
sourceName?: string;
|
||||
}
|
||||
|
||||
export type ConversionResult = { ok: true; output: string } | { ok: false; error: string };
|
||||
export interface ConversionFailure {
|
||||
ok: false;
|
||||
error: string;
|
||||
/** 1-based position of an input syntax error, when the parser knows it. */
|
||||
line?: number;
|
||||
column?: number;
|
||||
}
|
||||
|
||||
export type ConversionResult = { ok: true; output: string } | ConversionFailure;
|
||||
|
||||
/**
|
||||
* Schema describing a single option field, used by the settings UI
|
||||
|
||||
@@ -162,6 +162,18 @@ describe('useConversionResult — small inputs (main thread)', () => {
|
||||
expect(result.current.inputErrorColumn).toBeNull();
|
||||
});
|
||||
|
||||
it('surfaces the position of a JSONC error', () => {
|
||||
const { result } = setup({
|
||||
input: '[\n 1, /* two */\n 2 3\n]',
|
||||
format: 'jsonc',
|
||||
direction: 'reverse',
|
||||
options: { indent: '2' },
|
||||
});
|
||||
expect(result.current.inputError).toEqual(expect.any(String));
|
||||
expect(result.current.inputErrorLine).toBe(3);
|
||||
expect(result.current.inputErrorColumn).toBe(5);
|
||||
});
|
||||
|
||||
it('re-converts when the options change', () => {
|
||||
const { result, rerender } = setup({
|
||||
input: '[{"a":1}]',
|
||||
|
||||
@@ -34,6 +34,15 @@ describe('useFileAccept', () => {
|
||||
expect(result.allowedExtensions).toEqual(['yaml', 'yml', 'txt']);
|
||||
});
|
||||
|
||||
it('accepts .jsonc and .json files for JSONC going back', () => {
|
||||
const result = accept('jsonc', 'reverse');
|
||||
expect(result.accept).toEqual({
|
||||
'application/jsonc': ['.jsonc', '.json'],
|
||||
'text/plain': ['.txt'],
|
||||
});
|
||||
expect(result.allowedExtensions).toEqual(['jsonc', 'json', 'txt']);
|
||||
});
|
||||
|
||||
it('keys the dropzone map by the format MIME type', () => {
|
||||
const result = accept('jsonl', 'reverse');
|
||||
expect(result.accept).toEqual({
|
||||
|
||||
@@ -33,10 +33,13 @@
|
||||
"title_rest": "JSON.",
|
||||
"copied": "Copied",
|
||||
"error_position": "Ln {{line}}, Col {{column}}",
|
||||
"jsonc_hint": "This looks like JSONC — JSON with comments or trailing commas.",
|
||||
"jsonc_switch": "Convert JSONC → JSON",
|
||||
"output_aria": "{{format}} output (read-only)"
|
||||
},
|
||||
"formats": {
|
||||
"jsonl": "JSONL",
|
||||
"jsonc": "JSONC",
|
||||
"csv": "CSV",
|
||||
"tsv": "TSV",
|
||||
"yaml": "YAML",
|
||||
@@ -53,7 +56,8 @@
|
||||
"ready": "Ready",
|
||||
"suggested": "Suggested for the detected shape",
|
||||
"not_suggested": "Not suggested for the detected shape",
|
||||
"no_reverse": "Reverse parse not supported for this format"
|
||||
"no_reverse": "Reverse parse not supported for this format",
|
||||
"input_only": "Input only: converts to JSON in the → JSON direction"
|
||||
},
|
||||
"direction": {
|
||||
"forward": "JSON →",
|
||||
@@ -66,6 +70,14 @@
|
||||
"pretty": "Pretty-print each line",
|
||||
"pretty_desc": "Canonical JSONL is single-line. Enable for human-readable multi-line records."
|
||||
},
|
||||
"jsonc": {
|
||||
"indent": "Output layout",
|
||||
"indent_desc": "Comments and trailing commas are removed; values, numbers and key order stay exactly as written.",
|
||||
"indent_2": "2 spaces",
|
||||
"indent_4": "4 spaces",
|
||||
"indent_tab": "Tab",
|
||||
"indent_minify": "Minified"
|
||||
},
|
||||
"csv": {
|
||||
"header": "Include header row",
|
||||
"header_desc": "Emit the first row as column names derived from object keys.",
|
||||
@@ -292,7 +304,7 @@
|
||||
"about": {
|
||||
"title": "About JSONPrism",
|
||||
"lead": "A refracting tool for developers.",
|
||||
"p1": "JSONPrism takes a single JSON input and disperses it into many target formats — like white light through a prism — and parses six of them back. Conversion runs entirely on your device, so the data you paste or drop never leaves it.",
|
||||
"p1": "JSONPrism takes a single JSON input and disperses it into many target formats — like white light through a prism — and parses six of them back, plus JSONC (JSON with comments) into plain JSON. Conversion runs entirely on your device, so the data you paste or drop never leaves it.",
|
||||
"p2": "Built with React 19, TypeScript 7, Vite 8, Tailwind CSS v4 and shadcn/ui. The web version is served by Cloudflare Workers; the desktop and Android apps are built with Tauri 2. Source on GitHub.",
|
||||
"version": "Version {{version}}",
|
||||
"donate": {
|
||||
|
||||
@@ -33,10 +33,13 @@
|
||||
"title_rest": "JSON。",
|
||||
"copied": "コピー済み",
|
||||
"error_position": "{{line}} 行 {{column}} 列",
|
||||
"jsonc_hint": "JSONC(コメントや末尾カンマを含む JSON)のようです。",
|
||||
"jsonc_switch": "JSONC → JSON に変換",
|
||||
"output_aria": "{{format}} の出力(読み取り専用)"
|
||||
},
|
||||
"formats": {
|
||||
"jsonl": "JSONL",
|
||||
"jsonc": "JSONC",
|
||||
"csv": "CSV",
|
||||
"tsv": "TSV",
|
||||
"yaml": "YAML",
|
||||
@@ -53,7 +56,8 @@
|
||||
"ready": "利用可能",
|
||||
"suggested": "検出されたデータ形状に適しています",
|
||||
"not_suggested": "検出されたデータ形状には推奨されません",
|
||||
"no_reverse": "この形式は逆方向のパースに対応していません"
|
||||
"no_reverse": "この形式は逆方向のパースに対応していません",
|
||||
"input_only": "入力専用:→ JSON の方向で JSON に変換します"
|
||||
},
|
||||
"direction": {
|
||||
"forward": "JSON →",
|
||||
@@ -66,6 +70,14 @@
|
||||
"pretty": "各行を整形して出力",
|
||||
"pretty_desc": "標準の JSONL は 1 行 1 レコードです。人間が読みやすい複数行を希望する場合に有効化。"
|
||||
},
|
||||
"jsonc": {
|
||||
"indent": "出力レイアウト",
|
||||
"indent_desc": "コメントと末尾のカンマを取り除きます。値・数値・キーの順序は書かれたとおりに保たれます。",
|
||||
"indent_2": "スペース 2 つ",
|
||||
"indent_4": "スペース 4 つ",
|
||||
"indent_tab": "タブ",
|
||||
"indent_minify": "最小化"
|
||||
},
|
||||
"csv": {
|
||||
"header": "ヘッダー行を含める",
|
||||
"header_desc": "オブジェクトのキーから生成した列名を最初の行に出力します。",
|
||||
@@ -259,7 +271,7 @@
|
||||
"about": {
|
||||
"title": "JSONPrism について",
|
||||
"lead": "開発者のための分光ツール。",
|
||||
"p1": "JSONPrism はひとつの JSON 入力を、プリズムを通る白色光のように多くの形式へ分光し、そのうち 6 形式は JSON に戻すこともできます。変換はすべて端末上で行われるため、貼り付けたりドロップしたデータが外部に出ることはありません。",
|
||||
"p1": "JSONPrism はひとつの JSON 入力を、プリズムを通る白色光のように多くの形式へ分光し、そのうち 6 形式は JSON に戻すこともできます。JSONC(コメント付き JSON)も通常の JSON に変換できます。変換はすべて端末上で行われるため、貼り付けたりドロップしたデータが外部に出ることはありません。",
|
||||
"p2": "React 19、TypeScript 7、Vite 8、Tailwind CSS v4、shadcn/ui で構築。Web 版は Cloudflare Workers で配信され、デスクトップ版と Android 版は Tauri 2 で構築されています。ソースは GitHub にあります。",
|
||||
"version": "バージョン {{version}}",
|
||||
"donate": {
|
||||
|
||||
@@ -33,10 +33,13 @@
|
||||
"title_rest": "JSON.",
|
||||
"copied": "Đã chép",
|
||||
"error_position": "Dòng {{line}}, Cột {{column}}",
|
||||
"jsonc_hint": "Có vẻ đây là JSONC — JSON có comment hoặc dấu phẩy thừa.",
|
||||
"jsonc_switch": "Chuyển JSONC → JSON",
|
||||
"output_aria": "Kết quả {{format}} (chỉ đọc)"
|
||||
},
|
||||
"formats": {
|
||||
"jsonl": "JSONL",
|
||||
"jsonc": "JSONC",
|
||||
"csv": "CSV",
|
||||
"tsv": "TSV",
|
||||
"yaml": "YAML",
|
||||
@@ -53,7 +56,8 @@
|
||||
"ready": "Sẵn sàng",
|
||||
"suggested": "Gợi ý cho shape phát hiện được",
|
||||
"not_suggested": "Không gợi ý cho shape phát hiện được",
|
||||
"no_reverse": "Format này không hỗ trợ parse ngược"
|
||||
"no_reverse": "Format này không hỗ trợ parse ngược",
|
||||
"input_only": "Chỉ làm đầu vào: chuyển sang JSON ở chiều → JSON"
|
||||
},
|
||||
"direction": {
|
||||
"forward": "JSON →",
|
||||
@@ -66,6 +70,14 @@
|
||||
"pretty": "Pretty-print mỗi dòng",
|
||||
"pretty_desc": "JSONL chuẩn là một dòng một record. Bật cái này nếu muốn dạng dễ đọc nhiều dòng."
|
||||
},
|
||||
"jsonc": {
|
||||
"indent": "Bố cục output",
|
||||
"indent_desc": "Comment và dấu phẩy thừa bị bỏ; giá trị, số và thứ tự key giữ nguyên như bạn viết.",
|
||||
"indent_2": "2 dấu cách",
|
||||
"indent_4": "4 dấu cách",
|
||||
"indent_tab": "Tab",
|
||||
"indent_minify": "Thu gọn (minify)"
|
||||
},
|
||||
"csv": {
|
||||
"header": "Bao gồm dòng header",
|
||||
"header_desc": "Phát ra dòng đầu tiên là tên cột lấy từ key của object.",
|
||||
@@ -292,7 +304,7 @@
|
||||
"about": {
|
||||
"title": "Về JSONPrism",
|
||||
"lead": "Một công cụ tán sắc cho developer.",
|
||||
"p1": "JSONPrism nhận một đầu vào JSON và tán nó ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính — và đọc ngược được sáu trong số đó. Mọi chuyển đổi chạy hoàn toàn trên thiết bị của bạn, nên dữ liệu bạn dán hoặc thả vào không bao giờ rời khỏi máy.",
|
||||
"p1": "JSONPrism nhận một đầu vào JSON và tán nó ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính — và đọc ngược được sáu trong số đó, cùng với JSONC (JSON có comment) thành JSON thuần. Mọi chuyển đổi chạy hoàn toàn trên thiết bị của bạn, nên dữ liệu bạn dán hoặc thả vào không bao giờ rời khỏi máy.",
|
||||
"p2": "Xây dựng với React 19, TypeScript 7, Vite 8, Tailwind CSS v4 và shadcn/ui. Bản web chạy trên Cloudflare Workers; ứng dụng desktop và Android được xây dựng bằng Tauri 2. Mã nguồn trên GitHub.",
|
||||
"version": "Phiên bản {{version}}",
|
||||
"donate": {
|
||||
|
||||
@@ -33,10 +33,13 @@
|
||||
"title_rest": "JSON。",
|
||||
"copied": "已复制",
|
||||
"error_position": "第 {{line}} 行,第 {{column}} 列",
|
||||
"jsonc_hint": "这看起来是 JSONC——带注释或尾随逗号的 JSON。",
|
||||
"jsonc_switch": "转换 JSONC → JSON",
|
||||
"output_aria": "{{format}} 输出(只读)"
|
||||
},
|
||||
"formats": {
|
||||
"jsonl": "JSONL",
|
||||
"jsonc": "JSONC",
|
||||
"csv": "CSV",
|
||||
"tsv": "TSV",
|
||||
"yaml": "YAML",
|
||||
@@ -53,7 +56,8 @@
|
||||
"ready": "可用",
|
||||
"suggested": "适用于检测到的数据形状",
|
||||
"not_suggested": "不推荐用于检测到的数据形状",
|
||||
"no_reverse": "此格式不支持反向解析"
|
||||
"no_reverse": "此格式不支持反向解析",
|
||||
"input_only": "仅作输入:在 → JSON 方向转换为 JSON"
|
||||
},
|
||||
"direction": {
|
||||
"forward": "JSON →",
|
||||
@@ -66,6 +70,14 @@
|
||||
"pretty": "美化每一行",
|
||||
"pretty_desc": "标准 JSONL 为每条记录一行。如需多行人类可读输出,请启用此项。"
|
||||
},
|
||||
"jsonc": {
|
||||
"indent": "输出布局",
|
||||
"indent_desc": "移除注释和尾随逗号;值、数字和键的顺序保持原样。",
|
||||
"indent_2": "2 个空格",
|
||||
"indent_4": "4 个空格",
|
||||
"indent_tab": "制表符",
|
||||
"indent_minify": "压缩"
|
||||
},
|
||||
"csv": {
|
||||
"header": "包含表头行",
|
||||
"header_desc": "以对象键作为列名输出第一行。",
|
||||
@@ -259,7 +271,7 @@
|
||||
"about": {
|
||||
"title": "关于 JSONPrism",
|
||||
"lead": "为开发者打造的分光工具。",
|
||||
"p1": "JSONPrism 将一个 JSON 输入分解为多种目标格式——就像白光穿过棱镜——其中六种格式还能转换回 JSON。所有转换都在你的设备上完成,你粘贴或拖入的数据绝不会离开设备。",
|
||||
"p1": "JSONPrism 将一个 JSON 输入分解为多种目标格式——就像白光穿过棱镜——其中六种格式还能转换回 JSON,JSONC(带注释的 JSON)也能转为标准 JSON。所有转换都在你的设备上完成,你粘贴或拖入的数据绝不会离开设备。",
|
||||
"p2": "基于 React 19、TypeScript 7、Vite 8、Tailwind CSS v4 和 shadcn/ui 构建。网页版由 Cloudflare Workers 提供服务;桌面版和 Android 版使用 Tauri 2 构建。源代码托管在 GitHub。",
|
||||
"version": "版本 {{version}}",
|
||||
"donate": {
|
||||
|
||||
@@ -62,6 +62,16 @@ describe('runConversion', () => {
|
||||
).toBe('input-error');
|
||||
});
|
||||
|
||||
it('passes a reverse error position through when the parser knows it', () => {
|
||||
const { outcome } = runConversion({
|
||||
text: '// config\n{"a": 1 "b": 2}',
|
||||
format: 'jsonc',
|
||||
direction: 'reverse',
|
||||
options: { indent: '2' },
|
||||
});
|
||||
expect(outcome).toMatchObject({ kind: 'input-error', line: 2, column: 9 });
|
||||
});
|
||||
|
||||
it('flags precision loss on huge integers', () => {
|
||||
const { outcome } = runConversion({
|
||||
text: '{"id": 12345678901234567890}',
|
||||
|
||||
@@ -6,6 +6,7 @@ import { editorLanguageFor, outputLanguageFor } from '../editor-language';
|
||||
/** Expected CodeMirror language for text written in each format. */
|
||||
const FORMAT_LANGUAGE: Record<FormatId, string> = {
|
||||
jsonl: 'jsonl',
|
||||
jsonc: 'jsonc',
|
||||
csv: 'plain',
|
||||
tsv: 'plain',
|
||||
yaml: 'yaml',
|
||||
|
||||
+15
-9
@@ -71,15 +71,21 @@ function convertOnce({
|
||||
if (direction === 'reverse') {
|
||||
if (typeof converter.reverse !== 'function') return { kind: 'no-reverse' };
|
||||
const result = safeReverse(converter, { text, ...(sourceName ? { sourceName } : {}) }, options);
|
||||
return result.ok
|
||||
? {
|
||||
kind: 'ok',
|
||||
output: result.output,
|
||||
shape: null,
|
||||
precisionLoss: false,
|
||||
outputBytes: utf8ByteLength(result.output),
|
||||
}
|
||||
: { kind: 'input-error', message: result.error };
|
||||
if (!result.ok) {
|
||||
return {
|
||||
kind: 'input-error',
|
||||
message: result.error,
|
||||
...(result.line !== undefined ? { line: result.line } : {}),
|
||||
...(result.column !== undefined ? { column: result.column } : {}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: 'ok',
|
||||
output: result.output,
|
||||
shape: null,
|
||||
precisionLoss: false,
|
||||
outputBytes: utf8ByteLength(result.output),
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseCached(text);
|
||||
|
||||
+1
-1
@@ -92,7 +92,7 @@ export function errorPosition(
|
||||
return offsetToLineColumn(text, offset);
|
||||
}
|
||||
|
||||
function offsetToLineColumn(text: string, offset: number): { line: number; column: number } {
|
||||
export function offsetToLineColumn(text: string, offset: number): { line: number; column: number } {
|
||||
let line = 1;
|
||||
let column = 1;
|
||||
const end = Math.min(offset, text.length);
|
||||
|
||||
@@ -11,6 +11,8 @@ function languageOfFormat(format: FormatId): EditorLanguage {
|
||||
return 'xml';
|
||||
case 'jsonl':
|
||||
return 'jsonl';
|
||||
case 'jsonc':
|
||||
return 'jsonc';
|
||||
case 'markdown':
|
||||
return 'markdown';
|
||||
case 'sql':
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { useWorkspaceStore } from '../workspaceStore';
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -51,3 +51,26 @@ describe('workspaceStore', () => {
|
||||
expect(useWorkspaceStore.getState().optionsByFormat['jsonl']).toEqual({ pretty: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('workspaceStore initial state', () => {
|
||||
/** The store reads storage once, at module load — import a fresh copy per scenario. */
|
||||
async function loadStore() {
|
||||
vi.resetModules();
|
||||
const { useWorkspaceStore: store } = await import('../workspaceStore');
|
||||
return store;
|
||||
}
|
||||
|
||||
it('restores the stored format and direction', async () => {
|
||||
window.localStorage.setItem('jsonprism.selected_format', 'yaml');
|
||||
window.localStorage.setItem('jsonprism.direction', 'reverse');
|
||||
const store = await loadStore();
|
||||
expect(store.getState()).toMatchObject({ format: 'yaml', direction: 'reverse' });
|
||||
});
|
||||
|
||||
it('opens an input-only format in the → JSON direction', async () => {
|
||||
window.localStorage.setItem('jsonprism.selected_format', 'jsonc');
|
||||
window.localStorage.setItem('jsonprism.direction', 'forward');
|
||||
const store = await loadStore();
|
||||
expect(store.getState()).toMatchObject({ format: 'jsonc', direction: 'reverse' });
|
||||
});
|
||||
});
|
||||
@@ -45,13 +45,15 @@ function readInitialFormat(): FormatId {
|
||||
return isFormatId(stored) ? stored : DEFAULT_FORMAT;
|
||||
}
|
||||
|
||||
function readInitialDirection(): Direction {
|
||||
function readInitialDirection(format: FormatId): Direction {
|
||||
// An input-only format (JSONC) has no JSON → direction.
|
||||
if (getConverter(format).meta.inputOnly) return 'reverse';
|
||||
return safeGetItem(STORAGE_DIRECTION_KEY) === 'reverse' ? 'reverse' : 'forward';
|
||||
}
|
||||
|
||||
export const useWorkspaceStore = create<WorkspaceState>((set, get) => {
|
||||
const initialFormat = readInitialFormat();
|
||||
const initialDirection = readInitialDirection();
|
||||
const initialDirection = readInitialDirection(initialFormat);
|
||||
const initialOptions: Record<string, Record<string, unknown>> = {
|
||||
[initialFormat]: loadOptions(initialFormat, getConverter(initialFormat)),
|
||||
};
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { WorkerEnv } from '../env';
|
||||
import worker from '../index';
|
||||
import { handleVerify, VERIFIED_TTL_MS, type WorkerEnv } from '../verify';
|
||||
import { handleVerify, VERIFIED_TTL_MS } from '../verify';
|
||||
import { TEST_SECRET } from '../turnstile';
|
||||
|
||||
/** What the runtime hands the Worker: a Request carrying Cloudflare's `cf` properties. */
|
||||
type IncomingRequest = Parameters<typeof worker.fetch>[0];
|
||||
|
||||
const ORIGIN = 'https://jsonprism.poli0981.dev';
|
||||
const URL_VERIFY = `${ORIGIN}/api/turnstile/verify`;
|
||||
|
||||
const assetsFetch = vi.fn(async () => new Response('<!doctype html>'));
|
||||
|
||||
function env(overrides: Partial<WorkerEnv> = {}): WorkerEnv {
|
||||
return {
|
||||
ASSETS: {} as Fetcher,
|
||||
ASSETS: { fetch: assetsFetch } as unknown as Fetcher,
|
||||
ALLOWED_HOSTNAMES: 'jsonprism.poli0981.dev',
|
||||
TURNSTILE_SECRET: 'real-secret',
|
||||
...overrides,
|
||||
@@ -17,7 +23,7 @@ function env(overrides: Partial<WorkerEnv> = {}): WorkerEnv {
|
||||
|
||||
function verifyRequest(
|
||||
init: { body?: string; headers?: Record<string, string>; method?: string } = {},
|
||||
) {
|
||||
): IncomingRequest {
|
||||
return new Request(URL_VERIFY, {
|
||||
method: init.method ?? 'POST',
|
||||
headers: { Origin: ORIGIN, 'Content-Type': 'application/json', ...init.headers },
|
||||
@@ -27,6 +33,13 @@ function verifyRequest(
|
||||
|
||||
const call = (request: Request, e: WorkerEnv = env()) => handleVerify(request, e);
|
||||
|
||||
/** A limiter that allows the first `allowed` calls, like Cloudflare's binding once a client is over. */
|
||||
function limiter(allowed = Infinity) {
|
||||
let calls = 0;
|
||||
const limit = vi.fn(async (_options: RateLimitOptions) => ({ success: ++calls <= allowed }));
|
||||
return { limit } as RateLimit & { limit: typeof limit };
|
||||
}
|
||||
|
||||
let siteverify: ReturnType<typeof vi.fn<typeof fetch>>;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -151,4 +164,80 @@ describe('router', () => {
|
||||
const missing = await worker.fetch(new Request(`${ORIGIN}/api/nope`), env());
|
||||
expect(missing.status).toBe(404);
|
||||
});
|
||||
|
||||
it('hands pages and public files to the ASSETS binding', async () => {
|
||||
const page: IncomingRequest = new Request(`${ORIGIN}/about`);
|
||||
const res = await worker.fetch(page, env());
|
||||
expect(await res.text()).toBe('<!doctype html>');
|
||||
expect(assetsFetch).toHaveBeenCalledWith(page);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rate limiting', () => {
|
||||
const fromClient = (path: string): IncomingRequest =>
|
||||
new Request(`${ORIGIN}${path}`, { headers: { 'CF-Connecting-IP': '203.0.113.9' } });
|
||||
|
||||
it('counts pages against SITE_LIMITER and answers 429 in plain text once over', async () => {
|
||||
const site = limiter(2);
|
||||
const api = limiter();
|
||||
const e = env({ SITE_LIMITER: site, API_LIMITER: api });
|
||||
expect((await worker.fetch(fromClient('/'), e)).status).toBe(200);
|
||||
expect((await worker.fetch(fromClient('/theme-init.js'), e)).status).toBe(200);
|
||||
const res = await worker.fetch(fromClient('/'), e);
|
||||
expect(res.status).toBe(429);
|
||||
expect(res.headers.get('Retry-After')).toBe('60');
|
||||
expect(res.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8');
|
||||
expect(await res.text()).toContain('Too many requests');
|
||||
expect(assetsFetch).toHaveBeenCalledTimes(2);
|
||||
expect(site.limit).toHaveBeenCalledWith({ key: '203.0.113.9' });
|
||||
expect(api.limit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('counts every /api/* request against API_LIMITER and answers JSON 429', async () => {
|
||||
const site = limiter();
|
||||
const api = limiter(1);
|
||||
const e = env({ SITE_LIMITER: site, API_LIMITER: api });
|
||||
expect((await worker.fetch(fromClient('/api/health'), e)).status).toBe(200);
|
||||
for (const path of ['/api/health', '/api/nope', '/api/turnstile/verify']) {
|
||||
const res = await worker.fetch(fromClient(path), e);
|
||||
expect(res.status).toBe(429);
|
||||
expect(res.headers.get('Retry-After')).toBe('60');
|
||||
expect(await res.json()).toEqual({ ok: false, error: 'rate_limited' });
|
||||
}
|
||||
expect(siteverify).not.toHaveBeenCalled();
|
||||
expect(site.limit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies VERIFY_LIMITER on top of API_LIMITER', async () => {
|
||||
const api = limiter();
|
||||
const verify = limiter(0);
|
||||
const res = await worker.fetch(
|
||||
verifyRequest({ headers: { 'CF-Connecting-IP': '203.0.113.9' } }),
|
||||
env({ API_LIMITER: api, VERIFY_LIMITER: verify }),
|
||||
);
|
||||
expect(res.status).toBe(429);
|
||||
expect(api.limit).toHaveBeenCalledOnce();
|
||||
expect(verify.limit).toHaveBeenCalledWith({ key: '203.0.113.9' });
|
||||
});
|
||||
|
||||
it('lets requests through when the limiter itself fails', async () => {
|
||||
const broken = {
|
||||
limit: vi.fn().mockRejectedValue(new Error('backend down')),
|
||||
} as unknown as RateLimit;
|
||||
const res = await worker.fetch(fromClient('/'), env({ SITE_LIMITER: broken }));
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it('never logs the client address', async () => {
|
||||
const log = vi.mocked(console.log);
|
||||
await worker.fetch(fromClient('/'), env({ SITE_LIMITER: limiter(0) }));
|
||||
await worker.fetch(fromClient('/api/health'), env({ API_LIMITER: limiter(0) }));
|
||||
const lines = log.mock.calls.map((args) => String(args[0]));
|
||||
expect(lines).toHaveLength(2);
|
||||
for (const line of lines) {
|
||||
expect(JSON.parse(line)).toMatchObject({ event: 'ratelimit.exceeded' });
|
||||
expect(line).not.toContain('203.0.113.9');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { clientKey } from '../rate-limit';
|
||||
|
||||
const from = (ip?: string) =>
|
||||
new Request('https://jsonprism.poli0981.dev/', {
|
||||
headers: ip === undefined ? {} : { 'CF-Connecting-IP': ip },
|
||||
});
|
||||
|
||||
describe('clientKey', () => {
|
||||
it('keys IPv4 clients on the full address', () => {
|
||||
expect(clientKey(from('203.0.113.9'))).toBe('203.0.113.9');
|
||||
});
|
||||
|
||||
it('keys IPv6 clients on their /64 network', () => {
|
||||
const a = clientKey(from('2001:db8:85a3:42:1:2:3:4'));
|
||||
expect(a).toBe('2001:db8:85a3:42::/64');
|
||||
expect(clientKey(from('2001:db8:85a3:42:ffff::1'))).toBe(a);
|
||||
expect(clientKey(from('2001:DB8:85A3:0042::9'))).toBe(a);
|
||||
expect(clientKey(from('2001:db8:85a3:43::1'))).not.toBe(a);
|
||||
});
|
||||
|
||||
it('expands :: wherever it appears', () => {
|
||||
expect(clientKey(from('2001:db8::1'))).toBe('2001:db8:0:0::/64');
|
||||
expect(clientKey(from('::1'))).toBe('0:0:0:0::/64');
|
||||
expect(clientKey(from('2001:db8:1:2::'))).toBe('2001:db8:1:2::/64');
|
||||
});
|
||||
|
||||
it('keeps IPv4-mapped IPv6 addresses whole', () => {
|
||||
expect(clientKey(from('::ffff:192.0.2.1'))).toBe('::ffff:192.0.2.1');
|
||||
});
|
||||
|
||||
it('falls back to a shared key without the header', () => {
|
||||
expect(clientKey(from())).toBe('unknown');
|
||||
expect(clientKey(from(''))).toBe('unknown');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
/** Bindings and vars the Worker reads (declared in wrangler.jsonc). */
|
||||
export interface WorkerEnv {
|
||||
ASSETS: Fetcher;
|
||||
/** Comma-separated hostnames a token may have been issued on. */
|
||||
ALLOWED_HOSTNAMES: string;
|
||||
/** Secret set in the Cloudflare dashboard (.dev.vars locally). */
|
||||
TURNSTILE_SECRET?: string | undefined;
|
||||
/** Pages and public files: everything outside /api/ and the hashed /assets/ bundles. */
|
||||
SITE_LIMITER?: RateLimit;
|
||||
/** Every /api/* request. */
|
||||
API_LIMITER?: RateLimit;
|
||||
/** /api/turnstile/verify on top of API_LIMITER. */
|
||||
VERIFY_LIMITER?: RateLimit;
|
||||
}
|
||||
+18
-4
@@ -1,7 +1,6 @@
|
||||
/** JSON responses for the API routes, with defensive headers (assets get theirs from public/_headers). */
|
||||
/** Responses the Worker builds itself, with defensive headers (assets get theirs from public/_headers). */
|
||||
|
||||
const API_HEADERS: Record<string, string> = {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
const BASE_HEADERS: Record<string, string> = {
|
||||
'Cache-Control': 'no-store',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
@@ -16,7 +15,22 @@ export function json(
|
||||
): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { ...API_HEADERS, ...extraHeaders },
|
||||
headers: {
|
||||
...BASE_HEADERS,
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
...extraHeaders,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function text(
|
||||
body: string,
|
||||
status: number,
|
||||
extraHeaders: Record<string, string> = {},
|
||||
): Response {
|
||||
return new Response(body, {
|
||||
status,
|
||||
headers: { ...BASE_HEADERS, 'Content-Type': 'text/plain; charset=utf-8', ...extraHeaders },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+14
-4
@@ -1,18 +1,28 @@
|
||||
/**
|
||||
* JSONPrism edge Worker. Static assets (the SPA) are served by Workers Static
|
||||
* Assets before this code runs; `run_worker_first: ["/api/*"]` routes only the
|
||||
* API here. Conversion never happens server-side.
|
||||
* JSONPrism edge Worker. `run_worker_first` sends every request here except the
|
||||
* hashed bundles under /assets/, which Workers Static Assets serves directly.
|
||||
* Each request is counted against a per-client rate limit first; pages and
|
||||
* public files are then handed to the ASSETS binding (which still applies
|
||||
* public/_headers, public/_redirects and the SPA fallback), and /api/* is
|
||||
* answered here. Conversion never happens server-side.
|
||||
*
|
||||
* Only the default export may live in this module: workerd treats every named
|
||||
* export of the entry module as an entrypoint and refuses to start otherwise.
|
||||
*/
|
||||
|
||||
import type { WorkerEnv } from './env';
|
||||
import { json } from './http';
|
||||
import { handleVerify, type WorkerEnv } from './verify';
|
||||
import { throttle } from './rate-limit';
|
||||
import { handleVerify } from './verify';
|
||||
|
||||
export default {
|
||||
async fetch(request, env): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
if (!url.pathname.startsWith('/api/')) {
|
||||
return (await throttle(request, env.SITE_LIMITER, 'site')) ?? env.ASSETS.fetch(request);
|
||||
}
|
||||
const limited = await throttle(request, env.API_LIMITER, 'api');
|
||||
if (limited) return limited;
|
||||
switch (url.pathname) {
|
||||
case '/api/turnstile/verify':
|
||||
return handleVerify(request, env);
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Per-client throttles. Every request except the hashed bundles under /assets/
|
||||
* reaches the Worker (`run_worker_first` in wrangler.jsonc): pages and public
|
||||
* files count against SITE_LIMITER, /api/* against API_LIMITER, and the
|
||||
* human-check endpoint also against its own VERIFY_LIMITER.
|
||||
*
|
||||
* Cloudflare's counts are approximate: each edge machine checks a locally
|
||||
* cached per-data-centre count that syncs in the background, so a burst
|
||||
* spread over many fresh connections can pass well beyond the limit before
|
||||
* the 429s start (see docs/DEPLOYMENT.md). The limits throttle browsers,
|
||||
* crawlers and simple scripts; people never get near them.
|
||||
*/
|
||||
|
||||
import { json, logEvent, text } from './http';
|
||||
|
||||
/** Every limiter uses a 60-second period, so a minute is always enough. */
|
||||
const RETRY_AFTER = '60';
|
||||
|
||||
/** The SPA isn't loaded yet when a page is refused, so the edge answers in all four UI languages. */
|
||||
const SITE_MESSAGE = [
|
||||
'Too many requests. Wait a minute, then try again.',
|
||||
'Quá nhiều yêu cầu. Vui lòng đợi một phút rồi thử lại.',
|
||||
'リクエストが多すぎます。1 分ほど待ってから、もう一度お試しください。',
|
||||
'请求过多。请等待一分钟后再试。',
|
||||
].join('\n');
|
||||
|
||||
type LimitScope = 'site' | 'api';
|
||||
|
||||
/**
|
||||
* The limiter key: the client's IPv4 address, or the /64 network of an IPv6
|
||||
* address — one subscriber usually holds a whole /64 and could otherwise
|
||||
* rotate through it. Only ever a key; never logged.
|
||||
*/
|
||||
export function clientKey(request: Request): string {
|
||||
const ip = request.headers.get('CF-Connecting-IP')?.trim().toLowerCase();
|
||||
if (!ip) return 'unknown';
|
||||
// IPv4, or IPv6 with an embedded IPv4 tail (::ffff:192.0.2.1): keep it whole.
|
||||
if (!ip.includes(':') || ip.includes('.')) return ip;
|
||||
const [head = '', tail] = ip.split('::');
|
||||
const left = head ? head.split(':') : [];
|
||||
const right = tail ? tail.split(':') : [];
|
||||
const groups =
|
||||
tail === undefined
|
||||
? left
|
||||
: [
|
||||
...left,
|
||||
...Array<string>(Math.max(0, 8 - left.length - right.length)).fill('0'),
|
||||
...right,
|
||||
];
|
||||
const prefix = groups.slice(0, 4).map((group) => Number.parseInt(group, 16).toString(16));
|
||||
return `${prefix.join(':')}::/64`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts the request. Returns the 429 response when the client is over the
|
||||
* limit, otherwise null. Without the binding (unit tests) or when the limiter
|
||||
* itself fails, the request goes through: a broken counter must not take the
|
||||
* site down.
|
||||
*/
|
||||
export async function throttle(
|
||||
request: Request,
|
||||
limiter: RateLimit | undefined,
|
||||
scope: LimitScope,
|
||||
): Promise<Response | null> {
|
||||
if (!limiter) return null;
|
||||
const colo = (request.cf as { colo?: string } | undefined)?.colo;
|
||||
let success: boolean;
|
||||
try {
|
||||
({ success } = await limiter.limit({ key: clientKey(request) }));
|
||||
} catch (error) {
|
||||
logEvent('ratelimit.error', {
|
||||
scope,
|
||||
colo,
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
if (success) return null;
|
||||
logEvent('ratelimit.exceeded', { scope, colo });
|
||||
const headers = { 'Retry-After': RETRY_AFTER };
|
||||
return scope === 'api'
|
||||
? json({ ok: false, error: 'rate_limited' }, 429, headers)
|
||||
: text(SITE_MESSAGE, 429, headers);
|
||||
}
|
||||
+4
-12
@@ -7,18 +7,11 @@
|
||||
* public static files, so there is no server resource it unlocks.
|
||||
*/
|
||||
|
||||
import type { WorkerEnv } from './env';
|
||||
import { json, logEvent } from './http';
|
||||
import { clientKey } from './rate-limit';
|
||||
import { MAX_TOKEN_LENGTH, TEST_SECRET, verifyTurnstileToken } from './turnstile';
|
||||
|
||||
export interface WorkerEnv {
|
||||
ASSETS: Fetcher;
|
||||
/** Comma-separated hostnames a token may have been issued on. */
|
||||
ALLOWED_HOSTNAMES: string;
|
||||
/** Secret set in the Cloudflare dashboard (.dev.vars locally). */
|
||||
TURNSTILE_SECRET?: string | undefined;
|
||||
VERIFY_LIMITER?: RateLimit;
|
||||
}
|
||||
|
||||
/** Keep in sync with src/lib/turnstile.ts (TURNSTILE_ACTION). */
|
||||
const TURNSTILE_ACTION = 'gate';
|
||||
/** How long the browser may trust a passed check. Keep in sync with src/lib/human-check-storage.ts. */
|
||||
@@ -109,9 +102,8 @@ export async function handleVerify(request: Request, env: WorkerEnv): Promise<Re
|
||||
}
|
||||
|
||||
if (env.VERIFY_LIMITER) {
|
||||
// Generous per-client throttle; shared IPs (NAT, mobile carriers) still fit.
|
||||
const key = request.headers.get('CF-Connecting-IP') ?? 'unknown';
|
||||
const { success } = await env.VERIFY_LIMITER.limit({ key });
|
||||
// Stricter than API_LIMITER, still generous: shared IPs (NAT, mobile carriers) fit.
|
||||
const { success } = await env.VERIFY_LIMITER.limit({ key: clientKey(request) });
|
||||
if (!success) return finish(429, { ok: false, error: 'rate_limited' }, 'rate-limited');
|
||||
}
|
||||
|
||||
|
||||
+36
-5
@@ -3,8 +3,10 @@
|
||||
// Workers Builds (configured in the Cloudflare dashboard) runs
|
||||
// `npx wrangler deploy` on every push to `main`; the "build" section below runs
|
||||
// `npm run build` first. The Worker serves the Vite build from ./dist as static
|
||||
// assets (SPA fallback to index.html) and only runs code for /api/* — today
|
||||
// the Turnstile verification endpoint and a health check.
|
||||
// assets (SPA fallback to index.html). Every request except the hashed bundles
|
||||
// under /assets/ runs the Worker first, which rate limits it per client, then
|
||||
// hands pages to the ASSETS binding or answers /api/* itself (the Turnstile
|
||||
// verification endpoint and a health check).
|
||||
//
|
||||
// Secrets (set in the dashboard, never committed):
|
||||
// TURNSTILE_SECRET — Turnstile widget secret for jsonprism.poli0981.dev
|
||||
@@ -24,15 +26,34 @@
|
||||
"directory": "./dist",
|
||||
"binding": "ASSETS",
|
||||
"not_found_handling": "single-page-application",
|
||||
"run_worker_first": ["/api/*"]
|
||||
// Everything except /assets/* (content-hashed, immutable, the bulk of each
|
||||
// page load) goes through the Worker so it can be rate limited. Requests
|
||||
// that reach the Worker are billed as Worker requests; /assets/* stays free.
|
||||
"run_worker_first": ["/*", "!/assets/*"]
|
||||
},
|
||||
"vars": {
|
||||
// Comma-separated hostnames a Turnstile token may have been issued on.
|
||||
"ALLOWED_HOSTNAMES": "jsonprism.poli0981.dev"
|
||||
},
|
||||
// Per-client throttles (IPv4 address or IPv6 /64), counted per Cloudflare
|
||||
// data centre. Over the limit → 429 with Retry-After: 60. namespace_id must
|
||||
// be unique within the account; previews use the even twins below.
|
||||
"ratelimits": [
|
||||
{
|
||||
// Per-IP throttle for /api/turnstile/verify.
|
||||
// Pages and public files (index.html, theme-init.js, favicon…): about
|
||||
// three per page load, so 40 page loads a minute per client.
|
||||
"name": "SITE_LIMITER",
|
||||
"namespace_id": "4205",
|
||||
"simple": { "limit": 120, "period": 60 }
|
||||
},
|
||||
{
|
||||
// Every /api/* request.
|
||||
"name": "API_LIMITER",
|
||||
"namespace_id": "4203",
|
||||
"simple": { "limit": 60, "period": 60 }
|
||||
},
|
||||
{
|
||||
// /api/turnstile/verify, on top of API_LIMITER.
|
||||
"name": "VERIFY_LIMITER",
|
||||
"namespace_id": "4201",
|
||||
"simple": { "limit": 30, "period": 60 }
|
||||
@@ -40,7 +61,7 @@
|
||||
],
|
||||
// Workers Builds runs `npx wrangler preview` for non-production branches.
|
||||
// Previews inherit no vars or bindings, so they are declared again here:
|
||||
// a separate rate-limit counter, and no hostnames for the human check —
|
||||
// separate rate-limit counters, and no hostnames for the human check —
|
||||
// previews get no TURNSTILE_SECRET either, so the check reports
|
||||
// "unavailable" and lets testers continue. Web Analytics only loads on the
|
||||
// production hostname.
|
||||
@@ -49,6 +70,16 @@
|
||||
"ALLOWED_HOSTNAMES": ""
|
||||
},
|
||||
"ratelimits": [
|
||||
{
|
||||
"name": "SITE_LIMITER",
|
||||
"namespace_id": "4206",
|
||||
"simple": { "limit": 120, "period": 60 }
|
||||
},
|
||||
{
|
||||
"name": "API_LIMITER",
|
||||
"namespace_id": "4204",
|
||||
"simple": { "limit": 60, "period": 60 }
|
||||
},
|
||||
{
|
||||
"name": "VERIFY_LIMITER",
|
||||
"namespace_id": "4202",
|
||||
|
||||
Reference in new issue
Block a user