Porting an embroidery file library from Python to TypeScript, byte for byte
Machine embroidery has a file format problem. A Brother machine wants PES, a Janome wants JEF, a commercial Tajima head wants DST, a Pfaff wants VP3, and a Bernina often wants EXP. People buy a design, get the wrong file
Machine embroidery has a file format problem. A Brother machine wants PES, a Janome wants JEF, a commercial Tajima head wants DST, a Pfaff wants VP3, and a Bernina often wants EXP. People buy a design, get the wrong file, and search for "convert DST to PES". Most of the free converters they find upload the file to a server.
We wanted one that never uploads anything, so we ported pystitch, the Python embroidery library behind Ink/Stitch, to TypeScript and ran it in the browser. The result is the Embroidery File Converter, MIT licensed, with the source on GitHub.
Disclosure: we're MavenWright, and we also make a commercial embroidery app (StitchKit). The converter is free, MIT licensed and does not need it.
The interesting part was not the formats themselves. It was making the TypeScript version write the same bytes as the Python one, and finding out how many small Python behaviours that takes.
An embroidery file is a list of needle moves
An embroidery file is not an image. It's an ordered list of moves: stitch here, jump there without stitching, trim the thread, stop for a colour change, end. The machine moves the hoop from point to point. Units are usually 0.1 mm.
DST, the oldest and most widely read format, packs each move into 3 bytes. The x and y offsets are spread across those bytes as flags with weights of Β±1, Β±3, Β±9, Β±27 and Β±81, a balanced ternary system. This is how the port decodes x:
export function decodeDx(b0: number, b1: number, b2: number): number {
let x = 0;
x += getbit(b2, 2) * +81;
x += getbit(b2, 3) * -81;
x += getbit(b1, 2) * +27;
x += getbit(b1, 3) * -27;
x += getbit(b0, 2) * +9;
x += getbit(b0, 3) * -9;
x += getbit(b1, 0) * +3;
x += getbit(b1, 1) * -3;
x += getbit(b0, 0) * +1;
x += getbit(b0, 1) * -1;
return x;
}
Add up the positive weights and you get 121, so a single DST record can move at most 12.1 mm in each direction. The writer splits anything longer into several records. The y axis is decoded the same way and then flipped. The command lives in the top bits of the third byte: one pattern means "jump", another means "colour change", and 0b11110011 means "end of design".
Before the records there is a 512-byte text header made of lines like LA:design name. That LA: at offset 0 is the closest thing DST has to a magic number. DST stores no thread colours at all. A colour change is just a stop, which is why a DST opens grey in most viewers.
PES, Brother's format, is a wrapper. It starts with #PES and a version, and carries the actual stitches in an embedded PEC block, which uses a fixed table of 64 Brother thread colours. Writing PES therefore means matching every colour in the design to the nearest of those 64.
Why port instead of rewriting
Embroidery formats are full of undocumented details, and pystitch has years of them baked in: header quirks, colour tables, the order things are written in. A clean rewrite would lose that. So we set a strict goal: for the same input, the TypeScript writers produce the same bytes as pystitch, and the readers return the same stitches.
To check it, the repo has a parity harness. It sets up a Python 3.12 virtualenv with pystitch 1.0.1, runs both implementations on the same files, and compares the results byte for byte. Our last full run covered 1,615 design files across all five formats, plus 8,075 files written by our own app: the two implementations read all 9,690 identically and wrote 8,075 of 8,075 byte for byte. A smaller synthetic corpus and its reference outputs are committed to the repo, so the parity tests also run on a machine without Python.
Getting to zero mismatches meant copying Python behaviour that JavaScript doesn't have.
1. Python rounds half to even
Python 3's round() uses banker's rounding: round(2.5) is 2 and round(3.5) is 4. JavaScript's Math.round(2.5) is 3. pystitch rounds in several places: the centre of a design, colour distances, the per-stitch deltas in EXP and VP3. Each half-unit difference shifts a stitch by 0.1 mm and changes the bytes. The port has a pyRound that rounds half to even:
export function pyRound(v: number): number {
const f = Math.floor(v);
const d = v - f;
if (d < 0.5) return f;
if (d > 0.5) return f + 1;
return f % 2 === 0 ? f : f + 1;
}
2. JavaScript has a negative zero
Flipping the y axis in Python is -y, and for y = 0 that's just 0: Python integers have no negative zero. In JavaScript, -0 is a separate value. -0 === 0 is true, but Object.is(-0, 0) is false, and so are deep-equality checks that build on it. The port writes 0 - y instead, with a comment so nobody "simplifies" it back.
3. The order of a Python set
This one took the longest. When pystitch builds the PEC palette for a PES file, it iterates over Python sets of threads. A set has no defined order in the language, but CPython iterates it in the order of its internal hash table, which depends on the hashes, the table size, the probing sequence and when the table resizes. That order decides which palette slot each colour gets, and therefore the bytes of the file.
A JavaScript Set keeps insertion order, so it gives a different palette. The port includes pyset.ts, a small model of how CPython 3.12 inserts into and resizes a set table (linear probing, the perturb shift, resize thresholds), used only where pystitch iterates a set. A test checks it against a real CPython 3.12 interpreter. Because it reimplements CPython behaviour, the repo's NOTICE file carries the Python Software Foundation licence text as well as pystitch's MIT licence.
4. One deliberate difference: randomness
When a design that stores no colours (DST, EXP) is written to a format that needs them, pystitch fills in random colours with random.getrandbits(24). We wanted the same input to always give the same output, so the port uses a fixed list of stand-in colours instead. It's the one documented exception to byte parity, and the README says so.
Detecting a format you can't trust
PES (#PES), VP3 (%vsm%) and most DST files (LA:) can be recognised by their first bytes. EXP has no magic at all, some DST files have no header, and JEF has to be recognised by a consistency check on its header. Worse, a DST or EXP reader will happily "read" almost any file: every 3 bytes decode to some move.
So the detector never trusts the extension alone. A .dst file must also have a body that follows DST's record rules, and a .exp must follow the EXP grammar. Common non-embroidery files (PNG, JPEG, PDF, ZIP, GIF, MP4 and friends) and plain text are rejected by signature first, so a renamed photo gives a clear "this is not an embroidery file" instead of a screen full of random stitches.
Running it in the browser
The library in src/ has no browser or Node dependencies; it works on a Uint8Array:
const bytes = new Uint8Array(await file.arrayBuffer());
const { bytes: dst, warnings, outName } = convert(bytes, file.name, "dst");
The web app around it is a small Vite build. Reading, previewing and converting all happen on the user's device, with no upload and no server-side processing. The Docker image (linux/amd64 and linux/arm64) only serves those static files with nginx, with a default-src 'self' Content-Security-Policy, so it's easy to self-host:
docker run -d -p 8080:8080 mavenwright/embroidery-converter:1.0.0
Before each download the converter lists what the target format can't keep. DST and EXP lose thread colours, VP3 loses stops (the pause for placing appliquΓ© fabric), and JEF can only name hoops up to 200 Γ 200 mm.
Try it or take it apart
- Use it in the browser: Embroidery File Converter
- Read the code, the parity harness and the tests: github.com/mavenwright/embroidery-converter
- Thanks to the pystitch and Ink/Stitch contributors, whose work this is built on.
If you have an embroidery file the converter reads differently from your machine software, an issue with the file attached is the most useful bug report we can get.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.