3 Commits
Author SHA1 Message Date
poli0981andClaude Opus 4.7 8a27c5c969 fix(tauri): set File.lastModified from stat() so batch dedup works (v1.3.3) (#27)
`fileFromNativePath` was calling `new File([text], name, { type })`
without `lastModified`. The File API defaults `lastModified` to
`Date.now()` at construction time, so reading the same path twice
produced two File objects with different timestamps — and `batchStore`
dedups on `(name, size, lastModified)`, so dropping the same file
twice through Tauri native drag-drop / native picker added both
copies to the queue with no `duplicate` toast. Web wasn't affected
because `<input type="file">` and `react-dropzone` build File objects
from the OS mtime.

Fix: call `stat()` from `@tauri-apps/plugin-fs` and pass
`mtime.getTime()` into the File constructor. Fall back to an FNV-1a
hash of the path if stat throws (capability missing, file vanished
between read and stat) so repeat drops still dedup.

Also infer `type` from the extension instead of hard-coding
`application/json`. Add `fs:allow-stat` to the default capability.

3 new unit tests for `pathHashAsMillis`. Total: 193.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 20:33:12 +07:00
poli0981andClaude Opus 4.7 58ef7e739a fix(tauri): port batch extension filter to native drag-drop (v1.3.2) (#24)
The v1.3.0/v1.3.1 desktop bundles accepted any file dropped from File
Explorer / Finder / Nautilus into the workspace, because
`ConverterWorkspace.handleMultiFileDrop` (called by `useTauriDragDrop`
on `tauri://drag-drop` events) ran `batchStore.addFiles` directly and
skipped the `direction × format` extension whitelist that the
`react-dropzone` path in `BatchPanel` / `InputPanel` enforced. Files
like `.cs` / `.py` leaked into the queue with no `wrong_format` toast.

Extract `src/lib/file-filter.ts` exposing `getAllowedExtensions`,
`extOf`, and `filterByExtension` so all three drop entry points share
one implementation. The web `react-dropzone` paths keep their previous
behavior; the Tauri callback now filters + toasts before calling
`addFiles`.

Bump package / Cargo / Tauri version to 1.3.2.

7 new unit tests cover the helper. Total: 190.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 20:05:44 +07:00
poli0981andClaude Opus 4.7 4bf239e089 fix(workflow): announce-discussion unbound var + literal $VAR text (#21)
Two bugs in `.github/workflows/announce-discussion.yml` surfaced when
v1.3.1 published:

1. `DEPLOY_URL: unbound variable` when triggered by `release` event.
   `${{ github.event.workflow_run.* }}` evaluates to null on a release
   event, and the resulting env-var assignment leaves the variable
   unset (not empty), which `set -u` then trips on. Guard every
   dynamic value with `|| ''` so each env var is always at least an
   empty string.

2. Body strings used `$'...'` ANSI-C quoting (which expands backslash
   escapes but NOT variables), so the discussion body would have
   contained literal `$RELEASE_TAG` text. Rewrite to plain double-quoted
   strings, using `$'\n'` only for embedded newlines.

Also pass dynamic values (REPO_ID / CAT_ID / TITLE / BODY) into the
Create Discussion step through env vars instead of literal `${{ ... }}`
substitution — protects against titles/bodies containing quotes or
other shell-special characters that would otherwise break the command
line.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 18:32:59 +07:00
14 changed files with 244 additions and 39 deletions

No files matched your search

+31 -16
View File
@@ -76,30 +76,38 @@ jobs:
id: msg
env:
EVENT: ${{ github.event_name }}
RELEASE_TAG: ${{ github.event.release.tag_name }}
RELEASE_URL: ${{ github.event.release.html_url }}
RELEASE_BODY: ${{ github.event.release.body }}
DEPLOY_SHA: ${{ github.event.workflow_run.head_sha }}
DEPLOY_URL: ${{ github.event.workflow_run.html_url }}
DISPATCH_MSG: ${{ inputs.message }}
# `|| ''` guards each value so the env var is always set to an
# empty string (not unset) when the source field is missing for
# the active event type. Without this, `set -u` blows up below.
RELEASE_TAG: ${{ github.event.release.tag_name || '' }}
RELEASE_URL: ${{ github.event.release.html_url || '' }}
RELEASE_BODY: ${{ github.event.release.body || '' }}
DEPLOY_SHA: ${{ github.event.workflow_run.head_sha || '' }}
DEPLOY_URL: ${{ github.event.workflow_run.html_url || '' }}
DISPATCH_MSG: ${{ inputs.message || '' }}
run: |
set -euo pipefail
# NL is a literal newline used to assemble multi-line bodies
# without breaking the YAML literal-block-scalar indentation.
# Concatenating "$VAR""$NL""$NL""$OTHER" gives both interpolation
# AND embedded blank lines.
NL=$'\n'
case "$EVENT" in
release)
title="Release $RELEASE_TAG"
body=$'## $RELEASE_TAG\n\n$RELEASE_BODY\n\n[View release →]($RELEASE_URL)'
title="Release ${RELEASE_TAG}"
body="## ${RELEASE_TAG}${NL}${NL}${RELEASE_BODY}${NL}${NL}[View release →](${RELEASE_URL})"
;;
workflow_run)
short_sha="${DEPLOY_SHA:0:7}"
title="Deploy succeeded — $short_sha"
body=$'Latest commit deployed to GitHub Pages.\n\n[Deploy run →]($DEPLOY_URL)'
title="Deploy succeeded — ${short_sha}"
body="Latest commit deployed to GitHub Pages.${NL}${NL}[Deploy run →](${DEPLOY_URL})"
;;
workflow_dispatch)
title="Announcement"
body="$DISPATCH_MSG"
body="${DISPATCH_MSG}"
;;
*)
echo "::error::Unsupported event: $EVENT"
echo "::error::Unsupported event: ${EVENT}"
exit 1
;;
esac
@@ -115,6 +123,13 @@ jobs:
- name: Create Discussion
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Pass dynamic values through env vars (not literal `${{ ... }}`
# substitution) so a title/body containing quotes, backticks, or
# other shell-special characters doesn't break the command line.
REPO_ID: ${{ steps.ids.outputs.repo_id }}
CAT_ID: ${{ steps.ids.outputs.cat_id }}
TITLE: ${{ steps.msg.outputs.title }}
BODY: ${{ steps.msg.outputs.body }}
run: |
set -euo pipefail
MUTATION='mutation($repo: ID!, $cat: ID!, $title: String!, $body: String!) {
@@ -124,8 +139,8 @@ jobs:
}'
gh api graphql \
-f query="$MUTATION" \
-F repo="${{ steps.ids.outputs.repo_id }}" \
-F cat="${{ steps.ids.outputs.cat_id }}" \
-F title="${{ steps.msg.outputs.title }}" \
-F body="${{ steps.msg.outputs.body }}" \
-F repo="$REPO_ID" \
-F cat="$CAT_ID" \
-F title="$TITLE" \
-F body="$BODY" \
--jq '.data.createDiscussion.discussion.url'
+20
View File
@@ -8,6 +8,26 @@ 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 Phase 3".
## [1.3.3] — 2026-05-13
### Fixed
- **Tauri native drag-drop / file picker bỏ qua batch dedup**. v1.3.0–v1.3.2 desktop bundles cho phép drop cùng một file vào queue nhiều lần mà không hiển thị toast `duplicate`. Root cause: `fileFromNativePath` tạo `new File([text], name, { type })` không truyền `lastModified`, nên File API default về `Date.now()` mỗi lần gọi; key dedup của `batchStore` (`name|size|lastModified`) khác nhau giữa các lần drop cùng một file. Sửa: stat file qua `@tauri-apps/plugin-fs` để lấy mtime thật, fall back về hash FNV-1a của path nếu stat fail. Bonus: infer `type` từ extension thay vì hard-code `application/json`. Thêm permission `fs:allow-stat` vào default capability.
### Tests
- 3 unit test mới cho `pathHashAsMillis` trong `src/lib/__tests__/tauri.test.ts`. Total tests: **193**.
## [1.3.2] — 2026-05-13
### Fixed
- **Tauri native drag-drop bypassed the batch extension filter**. v1.3.0/v1.3.1 desktop bundles accepted any file dropped from File Explorer / Finder / Nautilus into the workspace, because `ConverterWorkspace.handleMultiFileDrop` called `batchStore.addFiles` directly — skipping the `direction × format` extension whitelist that the web `react-dropzone` path enforced. Files like `.cs`/`.py` leaked into the queue with no warning. Extracted `src/lib/file-filter.ts` (`getAllowedExtensions` + `extOf` + `filterByExtension`) and routed the Tauri callback, `BatchPanel`, and `InputPanel` through it so the wrong-format toast surfaces in all three entry points.
### Tests
- 7 new unit tests for `getAllowedExtensions`, `extOf`, and `filterByExtension` in `src/lib/__tests__/file-filter.test.ts`. Total tests: **190**.
## [1.3.1] — 2026-05-13
### Fixed
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "jsonprism",
"version": "1.3.1",
"version": "1.3.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "jsonprism",
"version": "1.3.1",
"version": "1.3.3",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/lang-json": "^6.0.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "jsonprism",
"private": true,
"version": "1.3.1",
"version": "1.3.3",
"type": "module",
"description": "Disperse JSON into many formats — JSONL, CSV, YAML, XML, TOML, RESX, Markdown, SQL — fully client-side.",
"author": "poli0981 <https://github.com/poli0981>",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "jsonprism"
version = "1.3.1"
version = "1.3.3"
description = "Disperse JSON into many formats."
authors = ["poli0981 <https://github.com/poli0981>"]
license = "Apache-2.0"
+1
View File
@@ -20,6 +20,7 @@
"fs:allow-read-text-file",
"fs:allow-write-text-file",
"fs:allow-write-file",
"fs:allow-stat",
{
"identifier": "fs:scope",
"allow": ["$HOME/**", "$DOCUMENT/**", "$DOWNLOAD/**", "$DESKTOP/**"]
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "JSONPrism",
"version": "1.3.1",
"version": "1.3.3",
"identifier": "com.poli0981.jsonprism",
"build": {
"beforeDevCommand": "npm run dev",
+6 -10
View File
@@ -13,6 +13,7 @@ import {
import { toast } from '@/components/ui/sonner';
import { useBatchStore, BATCH_MAX_FILES, type BatchItem } from '@/stores/batchStore';
import { processBatch, zipOutputs, downloadBlob } from '@/lib/batch-processor';
import { filterByExtension, getAllowedExtensions } from '@/lib/file-filter';
import { isTauri, nativeOpenFiles, nativeSaveBlob, fileFromNativePath } from '@/lib/tauri';
import { getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
@@ -68,19 +69,14 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
// Whitelist of file extensions that match the current direction × format.
// The browser's native `<input accept>` is only a hint, so we re-validate
// in JS to reject files chosen via "Browse" with "All files" filter.
const allowedExtensions = useMemo(() => {
return isReverse ? [converter.meta.extension.toLowerCase(), 'txt'] : ['json', 'txt'];
}, [isReverse, converter.meta.extension]);
const allowedExtensions = useMemo(
() => getAllowedExtensions(isReverse ? 'reverse' : 'forward', converter.meta.extension),
[isReverse, converter.meta.extension],
);
const handleAddFiles = useCallback(
(files: File[]) => {
const valid: File[] = [];
let wrongFormat = 0;
for (const f of files) {
const ext = (f.name.split('.').pop() ?? '').toLowerCase();
if (allowedExtensions.includes(ext)) valid.push(f);
else wrongFormat += 1;
}
const { valid, wrongFormat } = filterByExtension(files, allowedExtensions);
if (wrongFormat > 0) {
toast.warning(t('batch.toast.wrong_format', { count: wrongFormat }));
}
@@ -4,6 +4,7 @@ import { toast } from '@/components/ui/sonner';
import { getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
import { parseJsonInput } from '@/lib/detect';
import { filterByExtension, getAllowedExtensions } from '@/lib/file-filter';
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts';
import { useTauriDragDrop } from '@/hooks/useTauriDragDrop';
import { useBatchStore } from '@/stores/batchStore';
@@ -39,7 +40,16 @@ export function ConverterWorkspace() {
const handleMultiFileDrop = useCallback(
(files: File[]) => {
const result = addBatchFiles(files);
const allowed = getAllowedExtensions(
direction === 'reverse' ? 'reverse' : 'forward',
getConverter(format).meta.extension,
);
const { valid, wrongFormat } = filterByExtension(files, allowed);
if (wrongFormat > 0) {
toast.warning(t('batch.toast.wrong_format', { count: wrongFormat }));
}
if (valid.length === 0) return;
const result = addBatchFiles(valid);
if (result.added > 0) {
toast.success(t('batch.toast.added', { count: result.added }));
setBatchOpen(true);
@@ -52,7 +62,7 @@ export function ConverterWorkspace() {
}
}
},
[addBatchFiles, t],
[addBatchFiles, direction, format, t],
);
// Native OS drag-drop bridge (no-op outside Tauri).
+3 -5
View File
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { useDropzone } from 'react-dropzone';
import { Eraser, FileText, FolderOpen } from 'lucide-react';
import { toast } from '@/components/ui/sonner';
import { extOf, getAllowedExtensions } from '@/lib/file-filter';
import { SAMPLE_JSON } from '@/lib/sample';
import { isTauri, nativeOpenFiles, fileFromNativePath } from '@/lib/tauri';
import { getConverter } from '@/converters/registry';
@@ -70,15 +71,12 @@ export function InputPanel({
// Allowed extensions for the single-file "Open" / drag-drop path.
// `<input accept>` is only a hint to the OS picker — re-validate in JS.
const allowedExtensions = useMemo(
() => (isReverse ? [converter.meta.extension.toLowerCase(), 'txt'] : ['json', 'txt']),
() => getAllowedExtensions(isReverse ? 'reverse' : 'forward', converter.meta.extension),
[isReverse, converter.meta.extension],
);
const hasAllowedExt = useCallback(
(name: string) => {
const ext = (name.split('.').pop() ?? '').toLowerCase();
return allowedExtensions.includes(ext);
},
(name: string) => allowedExtensions.includes(extOf(name)),
[allowedExtensions],
);
+54
View File
@@ -0,0 +1,54 @@
import { describe, expect, it } from 'vitest';
import { extOf, filterByExtension, getAllowedExtensions } from '../file-filter';
function f(name: string): File {
return new File(['x'], name);
}
describe('getAllowedExtensions', () => {
it('returns json + txt for forward direction regardless of format', () => {
expect(getAllowedExtensions('forward', 'yaml')).toEqual(['json', 'txt']);
expect(getAllowedExtensions('forward', 'resx')).toEqual(['json', 'txt']);
});
it('returns format extension + txt for reverse direction, lowercased', () => {
expect(getAllowedExtensions('reverse', 'yaml')).toEqual(['yaml', 'txt']);
expect(getAllowedExtensions('reverse', 'RESX')).toEqual(['resx', 'txt']);
expect(getAllowedExtensions('reverse', 'toml')).toEqual(['toml', 'txt']);
});
});
describe('extOf', () => {
it('lowercases the trailing extension', () => {
expect(extOf('foo.JSON')).toBe('json');
expect(extOf('a.b.cs')).toBe('cs');
});
it('returns empty string for names with no extension', () => {
expect(extOf('noext')).toBe('');
expect(extOf('trailing.')).toBe('');
expect(extOf('.hidden')).toBe('hidden');
});
});
describe('filterByExtension', () => {
it('partitions by extension whitelist (case-insensitive)', () => {
const cs = f('a.cs');
const json = f('b.json');
const yaml = f('c.yaml');
const result = filterByExtension([cs, json, yaml], ['json', 'txt']);
expect(result.valid).toEqual([json]);
expect(result.wrongFormat).toBe(2);
});
it('accepts uppercase extensions because whitelist comparison is lowercased', () => {
const upper = f('FOO.JSON');
const result = filterByExtension([upper], ['json', 'txt']);
expect(result.valid).toEqual([upper]);
expect(result.wrongFormat).toBe(0);
});
it('returns empty result for empty input', () => {
expect(filterByExtension([], ['json'])).toEqual({ valid: [], wrongFormat: 0 });
});
});
+22
View File
@@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest';
import { pathHashAsMillis } from '../tauri';
describe('pathHashAsMillis', () => {
it('is deterministic for the same input', () => {
const a = pathHashAsMillis('C:/Users/me/data.json');
const b = pathHashAsMillis('C:/Users/me/data.json');
expect(a).toBe(b);
});
it('produces different hashes for different paths', () => {
expect(pathHashAsMillis('/a/foo.json')).not.toBe(pathHashAsMillis('/a/bar.json'));
expect(pathHashAsMillis('/a/foo.json')).not.toBe(pathHashAsMillis('/b/foo.json'));
});
it('returns a non-negative integer (unsigned 32-bit) even for empty input', () => {
const h = pathHashAsMillis('');
expect(Number.isInteger(h)).toBe(true);
expect(h).toBeGreaterThanOrEqual(0);
expect(h).toBeLessThanOrEqual(0xffffffff);
});
});
+41
View File
@@ -0,0 +1,41 @@
export type FileFilterDirection = 'forward' | 'reverse';
/**
* Allowed file extensions for a given direction × format combo.
* Forward: JSON-only input. Reverse: the format's native extension.
* `.txt` is always accepted as a freeform escape hatch.
*
* Returned extensions are lowercase, without the leading dot.
*/
export function getAllowedExtensions(
direction: FileFilterDirection,
formatExtension: string,
): string[] {
if (direction === 'reverse') {
return [formatExtension.toLowerCase(), 'txt'];
}
return ['json', 'txt'];
}
/** Lowercase extension of a filename, empty string if there's no dot. */
export function extOf(name: string): string {
const idx = name.lastIndexOf('.');
if (idx < 0 || idx === name.length - 1) return '';
return name.slice(idx + 1).toLowerCase();
}
export interface FilterByExtensionResult {
valid: File[];
wrongFormat: number;
}
/** Split files into (accepted, wrong-format count) by extension whitelist. */
export function filterByExtension(files: File[], allowed: string[]): FilterByExtensionResult {
const valid: File[] = [];
let wrongFormat = 0;
for (const f of files) {
if (allowed.includes(extOf(f.name))) valid.push(f);
else wrongFormat += 1;
}
return { valid, wrongFormat };
}
+49 -1
View File
@@ -70,14 +70,62 @@ export async function nativeReadText(path: string): Promise<string> {
return readTextFile(path);
}
// MIME type per extension. Used so File objects created from native paths
// carry a sensible `type` instead of being hard-coded to `application/json`.
const TYPE_BY_EXT: Record<string, string> = {
json: 'application/json',
yaml: 'application/x-yaml',
yml: 'application/x-yaml',
toml: 'application/toml',
xml: 'application/xml',
csv: 'text/csv',
tsv: 'text/tab-separated-values',
resx: 'application/xml',
txt: 'text/plain',
};
/**
* FNV-1a 32-bit hash of a path, returned as an unsigned 32-bit integer.
* Used as a stable `lastModified` for File objects when `stat()` is
* unavailable — `batchStore` dedups on `(name, size, lastModified)`,
* so the value must be deterministic across repeated drops of the same path.
*/
export function pathHashAsMillis(path: string): number {
let h = 0x811c9dc5;
for (let i = 0; i < path.length; i += 1) {
h ^= path.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return h >>> 0;
}
/**
* Convert a native file path to a browser-style File so the
* existing batch store and editor flows can consume it unchanged.
*
* `lastModified` is read from the file's real mtime via `stat()` so that
* re-dropping the same file dedups correctly (batchStore keys on
* name|size|lastModified). Falling back to `Date.now()` would break dedup
* because every drop produces a fresh timestamp.
*/
export async function fileFromNativePath(path: string): Promise<File> {
const text = await nativeReadText(path);
const name = path.replace(/^.*[\\/]/, ''); // basename
return new File([text], name, { type: 'application/json' });
const ext = (name.split('.').pop() ?? '').toLowerCase();
const type = TYPE_BY_EXT[ext] ?? 'application/octet-stream';
let lastModified: number;
try {
const { stat } = await import('@tauri-apps/plugin-fs');
const info = await stat(path);
lastModified = info.mtime ? info.mtime.getTime() : pathHashAsMillis(path);
} catch {
// Capability missing or file vanished between read + stat — fall back
// to a deterministic hash so repeat drops still dedup.
lastModified = pathHashAsMillis(path);
}
return new File([text], name, { type, lastModified });
}
/**